use std::{borrow::Cow, slice};
use o3::alloc;
use crate::{
field::{self, Lower, Value, storage},
h1::field::Entry,
};
type Field<'field, N> = (N, Value<Cow<'field, [u8]>>);
#[derive(Debug)]
pub enum Error {
Name(storage::Error),
Value(storage::Error),
Allocation(alloc::Error),
}
#[derive(PartialEq, Eq)]
pub struct List<'field, N = Lower<Cow<'field, str>>> {
entries: Vec<Field<'field, N>>,
}
impl<N> Default for List<'_, N> {
fn default() -> Self {
Self::new()
}
}
impl<'field, N> List<'field, N> {
pub fn new() -> Self {
Self {
entries: Vec::new(),
}
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn iter(&self) -> slice::Iter<'_, Field<'field, N>> {
self.entries.iter()
}
fn try_append(&mut self, field: Field<'field, N>) -> Result<(), alloc::Error> {
alloc::try_vacant(&mut self.entries)?.insert(field);
Ok(())
}
}
impl<'field, N: AsRef<[u8]>> List<'field, N> {
pub fn get(&self, name: &str) -> Option<&Value<Cow<'field, [u8]>>> {
self.entries
.iter()
.find(|entry| entry.0.as_ref().eq_ignore_ascii_case(name.as_bytes()))
.map(|entry| &entry.1)
}
pub fn contains_key(&self, name: &str) -> bool {
self.get(name).is_some()
}
}
impl<Scope: Copy> field::Source<Scope> for List<'_, storage::Lower<Cow<'_, str>, Scope>> {
fn emit<'field>(&'field self, sink: &mut impl field::Sink<'field, Scope>) {
for (name, value) in &self.entries {
sink.field(name.borrow(), value.borrow());
}
}
}
impl List<'_> {
pub fn try_push(&mut self, name: &[u8], value: &[u8]) -> Result<(), Error> {
let name = Lower::try_copy(name).map_err(Error::Name)?;
let value = Value::try_copy(value).map_err(Error::Value)?;
self.try_append((name, value))
.map_err(Error::Allocation)
}
pub fn try_entry(&mut self, field: Entry<'_>) -> Result<(), Error> {
let name = Lower::try_entry(field)
.map_err(storage::Error::Allocation)
.map_err(Error::Name)?;
let value = Value::try_entry(field)
.map_err(storage::Error::Allocation)
.map_err(Error::Value)?;
self.try_append((name, value))
.map_err(Error::Allocation)
}
}
impl<'a, 'field, N> IntoIterator for &'a List<'field, N> {
type Item = &'a Field<'field, N>;
type IntoIter = slice::Iter<'a, Field<'field, N>>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
const _: () = assert!(core::mem::size_of::<Error>() <= 3 * core::mem::size_of::<usize>());