github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/utils/cser/read_writer_test.go (about)

     1  package cser
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/require"
     7  
     8  	"github.com/unicornultrafoundation/go-u2u/utils/bits"
     9  	"github.com/unicornultrafoundation/go-u2u/utils/fast"
    10  )
    11  
    12  func TestUint64Compact(t *testing.T) {
    13  	require := require.New(t)
    14  	var (
    15  		canonical    = []byte{0b01111111, 0b11111111}
    16  		nonCanonical = []byte{0b01111111, 0b01111111, 0b10000000}
    17  	)
    18  
    19  	r := fast.NewReader(canonical)
    20  	got := readUint64Compact(r)
    21  	require.Equal(uint64(0x3fff), got)
    22  
    23  	r = fast.NewReader(nonCanonical)
    24  	require.Panics(func() {
    25  		_ = readUint64Compact(r)
    26  	})
    27  }
    28  
    29  func TestUint64BitCompact(t *testing.T) {
    30  	require := require.New(t)
    31  	var (
    32  		canonical    = []byte{0b11111111, 0b00111111}
    33  		nonCanonical = []byte{0b01111111, 0b01111111, 0b00000000}
    34  	)
    35  
    36  	r := fast.NewReader(canonical)
    37  	got := readUint64BitCompact(r, len(canonical))
    38  	require.Equal(uint64(0x3fff), got)
    39  
    40  	r = fast.NewReader(nonCanonical)
    41  	require.Panics(func() {
    42  		_ = readUint64BitCompact(r, len(nonCanonical))
    43  	})
    44  }
    45  
    46  func TestI64(t *testing.T) {
    47  	require := require.New(t)
    48  
    49  	w := NewWriter()
    50  
    51  	canonical := w.I64
    52  	nonCanonical := func(v int64) {
    53  		w.Bool(v <= 0)
    54  		if v < 0 {
    55  			w.U64(uint64(-v))
    56  		} else {
    57  			w.U64(uint64(v))
    58  		}
    59  	}
    60  
    61  	canonical(0)
    62  	nonCanonical(0)
    63  
    64  	r := &Reader{
    65  		BitsR:  bits.NewReader(w.BitsW.Array),
    66  		BytesR: fast.NewReader(w.BytesW.Bytes()),
    67  	}
    68  
    69  	got := r.I64()
    70  	require.Zero(got)
    71  
    72  	require.Panics(func() {
    73  		_ = r.I64()
    74  	})
    75  }
    76  
    77  func TestPaddedBytes(t *testing.T) {
    78  	require := require.New(t)
    79  
    80  	var data = []struct {
    81  		In  []byte
    82  		N   int
    83  		Exp []byte
    84  	}{
    85  		{In: nil, N: 0, Exp: nil},
    86  		{In: []byte{}, N: 0, Exp: []byte{}},
    87  		{In: nil, N: 1, Exp: []byte{0}},
    88  		{In: []byte{}, N: 1, Exp: []byte{0}},
    89  		{In: []byte{10, 20}, N: 1, Exp: []byte{10, 20}},
    90  		{In: []byte{10, 20}, N: 4, Exp: []byte{0, 0, 10, 20}},
    91  	}
    92  
    93  	for i, d := range data {
    94  		got := PaddedBytes(d.In, d.N)
    95  		require.Equal(d.Exp, got, i)
    96  	}
    97  }