memory.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package ezdb
  2. type MemoryCollection[T any] struct {
  3. c Collection[T]
  4. m map[string]T
  5. open bool
  6. }
  7. func (c *MemoryCollection[T]) Close() error {
  8. if c.c != nil {
  9. return c.c.Close()
  10. }
  11. c.m = map[string]T{}
  12. c.open = false
  13. return nil
  14. }
  15. func (c *MemoryCollection[T]) Delete(key string) error {
  16. if !c.open {
  17. return ErrClosed
  18. }
  19. if c.c != nil {
  20. if err := c.c.Delete(key); err != nil {
  21. return err
  22. }
  23. }
  24. delete(c.m, key)
  25. return nil
  26. }
  27. func (c *MemoryCollection[T]) Get(key string) (T, error) {
  28. if !c.open {
  29. return c.m[""], ErrClosed
  30. }
  31. if value, ok := c.m[key]; ok {
  32. return value, nil
  33. }
  34. return c.m[""], ErrNotFound
  35. }
  36. func (c *MemoryCollection[T]) Has(key string) (bool, error) {
  37. if !c.open {
  38. return false, ErrClosed
  39. }
  40. _, ok := c.m[key]
  41. return ok, nil
  42. }
  43. func (c *MemoryCollection[T]) Iter() Iterator[T] {
  44. m := newMemoryIterator[T](c.m, nil)
  45. if !c.open {
  46. m.Release()
  47. }
  48. return m
  49. }
  50. func (c *MemoryCollection[T]) Open() error {
  51. if c.c != nil {
  52. if err := c.c.Open(); err != nil {
  53. return err
  54. }
  55. all, err := c.c.Iter().GetAll()
  56. if err != nil {
  57. return err
  58. }
  59. c.m = all
  60. } else {
  61. c.m = map[string]T{}
  62. }
  63. c.open = true
  64. return nil
  65. }
  66. func (c *MemoryCollection[T]) Put(key string, value T) error {
  67. if !c.open {
  68. return ErrClosed
  69. }
  70. if err := ValidateKey(key); err != nil {
  71. return err
  72. }
  73. if c.c != nil {
  74. if err := c.c.Put(key, value); err != nil {
  75. return err
  76. }
  77. }
  78. c.m[key] = value
  79. return nil
  80. }
  81. // Memory creates an in-memory collection, which offers fast access without a document marshaler.
  82. //
  83. // If the collection c is non-nil, it will be used as a persistence backend.
  84. //
  85. // If T is a pointer type, the same pointer will be used whenever a document is read from this collection, so you should take care to treat documents as immutable.
  86. func Memory[T any](c Collection[T]) *MemoryCollection[T] {
  87. return &MemoryCollection[T]{
  88. c: c,
  89. m: map[string]T{},
  90. }
  91. }