github.com/igoogolx/clash@v1.19.8/component/fakeip/memory.go (about)

     1  package fakeip
     2  
     3  import (
     4  	"net"
     5  
     6  	"github.com/igoogolx/clash/common/cache"
     7  )
     8  
     9  type memoryStore struct {
    10  	cache *cache.LruCache
    11  }
    12  
    13  // GetByHost implements store.GetByHost
    14  func (m *memoryStore) GetByHost(host string) (net.IP, bool) {
    15  	if elm, exist := m.cache.Get(host); exist {
    16  		ip := elm.(net.IP)
    17  
    18  		// ensure ip --> host on head of linked list
    19  		m.cache.Get(ipToUint(ip.To4()))
    20  		return ip, true
    21  	}
    22  
    23  	return nil, false
    24  }
    25  
    26  // PutByHost implements store.PutByHost
    27  func (m *memoryStore) PutByHost(host string, ip net.IP) {
    28  	m.cache.Set(host, ip)
    29  }
    30  
    31  // GetByIP implements store.GetByIP
    32  func (m *memoryStore) GetByIP(ip net.IP) (string, bool) {
    33  	if elm, exist := m.cache.Get(ipToUint(ip.To4())); exist {
    34  		host := elm.(string)
    35  
    36  		// ensure host --> ip on head of linked list
    37  		m.cache.Get(host)
    38  		return host, true
    39  	}
    40  
    41  	return "", false
    42  }
    43  
    44  // PutByIP implements store.PutByIP
    45  func (m *memoryStore) PutByIP(ip net.IP, host string) {
    46  	m.cache.Set(ipToUint(ip.To4()), host)
    47  }
    48  
    49  // DelByIP implements store.DelByIP
    50  func (m *memoryStore) DelByIP(ip net.IP) {
    51  	ipNum := ipToUint(ip.To4())
    52  	if elm, exist := m.cache.Get(ipNum); exist {
    53  		m.cache.Delete(elm.(string))
    54  	}
    55  	m.cache.Delete(ipNum)
    56  }
    57  
    58  // Exist implements store.Exist
    59  func (m *memoryStore) Exist(ip net.IP) bool {
    60  	return m.cache.Exist(ipToUint(ip.To4()))
    61  }
    62  
    63  // CloneTo implements store.CloneTo
    64  // only for memoryStore to memoryStore
    65  func (m *memoryStore) CloneTo(store store) {
    66  	if ms, ok := store.(*memoryStore); ok {
    67  		m.cache.CloneTo(ms.cache)
    68  	}
    69  }