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 clamped value `val` to the configured maximum and minimum
44 /// buffer sizes.
45 pub fn clamp(&self, val: T) -> T {
46 val.clamp(self.min, self.max)
47 }
48}
49
50impl<T: Copy> BufferSizeSettings<T> {
51 /// Returns the configured default buffer size.
52 pub fn default(&self) -> T {
53 self.default
54 }
55
56 /// Returns the configured maximum buffer size.
57 pub fn max(&self) -> T {
58 self.max
59 }
60
61 /// Returns the configured minimum buffer size.
62 pub fn min(&self) -> T {
63 self.min
64 }
65
66 /// Returns a tuple of the minimum and maximum buffer size, in this order.
67 pub fn min_max(&self) -> (T, T) {
68 (self.min, self.max)
69 }
70}
71
72#[cfg(any(test, feature = "testutils"))]
73pub(crate) mod testutil {
74 use super::*;
75
76 /// A marker trait that allows a type to implement [`SettingsContext`] that
77 /// always yields a default value for the settings type.
78 pub trait AlwaysDefaultsSettingsContext {}
79
80 impl<T, O> SettingsContext<T> for O
81 where
82 T: Default + 'static,
83 O: AlwaysDefaultsSettingsContext,
84 {
85 fn settings(&self) -> impl Deref<Target = T> + '_ {
86 DefaultSettings(T::default())
87 }
88 }
89
90 struct DefaultSettings<T>(T);
91
92 impl<T> Deref for DefaultSettings<T> {
93 type Target = T;
94
95 fn deref(&self) -> &Self::Target {
96 let Self(s) = self;
97 s
98 }
99 }
100}