memory.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 := MemoryIter[T](c.m, nil, 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. iter := c.c.Iter()
  56. defer iter.Release()
  57. all, err := iter.GetAll()
  58. if err != nil {
  59. return err
  60. }
  61. c.m = all
  62. } else {
  63. c.m = map[string]T{}
  64. }
  65. c.open = true
  66. return nil
  67. }
  68. func (c *MemoryCollection[T]) Put(key string, value T) error {
  69. if !c.open {
  70. return ErrClosed
  71. }
  72. if err := ValidateKey(key); err != nil {
  73. return err
  74. }
  75. if c.c != nil {
  76. if err := c.c.Put(key, value); err != nil {
  77. return err
  78. }
  79. }
  80. c.m[key] = value
  81. return nil
  82. }
  83. // Memory creates an in-memory collection, which offers fast access without a document marshaler.
  84. //
  85. // If the collection c is non-nil, it will be used as a persistence backend.
  86. //
  87. // 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.
  88. func Memory[T any](c Collection[T]) *MemoryCollection[T] {
  89. return &MemoryCollection[T]{
  90. c: c,
  91. m: map[string]T{},
  92. }
  93. }