Skip to main content

sark_http/uri/target/
mod.rs

1//! Lossless absolute-URI and client-target proofs.
2
3use std::{fmt, num, str};
4
5use o3::alloc;
6
7use crate::uri::{self, path};
8
9mod plan;
10pub use plan::Plan;
11mod raw;
12mod relative;
13pub use relative::Relative;
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum Error {
17    Colon,
18    Scheme(uri::Error),
19    Separator { colon: usize, len: usize },
20    UserInfo,
21    Authority(uri::Error),
22    Start { byte: Option<u8> },
23    Origin(path::Error),
24    Length,
25    Index { value: usize },
26    Allocation(alloc::Exhausted),
27}
28
29#[derive(Clone, Copy, PartialEq, Eq)]
30pub struct Absolute<'a> {
31    scheme: &'a str,
32    parsed: uri::Authority<'a>,
33    origin: Origin<'a>,
34}
35
36impl<'a> Absolute<'a> {
37    pub fn parse(value: &'a str) -> Result<Self, Error> {
38        let (scheme, rest) = value.split_once(':').ok_or(Error::Colon)?;
39        uri::Scheme::validate(scheme.as_bytes()).map_err(Error::Scheme)?;
40        let rest = rest.strip_prefix("//").ok_or(Error::Separator {
41            colon: scheme.len(),
42            len: value.len(),
43        })?;
44        let (raw, tail) = raw::split_authority(rest);
45        let parsed = authority(raw)?;
46        let origin = Origin::from_uri(tail)?;
47        Ok(Self {
48            scheme,
49            parsed,
50            origin,
51        })
52    }
53
54    pub const fn scheme(self) -> &'a str {
55        self.scheme
56    }
57
58    pub const fn authority(self) -> uri::Authority<'a> {
59        self.parsed
60    }
61
62    pub const fn origin(self) -> Origin<'a> {
63        self.origin
64    }
65}
66
67#[derive(Clone, Copy, PartialEq, Eq)]
68pub struct Origin<'a> {
69    value: &'a str,
70    path_end: u32,
71    slash: Slash,
72}
73
74#[derive(Clone, Copy, PartialEq, Eq)]
75#[repr(u8)]
76enum Slash {
77    Present,
78    Insert,
79}
80
81impl<'a> Origin<'a> {
82    pub const ROOT: Self = Self {
83        value: "/",
84        path_end: 1,
85        slash: Slash::Present,
86    };
87
88    pub fn parse(value: &'a str) -> Result<Self, Error> {
89        if !value.starts_with('/') {
90            return Err(Error::Start {
91                byte: value.as_bytes().first().copied(),
92            });
93        }
94        Self::validated(value, Slash::Present)
95    }
96
97    fn from_uri(value: &'a str) -> Result<Self, Error> {
98        match value.as_bytes().first() {
99            Some(b'/') => Self::validated(value, Slash::Present),
100            Some(b'?') => Self::validated(value, Slash::Insert),
101            Some(byte) => Err(Error::Start { byte: Some(*byte) }),
102            None => Self::validated(value, Slash::Insert),
103        }
104    }
105
106    fn validated(value: &'a str, slash: Slash) -> Result<Self, Error> {
107        Ok(Self {
108            value,
109            path_end: path_end(value)?,
110            slash,
111        })
112    }
113
114    fn prefix(self) -> &'a str {
115        match self.slash {
116            Slash::Present => "",
117            Slash::Insert => "/",
118        }
119    }
120
121    fn path_end(self) -> usize {
122        self.path_end as usize + usize::from(self.slash == Slash::Insert)
123    }
124}
125
126impl<'a> From<&'a Target> for Origin<'a> {
127    fn from(target: &'a Target) -> Self {
128        let relative = Relative::from_target(target);
129        Self {
130            value: relative.value,
131            path_end: relative.path_end,
132            slash: Slash::Present,
133        }
134    }
135}
136
137fn authority(raw: &str) -> Result<uri::Authority<'_>, Error> {
138    if raw.as_bytes().contains(&b'@') {
139        return Err(Error::UserInfo);
140    }
141    uri::Authority::parse(raw.as_bytes()).map_err(Error::Authority)
142}
143
144fn path_end(value: &str) -> Result<u32, Error> {
145    let scan = path::Scan::new(value.as_bytes())
146        .complete()
147        .map_err(Error::Origin)?;
148    narrow(scan.path_end())
149}
150
151fn narrow(value: usize) -> Result<u32, Error> {
152    if value > u32::MAX as usize {
153        return Err(Error::Index { value });
154    }
155    Ok(value as u32)
156}
157
158#[derive(Clone, Copy, Debug)]
159struct Head {
160    scheme: Option<num::NonZero<u32>>,
161    host: u32,
162    end: u32,
163}
164
165impl Head {
166    fn new(scheme: Option<num::NonZero<u32>>, host: usize, end: usize) -> Result<Self, Error> {
167        Ok(Self {
168            scheme,
169            host: narrow(host)?,
170            end: narrow(end)?,
171        })
172    }
173
174    fn start(self) -> usize {
175        self.scheme.map_or(0, |end| end.get() as usize + 3)
176    }
177}
178
179/// An owned URI target with one admitted authority and origin form.
180///
181/// Component offsets retain the parser's bounds and grammar proofs. [`Self::try_clone`]
182/// copies the owned bytes; targets never share reference-counted storage.
183#[derive(Debug)]
184pub struct Target {
185    value: Box<str>,
186    head: Head,
187    path_end: u32,
188}
189
190impl Target {
191    pub fn parse(value: &str) -> Result<Self, Error> {
192        raw::absolute(value)
193    }
194
195    pub fn new(raw: &str, origin: Origin<'_>) -> Result<Self, Error> {
196        let host = authority(raw)?.host().len();
197        let head = Head::new(None, host, raw.len())?;
198        Self::join(head, "", raw, origin)
199    }
200
201    pub fn from_host(
202        host: &str,
203        port: Option<num::NonZero<u16>>,
204        origin: Origin<'_>,
205    ) -> Result<Self, Error> {
206        let brackets = !host.starts_with('[') && host.contains(':');
207        let length = host.len() + usize::from(brackets) * 2;
208        let host_end = if brackets {
209            if !uri::Authority::is_ip(host.as_bytes()) {
210                return Err(Error::Authority(uri::Error::InvalidHost));
211            }
212            length
213        } else {
214            if host.is_empty() && port.is_some() {
215                return Err(Error::Authority(uri::Error::InvalidHost));
216            }
217            let len = uri::host_end(host.as_bytes()).map_err(Error::Authority)?;
218            if port.is_some() && len != host.len() {
219                return Err(Error::Authority(uri::Error::InvalidPort));
220            }
221            len
222        };
223        let mut digits = fmt::NumBuffer::new();
224        let port = port.map(|port| port.get().format_into(&mut digits));
225        let end = length + port.map_or(0, |port| port.len() + 1);
226        let (left, right) = if brackets { ("[", "]") } else { ("", "") };
227        let sep = if port.is_some() { ":" } else { "" };
228        let bytes = [
229            left,
230            host,
231            right,
232            sep,
233            port.unwrap_or_default(),
234            origin.prefix(),
235            origin.value,
236        ];
237        let output = raw::Parts::new(&bytes)?;
238        let path_end = end.checked_add(origin.path_end()).ok_or(Error::Length)?;
239        let head = Head::new(None, host_end, end)?;
240        let path_end = narrow(path_end)?;
241        let value = output.try_copy()?;
242        Ok(Self {
243            value,
244            head,
245            path_end,
246        })
247    }
248
249    pub fn scheme_str(&self) -> Option<&str> {
250        raw::scheme(self)
251    }
252
253    /// Copies the admitted bytes and offsets without parsing again.
254    pub fn try_clone(&self) -> Result<Self, alloc::Exhausted> {
255        Ok(Self {
256            value: raw::clone(&self.value)?,
257            head: self.head,
258            path_end: self.path_end,
259        })
260    }
261
262    pub fn authority(&self) -> &str {
263        raw::authority(self)
264    }
265
266    /// The host spelling in the authority, including IPv6 brackets.
267    pub fn host_raw(&self) -> &str {
268        raw::host(self)
269    }
270
271    pub fn host(&self) -> &str {
272        let host = self.host_raw();
273        host.strip_prefix('[')
274            .and_then(|host| host.strip_suffix(']'))
275            .unwrap_or(host)
276    }
277
278    pub fn path(&self) -> &str {
279        raw::path(self)
280    }
281
282    pub fn path_query(&self) -> &str {
283        raw::origin(self)
284    }
285
286    pub fn query(&self) -> Option<&str> {
287        raw::query(self)
288    }
289
290    pub fn retarget(self, raw: &str) -> Result<Self, Error> {
291        let parsed = authority(raw)?;
292        let start = self.head.start();
293        let head = Head::new(
294            self.head.scheme,
295            start + parsed.host().len(),
296            start + raw.len(),
297        )?;
298        Self::join(head, raw::prefix(&self), raw, Origin::from(&self))
299    }
300
301    pub fn with_origin(&self, origin: Origin<'_>) -> Result<Self, Error> {
302        Self::join(self.head, raw::head(self), "", origin)
303    }
304
305    fn join(head: Head, prefix: &str, raw: &str, origin: Origin<'_>) -> Result<Self, Error> {
306        let end = head.end as usize;
307        let bytes = [prefix, raw, origin.prefix(), origin.value];
308        let output = raw::Parts::new(&bytes)?;
309        let path_end = end.checked_add(origin.path_end()).ok_or(Error::Length)?;
310        let path_end = narrow(path_end)?;
311        let value = output.try_copy()?;
312        Ok(Self {
313            value,
314            head,
315            path_end,
316        })
317    }
318
319    /// Removes dot segments while retaining the admitted component syntax.
320    pub fn normalize(self) -> Result<Self, Error> {
321        let relative = Relative::from_target(&self);
322        if !relative.has_dots() {
323            return Ok(self);
324        }
325        raw::resolve(relative, &self)
326    }
327
328    /// Borrows the authority components proved when this target was admitted.
329    pub fn parts(&self) -> uri::Authority<'_> {
330        let host = self.host_raw().as_bytes();
331        let port = raw::port(self);
332        uri::Authority::new(host, port)
333    }
334}
335
336impl AsRef<str> for Target {
337    fn as_ref(&self) -> &str {
338        &self.value
339    }
340}
341
342impl str::FromStr for Target {
343    type Err = Error;
344
345    fn from_str(value: &str) -> Result<Self, Self::Err> {
346        if !value.contains("://") {
347            return Self::new(value, Origin::ROOT);
348        }
349        Self::parse(value)
350    }
351}
352
353impl PartialEq for Target {
354    fn eq(&self, other: &Self) -> bool {
355        let scheme = match (self.scheme_str(), other.scheme_str()) {
356            (Some(left), Some(right)) => left.eq_ignore_ascii_case(right),
357            (None, None) => true,
358            _ => false,
359        };
360        scheme
361            && self.authority().eq_ignore_ascii_case(other.authority())
362            && self.path_query() == other.path_query()
363    }
364}
365
366impl Eq for Target {}
367
368const _: () = assert!(core::mem::size_of::<Absolute<'_>>() <= 9 * core::mem::size_of::<usize>());
369const _: () = assert!(core::mem::size_of::<Slash>() == core::mem::size_of::<bool>());
370const _: () = assert!(core::mem::size_of::<Origin<'_>>() <= 3 * core::mem::size_of::<usize>());
371const _: () = assert!(core::mem::size_of::<Target>() <= 4 * core::mem::size_of::<usize>());