SetBits function sets multiple bits at the specified offsets in the bitmap for the provided key
(k string, off ...uint)
| 88 | |
| 89 | // SetBits function sets multiple bits at the specified offsets in the bitmap for the provided key |
| 90 | func (b *BitmapStructure) SetBits(k string, off ...uint) error { |
| 91 | // Convert the key to bytes |
| 92 | key := stringToBytesWithKey(k) |
| 93 | // Create a new bitset |
| 94 | bit := bitset.New(1) |
| 95 | // Get the current bits for the key |
| 96 | value, err := b.getBits(key) |
| 97 | if err != nil && !errors.Is(err, _const.ErrKeyNotFound) { |
| 98 | return err |
| 99 | } |
| 100 | // If the key is not found, initialize it with the new bitset |
| 101 | if err == _const.ErrKeyNotFound { |
| 102 | buf, _ := bitsetToByteArray(bit) |
| 103 | err = b.db.Put(key, buf) |
| 104 | if err != nil { |
| 105 | return err |
| 106 | } |
| 107 | value, err = b.getBits(key) |
| 108 | if err != nil { |
| 109 | return err |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | // Unmarshal the current bits into the bitset |
| 114 | err = bit.UnmarshalBinary(value) |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | // Set the bits at the specified offsets |
| 119 | for _, u := range off { |
| 120 | bit.Set(u) |
| 121 | } |
| 122 | // Convert the bitset to a byte array |
| 123 | buf, err := bitsetToByteArray(bit) |
| 124 | if err != nil { |
| 125 | return err |
| 126 | } |
| 127 | // Store the updated bitset in the database |
| 128 | return b.db.Put(key, buf) |
| 129 | } |
| 130 | |
| 131 | // GetBits function retrieves the bits for the provided key |
| 132 | func (b *BitmapStructure) GetBits(k string) (*BitSet, error) { |