#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Params<'a> {
raw: &'a [u8],
}
impl<'a> Params<'a> {
pub(crate) const fn new(raw: &'a [u8]) -> Self {
Self { raw }
}
#[must_use]
pub const fn as_bytes(self) -> &'a [u8] {
self.raw
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.raw.is_empty()
}
#[must_use]
pub fn len(self) -> usize {
if self.raw.is_empty() {
return 0;
}
let mut count = 1;
for &byte in self.raw {
if byte == b';' {
count += 1;
}
}
count
}
#[must_use]
pub fn get(self, index: usize) -> Option<Param<'a>> {
self.iter().nth(index)
}
#[must_use]
pub const fn iter(self) -> ParamIter<'a> {
ParamIter {
remaining: self.raw,
done: self.raw.is_empty(),
}
}
}
#[derive(Clone, Debug)]
pub struct ParamIter<'a> {
remaining: &'a [u8],
done: bool,
}
impl<'a> Iterator for ParamIter<'a> {
type Item = Param<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
if let Some(separator) = self.remaining.iter().position(|&byte| byte == b';') {
let (value, rest) = self.remaining.split_at(separator);
self.remaining = &rest[1..];
Some(Param::new(value))
} else {
self.done = true;
Some(Param::new(self.remaining))
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Param<'a> {
raw: &'a [u8],
}
impl<'a> Param<'a> {
const fn new(raw: &'a [u8]) -> Self {
Self { raw }
}
#[must_use]
pub const fn as_bytes(self) -> &'a [u8] {
self.raw
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.raw.is_empty()
}
#[must_use]
pub fn len(self) -> usize {
let mut count = 1;
for &byte in self.raw {
if byte == b':' {
count += 1;
}
}
count
}
#[must_use]
pub fn get(self, index: usize) -> Option<Subparam<'a>> {
self.subparams().nth(index)
}
#[must_use]
pub const fn subparams(self) -> SubparamIter<'a> {
SubparamIter {
remaining: self.raw,
done: false,
}
}
#[must_use]
pub fn value(self) -> Option<u64> {
self.get(0).and_then(Subparam::value)
}
}
#[derive(Clone, Debug)]
pub struct SubparamIter<'a> {
remaining: &'a [u8],
done: bool,
}
impl<'a> Iterator for SubparamIter<'a> {
type Item = Subparam<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
if let Some(separator) = self.remaining.iter().position(|&byte| byte == b':') {
let (value, rest) = self.remaining.split_at(separator);
self.remaining = &rest[1..];
Some(Subparam::new(value))
} else {
self.done = true;
Some(Subparam::new(self.remaining))
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Subparam<'a> {
raw: &'a [u8],
}
impl<'a> Subparam<'a> {
const fn new(raw: &'a [u8]) -> Self {
Self { raw }
}
#[must_use]
pub const fn as_bytes(self) -> &'a [u8] {
self.raw
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.raw.is_empty()
}
#[must_use]
pub fn value(self) -> Option<u64> {
if self.raw.is_empty() {
return None;
}
let mut value = 0_u64;
for &byte in self.raw {
if !byte.is_ascii_digit() {
return None;
}
value = value.checked_mul(10)?.checked_add(u64::from(byte - b'0'))?;
}
Some(value)
}
}