bitvector.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. package bitvector
  17. import (
  18. "errors"
  19. )
  20. var errInvalidLength = errors.New("invalid length")
  21. type BitVector struct {
  22. len int
  23. b []byte
  24. }
  25. func New(l int) (bv *BitVector, err error) {
  26. return NewFromBytes(make([]byte, l/8+1), l)
  27. }
  28. func NewFromBytes(b []byte, l int) (bv *BitVector, err error) {
  29. if l <= 0 {
  30. return nil, errInvalidLength
  31. }
  32. if len(b)*8 < l {
  33. return nil, errInvalidLength
  34. }
  35. return &BitVector{
  36. len: l,
  37. b: b,
  38. }, nil
  39. }
  40. func (bv *BitVector) Get(i int) bool {
  41. bi := i / 8
  42. return bv.b[bi]&(0x1<<uint(i%8)) != 0
  43. }
  44. func (bv *BitVector) Set(i int, v bool) {
  45. bi := i / 8
  46. cv := bv.Get(i)
  47. if cv != v {
  48. bv.b[bi] ^= 0x1 << uint8(i%8)
  49. }
  50. }
  51. func (bv *BitVector) Bytes() []byte {
  52. return bv.b
  53. }
  54. func (bv *BitVector) Length() int {
  55. return bv.len
  56. }