netstack3_base/event.rs
1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Types and traits defining events emitted from core to bindings.
6
7/// A context for emitting events.
8///
9/// `EventContext` encodes the common pattern for emitting atomic events of type
10/// `T` from core. An implementation of `EventContext` must guarantee that
11/// events are processed in the order they are emitted.
12pub trait EventContext<T> {
13 /// Handles `event`.
14 fn on_event(&mut self, event: T);
15}
16
17#[cfg(any(test, feature = "testutils"))]
18pub(crate) mod testutil {
19 use super::*;
20
21 use alloc::vec::Vec;
22 use core::fmt::Debug;
23
24 /// A fake [`EventContext`].
25 pub struct FakeEventCtx<E: Debug> {
26 events: Vec<E>,
27 must_watch_all_events: bool,
28 }
29
30 impl<E: Debug> EventContext<E> for FakeEventCtx<E> {
31 fn on_event(&mut self, event: E) {
32 self.events.push(event)
33 }
34 }
35
36 impl<E: Debug> Drop for FakeEventCtx<E> {
37 fn drop(&mut self) {
38 if self.must_watch_all_events {
39 assert!(
40 self.events.is_empty(),
41 "dropped context with unacknowledged events: {:?}",
42 self.events
43 );
44 }
45 }
46 }
47
48 impl<E: Debug> Default for FakeEventCtx<E> {
49 fn default() -> Self {
50 Self { events: Default::default(), must_watch_all_events: false }
51 }
52 }
53
54 impl<E: Debug> FakeEventCtx<E> {
55 /// Takes all events from the context.
56 ///
57 /// After calling `take`, the caller opts into event watching and must
58 /// acknowledge all events before fropping the `FakeEventCtx`.
59 pub fn take(&mut self) -> Vec<E> {
60 // Any client that calls `take()` is opting into watching events
61 // and must watch them all.
62 self.must_watch_all_events = true;
63 core::mem::take(&mut self.events)
64 }
65 }
66}