Skip to main content

endpoint_libs/
lib.rs

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