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"
"github.com/Dreamacro/clash/common/cache"
)
type memoryStore struct {
2022-04-05 20:23:16 +08:00
cacheIP *cache.LruCache[string, net.IP]
cacheHost *cache.LruCache[uint32, string]
2021-10-11 20:48:58 +08:00
}
// GetByHost implements store.GetByHost
func (m *memoryStore) GetByHost(host string) (net.IP, 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
2022-04-05 20:23:16 +08:00
m.cacheHost.Get(ipToUint(ip.To4()))
2021-10-11 20:48:58 +08:00
return ip, true
}
return nil, false
}
// PutByHost implements store.PutByHost
func (m *memoryStore) PutByHost(host string, ip net.IP) {
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 net.IP) (string, bool) {
2022-04-05 20:23:16 +08:00
if host, exist := m.cacheHost.Get(ipToUint(ip.To4())); 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 net.IP, host string) {
2022-04-05 20:23:16 +08:00
m.cacheHost.Set(ipToUint(ip.To4()), 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 net.IP) {
ipNum := ipToUint(ip.To4())
2022-04-05 20:23:16 +08:00
if host, exist := m.cacheHost.Get(ipNum); exist {
m.cacheIP.Delete(host)
2021-11-23 22:01:49 +08:00
}
2022-04-05 20:23:16 +08:00
m.cacheHost.Delete(ipNum)
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 net.IP) bool {
2022-04-05 20:23:16 +08:00
return m.cacheHost.Exist(ipToUint(ip.To4()))
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.NewLRUCache[string, net.IP](cache.WithSize[string, net.IP](size)),
cacheHost: cache.NewLRUCache[uint32, string](cache.WithSize[uint32, string](size)),
}
2022-03-23 01:05:43 +08:00
}