github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/batch.go (about) 1 // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package bitalosdb 16 17 import ( 18 "sync" 19 20 "github.com/zuoyebang/bitalosdb/internal/consts" 21 ) 22 23 type Batch struct { 24 db *DB 25 bitowers [consts.DefaultBitowerNum]*BatchBitower 26 } 27 28 var batchPool = sync.Pool{ 29 New: func() interface{} { 30 return &Batch{} 31 }, 32 } 33 34 func newBatch(db *DB) *Batch { 35 b := batchPool.Get().(*Batch) 36 b.db = db 37 for i := range b.bitowers { 38 b.bitowers[i] = nil 39 b.bitowers[i] = newBatchBitowerByIndex(db, i) 40 } 41 return b 42 } 43 44 func (b *Batch) getBatchBitower(key []byte) *BatchBitower { 45 index := b.db.getBitowerIndexByKey(key) 46 if b.bitowers[index] == nil { 47 b.bitowers[index] = newBatchBitowerByIndex(b.db, index) 48 } 49 return b.bitowers[index] 50 } 51 52 func (b *Batch) Set(key, value []byte, opts *WriteOptions) error { 53 return b.getBatchBitower(key).Set(key, value, opts) 54 } 55 56 func (b *Batch) SetMultiValue(key []byte, values ...[]byte) error { 57 return b.getBatchBitower(key).SetMultiValue(key, values...) 58 } 59 60 func (b *Batch) PrefixDeleteKeySet(key []byte, opts *WriteOptions) error { 61 return b.getBatchBitower(key).PrefixDeleteKeySet(key, opts) 62 } 63 64 func (b *Batch) Delete(key []byte, opts *WriteOptions) error { 65 return b.getBatchBitower(key).Delete(key, opts) 66 } 67 68 func (b *Batch) Commit(o *WriteOptions) error { 69 return b.db.Apply(b, o) 70 } 71 72 func (b *Batch) Close() error { 73 for i := range b.bitowers { 74 if b.bitowers[i] != nil { 75 b.bitowers[i].Close() 76 b.bitowers[i] = nil 77 } 78 } 79 b.db = nil 80 return nil 81 } 82 83 func (b *Batch) Reset() { 84 for i := range b.bitowers { 85 if b.bitowers[i] != nil { 86 b.bitowers[i].Reset() 87 } 88 } 89 } 90 91 func (b *Batch) Empty() bool { 92 for i := range b.bitowers { 93 if b.bitowers[i] != nil && !b.bitowers[i].Empty() { 94 return false 95 } 96 } 97 return true 98 } 99 100 func (b *Batch) Count() uint32 { 101 var count uint32 102 for i := range b.bitowers { 103 if b.bitowers[i] != nil { 104 count += b.bitowers[i].Count() 105 } 106 } 107 return count 108 }