map.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package critbitgo
  2. import (
  3. "unsafe"
  4. )
  5. // The map is sorted according to the natural ordering of its keys
  6. type SortedMap struct {
  7. trie *Trie
  8. }
  9. func (m *SortedMap) Contains(key string) bool {
  10. return m.trie.Contains(*(*[]byte)(unsafe.Pointer(&key)))
  11. }
  12. func (m *SortedMap) Get(key string) (value interface{}, ok bool) {
  13. return m.trie.Get(*(*[]byte)(unsafe.Pointer(&key)))
  14. }
  15. func (m *SortedMap) Set(key string, value interface{}) {
  16. m.trie.Set([]byte(key), value)
  17. }
  18. func (m *SortedMap) Delete(key string) (value interface{}, ok bool) {
  19. return m.trie.Delete(*(*[]byte)(unsafe.Pointer(&key)))
  20. }
  21. func (m *SortedMap) Clear() {
  22. m.trie.Clear()
  23. }
  24. func (m *SortedMap) Size() int {
  25. return m.trie.Size()
  26. }
  27. // Returns a slice of sorted keys
  28. func (m *SortedMap) Keys() []string {
  29. keys := make([]string, 0, m.Size())
  30. m.trie.Allprefixed([]byte{}, func(k []byte, v interface{}) bool {
  31. keys = append(keys, string(k))
  32. return true
  33. })
  34. return keys
  35. }
  36. // Executes a provided function for each element that has a given prefix.
  37. // if handle returns `false`, the iteration is aborted.
  38. func (m *SortedMap) Each(prefix string, handle func(key string, value interface{}) bool) bool {
  39. return m.trie.Allprefixed([]byte(prefix), func(k []byte, v interface{}) bool {
  40. return handle(string(k), v)
  41. })
  42. }
  43. // Create a SortedMap
  44. func NewSortedMap() *SortedMap {
  45. return &SortedMap{NewTrie()}
  46. }