netstack3_base/
settings.rs

1// Copyright 2025 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//! Common patterns for runtime configurable settings in netstack.
6
7use core::ops::Deref;
8
9/// Abstracts access to stack settings.
10///
11/// This trait is implemented by *bindings* to allow core access to
12/// runtime-configurable behavior for the network stack.
13///
14/// Separate modules declare their own `T` for settings structures that can be
15/// retrieved via this trait.
16pub trait SettingsContext<T> {
17    /// Borrows the current settings values.
18    fn settings(&self) -> impl Deref<Target = T> + '_;
19}
20
21/// Common settings applied to buffer size configuration.
22///
23/// This type is a witness for a valid configuration where `min <= default <=
24/// max`.
25#[derive(Copy, Clone, Debug, Eq, PartialEq)]
26pub struct BufferSizeSettings<T> {
27    default: T,
28    max: T,
29    min: T,
30}
31
32impl<T: Copy + Ord> BufferSizeSettings<T> {
33    /// Creates a new value with provided `min`, `default`, `max` sizes.
34    ///
35    /// Returns `None` if `min <= default <= max` is violated.
36    pub fn new(min: T, default: T, max: T) -> Option<Self> {
37        if min > default || max < default {
38            return None;
39        }
40        Some(Self { default, max, min })
41    }
42
43    /// Returns the configured default buffer size.
44    pub fn default(&self) -> T {
45        self.default
46    }
47
48    /// Returns the configured maximum buffer size.
49    pub fn max(&self) -> T {
50        self.max
51    }
52
53    /// Returns the configured minimum buffer size.
54    pub fn min(&self) -> T {
55        self.min
56    }
57
58    /// Returns a tuple of the minimum and maximum buffer size, in this order.
59    pub fn min_max(&self) -> (T, T) {
60        (self.min, self.max)
61    }
62
63    /// Returns the clamped value `val` to the configured maximum and minimum
64    /// buffer sizes.
65    pub fn clamp(&self, val: T) -> T {
66        val.clamp(self.min, self.max)
67    }
68}
69
70#[cfg(any(test, feature = "testutils"))]
71pub(crate) mod testutil {
72    use super::*;
73
74    /// A marker trait that allows a type to implement [`SettingsContext`] that
75    /// always yields a default value for the settings type.
76    pub trait AlwaysDefaultsSettingsContext {}
77
78    impl<T, O> SettingsContext<T> for O
79    where
80        T: Default + 'static,
81        O: AlwaysDefaultsSettingsContext,
82    {
83        fn settings(&self) -> impl Deref<Target = T> + '_ {
84            DefaultSettings(T::default())
85        }
86    }
87
88    struct DefaultSettings<T>(T);
89
90    impl<T> Deref for DefaultSettings<T> {
91        type Target = T;
92
93        fn deref(&self) -> &Self::Target {
94            let Self(s) = self;
95            s
96        }
97    }
98}