Improve code elegance in DNS cache removal function

This commit is contained in:
B. Blechschmidt 2023-03-25 22:23:46 +01:00
parent 58faf871c3
commit 33892e28dc

View file

@ -1,7 +1,7 @@
use hashlink::linked_hash_map::RawEntryMut; use hashlink::linked_hash_map::RawEntryMut;
use hashlink::LruCache; use hashlink::LruCache;
use smoltcp::wire::Ipv4Cidr; use smoltcp::wire::Ipv4Cidr;
use std::collections::{HashMap, LinkedList}; use std::collections::HashMap;
use std::convert::{TryFrom, TryInto}; use std::convert::{TryFrom, TryInto};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr; use std::str::FromStr;
@ -188,19 +188,19 @@ impl VirtualDns {
fn allocate_ip(&mut self, name: String) -> Option<IpAddr> { fn allocate_ip(&mut self, name: String) -> Option<IpAddr> {
let now = Instant::now(); let now = Instant::now();
// Building the to_remove list seems to be a bit clunky. loop {
// But removing inside the loop does not immediately work due to borrow rules. let p = self.lru_cache.iter().next();
// TODO: Is there a better solution? if p.is_none() {
let mut to_remove = LinkedList::<IpAddr>::new(); break;
for (ip, entry) in self.lru_cache.iter() { }
let (ip, entry) = p.unwrap();
if now > entry.expiry { if now > entry.expiry {
to_remove.push_back(*ip); let name = entry.name.clone();
self.name_to_ip.remove(&entry.name); self.lru_cache.remove(&ip.clone());
self.name_to_ip.remove(&name);
continue; continue;
} }
} break;
for ip in to_remove {
self.lru_cache.remove(&ip);
} }
if let Some(ip) = self.name_to_ip.get(&name) { if let Some(ip) = self.name_to_ip.get(&name) {