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.

74 lines
1.3 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) Close() {
  37. mBatch.ops = nil
  38. }
  39. func (mBatch *memBatch) write(doSync bool) {
  40. if mtx := mBatch.db.Mutex(); mtx != nil {
  41. mtx.Lock()
  42. defer mtx.Unlock()
  43. }
  44. for i, op := range mBatch.ops {
  45. if doSync && i == (len(mBatch.ops)-1) {
  46. switch op.opType {
  47. case opTypeSet:
  48. mBatch.db.SetNoLockSync(op.key, op.value)
  49. case opTypeDelete:
  50. mBatch.db.DeleteNoLockSync(op.key)
  51. }
  52. break // we're done.
  53. }
  54. switch op.opType {
  55. case opTypeSet:
  56. mBatch.db.SetNoLock(op.key, op.value)
  57. case opTypeDelete:
  58. mBatch.db.DeleteNoLock(op.key)
  59. }
  60. }
  61. }