/* leb128.pk - Support for LEB128 and ULEB128 encoding.  */

/* Copyright (C) 2019, 2020, 2021, 2022, 2023 Jose E. Marchesi.  */

/* This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* LEB128 or Little Endian Base 128 is a variable-length encoding for
   arbitrarily large integers.  It is used in DWARF.  */

type LEB128_Byte =
  struct uint<8>
  {
    uint<1> hi : hi == 1;
    uint<7> lo;
  };

type ULEB128 =
  struct
  {
    LEB128_Byte[] variable;
    byte last;

    method value = uint<64>:
      {
       var shift = 0;
       var result = 0UL;
       fun extract = (uint<64> b) uint<64>: { return (b & 0x7f) <<. shift; }

       /* poke supports up to 64-bit integers.  */
       if (variable'length > 9)
         raise E_generic;

       for (v in variable)
         {
           result = result | extract (v);
           shift = shift + 7;
         }
       result |= extract (last);

       return result;
      }

    method _print = void:
      {
       var val = 0UL;

       try val = value;
       catch
       {
         print "#<uleb128:";
         for (b in variable)
           printf "%v,", b;
         printf "%v", last;
         print ">";
         return;
       }

       printf ("%<leb128:#<uleb128:%<integer:%u64d%>>%>",
               value);
      }
  };

type LEB128 =
  struct
  {
    LEB128_Byte[] variable;
    byte last;

    method value = int<64>:
      {
       var shift = 0;
       var result = 0UL;
       fun extract = (int<64> b) int<64>: { return (b & 0x7f) <<. shift; }

       /* poke supports up to 64-bit integers.  */
       if (variable'length > 9)
         raise E_generic;

       for (v in variable)
         {
           result = result | extract (v);
           shift = shift + 7;
         }
       result |= extract (last);

       if (shift < (variable'size/#B) && last & 0b1000_0000)
         result = result | (!0 <<. shift);

       return result;
      }

    method _print = void:
      {
       var val = 0UL;

       try val = value;
       catch
       {
         print "#<leb128:";
         for (b in variable)
           printf "%v,", b;
         printf "%v", last;
         print ">";
         return;
       }

       printf ("%<leb128:#<leb128:%<integer:%u64d%>>%>",
               value);
      }
  };
