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.

70 lines
1.2 KiB

  1. package db
  2. import "sync"
  3. type atomicSetDeleter interface {
  4. Mutex() *sync.Mutex
  5. SetNoLock(key, value []byte)
  6. SetNoLockSync(key, value []byte)
  7. DeleteNoLock(key []byte)
  8. DeleteNoLockSync(key []byte)
  9. }
  10. type memBatch struct {
  11. db atomicSetDeleter
  12. ops []operation
  13. }
  14. type opType int
  15. const (
  16. opTypeSet opType = 1
  17. opTypeDelete opType = 2
  18. )
  19. type operation struct {
  20. opType
  21. key []byte
  22. value []byte
  23. }
  24. func (mBatch *memBatch) Set(key, value []byte) {
  25. mBatch.ops = append(mBatch.ops, operation{opTypeSet, key, value})
  26. }
  27. func (mBatch *memBatch) Delete(key []byte) {
  28. mBatch.ops = append(mBatch.ops, operation{opTypeDelete, key, nil})
  29. }
  30. func (mBatch *memBatch) Write() {
  31. mBatch.write(false)
  32. }
  33. func (mBatch *memBatch) WriteSync() {
  34. mBatch.write(true)
  35. }
  36. func (mBatch *memBatch) write(doSync bool) {
  37. mtx := mBatch.db.Mutex()
  38. mtx.Lock()
  39. defer mtx.Unlock()
  40. for i, op := range mBatch.ops {
  41. if doSync && i == (len(mBatch.ops)-1) {
  42. switch op.opType {
  43. case opTypeSet:
  44. mBatch.db.SetNoLockSync(op.key, op.value)
  45. case opTypeDelete:
  46. mBatch.db.DeleteNoLockSync(op.key)
  47. }
  48. break // we're done.
  49. }
  50. switch op.opType {
  51. case opTypeSet:
  52. mBatch.db.SetNoLock(op.key, op.value)
  53. case opTypeDelete:
  54. mBatch.db.DeleteNoLock(op.key)
  55. }
  56. }
  57. }