use core::fmt;
use core::num::NonZeroUsize;
use calandria::RetainedBytes;
use crate::{MatchKey, write::WriteQueueLimits};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MatchKeySpace {
first: MatchKey,
last: MatchKey,
}
impl MatchKeySpace {
pub const fn new(first: u32, last: u32) -> Result<Self, LimitsError> {
if first > last {
return Err(LimitsError::EmptyMatchKeySpace);
}
Ok(Self {
first: MatchKey::new(first),
last: MatchKey::new(last),
})
}
pub const fn first(self) -> MatchKey {
self.first
}
pub const fn last(self) -> MatchKey {
self.last
}
pub fn capacity(self) -> u64 {
u64::from(self.last.get()) - u64::from(self.first.get()) + 1
}
pub(crate) const fn next(self, current: MatchKey) -> MatchKey {
if current.get() == self.last.get() {
self.first
} else {
MatchKey::new(current.get() + 1)
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ConnectionLimits {
max_operations: NonZeroUsize,
max_retained_bytes: RetainedBytes,
max_write_frames: NonZeroUsize,
max_write_retained_bytes: RetainedBytes,
match_keys: MatchKeySpace,
}
impl ConnectionLimits {
pub const fn new(
max_operations: usize,
max_retained_bytes: RetainedBytes,
max_write_frames: usize,
max_write_retained_bytes: RetainedBytes,
match_keys: MatchKeySpace,
) -> Result<Self, LimitsError> {
let Some(max_operations) = NonZeroUsize::new(max_operations) else {
return Err(LimitsError::ZeroOperationCapacity);
};
let Some(max_write_frames) = NonZeroUsize::new(max_write_frames) else {
return Err(LimitsError::ZeroWriteCapacity);
};
Ok(Self {
max_operations,
max_retained_bytes,
max_write_frames,
max_write_retained_bytes,
match_keys,
})
}
pub const fn max_operations(self) -> usize {
self.max_operations.get()
}
pub const fn max_retained_bytes(self) -> RetainedBytes {
self.max_retained_bytes
}
pub const fn max_write_frames(self) -> usize {
self.max_write_frames.get()
}
pub const fn max_write_retained_bytes(self) -> RetainedBytes {
self.max_write_retained_bytes
}
pub const fn match_keys(self) -> MatchKeySpace {
self.match_keys
}
pub(crate) const fn write_queue_limits(self) -> WriteQueueLimits {
WriteQueueLimits::new(self.max_write_frames, self.max_write_retained_bytes)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum LimitsError {
ZeroOperationCapacity,
ZeroWriteCapacity,
EmptyMatchKeySpace,
}
impl fmt::Display for LimitsError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::ZeroOperationCapacity => "operation capacity must be nonzero",
Self::ZeroWriteCapacity => "write-frame capacity must be nonzero",
Self::EmptyMatchKeySpace => "match-key range must be nonempty",
})
}
}
impl core::error::Error for LimitsError {}