netstack3_base/testutil/
monotonic_id.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//! A convenient monotonically increasing identifier to use in tests.
6
7use core::fmt::{self, Debug, Display};
8use core::sync::atomic::{self, AtomicUsize};
9
10/// A convenient monotonically increasing identifier to use in tests.
11pub struct MonotonicIdentifier(usize);
12
13impl Debug for MonotonicIdentifier {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        // NB: This type is used as part of the debug implementation in device
16        // IDs which should provide enough context themselves on the type. For
17        // brevity we omit the type name.
18        let Self(id) = self;
19        Debug::fmt(id, f)
20    }
21}
22
23impl Display for MonotonicIdentifier {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        Debug::fmt(self, f)
26    }
27}
28
29static MONOTONIC_COUNTER: AtomicUsize = AtomicUsize::new(1);
30
31impl MonotonicIdentifier {
32    /// Creates a new identifier with the next value.
33    pub fn new() -> Self {
34        Self(MONOTONIC_COUNTER.fetch_add(1, atomic::Ordering::SeqCst))
35    }
36}
37
38impl Default for MonotonicIdentifier {
39    fn default() -> Self {
40        Self::new()
41    }
42}