SetBits Set the bit at the specified offset in the bitmap to the specified value If the key does not exist, it will be created If the bitmap length is not sufficient, it will be extended
(key string, args ...interface{})
| 58 | // If the key does not exist, it will be created |
| 59 | // If the bitmap length is not sufficient, it will be extended |
| 60 | func (b *BitMapStructure) SetBits(key string, args ...interface{}) error { |
| 61 | // Validate arguments |
| 62 | if len(args) == 0 || len(args)%2 != 0 { |
| 63 | return ErrInvalidArgs |
| 64 | } |
| 65 | |
| 66 | // Get bitmap |
| 67 | bitmap, length, err := b.getBitmapFromDB(key, true) |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | |
| 72 | offsets := make([]uint, 0, len(args)/2) |
| 73 | values := make([]bool, 0, len(args)/2) |
| 74 | maxNotFalseOffset := uint(0) |
| 75 | for i := 0; i < len(args); i += 2 { |
| 76 | offsets = append(offsets, uint(args[i].(int))) |
| 77 | values = append(values, args[i+1].(bool)) |
| 78 | if args[i+1].(bool) && uint(args[i].(int)) > maxNotFalseOffset { |
| 79 | maxNotFalseOffset = uint(args[i].(int)) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // If the bitmap length is not sufficient, extend it |
| 84 | if maxNotFalseOffset >= length { |
| 85 | length = maxNotFalseOffset + 1 |
| 86 | newSize := len2Size(length) |
| 87 | newBitmap := make([]byte, newSize) |
| 88 | copy(newBitmap, bitmap) |
| 89 | bitmap = newBitmap |
| 90 | } |
| 91 | |
| 92 | for i := 0; i < len(args)/2; i++ { |
| 93 | offset := offsets[i] |
| 94 | if offset < length { |
| 95 | b.setBit(bitmap, offset, values[i]) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | return b.setBitmapToDB(key, bitmap, length) |
| 100 | } |
| 101 | |
| 102 | // GetBit Get the value of the bit at the specified offset in the bitmap |
| 103 | // If the key does not exist, it returns an error |