Skip to main content

sark_http/uri/target/
mod.rs

1//! Lossless absolute-URI and client-target proofs.
2
3use std::{mem, num, str};
4
5use o3::alloc::{self, StrExt as _, array};
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 bytes = value.as_bytes();
39        let colon = bytes
40            .iter()
41            .position(|byte| *byte == b':')
42            .ok_or(Error::Colon)?;
43        // SAFETY: the located ASCII ':' ends this UTF-8 prefix inside the same input.
44        let scheme = unsafe { raw::slice(value, 0..colon) };
45        uri::Scheme::validate(scheme.as_bytes()).map_err(Error::Scheme)?;
46        let start = colon.checked_add(3).ok_or(Error::Length)?;
47        if bytes.get(colon..start) != Some(b"://") {
48            return Err(Error::Separator {
49                colon,
50                len: bytes.len(),
51            });
52        }
53        let rest = bytes.get(start..).ok_or(Error::Length)?;
54        let len = match rest
55            .iter()
56            .position(|byte| matches!(*byte, b'/' | b'?' | b'#'))
57        {
58            Some(len) => len,
59            None => rest.len(),
60        };
61        let end = start.checked_add(len).ok_or(Error::Length)?;
62        let raw = value.get(start..end).ok_or(Error::Length)?;
63        let parsed = authority(raw)?;
64        let origin = Origin::from_uri(value.get(end..).ok_or(Error::Length)?)?;
65        Ok(Self {
66            scheme,
67            parsed,
68            origin,
69        })
70    }
71
72    pub const fn scheme(self) -> &'a str {
73        self.scheme
74    }
75
76    pub const fn authority(self) -> uri::Authority<'a> {
77        self.parsed
78    }
79
80    pub const fn origin(self) -> Origin<'a> {
81        self.origin
82    }
83}
84
85#[derive(Clone, Copy, PartialEq, Eq)]
86pub struct Origin<'a> {
87    value: &'a str,
88    path_end: u32,
89    slash: Slash,
90}
91
92#[derive(Clone, Copy, PartialEq, Eq)]
93#[repr(u8)]
94enum Slash {
95    Present,
96    Insert,
97}
98
99impl<'a> Origin<'a> {
100    pub const ROOT: Self = Self {
101        value: "/",
102        path_end: 1,
103        slash: Slash::Present,
104    };
105
106    pub fn parse(value: &'a str) -> Result<Self, Error> {
107        if !value.starts_with('/') {
108            return Err(Error::Start {
109                byte: value.as_bytes().first().copied(),
110            });
111        }
112        Self::validated(value, Slash::Present)
113    }
114
115    fn from_uri(value: &'a str) -> Result<Self, Error> {
116        match value.as_bytes().first() {
117            Some(b'/') => Self::validated(value, Slash::Present),
118            Some(b'?') => Self::validated(value, Slash::Insert),
119            Some(byte) => Err(Error::Start { byte: Some(*byte) }),
120            None => Self::validated(value, Slash::Insert),
121        }
122    }
123
124    fn validated(value: &'a str, slash: Slash) -> Result<Self, Error> {
125        let plan = path::Scan::new(value.as_bytes())
126            .complete()
127            .map_err(Error::Origin)?;
128        Ok(Self {
129            value,
130            path_end: narrow(plan.path_end())?,
131            slash,
132        })
133    }
134
135    fn len(self) -> Result<usize, Error> {
136        let prefix = match self.slash {
137            Slash::Present => 0,
138            Slash::Insert => 1,
139        };
140        self.value.len().checked_add(prefix).ok_or(Error::Length)
141    }
142
143    fn append_to(self, output: &mut String) {
144        match self.slash {
145            Slash::Present => {}
146            Slash::Insert => output.push('/'),
147        }
148        output.push_str(self.value);
149    }
150
151    fn path_end(self) -> usize {
152        self.path_end as usize + usize::from(self.slash == Slash::Insert)
153    }
154}
155
156/// An owned URI target with one admitted authority and origin form.
157///
158/// Component offsets retain the parser's bounds and grammar proofs. [`Self::try_clone`]
159/// copies the owned bytes; targets never share reference-counted storage.
160#[derive(Debug)]
161pub struct Target {
162    value: Box<str>,
163    scheme_end: Option<num::NonZero<u32>>,
164    host_end: u32,
165    authority_end: u32,
166    path_end: u32,
167}
168
169impl Target {
170    pub fn parse(value: &str) -> Result<Self, Error> {
171        let parsed = Absolute::parse(value)?;
172        let start = parsed.scheme().len() + 3;
173        let end = value.len() - parsed.origin().value.len();
174        // SAFETY: parsing retained these authority boundaries in this exact immutable input.
175        let raw = unsafe { raw::slice(value, start..end) };
176        pack(
177            Some(parsed.scheme()),
178            raw,
179            parsed.authority(),
180            parsed.origin(),
181        )
182    }
183
184    pub fn new(raw: &str, origin: Origin<'_>) -> Result<Self, Error> {
185        let parsed = authority(raw)?;
186        pack(None, raw, parsed, origin)
187    }
188
189    pub fn from_host(
190        host: &str,
191        port: Option<num::NonZero<u16>>,
192        origin: Origin<'_>,
193    ) -> Result<Self, Error> {
194        let brackets = !host.starts_with('[') && host.contains(':');
195        // A str fits in isize::MAX, leaving room for brackets and a decimal u16 port.
196        let authority_len = host.len() + usize::from(brackets) * 2;
197        let host_end = if brackets {
198            if !uri::Authority::is_ip(host.as_bytes()) {
199                return Err(Error::Authority(uri::Error::InvalidHost));
200            }
201            authority_len
202        } else {
203            if host.is_empty() && port.is_some() {
204                return Err(Error::Authority(uri::Error::InvalidHost));
205            }
206            let len = uri::host_end(host.as_bytes()).map_err(Error::Authority)?;
207            if port.is_some() && len != host.len() {
208                return Err(Error::Authority(uri::Error::InvalidPort));
209            }
210            len
211        };
212        let mut digits = [mem::MaybeUninit::uninit(); 20];
213        let port = port.map(|port| raw::decimal(port, &mut digits));
214        let end = authority_len + port.map_or(0, |port| port.len() + 1);
215        let capacity = end.checked_add(origin.len()?).ok_or(Error::Length)?;
216        let path_end = end.checked_add(origin.path_end()).ok_or(Error::Length)?;
217        let bounds = plan::Bounds::new(0, host_end, end, path_end)?;
218        let mut value = buffer(capacity)?;
219        if brackets {
220            value.push('[');
221        }
222        value.push_str(host);
223        if brackets {
224            value.push(']');
225        }
226        if let Some(port) = port {
227            value.push(':');
228            value.push_str(port);
229        }
230        origin.append_to(&mut value);
231        // SAFETY: every measured host, port, and origin byte filled the exact capacity.
232        Ok(bounds.build(unsafe { raw::boxed(value) }))
233    }
234
235    pub fn scheme_str(&self) -> Option<&str> {
236        self.scheme_end.map(|end| {
237            // SAFETY: admission retains the ASCII scheme prefix in this immutable owner.
238            unsafe { raw::slice(&self.value, 0..end.get() as usize) }
239        })
240    }
241
242    /// Copies the admitted bytes and offsets without parsing again.
243    pub fn try_clone(&self) -> Result<Self, alloc::Exhausted> {
244        let value = self.value.try_to_owned()?;
245        Ok(Self {
246            // SAFETY: StrExt copies this exact UTF-8 allocation with length equal to capacity.
247            value: unsafe { raw::boxed(value) },
248            scheme_end: self.scheme_end,
249            host_end: self.host_end,
250            authority_end: self.authority_end,
251            path_end: self.path_end,
252        })
253    }
254
255    pub fn authority(&self) -> &str {
256        // SAFETY: construction retains these authority boundaries in this immutable owner.
257        unsafe { raw::slice(&self.value, self.start()..self.authority_end as usize) }
258    }
259
260    /// The host spelling in the authority, including IPv6 brackets.
261    pub fn host_raw(&self) -> &str {
262        // SAFETY: construction retains this authority host range on ASCII boundaries.
263        unsafe { raw::slice(&self.value, self.start()..self.host_end as usize) }
264    }
265
266    pub fn host(&self) -> &str {
267        let host = self.host_raw();
268        host.strip_prefix('[')
269            .and_then(|host| host.strip_suffix(']'))
270            .unwrap_or(host)
271    }
272
273    pub fn path(&self) -> &str {
274        let range = self.authority_end as usize..self.path_end as usize;
275        // SAFETY: admission retains the complete ASCII path between these boundaries.
276        unsafe { raw::slice(&self.value, range) }
277    }
278
279    pub fn path_query(&self) -> &str {
280        // SAFETY: the admitted ASCII authority ends at this immutable owner's origin.
281        unsafe { raw::slice(&self.value, self.authority_end as usize..self.value.len()) }
282    }
283
284    pub fn query(&self) -> Option<&str> {
285        let end = self.path_end as usize;
286        (end != self.value.len()).then(|| {
287            // SAFETY: an admitted nonterminal path boundary contains its ASCII query separator.
288            unsafe { raw::slice(&self.value, end + 1..self.value.len()) }
289        })
290    }
291
292    pub fn retarget(self, raw: &str) -> Result<Self, Error> {
293        let parsed = authority(raw)?;
294        pack(self.scheme_str(), raw, parsed, Origin::from(&self))
295    }
296
297    pub fn with_origin(&self, origin: Origin<'_>) -> Result<Self, Error> {
298        pack(self.scheme_str(), self.authority(), self.parts(), origin)
299    }
300
301    /// Removes dot segments while retaining the admitted component syntax.
302    pub fn normalize(self) -> Result<Self, Error> {
303        let relative = Relative::from_target(&self);
304        if !relative.has_dots() {
305            return Ok(self);
306        }
307        relative.materialize(&self)
308    }
309
310    fn start(&self) -> usize {
311        match self.scheme_end {
312            Some(end) => end.get() as usize + 3,
313            None => 0,
314        }
315    }
316
317    /// Borrows the authority components proved when this target was admitted.
318    pub fn parts(&self) -> uri::Authority<'_> {
319        let host = self.host_raw().as_bytes();
320        let port = (self.host_end != self.authority_end).then(|| {
321            let range = self.host_end as usize + 1..self.authority_end as usize;
322            // SAFETY: admission places ':' after the host and proves this ASCII port range.
323            unsafe { raw::slice(&self.value, range) }.as_bytes()
324        });
325        uri::Authority::new(host, port)
326    }
327}
328
329impl<'a> From<&'a Target> for Origin<'a> {
330    fn from(target: &'a Target) -> Self {
331        Self {
332            value: target.path_query(),
333            path_end: target.path_end - target.authority_end,
334            slash: Slash::Present,
335        }
336    }
337}
338
339impl AsRef<str> for Target {
340    fn as_ref(&self) -> &str {
341        &self.value
342    }
343}
344
345impl str::FromStr for Target {
346    type Err = Error;
347
348    fn from_str(value: &str) -> Result<Self, Self::Err> {
349        if !value.contains("://") {
350            return Self::new(value, Origin::ROOT);
351        }
352        Self::parse(value)
353    }
354}
355
356impl PartialEq for Target {
357    fn eq(&self, other: &Self) -> bool {
358        let scheme = match (self.scheme_str(), other.scheme_str()) {
359            (Some(left), Some(right)) => left.eq_ignore_ascii_case(right),
360            (None, None) => true,
361            _ => false,
362        };
363        scheme
364            && self.authority().eq_ignore_ascii_case(other.authority())
365            && self.path_query() == other.path_query()
366    }
367}
368
369impl Eq for Target {}
370
371fn authority(raw: &str) -> Result<uri::Authority<'_>, Error> {
372    if raw.as_bytes().contains(&b'@') {
373        return Err(Error::UserInfo);
374    }
375    uri::Authority::parse(raw.as_bytes()).map_err(Error::Authority)
376}
377
378fn pack(
379    scheme: Option<&str>,
380    raw: &str,
381    parsed: uri::Authority<'_>,
382    origin: Origin<'_>,
383) -> Result<Target, Error> {
384    let start = match scheme {
385        Some(scheme) => scheme.len().checked_add(3).ok_or(Error::Length)?,
386        None => 0,
387    };
388    let end = start.checked_add(raw.len()).ok_or(Error::Length)?;
389    let capacity = end.checked_add(origin.len()?).ok_or(Error::Length)?;
390    let host_end = start + parsed.host().len();
391    let path_end = end.checked_add(origin.path_end()).ok_or(Error::Length)?;
392    let bounds = plan::Bounds::new(scheme.map_or(0, str::len), host_end, end, path_end)?;
393    let mut value = buffer(capacity)?;
394    if let Some(scheme) = scheme {
395        value.push_str(scheme);
396        value.push_str("://");
397    }
398    value.push_str(raw);
399    origin.append_to(&mut value);
400    // SAFETY: the scheme, authority, and origin filled the exact measured capacity.
401    Ok(bounds.build(unsafe { raw::boxed(value) }))
402}
403
404fn narrow(value: usize) -> Result<u32, Error> {
405    if value > u32::MAX as usize {
406        return Err(Error::Index { value });
407    }
408    Ok(value as u32)
409}
410
411fn buffer(capacity: usize) -> Result<String, Error> {
412    array::Plan::try_new(capacity)
413        .map_err(|_| Error::Length)?
414        .try_string()
415        .map_err(Error::Allocation)
416}
417
418const _: () = assert!(core::mem::size_of::<Absolute<'_>>() <= 9 * core::mem::size_of::<usize>());
419const _: () = assert!(core::mem::size_of::<Slash>() == core::mem::size_of::<bool>());
420const _: () = assert!(core::mem::size_of::<Origin<'_>>() <= 3 * core::mem::size_of::<usize>());
421const _: () = assert!(core::mem::size_of::<Target>() <= 4 * core::mem::size_of::<usize>());