perf(structure-value): perf set bit

This commit is contained in:
bandl 2021-11-04 16:31:55 +08:00
parent b6dedfa384
commit 0f1142d434
1 changed files with 15 additions and 13 deletions

View File

@ -147,26 +147,28 @@ func (v *Value) ChangeValueLength(f func()) UpdateLength {
func (v *Value) SetByte(offset int, val bool) { func (v *Value) SetByte(offset int, val bool) {
v.onType = DynamicNull // 位图使用无类型 v.onType = DynamicNull // 位图使用无类型
b := byte(0)
if val {
b = byte(1)
}
if v.length >= offset { // 扩容
v.val[offset] = b if len(v.val) <= offset/8 {
newByte := make([]byte, (offset/8)+1)
copy(newByte, v.val[:len(v.val)])
v.val = newByte
v.length = len(v.val)
}
if val {
// true 位
v.val[offset/8] |= (0b1 << (offset % 8))
return return
} }
newByte := make([]byte, offset+1) // false 位
newByte[offset] = b v.val[offset/8] ^= (0b1 << (offset % 8))
copy(newByte, v.val[:v.length])
v.val = newByte
v.length = len(newByte)
} }
func (v *Value) GetByte(offset int) (bool, error) { func (v *Value) GetByte(offset int) (bool, error) {
if v.length >= offset { if len(v.val) >= offset/8 {
return v.val[offset] == byte(1), nil // 采用 & 来运算 是否为 true
return v.val[offset/8]&(0b1<<(offset%8)) != 0, nil
} }
return false, errorx.New("the maximum length is exceeded") return false, errorx.New("the maximum length is exceeded")