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