github.com/ydb-platform/ydb-go-sdk/v3@v3.89.2/internal/decimal/decimal_test.go (about)

     1  package decimal
     2  
     3  import (
     4  	"encoding/binary"
     5  	"testing"
     6  )
     7  
     8  func TestFromBytes(t *testing.T) {
     9  	for _, test := range []struct {
    10  		name      string
    11  		bts       []byte
    12  		precision uint32
    13  		scale     uint32
    14  		format    string
    15  	}{
    16  		{
    17  			bts:       uint128(0xffffffffffffffff, 0xffffffffffffffff),
    18  			precision: 22,
    19  			scale:     9,
    20  			format:    "-0.000000001",
    21  		},
    22  		{
    23  			bts:       uint128(0xffffffffffffffff, 0),
    24  			precision: 22,
    25  			scale:     9,
    26  			format:    "-18446744073.709551616",
    27  		},
    28  		{
    29  			bts:       uint128(0x4000000000000000, 0),
    30  			precision: 22,
    31  			scale:     9,
    32  			format:    "inf",
    33  		},
    34  		{
    35  			bts:       uint128(0x8000000000000000, 0),
    36  			precision: 22,
    37  			scale:     9,
    38  			format:    "-inf",
    39  		},
    40  		{
    41  			bts:       uint128s(1000000000),
    42  			precision: 22,
    43  			scale:     9,
    44  			format:    "1.000000000",
    45  		},
    46  		{
    47  			bts:       []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 250, 240, 128},
    48  			precision: 22,
    49  			scale:     9,
    50  			format:    "0.050000000",
    51  		},
    52  	} {
    53  		t.Run(test.name, func(t *testing.T) {
    54  			x := FromBytes(test.bts, test.precision, test.scale)
    55  			p := Append(nil, x)
    56  			y := FromBytes(p, test.precision, test.scale)
    57  			if x.Cmp(y) != 0 {
    58  				t.Errorf(
    59  					"parsed bytes serialized to different value: %v; want %v",
    60  					x, y,
    61  				)
    62  			}
    63  			formatted := Format(x, test.precision, test.scale)
    64  			if test.format != formatted {
    65  				t.Errorf("unexpected decimal format. Expected: %s, actual %s", test.format, formatted)
    66  			}
    67  			t.Logf(
    68  				"%s %s",
    69  				Format(x, test.precision, test.scale),
    70  				Format(y, test.precision, test.scale),
    71  			)
    72  		})
    73  	}
    74  }
    75  
    76  func uint128(hi, lo uint64) []byte {
    77  	p := make([]byte, 16)
    78  	binary.BigEndian.PutUint64(p[:8], hi)
    79  	binary.BigEndian.PutUint64(p[8:], lo)
    80  
    81  	return p
    82  }
    83  
    84  func uint128s(lo uint64) []byte {
    85  	return uint128(0, lo)
    86  }