1 // Package bitmask implements a simple bitmask type 2 package bitmask // import "vimagination.zapto.org/bitmask" 3 4 // BitMask is the main type. It is completely safe to cast from an existing byte 5 // slice or to create a BitMask with make. 6 type BitMask []byte 7 8 // New creates a new BitMask with enough storage to hold at least the required 9 // number of bits. 10 func New(bits int) BitMask { 11 numCells := bits >> 3 12 if bits&7 != 0 { 13 numCells++ 14 } 15 return make(BitMask, numCells) 16 } 17 18 // Get will retrieve the bool stored at given bit position. 19 func (b BitMask) Get(bit int) bool { 20 pos := bit >> 3 21 if pos > len(b) { 22 return false 23 } 24 return b[pos]&byte(1<<byte(bit&7)) != 0 25 } 26 27 // Set will set the given bool at the given position. 28 func (b BitMask) Set(bit int, d bool) { 29 pos := bit >> 3 30 if pos > len(b) { 31 return 32 } 33 shift := byte(1 << byte(bit&7)) 34 if d { 35 b[pos] |= shift 36 } else { 37 b[pos] &^= shift 38 } 39 } 40 41 // SetIfNot will set the given bool at the given position and return true if 42 // the value has changed. 43 func (b BitMask) SetIfNot(bit int, d bool) bool { 44 pos := bit >> 3 45 if pos > len(b) { 46 return false 47 } 48 if (b[pos]&byte(1<<byte(bit&7)) != 0) == d { 49 return false 50 } 51 shift := byte(1 << byte(bit&7)) 52 if d { 53 b[pos] |= shift 54 } else { 55 b[pos] &^= shift 56 } 57 return true 58 }