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.

76 lines
1.3 KiB

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