mihomo/component/fakeip/memory.go

81 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-12-02 17:07:36 +08:00
"github.com/metacubex/mihomo/common/lru"
2021-10-11 20:48:58 +08:00
)
type memoryStore struct {
2023-12-02 17:07:36 +08:00
cacheIP *lru.LruCache[string, netip.Addr]
cacheHost *lru.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 {
2024-09-11 16:10:35 +08:00
m.cacheIP.Clear()
m.cacheHost.Clear()
return nil
2022-04-05 20:23:16 +08:00
}
func newMemoryStore(size int) *memoryStore {
return &memoryStore{
2023-12-02 17:07:36 +08:00
cacheIP: lru.New[string, netip.Addr](lru.WithSize[string, netip.Addr](size)),
cacheHost: lru.New[netip.Addr, string](lru.WithSize[netip.Addr, string](size)),
2022-04-05 20:23:16 +08:00
}
2022-03-23 01:05:43 +08:00
}