(********************************************************************)
(*                                                                  *)
(*  bin32.s7i     32-bit binary value support library               *)
(*  Copyright (C) 2013 - 2024  Thomas Mertes                        *)
(*                                                                  *)
(*  This file is part of the Seed7 Runtime Library.                 *)
(*                                                                  *)
(*  The Seed7 Runtime Library is free software; you can             *)
(*  redistribute it and/or modify it under the terms of the GNU     *)
(*  Lesser General Public License as published by the Free Software *)
(*  Foundation; either version 2.1 of the License, or (at your      *)
(*  option) any later version.                                      *)
(*                                                                  *)
(*  The Seed7 Runtime Library 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 Lesser General Public License for more    *)
(*  details.                                                        *)
(*                                                                  *)
(*  You should have received a copy of the GNU Lesser General       *)
(*  Public License along with this program; if not, write to the    *)
(*  Free Software Foundation, Inc., 51 Franklin Street,             *)
(*  Fifth Floor, Boston, MA  02110-1301, USA.                       *)
(*                                                                  *)
(********************************************************************)


include "float.s7i";


(**
 *  Binary values with 32 bits.
 *  This type supports bitwise operations but no integer arithmetic.
 *  The internal representation is the same as for integer.
 *)
const type: bin32 is subtype object;

const proc: destroy (ref bin32: aValue)                        is action "GEN_DESTR";
const proc: (ref bin32: dest) ::= (ref bin32: source)          is action "INT_CREATE";
IN_PARAM_IS_VALUE(bin32);

const proc: (inout bin32: dest) := (in bin32: source)          is action "INT_CPY";


(**
 *  Convert to bin32.
 *  @return the unchanged value as bin32.
 *)
const func bin32: bin32 (in integer: number)                   is action "INT_ICONV1";


(**
 *  Default value of ''bin32'' (bin32(0)).
 *)
const bin32: (attr bin32) . value   is bin32(0);


(**
 *  Convert to bin32.
 *  @return the unchanged value as bin32.
 *)
const func bin32: bin32 (in char: ch) is
  return bin32(ord(ch));


(**
 *  Get bits in IEEE 754 single-precision representation from a float.
 *  IEEE 754 is a standard for floating point arithmetic.
 *  The single-precision format of IEEE 754 has a sign bit, an 8 bit
 *  exponent, and a 23 bit mantissa.
 *   bin32(1.0)  returns  bin32(16#3f800000)
 *  @param number Float value to be converted to bin32.
 *  @return 32 bits in IEEE 754 single-precision float representation.
 *)
const func bin32: bin32 (in float: number)                     is action "FLT_SINGLE2BITS";


(**
 *  Convert to integer.
 *  @return the unchanged value as integer.
 *)
const func integer: (attr integer) conv (in bin32: bits)       is action "INT_ICONV3";


(**
 *  Convert to bin32.
 *  @return the unchanged value as bin32.
 *)
const func bin32: (attr bin32) conv (in integer: anInt)        is action "INT_ICONV3";


(**
 *  Convert to integer.
 *  @return the unchanged value as integer.
 *)
const func integer: ord (in bin32: bits)                       is action "INT_ICONV1";


(**
 *  Convert to integer.
 *  @return the unchanged value as integer.
 *)
const func integer: integer (in bin32: bits)                   is action "INT_ICONV1";


(**
 *  Get a float from bits in IEEE 754 single-precision representation.
 *  IEEE 754 is a standard for floating point arithmetic.
 *  The single-precision format of IEEE 754 has a sign bit, an 8 bit
 *  exponent, and a 23 bit mantissa.
 *   float(bin32(16#3f800000))  returns  1.0
 *  @param bits Bits to be converted to a float.
 *  @return a float from bits in single-precision float representation.
 *)
const func float: float (in bin32: bits)                       is action "FLT_BITS2SINGLE";


(**
 *  Compare two bin32 values.
 *  @return -1, 0 or 1 if the first argument is considered to be
 *          respectively less than, equal to, or greater than the
 *          second.
 *)
const func integer: compare (in bin32: bits1, in bin32: bits2) is action "BIN_CMP";


(**
 *  Compute the hash value of a bin32 value.
 *  @return the hash value.
 *)
const func integer: hashCode (in bin32: bits)                  is action "INT_HASHCODE";


(**
 *  Compute pseudo-random bin32 value.
 *  The random values are uniform distributed.
 *  @return a random bin32 value.
 *)
const func bin32: rand (attr bin32) is
  return bin32(rand(0, 4294967295));


(**
 *  Number of bits in the minimum binary representation.
 *  Leading zero bits are not part of the minimum binary representation.
 *   bitLength(bin32(0))  returns 0
 *   bitLength(bin32(1))  returns 1
 *   bitLength(bin32(4))  returns 3
 *  @return the number of bits.
 *)
const func integer: bitLength (in bin32: bits)                 is action "BIN_BIT_LENGTH";


(**
 *  Number of lowest-order zero bits in the binary representation.
 *  This is equal to the index of the lowest-order one bit (indices start with 0).
 *  If there are only zero bits (''bits'' is bin32(0)) the result is -1.
 *   lowestSetBit(bin32(0))  returns -1
 *   lowestSetBit(bin32(1))  returns  0
 *   lowestSetBit(bin32(4))  returns  2
 *  @return the number of lowest-order zero bits or -1 for lowestSetBit(bin32(0)).
 *)
const func integer: lowestSetBit (in bin32: bits)              is action "BIN_LOWEST_SET_BIT";


(**
 *  Convert an ''bin32'' value to a [[string]].
 *  The values is converted to a string with decimal representation.
 *  @return the string result of the conversion.
 *  @exception MEMORY_ERROR Not enough memory to represent the result.
 *)
const func string: str (in bin32: bits)                        is action "BIN_STR";


(**
 *  Convert a ''bin32'' value to a [[string]] using a radix.
 *  The conversion uses the numeral system with the given ''base''.
 *  Digit values from 10 upward are encoded with lower case letters.
 *  E.g.: 10 is encoded with a, 11 with b, etc.
 *   bin32(48879) radix 16   returns "beef"
 *  @return the string result of the conversion.
 *  @exception RANGE_ERROR If base < 2 or base > 36 holds.
 *  @exception MEMORY_ERROR Not enough memory to represent the result.
 *)
const func string: (in bin32: bits) radix (in integer: base)   is action "BIN_radix";


(**
 *  Convert a ''bin32'' value to a [[string]] using a radix.
 *  The conversion uses the numeral system with the given ''base''.
 *  Digit values from 10 upward are encoded with upper case letters.
 *  E.g.: 10 is encoded with A, 11 with B, etc.
 *   bin64(48879) RADIX 16   returns "BEEF"
 *  @return the string result of the conversion.
 *  @exception RANGE_ERROR If base < 2 or base > 36 holds.
 *  @exception MEMORY_ERROR Not enough memory to represent the result.
 *)
const func string: (in bin32: bits) RADIX (in integer: base)   is action "BIN_RADIX";


(**
 *  Convert a ''bin32'' into a [[string]] of bytes with big-endian encoding.
 *  The result uses binary representation with a base of 256.
 *  The result contains chars (bytes) with an ordinal <= 255.
 *   bytes(bin32(1413829460), BE, 5)  returns "\0;TEST"
 *   bytes(bin32(1413829460), BE, 4)  returns "TEST"
 *   bytes(bin32(1413829460), BE, 3)  raises RANGE_ERROR
 *  @param bits Bin32 to be converted.
 *  @param length Determines the length of the result string.
 *  @return a string of ''length'' bytes with the unsigned binary
 *          representation of ''bits''.
 *  @exception RANGE_ERROR If ''length'' is negative or zero, or
 *                         if the result would not fit in ''length'' bytes.
 *  @exception MEMORY_ERROR Not enough memory to represent the result.
 *)
const func string: bytes (in bin32: bits, BE, in integer: length) is action "BIN_N_BYTES_BE";


(**
 *  Convert a ''bin32'' into a [[string]] of bytes with little-endian encoding.
 *  The result uses binary representation with a base of 256.
 *  The result contains chars (bytes) with an ordinal <= 255.
 *   bytes(bin32(1413829460), LE, 5)  returns "TEST\0;"
 *   bytes(bin32(1413829460), LE, 4)  returns "TEST"
 *   bytes(bin32(1413829460), LE, 3)  raises RANGE_ERROR
 *  @param bits Bin32 to be converted.
 *  @param length Determines the length of the result string.
 *  @return a string of ''length'' bytes with the unsigned binary
 *          representation of ''bits''.
 *  @exception RANGE_ERROR If ''length'' is negative or zero, or
 *                         if the result would not fit in ''length'' bytes.
 *  @exception MEMORY_ERROR Not enough memory to represent the result.
 *)
const func string: bytes (in bin32: bits, LE, in integer: length) is action "BIN_N_BYTES_LE";


(**
 *  Check if two bin32 values are equal.
 *  @return TRUE if the two values are equal,
 *          FALSE otherwise.
 *)
const func boolean: (in bin32: bits1) = (in bin32: bits2)      is action "INT_EQ";


(**
 *  Check if two bin32 values are not equal.
 *  @return FALSE if both values are equal,
 *          TRUE otherwise.
 *)
const func boolean: (in bin32: bits1) <> (in bin32: bits2)     is action "INT_NE";


(**
 *  Compute a bitwise ''and'' of two bin32 values.
 *   bin32(2#1100) & bin32(2#1010)  returns  bin32(2#1000)
 *  @return the bitwise ''and'' of the two values.
 *)
const func bin32: (in bin32: bits1) & (in bin32: bits2)        is action "BIN_AND";


(**
 *  Compute a bitwise inclusive ''or'' of two bin32 values.
 *   bin32(2#1100) | bin32(2#1010)  returns  bin32(2#1110)
 *  @return the bitwise inclusive ''or'' of the two values.
 *)
const func bin32: (in bin32: bits1) | (in bin32: bits2)        is action "BIN_OR";


(**
 *  Compute a bitwise exclusive or (''xor'') of two bin32 values.
 *   bin32(2#1100) >< bin32(2#1010)  returns  bin32(2#0110)
 *  @return the bitwise ''xor'' of the two values.
 *)
const func bin32: (in bin32: bits1) >< (in bin32: bits2)       is action "BIN_XOR";


(**
 *  Compute a bitwise ''not'' of a bin32 value.
 *   ~bin32(2#1)  returns  bin32(16#fffffffe)
 *  @return the bitwise ''not'' of the value.
 *)
const func bin32: ~ (in bin32: bits) is
  return bits >< bin32(16#ffffffff);


(**
 *  Compute ''bits'' logically left shifted by ''lshift''.
 *   bin32(16#abcdef) << 4  returns  bin32(16#abcdef0)
 *   bin32(1) << 64         raises OVERFLOW_ERROR
 *  @return the left shifted value.
 *  @exception OVERFLOW_ERROR If the shift amount is
 *             negative or greater equal 64.
 *)
const func bin32: (in bin32: bits) << (in integer: lshift)     is action "BIN_LSHIFT";


(**
 *  Compute ''bits'' logically right shifted by ''rshift''.
 *  Bits shifted beyond the lowest bit position are lost.
 *   bin32(16#abcdef) >> 4  returns  bin32(16#abcde)
 *  @return the right shifted value.
 *  @exception OVERFLOW_ERROR If the shift amount is
 *             negative or greater equal 64.
 *)
const func bin32: (in bin32: bits) >> (in integer: rshift)     is action "BIN_RSHIFT";


(**
 *  Logical left shift ''bits'' by ''lshift'' and assign the result back to ''bits''.
 *  @exception OVERFLOW_ERROR If the shift amount is
 *             negative or greater equal 64.
 *)
const proc: (inout bin32: bits) <<:= (in integer: lshift)      is action "BIN_LSHIFT_ASSIGN";


(**
 *  Logical right shift ''bits'' by ''rshift'' and assign the result back to ''bits''.
 *  Bits shifted beyond the lowest bit position are lost.
 *  @exception OVERFLOW_ERROR If the shift amount is
 *             negative or greater equal 64.
 *)
const proc: (inout bin32: bits) >>:= (in integer: rshift)      is action "BIN_RSHIFT_ASSIGN";


(**
 *  Compute a bitwise ''and'' and assign the result back to ''bits1''.
 *)
const proc: (inout bin32: bits1) &:= (in bin32: bits2)         is action "BIN_AND_ASSIGN";


(**
 *  Compute a bitwise inclusive ''or'' and assign the result back to ''bits1''.
 *)
const proc: (inout bin32: bits1) |:= (in bin32: bits2)         is action "BIN_OR_ASSIGN";


(**
 *  Compute a bitwise exclusive or (''xor'') and assign the result back to ''bits1''.
 *)
const proc: (inout bin32: bits1) ><:= (in bin32: bits2)        is action "BIN_XOR_ASSIGN";


(**
 *  Rotate the bits of a bin32 value left by shiftCount bits.
 *  The vacant bit positions at the right side are filled in with
 *  the bits that are shifted out at the left side.
 *   rotLeft(bin32(16#12345678), 8)  returns  bin32(16#34567812)
 *  @return the left rotated value.
 *  @exception OVERFLOW_ERROR If the shift amount is negative
 *             or greater than 32.
 *)
const func bin32: rotLeft (in bin32: x, in integer: shiftCount) is
  return (x << shiftCount | x >> (32 - shiftCount)) & bin32(16#ffffffff);


(**
 *  Rotate the bits of a bin32 value right by shiftCount bits.
 *  The vacant bit positions at the left side are filled in with
 *  the bits that are shifted out at the right side.
 *   rotRight(bin32(16#12345678), 8)  returns  bin32(16#78123456)
 *  @return the right rotated value.
 *  @exception OVERFLOW_ERROR If the shift amount is negative
 *             or greater than 32.
 *)
const func bin32: rotRight (in bin32: x, in integer: shiftCount) is
  return (x >> shiftCount | x << (32 - shiftCount)) & bin32(16#ffffffff);


(**
 *  Get bits in MBF single-precision representation from a float.
 *  Microsoft Binary Format (MBF) is a format for floating point numbers.
 *  The single-precision version of MBF has a 8 bit exponent, a sign bit
 *  and a 23 bit mantissa.
 *   float2MbfBits(1.0, SINGLE)  returns  bin32(16#81000000)
 *  @param number Float value to be converted to bin32.
 *  @return 32 bits in MBF single-precision float representation.
 *  @exception RANGE_ERROR If number is not representable in MBF.
 *             NaN, Infinity and -Infinity are not representable
 *             in MBF. Numbers with an absolute value larger than
 *             1.7014117331926443e+38 are also not representable
 *             in MBF.
 *)
const func bin32: float2MbfBits (in float: number, SINGLE) is func
  result
    var bin32: bits is bin32(0);
  local
    const integer: exponentBits is 8;
    const integer: mantissaBits is 23;
    const bin32: ieeeSignMask is bin32(1) << (exponentBits + mantissaBits);
    const bin32: mantissaMask is bin32(pred(1 << mantissaBits));
    const integer: maxExponent is pred(2 ** exponentBits);
    const integer: mbfExponentBias is 129;
    var floatElements: ieeeElements is floatElements.value;
    var bin32: fractionBits is bin32(0);
    var integer: mbfExponent is 0;
  begin
    if isNaN(number) or abs(number) = Infinity then
      raise RANGE_ERROR;
    elsif number <> 0.0 then
      ieeeElements := decompose(number);
      fractionBits := bin32(ieeeElements.fraction);
      if abs(float(fractionBits)) = 1.0 then
        # Because of the rounding to single the fraction could be 1.0.
        incr(ieeeElements.exponent);
        # Interpret the mantissa as 0.5.
      end if;
      mbfExponent := ieeeElements.exponent - 1 + mbfExponentBias;
      if mbfExponent > maxExponent then
        raise RANGE_ERROR;
      elsif mbfExponent > 0 then
        bits := (bin32(mbfExponent) << succ(mantissaBits)) |
                ((fractionBits & ieeeSignMask) >> exponentBits) |
                fractionBits & mantissaMask;
      end if;
    end if;
  end func;


(**
 *  Get a float from bits in MBF single-precision representation.
 *  Microsoft Binary Format (MBF) is a format for floating point numbers.
 *  The single-precision version of MBF has a 8 bit exponent, a sign bit
 *  and a 23 bit mantissa.
 *   mbfBits2Float(bin32(16#81000000))  returns  1.0
 *  @param bits Bits to be converted to a float.
 *  @return a float from bits in MBF single-precision float representation.
 *)
const func float: mbfBits2Float (in bin32: bits) is func
  result
    var float: aFloat is 0.0;
  local
    const integer: mantissaBits is 23;
    const bin32: mantissaMask is bin32(pred(1 << mantissaBits));
    const bin32: mantissaSign is bin32(1 << mantissaBits);
    const integer: exponentBias is 129;
    var integer: exponent is 0;
  begin
    exponent := ord(bits >> succ(mantissaBits));
    if exponent <> 0 then
      # Ignore sign bit and set implicit leading one bit of mantissa instead.
      aFloat := flt(ord(mantissaSign | bits & mantissaMask));
      # Check sign bit.
      if ord(bits & mantissaSign) <> 0 then
        aFloat := -aFloat;
      end if;
      aFloat := aFloat * 2.0 ** (exponent - exponentBias - mantissaBits);
    end if;
  end func;


(**
 *  Convert a string of four little-endian bytes to a bin32 value.
 *  @return the bin32 value.
 *)
const func bin32: bin32 (in string: fourBytes, LE) is
  return bin32(fourBytes[1])       |
         bin32(fourBytes[2]) <<  8 |
         bin32(fourBytes[3]) << 16 |
         bin32(fourBytes[4]) << 24;


(**
 *  Convert a string of four big-endian bytes to a bin32 value.
 *  @return the bin32 value.
 *)
const func bin32: bin32 (in string: fourBytes, BE) is
  return bin32(fourBytes[1]) << 24 |
         bin32(fourBytes[2]) << 16 |
         bin32(fourBytes[3]) <<  8 |
         bin32(fourBytes[4]);


# Allows 'array bin32' everywhere without extra type definition.
const type: _bin32Array is array bin32;


enable_output(bin32);

CASE_DECLS(bin32);
DECLARE_TERNARY(bin32);