github.com/tunabay/go-bitarray@v1.3.1/bitarray_internal_test.go (about) 1 // Copyright (c) 2021 Hirotsuna Mizuno. All rights reserved. 2 // Use of this source code is governed by the MIT license that can be found in 3 // the LICENSE file. 4 5 package bitarray 6 7 import ( 8 "fmt" 9 ) 10 11 // D returns the string representing of its internal state. 12 func (ba *BitArray) D() string { 13 if ba == nil { 14 return "<nil>" 15 } 16 if ba.b == nil { 17 return fmt.Sprintf("BA{nbit=%d, b=<nil>}", ba.nBits) 18 } 19 return fmt.Sprintf("BA{nbit=%d, b=%08b}", ba.nBits, ba.b) 20 } 21 22 // V validate the internal data representation. It panics on failure. 23 func (ba *BitArray) V() { 24 switch { 25 case ba == nil: 26 return 27 28 case ba.nBits < 0: 29 panicf("V: negative nBits %d.", ba.nBits) 30 31 case ba.b != nil && len(ba.b) == 0: 32 panicf("V: ba.b is an empty slice, must be nil: %08b", ba.b) 33 34 case ba.b == nil: 35 return 36 37 case len(ba.b) != (ba.nBits+7)>>3: 38 panicf("V: wrong len: len=%d, nBits=%d: %08b", len(ba.b), ba.nBits, ba.b) 39 40 case cap(ba.b)&7 != 0: 41 panicf("V: wrong cap: cap=%d, len=%d, nBits=%d.", cap(ba.b), len(ba.b), ba.nBits) 42 } 43 if fb := ba.nBits & 7; fb != 0 { 44 mask := byte(0xff) >> fb 45 if lb := ba.b[len(ba.b)-1] & mask; lb != 0 { 46 panicf("V: non-zero padding bits: nfrac=%d, lastbyte=%08b.", fb, lb) 47 } 48 } 49 } 50 51 // ZExpand expands the zero-filled BitArray with nil pointer to a normal 52 // data representation. 53 func (ba *BitArray) ZExpand() *BitArray { 54 if ba.IsZero() || ba.b != nil { 55 return ba 56 } 57 return &BitArray{ 58 b: allocByteSlice((ba.nBits + 7) >> 3), 59 nBits: ba.nBits, 60 } 61 } 62 63 // ZOptimize converts to optimized data representation if all bits are 0. 64 func (ba *BitArray) ZOptimize() *BitArray { 65 if ba.IsZero() || ba.b == nil || !allBytesZero(ba.b) { 66 return ba 67 } 68 return &BitArray{nBits: ba.nBits} 69 }