mihomo/component/fakeip/memory.go

80 lines
1.9 KiB
Go
Raw Normal View History

2021-10-11 20:48:58 +08:00
package fakeip
import (
"net/netip"
2021-10-11 20:48:58 +08:00
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/common/cache"
2021-10-11 20:48:58 +08:00
)
type memoryStore struct {
cacheIP *cache.LruCache[string, netip.Addr]
cacheHost *cache.LruCache[netip.Addr, string]
2021-10-11 20:48:58 +08:00
}
// GetByHost implements store.GetByHost
func (m *memoryStore) GetByHost(host string) (netip.Addr, bool) {
2022-04-05 20:23:16 +08:00
if ip, exist := m.cacheIP.Get(host); exist {
2021-10-11 20:48:58 +08:00
// ensure ip --> host on head of linked list
m.cacheHost.Get(ip)
2021-10-11 20:48:58 +08:00
return ip, true
}
return netip.Addr{}, false
2021-10-11 20:48:58 +08:00
}
// PutByHost implements store.PutByHost
func (m *memoryStore) PutByHost(host string, ip netip.Addr) {
2022-04-05 20:23:16 +08:00
m.cacheIP.Set(host, ip)
2021-10-11 20:48:58 +08:00
}
// GetByIP implements store.GetByIP
func (m *memoryStore) GetByIP(ip netip.Addr) (string, bool) {
if host, exist := m.cacheHost.Get(ip); exist {
2021-10-11 20:48:58 +08:00
// ensure host --> ip on head of linked list
2022-04-05 20:23:16 +08:00
m.cacheIP.Get(host)
2021-10-11 20:48:58 +08:00
return host, true
}
return "", false
}
// PutByIP implements store.PutByIP
func (m *memoryStore) PutByIP(ip netip.Addr, host string) {
m.cacheHost.Set(ip, host)
2021-10-11 20:48:58 +08:00
}
2021-11-23 22:01:49 +08:00
// DelByIP implements store.DelByIP
func (m *memoryStore) DelByIP(ip netip.Addr) {
if host, exist := m.cacheHost.Get(ip); exist {
2022-04-05 20:23:16 +08:00
m.cacheIP.Delete(host)
2021-11-23 22:01:49 +08:00
}
m.cacheHost.Delete(ip)
2021-11-23 22:01:49 +08:00
}
2021-10-11 20:48:58 +08:00
// Exist implements store.Exist
func (m *memoryStore) Exist(ip netip.Addr) bool {
return m.cacheHost.Exist(ip)
2021-10-11 20:48:58 +08:00
}
// CloneTo implements store.CloneTo
// only for memoryStore to memoryStore
func (m *memoryStore) CloneTo(store store) {
if ms, ok := store.(*memoryStore); ok {
2022-04-05 20:23:16 +08:00
m.cacheIP.CloneTo(ms.cacheIP)
m.cacheHost.CloneTo(ms.cacheHost)
2021-10-11 20:48:58 +08:00
}
}
2022-03-23 01:05:43 +08:00
// FlushFakeIP implements store.FlushFakeIP
func (m *memoryStore) FlushFakeIP() error {
2022-04-05 20:23:16 +08:00
_ = m.cacheIP.Clear()
return m.cacheHost.Clear()
}
func newMemoryStore(size int) *memoryStore {
return &memoryStore{
cacheIP: cache.New[string, netip.Addr](cache.WithSize[string, netip.Addr](size)),
cacheHost: cache.New[netip.Addr, string](cache.WithSize[netip.Addr, string](size)),
2022-04-05 20:23:16 +08:00
}
2022-03-23 01:05:43 +08:00
}