github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/segment/writer/metrics/compress/bit_reader_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 "testing" 22 23 "github.com/stretchr/testify/assert" 24 "github.com/stretchr/testify/require" 25 ) 26 27 func Test_bitReader_readBit(t *testing.T) { 28 var b byte = 0x1 29 for i := 0; i < 256; i++ { 30 buf := new(bytes.Buffer) 31 require.Nil(t, buf.WriteByte(b)) 32 br := newBitReader(buf) 33 actual, err := br.readBit() 34 require.Nil(t, err) 35 assert.Equal(t, bit((b&0x80) != 0), actual) 36 b++ 37 } 38 } 39 40 func Test_bitReader_readBits(t *testing.T) { 41 tests := []struct { 42 name string 43 nbits int 44 byteToRead byte 45 want uint64 46 wantErr error 47 }{ 48 { 49 name: "read a bit from 00000001", 50 nbits: 1, 51 byteToRead: 0x1, 52 want: 0, 53 wantErr: nil, 54 }, 55 { 56 name: "read 5 bits from 00000001", 57 nbits: 5, 58 byteToRead: 0x1, 59 want: 0, 60 wantErr: nil, 61 }, 62 { 63 name: "read 8 bits from 00000001", 64 nbits: 8, 65 byteToRead: 0x1, 66 want: 0x1, 67 wantErr: nil, 68 }, 69 { 70 name: "read a bit from 11111111", 71 nbits: 1, 72 byteToRead: 0xff, 73 want: 0x1, 74 wantErr: nil, 75 }, 76 { 77 name: "read 5 bits from 11111111", 78 nbits: 5, 79 byteToRead: 0xff, 80 want: 0x1f, 81 wantErr: nil, 82 }, 83 { 84 name: "read 8 bits from 11111111", 85 nbits: 8, 86 byteToRead: 0xff, 87 want: 0xff, 88 wantErr: nil, 89 }, 90 } 91 for _, tt := range tests { 92 t.Run(tt.name, func(t *testing.T) { 93 buf := new(bytes.Buffer) 94 err := buf.WriteByte(tt.byteToRead) 95 require.Nil(t, err) 96 b := newBitReader(buf) 97 got, err := b.readBits(tt.nbits) 98 assert.Equal(t, tt.wantErr, err) 99 assert.Equal(t, tt.want, got) 100 }) 101 } 102 } 103 104 func Test_bitReader_readByte(t *testing.T) { 105 var b byte = 0x1 106 for i := 0; i < 256; i++ { 107 buf := new(bytes.Buffer) 108 require.Nil(t, buf.WriteByte(b)) 109 br := newBitReader(buf) 110 byt, err := br.readByte() 111 require.Nil(t, err) 112 assert.Equal(t, b, byt) 113 b++ 114 } 115 }