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