Skip to main content

nym_http_api_client/
path.rs

1// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4use std::fmt::Debug;
5
6/// Collection of URL Path Segments
7pub type PathSegments<'a> = &'a [&'a str];
8
9fn sanitize_fragment(segment: &str) -> &str {
10    segment.trim_matches(|c: char| c.is_whitespace() || c == '/')
11}
12
13/// Defines a path that can be used to make a request to an API.
14pub trait RequestPath: Debug {
15    /// Sanitise the request path by removing empty segments and trimming whitespace and slashes
16    fn to_sanitized_segments(&self) -> Vec<&str>;
17}
18
19macro_rules! impl_stringified_sanitized_segments {
20    ($frag_iter:expr) => {{
21        let mut path_segments = Vec::new();
22
23        for segment in $frag_iter {
24            if !segment.is_empty() {
25                path_segments.push(sanitize_fragment(segment));
26            }
27        }
28
29        path_segments
30    }};
31}
32
33impl RequestPath for PathSegments<'_> {
34    fn to_sanitized_segments(&self) -> Vec<&str> {
35        impl_stringified_sanitized_segments!(self.iter())
36    }
37}
38
39impl<const N: usize> RequestPath for &[&str; N] {
40    fn to_sanitized_segments(&self) -> Vec<&str> {
41        impl_stringified_sanitized_segments!(self.iter())
42    }
43}
44
45impl RequestPath for &str {
46    fn to_sanitized_segments(&self) -> Vec<&str> {
47        impl_stringified_sanitized_segments!(self.split('/'))
48    }
49}
50
51impl RequestPath for String {
52    fn to_sanitized_segments(&self) -> Vec<&str> {
53        impl_stringified_sanitized_segments!(self.split('/'))
54    }
55}
56
57impl RequestPath for &String {
58    fn to_sanitized_segments(&self) -> Vec<&str> {
59        impl_stringified_sanitized_segments!(self.split('/'))
60    }
61}