valence_protocol/
bounded.rs

1use std::borrow::Borrow;
2use std::fmt::Display;
3
4use derive_more::{AsRef, Deref, DerefMut, From};
5
6/// A newtype wrapper for `T` which modifies the [`Encode`](crate::Encode) and
7/// [`Decode`](crate::Decode) impls to be bounded by some upper limit `MAX`.
8/// Implementations are expected to error eagerly if the limit is exceeded.
9///
10/// What exactly `MAX` represents depends on the type `T`. Here are some
11/// instances:
12/// - **arrays/slices**: The maximum number of elements.
13/// - **strings**: The maximum number of utf16 code units.
14/// - **[`RawBytes`]**: The maximum number of bytes.
15///
16/// [`RawBytes`]: crate::RawBytes
17#[derive(
18    Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Deref, DerefMut, AsRef, From,
19)]
20pub struct Bounded<T, const MAX: usize>(pub T);
21
22impl<T, const MAX: usize> Bounded<T, MAX> {
23    pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Bounded<U, MAX> {
24        Bounded(f(self.0))
25    }
26
27    pub fn map_into<U: From<T>>(self) -> Bounded<U, MAX> {
28        Bounded(self.0.into())
29    }
30}
31
32impl<T, const MAX: usize> Borrow<T> for Bounded<T, MAX> {
33    fn borrow(&self) -> &T {
34        &self.0
35    }
36}
37
38impl<T: Display, const MAX: usize> Display for Bounded<T, MAX> {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        self.0.fmt(f)
41    }
42}