github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/chain/trie/encoding_test.go (about) 1 package trie 2 3 import ( 4 "bytes" 5 "testing" 6 ) 7 8 func TestHexCompact(t *testing.T) { 9 tests := []struct{ hex, compact []byte }{ 10 11 {hex: []byte{}, compact: []byte{0x00}}, 12 {hex: []byte{16}, compact: []byte{0x20}}, 13 14 {hex: []byte{1, 2, 3, 4, 5}, compact: []byte{0x11, 0x23, 0x45}}, 15 16 {hex: []byte{0, 1, 2, 3, 4, 5}, compact: []byte{0x00, 0x01, 0x23, 0x45}}, 17 18 {hex: []byte{15, 1, 12, 11, 8, 16}, compact: []byte{0x3f, 0x1c, 0xb8}}, 19 20 {hex: []byte{0, 15, 1, 12, 11, 8, 16}, compact: []byte{0x20, 0x0f, 0x1c, 0xb8}}, 21 } 22 for _, test := range tests { 23 if c := hexToCompact(test.hex); !bytes.Equal(c, test.compact) { 24 t.Errorf("hexToCompact(%x) -> %x, want %x", test.hex, c, test.compact) 25 } 26 if h := compactToHex(test.compact); !bytes.Equal(h, test.hex) { 27 t.Errorf("compactToHex(%x) -> %x, want %x", test.compact, h, test.hex) 28 } 29 } 30 } 31 32 func TestHexKeybytes(t *testing.T) { 33 tests := []struct{ key, hexIn, hexOut []byte }{ 34 {key: []byte{}, hexIn: []byte{16}, hexOut: []byte{16}}, 35 {key: []byte{}, hexIn: []byte{}, hexOut: []byte{16}}, 36 { 37 key: []byte{0x12, 0x34, 0x56}, 38 hexIn: []byte{1, 2, 3, 4, 5, 6, 16}, 39 hexOut: []byte{1, 2, 3, 4, 5, 6, 16}, 40 }, 41 { 42 key: []byte{0x12, 0x34, 0x5}, 43 hexIn: []byte{1, 2, 3, 4, 0, 5, 16}, 44 hexOut: []byte{1, 2, 3, 4, 0, 5, 16}, 45 }, 46 { 47 key: []byte{0x12, 0x34, 0x56}, 48 hexIn: []byte{1, 2, 3, 4, 5, 6}, 49 hexOut: []byte{1, 2, 3, 4, 5, 6, 16}, 50 }, 51 } 52 for _, test := range tests { 53 if h := keybytesToHex(test.key); !bytes.Equal(h, test.hexOut) { 54 t.Errorf("keybytesToHex(%x) -> %x, want %x", test.key, h, test.hexOut) 55 } 56 if k := hexToKeybytes(test.hexIn); !bytes.Equal(k, test.key) { 57 t.Errorf("hexToKeybytes(%x) -> %x, want %x", test.hexIn, k, test.key) 58 } 59 } 60 } 61 62 func BenchmarkHexToCompact(b *testing.B) { 63 testBytes := []byte{0, 15, 1, 12, 11, 8, 16} 64 for i := 0; i < b.N; i++ { 65 hexToCompact(testBytes) 66 } 67 } 68 69 func BenchmarkCompactToHex(b *testing.B) { 70 testBytes := []byte{0, 15, 1, 12, 11, 8, 16} 71 for i := 0; i < b.N; i++ { 72 compactToHex(testBytes) 73 } 74 } 75 76 func BenchmarkKeybytesToHex(b *testing.B) { 77 testBytes := []byte{7, 6, 6, 5, 7, 2, 6, 2, 16} 78 for i := 0; i < b.N; i++ { 79 keybytesToHex(testBytes) 80 } 81 } 82 83 func BenchmarkHexToKeybytes(b *testing.B) { 84 testBytes := []byte{7, 6, 6, 5, 7, 2, 6, 2, 16} 85 for i := 0; i < b.N; i++ { 86 hexToKeybytes(testBytes) 87 } 88 }