github.com/yaling888/clash@v1.53.0/component/fakeip/memory.go (about) 1 package fakeip 2 3 import ( 4 "net/netip" 5 6 "github.com/yaling888/clash/common/cache" 7 ) 8 9 type memoryStore struct { 10 cacheIP *cache.LruCache[string, netip.Addr] 11 cacheHost *cache.LruCache[netip.Addr, string] 12 } 13 14 // GetByHost implements store.GetByHost 15 func (m *memoryStore) GetByHost(host string) (netip.Addr, bool) { 16 if ip, exist := m.cacheIP.Get(host); exist { 17 // ensure ip --> host on head of linked list 18 m.cacheHost.Get(ip) 19 return ip, true 20 } 21 22 return netip.Addr{}, false 23 } 24 25 // PutByHost implements store.PutByHost 26 func (m *memoryStore) PutByHost(host string, ip netip.Addr) { 27 m.cacheIP.Set(host, ip) 28 } 29 30 // GetByIP implements store.GetByIP 31 func (m *memoryStore) GetByIP(ip netip.Addr) (string, bool) { 32 if host, exist := m.cacheHost.Get(ip); exist { 33 // ensure host --> ip on head of linked list 34 m.cacheIP.Get(host) 35 return host, true 36 } 37 38 return "", false 39 } 40 41 // PutByIP implements store.PutByIP 42 func (m *memoryStore) PutByIP(ip netip.Addr, host string) { 43 m.cacheHost.Set(ip, host) 44 } 45 46 // DelByIP implements store.DelByIP 47 func (m *memoryStore) DelByIP(ip netip.Addr) { 48 if host, exist := m.cacheHost.Get(ip); exist { 49 m.cacheIP.Delete(host) 50 } 51 m.cacheHost.Delete(ip) 52 } 53 54 // Exist implements store.Exist 55 func (m *memoryStore) Exist(ip netip.Addr) bool { 56 return m.cacheHost.Exist(ip) 57 } 58 59 // CloneTo implements store.CloneTo 60 // only for memoryStore to memoryStore 61 func (m *memoryStore) CloneTo(store store) { 62 if ms, ok := store.(*memoryStore); ok { 63 m.cacheIP.CloneTo(ms.cacheIP) 64 m.cacheHost.CloneTo(ms.cacheHost) 65 } 66 } 67 68 // FlushFakeIP implements store.FlushFakeIP 69 func (m *memoryStore) FlushFakeIP() error { 70 _ = m.cacheIP.Clear() 71 return m.cacheHost.Clear() 72 } 73 74 func newMemoryStore(size int) *memoryStore { 75 return &memoryStore{ 76 cacheIP: cache.New[string, netip.Addr](cache.WithSize[string, netip.Addr](size)), 77 cacheHost: cache.New[netip.Addr, string](cache.WithSize[netip.Addr, string](size)), 78 } 79 }