2020-12-29 04:14:15 -06:00
|
|
|
use std::borrow::Cow;
|
|
|
|
use std::fmt;
|
|
|
|
|
|
|
|
use rocket::request::FromParam;
|
|
|
|
|
|
|
|
use rand::{self, distributions::Alphanumeric, Rng};
|
|
|
|
|
|
|
|
pub struct PasteId<'a>(Cow<'a, str>);
|
|
|
|
|
|
|
|
fn valid_id(id: &str) -> bool {
|
|
|
|
id.chars().all(char::is_alphanumeric)
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> PasteId<'a> {
|
|
|
|
pub fn new(size: usize) -> PasteId<'static> {
|
|
|
|
let id: String = rand::thread_rng()
|
|
|
|
.sample_iter(&Alphanumeric)
|
|
|
|
.take(size)
|
|
|
|
.map(char::from)
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
PasteId(Cow::Owned(id))
|
2021-01-21 05:04:59 -06:00
|
|
|
}
|
2020-12-29 04:14:15 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> FromParam<'a> for PasteId<'a> {
|
2021-07-08 08:18:19 -05:00
|
|
|
type Error = &'a str;
|
2020-12-29 04:14:15 -06:00
|
|
|
|
2021-07-08 08:18:19 -05:00
|
|
|
fn from_param(param: &'a str) -> Result<Self, Self::Error> {
|
2020-12-29 04:14:15 -06:00
|
|
|
match valid_id(param) {
|
|
|
|
true => Ok(PasteId(Cow::Borrowed(param))),
|
2021-01-21 05:04:59 -06:00
|
|
|
false => Err(param),
|
2020-12-29 04:14:15 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> fmt::Display for PasteId<'a> {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
write!(f, "{}", self.0)
|
|
|
|
}
|
|
|
|
}
|