### ----------------------------------------------------
### -- TinyFloats
### -- Licenses: Artistic-2.0
### -- Authors: Geoffrey Broadwell
### -- File: t/04-fp8-e5m2.rakutest
### ----------------------------------------------------
use v6.d;
use Test;

use TinyFloats;

plan 46;


sub check($e5m2, $num) {
    use Test;

    my $reduced  = e5m2-from-num($num);
    my $expanded = num-from-e5m2($e5m2);

    # diag "Reduced: $reduced.fmt('0x%02x'), Expanded: $expanded.fmt('%.10f')";
    ok $reduced  == $e5m2, "Able to reduce $num.fmt('%.10f') to $e5m2.fmt('0x%02x')";
    ok $expanded == $num || $expanded.isNaN && $num.isNaN,
                            "Able to expand $e5m2.fmt('0x%02x') to $num.fmt('%.10f')";
}


### Test cases below adapted from binary16 tests, as FP8-E5M2 is essentially
### binary16 with another byte of mantissa truncated off.

# Signed 0
check 0x00,  0e0;
check 0x80, -0e0;

# Signed Inf
check 0x7C,  Inf;
check 0xFC, -Inf;

# NaN
check 0x7E,  NaN;

# One
check 0x3C,  1e0;
check 0xBC, -1e0;

# One + 1/4
check 0x3D,  (1e0 + 1/4);
check 0xBD, -(1e0 + 1/4);

# One - 1/8
check 0x3B,  (1e0 - 1/8);
check 0xBB, -(1e0 - 1/8);

# Two
check 0x40,  2e0;
check 0xC0, -2e0;

# 8-bit max
check 0x7B,  57344e0;
check 0xFB, -57344e0;

# 8-bit min
check 0x01,  1e0/(2**16);
check 0x81, -1e0/(2**16);

# 8-bit 2*min
check 0x02,  1e0/(2**15);
check 0x82, -1e0/(2**15);

# 8-bit smallest normal
check 0x04,  1e0/(2**14);
check 0x84, -1e0/(2**14);

# 1/3, rounded to nearest
check 0x35,  .25e0 * (5/4);
check 0xB5, -.25e0 * (5/4);


done-testing;


