You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
852 B

  1. package db
  2. import "sync"
  3. type atomicSetDeleter interface {
  4. Mutex() *sync.Mutex
  5. SetNoLock(key, value []byte)
  6. DeleteNoLock(key []byte)
  7. }
  8. type memBatch struct {
  9. db atomicSetDeleter
  10. ops []operation
  11. }
  12. type opType int
  13. const (
  14. opTypeSet opType = 1
  15. opTypeDelete opType = 2
  16. )
  17. type operation struct {
  18. opType
  19. key []byte
  20. value []byte
  21. }
  22. func (mBatch *memBatch) Set(key, value []byte) {
  23. mBatch.ops = append(mBatch.ops, operation{opTypeSet, key, value})
  24. }
  25. func (mBatch *memBatch) Delete(key []byte) {
  26. mBatch.ops = append(mBatch.ops, operation{opTypeDelete, key, nil})
  27. }
  28. func (mBatch *memBatch) Write() {
  29. mtx := mBatch.db.Mutex()
  30. mtx.Lock()
  31. defer mtx.Unlock()
  32. for _, op := range mBatch.ops {
  33. switch op.opType {
  34. case opTypeSet:
  35. mBatch.db.SetNoLock(op.key, op.value)
  36. case opTypeDelete:
  37. mBatch.db.DeleteNoLock(op.key)
  38. }
  39. }
  40. }