#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ChannelOptions {
Bounded(usize),
Unbounded,
}
impl ChannelOptions {
#[inline]
#[must_use]
pub const fn capacity(&self) -> Option<usize> {
match self {
Self::Bounded(capacity) => Some(*capacity),
Self::Unbounded => None,
}
}
#[inline]
#[must_use]
pub const fn is_bounded(&self) -> bool {
matches!(self, Self::Bounded(_))
}
#[inline]
#[must_use]
pub const fn is_unbounded(&self) -> bool {
matches!(self, Self::Unbounded)
}
}
impl core::fmt::Display for ChannelOptions {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Bounded(capacity) => write!(f, "bounded({capacity})"),
Self::Unbounded => f.write_str("unbounded"),
}
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ChannelOptions {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_any(SpecVisitor)
}
}
#[cfg(feature = "serde")]
struct SpecVisitor;
#[cfg(feature = "serde")]
impl serde::de::Visitor<'_> for SpecVisitor {
type Value = ChannelOptions;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a capacity as a non-negative integer, or the string \"unbounded\"")
}
fn visit_u64<E>(self, capacity: u64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
usize::try_from(capacity)
.map(ChannelOptions::Bounded)
.map_err(|_| {
E::custom(format!(
"a capacity of {capacity} does not fit this machine"
))
})
}
fn visit_i64<E>(self, capacity: i64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
u64::try_from(capacity).map_or_else(
|_| {
Err(E::custom(format!(
"a channel is `{capacity}` deep in no sense — write a non-negative capacity, or \
\"unbounded\""
)))
},
|capacity| self.visit_u64(capacity),
)
}
fn visit_str<E>(self, word: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
if word == "unbounded" {
return Ok(ChannelOptions::Unbounded);
}
Err(E::custom(format!(
"`{word}` is not a channel — an integer is a bounded capacity and \"unbounded\" is the only \
word"
)))
}
}
#[cfg(test)]
mod tests;