sark_http/field/text/percent/
raw.rs1use o3::buffer::write::Sink;
2
3use crate::{
4 field,
5 field::{
6 storage::encoded,
7 text::percent::{Error, Length, octet, scan},
8 },
9};
10
11pub struct Encoder<'a> {
12 text: &'a str,
13 length: Length,
14}
15
16impl<'a> Encoder<'a> {
17 pub fn new(text: &'a str) -> Result<Self, Error> {
18 Ok(Self {
19 text,
20 length: Length::measure(text.as_bytes())?,
21 })
22 }
23
24 pub const unsafe fn from_length(text: &'a str, length: Length) -> Self {
28 Self { text, length }
29 }
30
31 pub const fn length(&self) -> Length {
32 self.length
33 }
34}
35
36impl encoded::Encoded for Encoder<'_> {}
37
38impl field::Encode for Encoder<'_> {
39 fn encoded_len(&self) -> usize {
40 self.length.get()
41 }
42
43 fn try_write<W: Sink>(self, out: &mut W) -> Result<(), W::Error> {
44 let mut bytes = self.text.as_bytes();
45 while !bytes.is_empty() {
46 let (literal, suffix) = scan::Scan::new(bytes).plain();
47 out.write_slice(literal)?;
48 let Some((&byte, tail)) = suffix.split_first() else {
49 return Ok(());
50 };
51 out.write_slice(&octet::encode(byte))?;
52 bytes = tail;
53 }
54 Ok(())
55 }
56}
57
58const _: () = assert!(core::mem::size_of::<Encoder<'_>>() == 3 * core::mem::size_of::<usize>());