#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct RangeStatus(pub u32);
impl RangeStatus {
pub const SERVED: Self = Self(0);
pub const OUT_OF_BOUNDS: Self = Self(1);
pub const TOO_LARGE: Self = Self(2);
pub const UNAVAILABLE: Self = Self(3);
pub const NO_SOURCE: Self = Self(4);
#[must_use]
pub const fn is_served(self) -> bool {
self.0 == Self::SERVED.0
}
#[must_use]
pub const fn name(self) -> Option<&'static str> {
match self {
Self::SERVED => Some("served"),
Self::OUT_OF_BOUNDS => Some("out of bounds"),
Self::TOO_LARGE => Some("larger than one request can cover"),
Self::UNAVAILABLE => Some("unavailable"),
Self::NO_SOURCE => Some("no source attached"),
_ => None,
}
}
}
impl core::fmt::Display for RangeStatus {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self.name() {
Some(name) => f.write_str(name),
None => write!(f, "range status {}", self.0),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Buf {
bytes: [u8; 64],
len: usize,
}
impl Buf {
const fn new() -> Self {
Self {
bytes: [0; 64],
len: 0,
}
}
fn text(&self) -> &str {
core::str::from_utf8(&self.bytes[..self.len]).expect("everything written here is utf8")
}
}
impl core::fmt::Write for Buf {
fn write_str(&mut self, text: &str) -> core::fmt::Result {
let end = self.len + text.len();
let room = self.bytes.get_mut(self.len..end).ok_or(core::fmt::Error)?;
room.copy_from_slice(text.as_bytes());
self.len = end;
Ok(())
}
}
fn printed(status: RangeStatus) -> Buf {
use core::fmt::Write as _;
let mut buf = Buf::new();
write!(&mut buf, "{status}").expect("a status is shorter than the buffer");
buf
}
#[test]
fn only_zero_means_the_bytes_are_there() {
assert!(RangeStatus::SERVED.is_served());
for status in [
RangeStatus::OUT_OF_BOUNDS,
RangeStatus::TOO_LARGE,
RangeStatus::UNAVAILABLE,
RangeStatus::NO_SOURCE,
] {
assert!(!status.is_served(), "{status} is not the bytes arriving");
}
}
#[test]
fn a_status_from_a_later_host_still_prints() {
let future = RangeStatus(9001);
assert_eq!(future.name(), None);
assert_eq!(printed(future).text(), "range status 9001");
}
}