sark_http/payload/response/headers/
list.rs1use std::{borrow::Cow, slice};
2
3use o3::alloc;
4
5use crate::{
6 field::{self, Lower, Value, storage},
7 h1::field::Entry,
8};
9
10type Field<'field, N> = (N, Value<Cow<'field, [u8]>>);
11
12#[derive(Debug)]
13pub enum Error {
14 Name(storage::Error),
15 Value(storage::Error),
16 Allocation(alloc::Error),
17}
18
19#[derive(PartialEq, Eq)]
20pub struct List<'field, N = Lower<Cow<'field, str>>> {
21 entries: Vec<Field<'field, N>>,
22}
23
24impl<N> Default for List<'_, N> {
25 fn default() -> Self {
26 Self::new()
27 }
28}
29
30impl<'field, N> List<'field, N> {
31 pub fn new() -> Self {
32 Self {
33 entries: Vec::new(),
34 }
35 }
36
37 pub fn is_empty(&self) -> bool {
38 self.entries.is_empty()
39 }
40
41 pub fn len(&self) -> usize {
42 self.entries.len()
43 }
44
45 pub fn iter(&self) -> slice::Iter<'_, Field<'field, N>> {
46 self.entries.iter()
47 }
48
49 fn try_append(&mut self, field: Field<'field, N>) -> Result<(), alloc::Error> {
50 alloc::try_vacant(&mut self.entries)?.insert(field);
51 Ok(())
52 }
53}
54
55impl<'field, N: AsRef<[u8]>> List<'field, N> {
56 pub fn get(&self, name: &str) -> Option<&Value<Cow<'field, [u8]>>> {
57 self.entries
58 .iter()
59 .find(|entry| entry.0.as_ref().eq_ignore_ascii_case(name.as_bytes()))
60 .map(|entry| &entry.1)
61 }
62
63 pub fn contains_key(&self, name: &str) -> bool {
64 self.get(name).is_some()
65 }
66}
67
68impl<Scope: Copy> field::Source<Scope> for List<'_, storage::Lower<Cow<'_, str>, Scope>> {
69 fn emit<'field>(&'field self, sink: &mut impl field::Sink<'field, Scope>) {
70 for (name, value) in &self.entries {
71 sink.field(name.borrow(), value.borrow());
72 }
73 }
74}
75
76impl List<'_> {
77 pub fn try_push(&mut self, name: &[u8], value: &[u8]) -> Result<(), Error> {
78 let name = Lower::try_copy(name).map_err(Error::Name)?;
79 let value = Value::try_copy(value).map_err(Error::Value)?;
80 self.try_append((name, value))
81 .map_err(Error::Allocation)
82 }
83
84 pub fn try_entry(&mut self, field: Entry<'_>) -> Result<(), Error> {
85 let name = Lower::try_entry(field)
86 .map_err(storage::Error::Allocation)
87 .map_err(Error::Name)?;
88 let value = Value::try_entry(field)
89 .map_err(storage::Error::Allocation)
90 .map_err(Error::Value)?;
91 self.try_append((name, value))
92 .map_err(Error::Allocation)
93 }
94}
95
96impl<'a, 'field, N> IntoIterator for &'a List<'field, N> {
97 type Item = &'a Field<'field, N>;
98 type IntoIter = slice::Iter<'a, Field<'field, N>>;
99
100 fn into_iter(self) -> Self::IntoIter {
101 self.iter()
102 }
103}
104
105const _: () = assert!(core::mem::size_of::<Error>() <= 3 * core::mem::size_of::<usize>());