rustdata-structureshashmaptreemap

How to check for expired items in a Rust BTreeMap?


I am working on a Rust project where I store a BeaconInfoEventContent struct in a BTreeMap. Here is my current implementation:

pub struct BeaconInfoEventContent {
    pub live: bool,
    pub ts: MilliSecondsSinceUnixEpoch,
    pub timeout: Duration,
}

impl BeaconInfoEventContent {
    pub fn new(
        timeout: Duration,
        live: bool,
        ts: Option<MilliSecondsSinceUnixEpoch>,
    ) -> Self {
        Self {
            live,
            ts: ts.unwrap_or_else(MilliSecondsSinceUnixEpoch::now),
            timeout,
        }
    }

    pub fn is_live(&self) -> bool {
        self.live
            && self
                .ts
                .to_system_time()
                .and_then(|t| t.checked_add(self.timeout))
                .is_some_and(|t| t > SystemTime::now())
    }
}


ExampleStruct {
   ...
   pub(crate) beacons: BTreeMap<OwnedUserId, BeaconInfoEventContent>,
   ....
}

I need to automatically update the BeaconInfoEventContent's live field when the duration expires. Is there a proper approach to this besides constant polling at a specific interval?


Solution

  • You could simply check the state of the item when accessing it, if you aren't worried about keeping the state of all items up-to-date until they are individually-accessed. There's some cost to checking on every access as well but probably not worth considering for now unless you're dealing with serious performance requirements

    It may become awkward if you're making immutable reads from the collection, for obvious reasons. You don't really want to break your API/contract by turning simple non-modifying reads into a mutable operation.

    Another option would be to implement some async/background process which examines the elements on a periodic basis and updates their state if they have expired. There is some initial setup to make it thread-safe (check out concurrency primitives like Arc/Mutex, you'll want a crate like Tokio), you may find this simplifies the overall design.