github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/segment/writer/metrics/compress/bit_writer_test.go (about) 1 /* 2 Copyright 2023. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package compress 18 19 import ( 20 "bytes" 21 "encoding/binary" 22 "testing" 23 24 fuzz "github.com/google/gofuzz" 25 "github.com/stretchr/testify/assert" 26 "github.com/stretchr/testify/require" 27 ) 28 29 func Test_bitWriter_writeBit(t *testing.T) { 30 tests := []struct { 31 name string 32 binary string 33 hex uint8 34 }{ 35 { 36 name: "write 1", 37 binary: "00000001", 38 hex: 0x1, 39 }, 40 { 41 name: "write 8", 42 binary: "00001000", 43 hex: 0x8, 44 }, 45 { 46 name: "write 113", 47 binary: "01110001", 48 hex: 0x71, 49 }, 50 { 51 name: "write 255", 52 binary: "11111111", 53 hex: 0xff, 54 }, 55 } 56 for _, tt := range tests { 57 t.Run(tt.name, func(t *testing.T) { 58 buf := new(bytes.Buffer) 59 bw := newBitWriter(buf) 60 for i := 0; i < len(tt.binary); i++ { 61 var err error 62 if tt.binary[i] == '1' { 63 err = bw.writeBit(one) 64 } else { 65 err = bw.writeBit(zero) 66 } 67 require.Nil(t, err) 68 } 69 assert.Equal(t, tt.hex, buf.Bytes()[0]) 70 }) 71 } 72 } 73 74 func Test_bitWriter_writeBits(t *testing.T) { 75 f := fuzz.New().NilChance(0) 76 77 for i := 0; i < 10; i++ { 78 var u64 uint64 79 f.Fuzz(&u64) 80 81 buf := new(bytes.Buffer) 82 bw := newBitWriter(buf) 83 require.Nil(t, bw.writeBits(u64, 64)) 84 85 wantBytes := make([]byte, 8) 86 binary.BigEndian.PutUint64(wantBytes, u64) 87 88 assert.Equal(t, wantBytes, buf.Bytes()) 89 } 90 } 91 92 func Test_bitWriter_writeByte(t *testing.T) { 93 var b byte = 0x1 94 for i := 0; i < 256; i++ { 95 buf := new(bytes.Buffer) 96 require.Nil(t, buf.WriteByte(b)) 97 bw := newBitWriter(buf) 98 require.Nil(t, bw.writeByte(b)) 99 assert.Equal(t, b, buf.Bytes()[0]) 100 b++ 101 } 102 }