Skip to main content

rok/utils/
utils.rs

1#![allow(dead_code)]
2use std::convert::TryFrom;
3use std::future::Future;
4use std::pin::Pin;
5
6use crate::http;
7use crate::http::header::{HeaderName, HeaderValue};
8use rand::distributions::Alphanumeric;
9use rand::Rng;
10
11pub(crate) type BoxFuture<T, E> = Pin<Box<dyn Future<Output=Result<T, E>> + Send + 'static>>;
12pub(crate) type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;
13
14pub(crate) fn parse_header<K, V>(
15    name: K,
16    value: V,
17) -> Result<(HeaderName, HeaderValue), crate::errors::errors::Error>
18    where
19        HeaderName: TryFrom<K>,
20        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
21        HeaderValue: TryFrom<V>,
22        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
23{
24    let name = <HeaderName as TryFrom<K>>::try_from(name).map_err(|e| {
25        let e = e.into();
26        crate::error_message!("parse header name failed, err: {}", e)
27    })?;
28
29    let value = <HeaderValue as TryFrom<V>>::try_from(value).map_err(|e| {
30        let e = e.into();
31        crate::error_message!("parse header value failed, err: {}", e)
32    })?;
33
34    Ok((name, value))
35}
36
37pub(crate) fn gen_random_string(length: usize) -> String {
38    rand::thread_rng()
39        .sample_iter(&Alphanumeric)
40        .map(char::from)
41        .take(length)
42        .collect::<String>()
43}
44
45#[macro_export]
46macro_rules! register_method {
47    ($func_name: ident, $method: expr) => {
48        pub fn $func_name(&mut self, path: impl AsRef<str>, ep: impl Endpoint) {
49            self.register($method, path, ep)
50        }
51    };
52}