Skip to main content

endpoint_libs/
lib.rs

1#![cfg_attr(test, allow(deprecated))]
2#![cfg_attr(not(any(feature = "std", feature = "std-deps")), no_std)]
3
4extern crate alloc;
5
6#[cfg(not(any(feature = "std", feature = "std-deps")))]
7#[doc(hidden)]
8pub mod eyre {
9    use alloc::boxed::Box;
10    use alloc::format;
11    use alloc::string::{String, ToString};
12    use core::any::Any;
13    use core::fmt::{self, Debug, Display};
14
15    pub type Result<T, E = Report> = core::result::Result<T, E>;
16    pub type Error = Report;
17
18    pub trait EyreHandler: Any + Send + Sync {
19        fn display(
20            &self,
21            error: &(dyn core::error::Error + 'static),
22            f: &mut fmt::Formatter<'_>,
23        ) -> fmt::Result;
24
25        fn debug(
26            &self,
27            error: &(dyn core::error::Error + 'static),
28            f: &mut fmt::Formatter<'_>,
29        ) -> fmt::Result;
30
31        fn track_caller(&mut self, _location: &'static core::panic::Location<'static>) {}
32    }
33
34    pub struct DefaultHandler;
35
36    impl DefaultHandler {
37        pub fn default_with(_error: &(dyn core::error::Error + 'static)) -> Box<dyn EyreHandler> {
38            Box::new(DefaultHandler)
39        }
40    }
41
42    impl EyreHandler for DefaultHandler {
43        fn display(
44            &self,
45            error: &(dyn core::error::Error + 'static),
46            f: &mut fmt::Formatter<'_>,
47        ) -> fmt::Result {
48            Display::fmt(error, f)
49        }
50
51        fn debug(
52            &self,
53            error: &(dyn core::error::Error + 'static),
54            f: &mut fmt::Formatter<'_>,
55        ) -> fmt::Result {
56            Debug::fmt(error, f)
57        }
58    }
59
60    trait ErrorObj: Any + Send + Sync + Display + Debug {
61        fn as_any(&self) -> &(dyn Any + Send + Sync);
62        fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync>;
63        fn as_core_error(&self) -> &(dyn core::error::Error + 'static);
64    }
65
66    struct WrappedError<E>(E);
67
68    impl<E: Display> Display for WrappedError<E> {
69        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70            Display::fmt(&self.0, f)
71        }
72    }
73
74    impl<E: Debug> Debug for WrappedError<E> {
75        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76            Debug::fmt(&self.0, f)
77        }
78    }
79
80    impl<E: Display + Debug> core::error::Error for WrappedError<E> {}
81
82    impl<E: Display + Debug + Send + Sync + 'static> ErrorObj for WrappedError<E> {
83        fn as_any(&self) -> &(dyn Any + Send + Sync) {
84            &self.0
85        }
86        fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync> {
87            Box::new(self.0)
88        }
89        fn as_core_error(&self) -> &(dyn core::error::Error + 'static) {
90            self
91        }
92    }
93
94    pub struct Report {
95        inner: Box<dyn ErrorObj>,
96        handler: Box<dyn EyreHandler>,
97    }
98
99    impl Report {
100        #[track_caller]
101        pub fn new<E>(error: E) -> Self
102        where
103            E: Display + Debug + Send + Sync + 'static,
104        {
105            let location = core::panic::Location::caller();
106            let wrapped = Box::new(WrappedError(error));
107            let mut handler = DefaultHandler::default_with(wrapped.as_core_error());
108            handler.track_caller(location);
109            Self {
110                inner: wrapped,
111                handler,
112            }
113        }
114
115        #[track_caller]
116        pub fn msg<M>(message: M) -> Self
117        where
118            M: Display + Debug + Send + Sync + 'static,
119        {
120            Self::new(message)
121        }
122
123        pub fn wrap_err<D>(self, msg: D) -> Self
124        where
125            D: Display + Send + Sync + 'static,
126        {
127            Self::msg(format!("{msg}: {}", self.inner))
128        }
129
130        pub fn handler(&self) -> &(dyn Any + Send + Sync) {
131            &*self.handler
132        }
133
134        pub fn is<T: Any + Send + Sync + 'static>(&self) -> bool {
135            self.inner.as_any().is::<T>()
136        }
137
138        pub fn downcast_ref<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
139            self.inner.as_any().downcast_ref::<T>()
140        }
141
142        pub fn downcast<T: Any + Send + Sync + 'static>(self) -> core::result::Result<T, Self> {
143            if self.is::<T>() {
144                match self.inner.into_any().downcast::<T>() {
145                    Ok(boxed) => Ok(*boxed),
146                    Err(_) => unreachable!(),
147                }
148            } else {
149                Err(self)
150            }
151        }
152    }
153
154    impl AsRef<dyn core::error::Error + 'static> for Report {
155        fn as_ref(&self) -> &(dyn core::error::Error + 'static) {
156            self.inner.as_core_error()
157        }
158    }
159
160    impl Display for Report {
161        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162            self.handler.display(self.inner.as_core_error(), f)
163        }
164    }
165
166    impl Debug for Report {
167        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168            self.handler.debug(self.inner.as_core_error(), f)
169        }
170    }
171
172    impl<E> From<E> for Report
173    where
174        E: core::error::Error + Send + Sync + 'static,
175    {
176        #[track_caller]
177        fn from(error: E) -> Self {
178            Self::new(error)
179        }
180    }
181
182    pub trait WrapErr<T, E> {
183        fn wrap_err<D>(self, msg: D) -> Result<T, Report>
184        where
185            D: Display + Send + Sync + 'static;
186
187        fn wrap_err_with<D, F>(self, f: F) -> Result<T, Report>
188        where
189            D: Display + Send + Sync + 'static,
190            F: FnOnce() -> D;
191
192        fn context<D>(self, msg: D) -> Result<T, Report>
193        where
194            D: Display + Send + Sync + 'static,
195            Self: Sized,
196        {
197            self.wrap_err(msg)
198        }
199
200        fn with_context<D, F>(self, f: F) -> Result<T, Report>
201        where
202            D: Display + Send + Sync + 'static,
203            F: FnOnce() -> D,
204            Self: Sized,
205        {
206            self.wrap_err_with(f)
207        }
208    }
209
210    pub use WrapErr as Context;
211
212    impl<T, E> WrapErr<T, E> for core::result::Result<T, E>
213    where
214        E: Into<Report>,
215    {
216        #[track_caller]
217        fn wrap_err<D>(self, msg: D) -> Result<T, Report>
218        where
219            D: Display + Send + Sync + 'static,
220        {
221            match self {
222                Ok(v) => Ok(v),
223                Err(e) => Err(e.into().wrap_err(msg)),
224            }
225        }
226
227        #[track_caller]
228        fn wrap_err_with<D, F>(self, f: F) -> Result<T, Report>
229        where
230            D: Display + Send + Sync + 'static,
231            F: FnOnce() -> D,
232        {
233            match self {
234                Ok(v) => Ok(v),
235                Err(e) => Err(e.into().wrap_err(f())),
236            }
237        }
238    }
239
240    pub trait ContextCompat<T> {
241        fn context<D>(self, msg: D) -> Result<T, Report>
242        where
243            D: Display + Send + Sync + 'static;
244
245        fn with_context<D, F>(self, f: F) -> Result<T, Report>
246        where
247            D: Display + Send + Sync + 'static,
248            F: FnOnce() -> D;
249
250        fn wrap_err<D>(self, msg: D) -> Result<T, Report>
251        where
252            D: Display + Send + Sync + 'static,
253            Self: Sized,
254        {
255            self.context(msg)
256        }
257
258        fn wrap_err_with<D, F>(self, f: F) -> Result<T, Report>
259        where
260            D: Display + Send + Sync + 'static,
261            F: FnOnce() -> D,
262            Self: Sized,
263        {
264            self.with_context(f)
265        }
266    }
267
268    impl<T> ContextCompat<T> for Option<T> {
269        #[track_caller]
270        fn context<D>(self, msg: D) -> Result<T, Report>
271        where
272            D: Display + Send + Sync + 'static,
273        {
274            match self {
275                Some(v) => Ok(v),
276                None => Err(Report::msg(msg.to_string())),
277            }
278        }
279
280        #[track_caller]
281        fn with_context<D, F>(self, f: F) -> Result<T, Report>
282        where
283            D: Display + Send + Sync + 'static,
284            F: FnOnce() -> D,
285        {
286            match self {
287                Some(v) => Ok(v),
288                None => Err(Report::msg(f().to_string())),
289            }
290        }
291    }
292
293    pub use crate::{
294        __endpoint_libs_bail as bail, __endpoint_libs_ensure as ensure,
295        __endpoint_libs_eyre as eyre,
296    };
297}
298
299#[cfg(not(any(feature = "std", feature = "std-deps")))]
300#[doc(hidden)]
301#[macro_export]
302macro_rules! __endpoint_libs_eyre {
303    ($msg:literal $(,)?) => {
304        $crate::eyre::Report::msg(::alloc::format!($msg))
305    };
306    ($err:expr $(,)?) => {
307        $crate::eyre::Report::msg(::alloc::format!("{}", $err))
308    };
309    ($fmt:expr, $($arg:tt)*) => {
310        $crate::eyre::Report::msg(::alloc::format!($fmt, $($arg)*))
311    };
312}
313
314#[cfg(not(any(feature = "std", feature = "std-deps")))]
315#[doc(hidden)]
316#[macro_export]
317macro_rules! __endpoint_libs_bail {
318    ($($tt:tt)*) => {
319        return ::core::result::Result::Err($crate::__endpoint_libs_eyre!($($tt)*))
320    };
321}
322
323#[cfg(not(any(feature = "std", feature = "std-deps")))]
324#[doc(hidden)]
325#[macro_export]
326macro_rules! __endpoint_libs_ensure {
327    ($cond:expr, $($tt:tt)*) => {
328        if !($cond) {
329            $crate::__endpoint_libs_bail!($($tt)*);
330        }
331    };
332    ($cond:expr) => {
333        if !($cond) {
334            $crate::__endpoint_libs_bail!(concat!("Condition failed: `", stringify!($cond), "`"));
335        }
336    };
337}
338
339#[cfg(not(feature = "std"))]
340#[doc(hidden)]
341pub mod convert_case {
342    use alloc::string::String;
343    use alloc::vec::Vec;
344
345    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
346    pub enum Case {
347        Snake,
348        Camel,
349        Pascal,
350    }
351
352    fn split_words(input: &str) -> Vec<String> {
353        let mut words = Vec::new();
354        let mut current = String::new();
355        let chars: Vec<char> = input.chars().collect();
356        for i in 0..chars.len() {
357            let ch = chars[i];
358            if !ch.is_alphanumeric() {
359                if !current.is_empty() {
360                    words.push(core::mem::take(&mut current));
361                }
362                continue;
363            }
364            if i > 0 && ch.is_uppercase() {
365                let prev = chars[i - 1];
366                let next_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase());
367                if prev.is_lowercase() || prev.is_numeric() || (prev.is_uppercase() && next_lower) {
368                    if !current.is_empty() {
369                        words.push(core::mem::take(&mut current));
370                    }
371                }
372            }
373            current.push(ch);
374        }
375        if !current.is_empty() {
376            words.push(current);
377        }
378        words
379    }
380
381    fn capitalize(word: &str) -> String {
382        let mut chars = word.chars();
383        match chars.next() {
384            None => String::new(),
385            Some(first) => {
386                let mut out = String::new();
387                for c in first.to_uppercase() {
388                    out.push(c);
389                }
390                for c in chars {
391                    for lc in c.to_lowercase() {
392                        out.push(lc);
393                    }
394                }
395                out
396            }
397        }
398    }
399
400    fn lowercase(word: &str) -> String {
401        let mut out = String::new();
402        for c in word.chars() {
403            for lc in c.to_lowercase() {
404                out.push(lc);
405            }
406        }
407        out
408    }
409
410    pub trait Casing {
411        fn to_case(&self, case: Case) -> String;
412    }
413
414    impl<T: AsRef<str> + ?Sized> Casing for T {
415        fn to_case(&self, case: Case) -> String {
416            let words = split_words(self.as_ref());
417            match case {
418                Case::Snake => {
419                    let mut out = String::new();
420                    for (i, w) in words.iter().enumerate() {
421                        if i > 0 {
422                            out.push('_');
423                        }
424                        out.push_str(&lowercase(w));
425                    }
426                    out
427                }
428                Case::Pascal => {
429                    let mut out = String::new();
430                    for w in &words {
431                        out.push_str(&capitalize(w));
432                    }
433                    out
434                }
435                Case::Camel => {
436                    let mut out = String::new();
437                    for (i, w) in words.iter().enumerate() {
438                        if i == 0 {
439                            out.push_str(&lowercase(w));
440                        } else {
441                            out.push_str(&capitalize(w));
442                        }
443                    }
444                    out
445                }
446            }
447        }
448    }
449}
450
451#[cfg(not(feature = "std"))]
452#[doc(hidden)]
453pub mod urlencoding {
454    use alloc::borrow::Cow;
455    use alloc::string::String;
456    use alloc::vec::Vec;
457    use core::fmt;
458
459    #[derive(Debug)]
460    pub struct FromUrlEncodingError;
461
462    impl fmt::Display for FromUrlEncodingError {
463        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464            f.write_str("invalid percent-encoded UTF-8 sequence")
465        }
466    }
467
468    impl core::error::Error for FromUrlEncodingError {}
469
470    pub fn encode(data: &str) -> Cow<'_, str> {
471        let bytes = data.as_bytes();
472        let safe = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~');
473        if bytes.iter().copied().all(safe) {
474            return Cow::Borrowed(data);
475        }
476        const HEX: &[u8; 16] = b"0123456789ABCDEF";
477        let mut out = String::with_capacity(bytes.len() * 3);
478        for &b in bytes {
479            if safe(b) {
480                out.push(b as char);
481            } else {
482                out.push('%');
483                out.push(HEX[(b >> 4) as usize] as char);
484                out.push(HEX[(b & 0x0f) as usize] as char);
485            }
486        }
487        Cow::Owned(out)
488    }
489
490    pub fn decode(data: &str) -> Result<Cow<'_, str>, FromUrlEncodingError> {
491        let bytes = data.as_bytes();
492        if !bytes.contains(&b'%') {
493            return Ok(Cow::Borrowed(data));
494        }
495        let hex = |b: u8| -> Result<u8, FromUrlEncodingError> {
496            match b {
497                b'0'..=b'9' => Ok(b - b'0'),
498                b'a'..=b'f' => Ok(b - b'a' + 10),
499                b'A'..=b'F' => Ok(b - b'A' + 10),
500                _ => Err(FromUrlEncodingError),
501            }
502        };
503        let mut out = Vec::with_capacity(bytes.len());
504        let mut i = 0;
505        while i < bytes.len() {
506            if bytes[i] == b'%' {
507                if i + 2 >= bytes.len() {
508                    return Err(FromUrlEncodingError);
509                }
510                out.push((hex(bytes[i + 1])? << 4) | hex(bytes[i + 2])?);
511                i += 3;
512            } else {
513                out.push(bytes[i]);
514                i += 1;
515            }
516        }
517        String::from_utf8(out)
518            .map(Cow::Owned)
519            .map_err(|_| FromUrlEncodingError)
520    }
521}
522
523pub mod libs;
524#[cfg(feature = "types")]
525pub mod model;