Skip to main content

rustflexstack/geonet/
packet_buffer.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! GeoNetworking packet buffers (ETSI TS 103 836-4-1 V2.2.1 (2026-04),
5//! clauses 8.5 and 8.6).
6//!
7//! [`PacketBuffer`] implements the maintenance rules shared by the Location
8//! Service packet buffer (clause 8.5.3) and the UC/BC forwarding packet
9//! buffers (clause 8.6.3):
10//!
11//! 1. packets are queued at the tail;
12//! 2. on overflow, packets are removed from the head (head drop);
13//! 3. a flush returns the stored packets in FIFO order;
14//! 4. packets whose queuing time exceeds their lifetime are discarded;
15//! 5. a flushed packet carries its lifetime reduced by the queuing time.
16//!
17//! [`CbfPacketBuffer`] is the CBF packet buffer (clause 8.6.3), in which every
18//! packet is associated with a timer, as set by the CBF algorithms of clauses
19//! E.3 and F.3.
20//!
21//! Both buffers are clock-agnostic: all operations take the current time in
22//! milliseconds.
23//!
24//! Mirrors `flexstack/geonet/packet_buffer.py`.
25
26use std::collections::VecDeque;
27
28struct Entry<T> {
29    item: T,
30    size: usize,
31    lifetime_ms: u64,
32    enqueued_ms: u64,
33    deadline_ms: u64,
34}
35
36impl<T> Entry<T> {
37    /// Lifetime left after the queuing time (0 when expired).
38    fn remaining_lifetime_ms(&self, now_ms: u64) -> u64 {
39        (self.enqueued_ms + self.lifetime_ms).saturating_sub(now_ms)
40    }
41}
42
43/// FIFO packet buffer with head drop and lifetime expiry (clauses 8.5.3, 8.6.3).
44pub struct PacketBuffer<T> {
45    capacity: usize,
46    entries: VecDeque<Entry<T>>,
47    size: usize,
48}
49
50impl<T> PacketBuffer<T> {
51    /// Buffer of `capacity` octets.
52    pub fn new(capacity: usize) -> Self {
53        PacketBuffer {
54            capacity,
55            entries: VecDeque::new(),
56            size: 0,
57        }
58    }
59
60    pub fn len(&self) -> usize {
61        self.entries.len()
62    }
63
64    pub fn is_empty(&self) -> bool {
65        self.entries.is_empty()
66    }
67
68    /// Octets currently stored.
69    pub fn size(&self) -> usize {
70        self.size
71    }
72
73    /// Queue a packet at the tail; remove packets from the head while the
74    /// capacity is exceeded. Returns the number of packets dropped (a packet
75    /// larger than the whole buffer drops itself).
76    pub fn push(&mut self, item: T, size: usize, lifetime_ms: u64, now_ms: u64) -> usize {
77        self.entries.push_back(Entry {
78            item,
79            size,
80            lifetime_ms,
81            enqueued_ms: now_ms,
82            deadline_ms: 0,
83        });
84        self.size += size;
85        let mut dropped = 0;
86        while self.size > self.capacity {
87            match self.entries.pop_front() {
88                Some(e) => {
89                    self.size -= e.size;
90                    dropped += 1;
91                }
92                None => break,
93            }
94        }
95        dropped
96    }
97
98    /// Discard the packets whose queuing time reached their lifetime.
99    pub fn purge(&mut self, now_ms: u64) -> usize {
100        let before = self.entries.len();
101        let mut size = 0;
102        self.entries.retain(|e| {
103            let keep = e.remaining_lifetime_ms(now_ms) > 0;
104            if keep {
105                size += e.size;
106            }
107            keep
108        });
109        self.size = size;
110        before - self.entries.len()
111    }
112
113    /// Empty the buffer, returning `(packet, remaining lifetime in ms)` in
114    /// FIFO order; expired packets are discarded.
115    pub fn flush(&mut self, now_ms: u64) -> Vec<(T, u64)> {
116        self.size = 0;
117        self.entries
118            .drain(..)
119            .filter_map(|e| {
120                let remaining = e.remaining_lifetime_ms(now_ms);
121                (remaining > 0).then_some((e.item, remaining))
122            })
123            .collect()
124    }
125
126    /// Discard every stored packet.
127    pub fn clear(&mut self) {
128        self.entries.clear();
129        self.size = 0;
130    }
131}
132
133/// CBF packet buffer (clause 8.6.3): packets keyed by their identifier
134/// (source GN_ADDR, sequence number), each with its own CBF timer.
135pub struct CbfPacketBuffer<K: PartialEq + Clone, T> {
136    capacity: usize,
137    entries: VecDeque<(K, Entry<T>)>,
138    size: usize,
139}
140
141impl<K: PartialEq + Clone, T> CbfPacketBuffer<K, T> {
142    /// Buffer of `capacity` octets.
143    pub fn new(capacity: usize) -> Self {
144        CbfPacketBuffer {
145            capacity,
146            entries: VecDeque::new(),
147            size: 0,
148        }
149    }
150
151    pub fn len(&self) -> usize {
152        self.entries.len()
153    }
154
155    pub fn is_empty(&self) -> bool {
156        self.entries.is_empty()
157    }
158
159    pub fn contains(&self, key: &K) -> bool {
160        self.entries.iter().any(|(k, _)| k == key)
161    }
162
163    /// The buffered packet of `key`, if any.
164    pub fn get(&self, key: &K) -> Option<&T> {
165        self.entries
166            .iter()
167            .find(|(k, _)| k == key)
168            .map(|(_, e)| &e.item)
169    }
170
171    /// Buffer a packet and start its timer; head drop on overflow.
172    #[allow(clippy::too_many_arguments)]
173    pub fn insert(
174        &mut self,
175        key: K,
176        item: T,
177        size: usize,
178        lifetime_ms: u64,
179        now_ms: u64,
180        timeout_ms: f64,
181    ) -> usize {
182        self.remove(&key);
183        self.entries.push_back((
184            key,
185            Entry {
186                item,
187                size,
188                lifetime_ms,
189                enqueued_ms: now_ms,
190                deadline_ms: now_ms + timeout_ms.max(0.0).ceil() as u64,
191            },
192        ));
193        self.size += size;
194        let mut dropped = 0;
195        while self.size > self.capacity {
196            match self.entries.pop_front() {
197                Some((_, e)) => {
198                    self.size -= e.size;
199                    dropped += 1;
200                }
201                None => break,
202            }
203        }
204        dropped
205    }
206
207    /// Stop the timer of a packet and remove it from the buffer.
208    pub fn remove(&mut self, key: &K) -> Option<T> {
209        let index = self.entries.iter().position(|(k, _)| k == key)?;
210        let (_, entry) = self.entries.remove(index)?;
211        self.size -= entry.size;
212        Some(entry.item)
213    }
214
215    /// Time left until the timer of `key` expires.
216    pub fn remaining_timeout_ms(&self, key: &K, now_ms: u64) -> Option<u64> {
217        self.entries
218            .iter()
219            .find(|(k, _)| k == key)
220            .map(|(_, e)| e.deadline_ms.saturating_sub(now_ms))
221    }
222
223    /// Restart the timer of a buffered packet.
224    pub fn restart(&mut self, key: &K, now_ms: u64, timeout_ms: f64) {
225        if let Some((_, e)) = self.entries.iter_mut().find(|(k, _)| k == key) {
226            e.deadline_ms = now_ms + timeout_ms.max(0.0).ceil() as u64;
227        }
228    }
229
230    /// Earliest timer expiry, in ms, or None when the buffer is empty.
231    pub fn next_deadline(&self) -> Option<u64> {
232        self.entries.iter().map(|(_, e)| e.deadline_ms).min()
233    }
234
235    /// Remove the packets whose timer expired, returning `(key, packet,
236    /// remaining lifetime in ms)` in queue order; packets whose lifetime ran
237    /// out while buffered are discarded.
238    pub fn pop_expired(&mut self, now_ms: u64) -> Vec<(K, T, u64)> {
239        let mut out = Vec::new();
240        let mut kept = VecDeque::new();
241        for (key, entry) in self.entries.drain(..) {
242            if entry.deadline_ms <= now_ms {
243                self.size -= entry.size;
244                let remaining = entry.remaining_lifetime_ms(now_ms);
245                if remaining > 0 {
246                    out.push((key, entry.item, remaining));
247                }
248            } else {
249                kept.push_back((key, entry));
250            }
251        }
252        self.entries = kept;
253        out
254    }
255}
256
257/// Segment-based CBF timeout TO_CBF (equations E.1 to E.3, and F.1, F.2).
258///
259/// `distance_m` is the forwarding progress PROG (non-area CBF, clause E.3.2)
260/// or the forwarding distance F_DIST (area CBF, clause F.3.2); `to_acc` is
261/// the optional Access Layer constraint TO_ACC.
262///
263/// SEGN = max(1, ceil(D / DIST_MAX));
264/// TO_CBF_WO_ACC = TO_CBF_MAX * SEGN + (TO_CBF_MIN - TO_CBF_MAX) / DIST_MAX
265/// * (D - DIST_MAX * (SEGN - 1)); TO_CBF = max(TO_CBF_WO_ACC, TO_ACC).
266pub fn cbf_timeout_ms(
267    distance_m: f64,
268    to_cbf_min: f64,
269    to_cbf_max: f64,
270    dist_max: f64,
271    to_acc: f64,
272) -> f64 {
273    let distance_m = distance_m.max(0.0);
274    let segn = (distance_m / dist_max).ceil().max(1.0);
275    let wo_acc = to_cbf_max * segn
276        + (to_cbf_min - to_cbf_max) / dist_max * (distance_m - dist_max * (segn - 1.0));
277    wo_acc.max(to_acc)
278}
279
280/// Recalculated timeout TO_CBF_UPDATE (equation E.4) on reception of a
281/// forwarded copy from a sender that is not a better forwarder.
282pub fn cbf_timeout_update_ms(to_cbf: f64, to_cbf_rp: f64, to_cbf_max: f64) -> f64 {
283    if (to_cbf - to_cbf_rp).abs() < to_cbf_max {
284        to_cbf.min(to_cbf_rp)
285    } else {
286        to_cbf.max(to_cbf_rp)
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    const TO_MIN: f64 = 1.0;
295    const TO_MAX: f64 = 100.0;
296    const DIST_MAX: f64 = 1000.0;
297
298    #[test]
299    fn fifo_flush_with_reduced_lifetime() {
300        let mut buffer = PacketBuffer::new(100);
301        buffer.push("a", 10, 1000, 0);
302        buffer.push("b", 10, 1000, 100);
303        assert_eq!(buffer.flush(300), vec![("a", 700), ("b", 800)]);
304        assert!(buffer.is_empty());
305        assert_eq!(buffer.size(), 0);
306    }
307
308    #[test]
309    fn head_drop_on_overflow() {
310        let mut buffer = PacketBuffer::new(25);
311        buffer.push("a", 10, 1000, 0);
312        buffer.push("b", 10, 1000, 0);
313        assert_eq!(buffer.push("c", 10, 1000, 0), 1);
314        let items: Vec<_> = buffer.flush(0).into_iter().map(|(i, _)| i).collect();
315        assert_eq!(items, vec!["b", "c"]);
316    }
317
318    #[test]
319    fn packet_larger_than_buffer_is_dropped() {
320        let mut buffer = PacketBuffer::new(5);
321        assert_eq!(buffer.push("a", 10, 1000, 0), 1);
322        assert_eq!(buffer.len(), 0);
323    }
324
325    #[test]
326    fn expired_packets_are_discarded() {
327        let mut buffer = PacketBuffer::new(100);
328        buffer.push("short", 10, 50, 0);
329        buffer.push("long", 10, 5000, 0);
330        assert_eq!(buffer.purge(50), 1);
331        buffer.push("short2", 10, 50, 0);
332        assert_eq!(buffer.flush(60), vec![("long", 4940)]);
333    }
334
335    #[test]
336    fn cbf_timer_expiry_and_restart() {
337        let mut buffer = CbfPacketBuffer::new(1000);
338        buffer.insert(1u32, "p1", 10, 1000, 0, 50.0);
339        buffer.insert(2u32, "p2", 10, 1000, 0, 80.0);
340        assert_eq!(buffer.next_deadline(), Some(50));
341        assert_eq!(buffer.remaining_timeout_ms(&1, 20), Some(30));
342        buffer.restart(&1, 20, 100.0);
343        assert_eq!(buffer.pop_expired(80), vec![(2, "p2", 920)]);
344        assert!(buffer.contains(&1));
345        assert_eq!(buffer.get(&1), Some(&"p1"));
346        assert_eq!(buffer.remove(&1), Some("p1"));
347        assert_eq!(buffer.next_deadline(), None);
348    }
349
350    #[test]
351    fn cbf_head_drop_and_lifetime() {
352        let mut buffer = CbfPacketBuffer::new(15);
353        buffer.insert(1u32, "a", 10, 1000, 0, 10.0);
354        buffer.insert(2u32, "b", 10, 5, 0, 10.0);
355        assert!(!buffer.contains(&1));
356        assert!(buffer.pop_expired(10).is_empty()); // lifetime ran out
357    }
358
359    #[test]
360    fn cbf_timeout_example_values() {
361        let to = |d: f64| cbf_timeout_ms(d, TO_MIN, TO_MAX, DIST_MAX, 0.0);
362        assert!((to(DIST_MAX) - TO_MIN).abs() < 1e-9);
363        assert!((to(0.0) - TO_MAX).abs() < 1e-9);
364        assert!((to(2.0 * DIST_MAX) - (TO_MAX + TO_MIN)).abs() < 1e-9);
365        assert!((to(2.0001 * DIST_MAX) - 3.0 * TO_MAX).abs() < 0.1);
366        assert!((to(DIST_MAX / 2.0) - (TO_MIN + TO_MAX) / 2.0).abs() < 1e-9);
367    }
368
369    #[test]
370    fn cbf_timeout_access_layer_constraint() {
371        assert_eq!(
372            cbf_timeout_ms(DIST_MAX, TO_MIN, TO_MAX, DIST_MAX, 40.0),
373            40.0
374        );
375    }
376
377    #[test]
378    fn cbf_timeout_update() {
379        assert_eq!(cbf_timeout_update_ms(30.0, 60.0, TO_MAX), 30.0);
380        assert_eq!(cbf_timeout_update_ms(30.0, 150.0, TO_MAX), 150.0);
381    }
382}