github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/x/linkedhashmap/map.go (about) 1 package linkedhashmap 2 3 import ( 4 "github.com/sagernet/sing/common" 5 "github.com/sagernet/sing/common/x/collections" 6 "github.com/sagernet/sing/common/x/list" 7 ) 8 9 var _ collections.Map[string, any] = (*Map[string, any])(nil) 10 11 type Map[K comparable, V any] struct { 12 raw list.List[collections.MapEntry[K, V]] 13 rawMap map[K]*list.Element[collections.MapEntry[K, V]] 14 } 15 16 func (m *Map[K, V]) init() { 17 if m.rawMap == nil { 18 m.rawMap = make(map[K]*list.Element[collections.MapEntry[K, V]]) 19 } 20 } 21 22 func (m *Map[K, V]) Size() int { 23 return m.raw.Size() 24 } 25 26 func (m *Map[K, V]) IsEmpty() bool { 27 return m.raw.IsEmpty() 28 } 29 30 func (m *Map[K, V]) ContainsKey(key K) bool { 31 m.init() 32 _, loaded := m.rawMap[key] 33 return loaded 34 } 35 36 func (m *Map[K, V]) Get(key K) (V, bool) { 37 m.init() 38 value, loaded := m.rawMap[key] 39 if loaded { 40 return value.Value.Value, true 41 } else { 42 return common.DefaultValue[V](), false 43 } 44 } 45 46 func (m *Map[K, V]) Put(key K, value V) V { 47 m.init() 48 entry, loaded := m.rawMap[key] 49 if loaded { 50 oldValue := entry.Value.Value 51 entry.Value.Value = value 52 return oldValue 53 } 54 entry = m.raw.PushBack(collections.MapEntry[K, V]{Key: key, Value: value}) 55 m.rawMap[key] = entry 56 return common.DefaultValue[V]() 57 } 58 59 func (m *Map[K, V]) Remove(key K) bool { 60 m.init() 61 entry, loaded := m.rawMap[key] 62 if !loaded { 63 return false 64 } 65 m.raw.Remove(entry) 66 delete(m.rawMap, key) 67 return true 68 } 69 70 func (m *Map[K, V]) PutAll(other collections.Map[K, V]) { 71 m.init() 72 for _, item := range other.Entries() { 73 entry, loaded := m.rawMap[item.Key] 74 if loaded { 75 entry.Value.Value = item.Value 76 continue 77 } 78 entry = m.raw.PushBack(item) 79 m.rawMap[item.Key] = entry 80 } 81 } 82 83 func (m *Map[K, V]) Clear() { 84 *m = Map[K, V]{} 85 } 86 87 func (m *Map[K, V]) Keys() []K { 88 result := make([]K, 0, m.raw.Len()) 89 for item := m.raw.Front(); item != nil; item = item.Next() { 90 result = append(result, item.Value.Key) 91 } 92 return result 93 } 94 95 func (m *Map[K, V]) Values() []V { 96 result := make([]V, 0, m.raw.Len()) 97 for item := m.raw.Front(); item != nil; item = item.Next() { 98 result = append(result, item.Value.Value) 99 } 100 return result 101 } 102 103 func (m *Map[K, V]) Entries() []collections.MapEntry[K, V] { 104 result := make([]collections.MapEntry[K, V], 0, m.raw.Len()) 105 for item := m.raw.Front(); item != nil; item = item.Next() { 106 result = append(result, item.Value) 107 } 108 return result 109 }