github.com/ethersphere/bee/v2@v2.2.0/pkg/bitvector/bitvector.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package bitvector provides functionality of a 18 // simple bit vector implementation. 19 package bitvector 20 21 import ( 22 "errors" 23 ) 24 25 var errInvalidLength = errors.New("invalid length") 26 27 // BitVector is a convenience object for manipulating and representing bit vectors 28 type BitVector struct { 29 len int 30 b []byte 31 } 32 33 // New creates a new bit vector with the given length 34 func New(l int) (*BitVector, error) { 35 return NewFromBytes(make([]byte, l/8+1), l) 36 } 37 38 // NewFromBytes creates a bit vector from the passed byte slice. 39 // 40 // Leftmost bit in byte slice becomes leftmost bit in bit vector 41 func NewFromBytes(b []byte, l int) (*BitVector, error) { 42 if l <= 0 { 43 return nil, errInvalidLength 44 } 45 if len(b)*8 < l { 46 return nil, errInvalidLength 47 } 48 return &BitVector{ 49 len: l, 50 b: b, 51 }, nil 52 } 53 54 // Get gets the corresponding bit, counted from left to right 55 func (bv *BitVector) Get(i int) bool { 56 bi := i / 8 57 return bv.b[bi]&(0x1<<uint(i%8)) != 0 58 } 59 60 // Set sets the bit corresponding to the index in the bitvector, counted from left to right 61 func (bv *BitVector) Set(i int) { 62 bi := i / 8 63 if !bv.Get(i) { 64 bv.b[bi] ^= 0x1 << uint8(i%8) 65 } 66 } 67 68 // Bytes retrieves the underlying bytes of the bitvector 69 func (bv *BitVector) Bytes() []byte { 70 return bv.b 71 }