nestedmaps.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package nestedmaps
  2. type next[NK comparable, M ~map[NK]NV, NV any] struct {
  3. last Path[M]
  4. key NK
  5. }
  6. func (me next[NK, CV, NV]) Exists() bool {
  7. _, ok := me.last.Get()[me.key]
  8. return ok
  9. }
  10. func (me next[NK, CV, NV]) Get() NV {
  11. return me.last.Get()[me.key]
  12. }
  13. func (me next[NK, CV, NV]) Set(value NV) {
  14. if me.last.Get() == nil {
  15. me.last.Set(make(CV))
  16. }
  17. me.last.Get()[me.key] = value
  18. }
  19. func (me next[NK, CV, NV]) Delete() {
  20. m := me.last.Get()
  21. delete(m, me.key)
  22. if len(m) == 0 {
  23. me.last.Delete()
  24. }
  25. }
  26. func Next[K comparable, M ~map[K]V, V any](
  27. last Path[M],
  28. key K,
  29. ) Path[V] {
  30. ret := next[K, M, V]{}
  31. ret.last = last
  32. ret.key = key
  33. return ret
  34. }
  35. type root[K comparable, V any, M ~map[K]V] struct {
  36. m *M
  37. }
  38. func (me root[K, V, M]) Exists() bool {
  39. return *me.m != nil
  40. }
  41. func (me root[K, V, M]) Get() M {
  42. return *me.m
  43. }
  44. func (me root[K, V, M]) Set(value M) {
  45. *me.m = value
  46. }
  47. func (me root[K, V, M]) Delete() {
  48. *me.m = nil
  49. }
  50. func Begin[K comparable, M ~map[K]V, V any](m *M) Path[M] {
  51. ret := root[K, V, M]{}
  52. ret.m = m
  53. return ret
  54. }
  55. type Path[V any] interface {
  56. Set(V)
  57. Get() V
  58. Exists() bool
  59. Delete()
  60. }