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