github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/binary/word256_test.go (about)

     1  package binary
     2  
     3  import (
     4  	"encoding/json"
     5  	"math/big"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  	"github.com/tmthrgd/go-hex"
    11  )
    12  
    13  func TestWord256_UnpadLeft(t *testing.T) {
    14  	bs := []byte{0x45, 0x12}
    15  	w := LeftPadWord256(bs)
    16  	wExpected := Word256{}
    17  	wExpected[30] = bs[0]
    18  	wExpected[31] = bs[1]
    19  	assert.Equal(t, wExpected, w)
    20  	assert.Equal(t, bs, w.UnpadLeft())
    21  }
    22  
    23  func TestWord256_UnpadRight(t *testing.T) {
    24  	bs := []byte{0x45, 0x12}
    25  	w := RightPadWord256(bs)
    26  	wExpected := Word256{}
    27  	wExpected[0] = bs[0]
    28  	wExpected[1] = bs[1]
    29  	assert.Equal(t, wExpected, w)
    30  	assert.Equal(t, bs, w.UnpadRight())
    31  }
    32  
    33  func TestLeftPadWord256(t *testing.T) {
    34  	assert.Equal(t, Zero256, LeftPadWord256(nil))
    35  	assert.Equal(t,
    36  		Word256{
    37  			0, 0, 0, 0, 0, 0, 0, 0,
    38  			0, 0, 0, 0, 0, 0, 0, 0,
    39  			0, 0, 0, 0, 0, 0, 0, 0,
    40  			0, 0, 0, 0, 0, 1, 2, 3,
    41  		},
    42  		LeftPadWord256([]byte{1, 2, 3}))
    43  }
    44  
    45  func TestTwosComplement(t *testing.T) {
    46  	v := Int64ToWord256(-10)
    47  	require.Equal(t, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6",
    48  		hex.EncodeUpperToString(v[:]))
    49  
    50  	upper, ok := new(big.Int).SetString("32423973453453434237423", 10)
    51  	require.True(t, ok)
    52  	inc, ok := new(big.Int).SetString("3242397345345343421", 10)
    53  	require.True(t, ok)
    54  	for i := new(big.Int).Neg(upper); i.Cmp(upper) == -1; i.Add(i, inc) {
    55  		v := BigIntFromWord256(BigIntToWord256(i))
    56  		require.True(t, i.Cmp(v) == 0, "expected %d == %d", i, v)
    57  	}
    58  }
    59  
    60  func TestOne256(t *testing.T) {
    61  	assert.Equal(t, Int64ToWord256(1), One256)
    62  }
    63  
    64  func TestWord256_MarshalText(t *testing.T) {
    65  	w := Word256{1, 2, 3, 4, 5}
    66  	out, err := json.Marshal(w)
    67  	require.NoError(t, err)
    68  	assert.Equal(t, "\"0102030405000000000000000000000000000000000000000000000000000000\"", string(out))
    69  	bs2 := new(Word256)
    70  	err = json.Unmarshal(out, bs2)
    71  	require.NoError(t, err)
    72  	assert.Equal(t, w, *bs2)
    73  }
    74  
    75  func TestInt64ToWord256(t *testing.T) {
    76  	i := int64(-34)
    77  	assert.Equal(t, i, Int64FromWord256(Int64ToWord256(i)))
    78  }