btree.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2021 Andrew Werner.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. // implied. See the License for the specific language governing
  13. // permissions and limitations under the License.
  14. package btree
  15. import "github.com/ajwerner/btree/internal/abstract"
  16. // Map is a ordered map from K to V.
  17. type Map[K, V any] struct {
  18. abstract.Map[K, V, struct{}]
  19. }
  20. // MakeMap constructs a new Map with the provided comparison function.
  21. func MakeMap[K, V any](cmp func(K, K) int) Map[K, V] {
  22. return Map[K, V]{
  23. Map: abstract.MakeMap[K, V, struct{}](cmp, nil),
  24. }
  25. }
  26. // Clone clones the Map, lazily. It does so in constant time.
  27. func (m *Map[K, V]) Clone() Map[K, V] {
  28. return Map[K, V]{Map: m.Map.Clone()}
  29. }
  30. // Set is an ordered set of items of type T.
  31. type Set[T any] Map[T, struct{}]
  32. // MakeSet constructs a new Set with the provided comparison function.
  33. func MakeSet[T any](cmp func(T, T) int) Set[T] {
  34. return (Set[T])(MakeMap[T, struct{}](cmp))
  35. }
  36. // Clone clones the Set, lazily. It does so in constant time.
  37. func (t *Set[T]) Clone() Set[T] {
  38. return (Set[T])((*Map[T, struct{}])(t).Clone())
  39. }
  40. // Upsert inserts or updates the provided item. It returns
  41. // the overwritten item if a previous value existed for the key.
  42. func (t *Set[T]) Upsert(item T) (replaced T, overwrote bool) {
  43. replaced, _, overwrote = t.Map.Upsert(item, struct{}{})
  44. return replaced, overwrote
  45. }
  46. // Delete removes the value with the provided key. It returns true if the
  47. // item existed in the set.
  48. func (t *Set[K]) Delete(item K) (removed bool) {
  49. _, _, removed = t.Map.Delete(item)
  50. return removed
  51. }