github.com/scottcagno/storage@v1.8.0/pkg/bits/rawbits.go (about) 1 package bits 2 3 import ( 4 "fmt" 5 "strconv" 6 "unsafe" 7 ) 8 9 type sliceType = byte 10 11 var ( 12 wordSize uint = uint(unsafe.Sizeof(sliceType(0))) 13 log2WordSize uint = log2(wordSize) 14 ) 15 16 func log2(i uint) uint { 17 var n uint 18 for ; i > 0; n++ { 19 i >>= 1 20 } 21 return n - 1 22 } 23 24 func roundTo(value uint, roundTo uint) uint { 25 return (value + (roundTo - 1)) &^ (roundTo - 1) 26 } 27 28 func checkResize(bs *[]byte, i uint) { 29 if *bs == nil { 30 *bs = make([]byte, 8) 31 return 32 } 33 if i > uint(len(*bs)*8) { 34 newbs := make([]byte, roundTo(i, 8)) 35 copy(newbs, *bs) 36 *bs = newbs 37 } 38 return 39 } 40 41 func RawBytesHasBit(bs *[]byte, i uint) bool { 42 checkResize(bs, i) 43 //_ = (*bs)[i>>3] 44 // 45 // b.bits[i>>lg2ws]&(1<<(i&(ws-1))) != 0 46 return (*bs)[i>>3]&(1<<(i&(7))) != 0 47 } 48 49 func RawBytesSetBit(bs *[]byte, i uint) { 50 checkResize(bs, i) 51 //_ = (*bs)[i>>3] 52 // 53 // b.bits[i>>lg2ws] |= 1 << (i & (ws - 1)) 54 (*bs)[i>>3] |= 1 << (i & (7)) 55 } 56 57 func RawBytesGetBit(bs *[]byte, i uint) uint { 58 checkResize(bs, i) 59 //_ = (*bs)[i>>3] 60 // 61 // b.bits[i>>lg2ws] & (1 << (i & (ws - 1))) 62 return uint((*bs)[i>>3] & (1 << (i & (7)))) 63 } 64 65 func RawBytesUnsetBit(bs *[]byte, i uint) { 66 checkResize(bs, i) 67 //_ = (*bs)[i>>3] 68 // 69 // b.bits[i>>lg2ws] &^= 1 << (i & (ws - 1)) 70 (*bs)[i>>3] &^= 1 << (i & (7)) 71 } 72 73 func RawBytesStringer(bs *[]byte) string { 74 // print binary value of bitset 75 //var res string = "16" // set this to the "bit resolution" you'd like to see 76 var res = strconv.Itoa(len(*bs)) 77 return fmt.Sprintf("%."+res+"b (%s bits)", bs, res) 78 79 }