2016-12-10 03:56:49 +00:00
|
|
|
use std::fmt;
|
|
|
|
use std::borrow::Cow;
|
|
|
|
|
|
|
|
use rocket::request::FromParam;
|
2017-03-31 07:18:58 +00:00
|
|
|
use rocket::http::RawStr;
|
2016-12-10 03:56:49 +00:00
|
|
|
use rand::{self, Rng};
|
|
|
|
|
2016-12-23 10:38:50 +00:00
|
|
|
/// Table to retrieve base62 values from.
|
2018-07-28 16:58:10 +00:00
|
|
|
const BASE62: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
2016-12-10 03:56:49 +00:00
|
|
|
|
2016-12-23 10:38:50 +00:00
|
|
|
/// A _probably_ unique paste ID.
|
2016-12-10 03:56:49 +00:00
|
|
|
pub struct PasteID<'a>(Cow<'a, str>);
|
|
|
|
|
|
|
|
impl<'a> PasteID<'a> {
|
2016-12-23 10:38:50 +00:00
|
|
|
/// Generate a _probably_ unique ID with `size` characters. For readability,
|
|
|
|
/// the characters used are from the sets [0-9], [A-Z], [a-z]. The
|
2017-08-01 18:38:02 +00:00
|
|
|
/// probability of a collision depends on the value of `size` and the number
|
|
|
|
/// of IDs generated thus far.
|
2016-12-10 03:56:49 +00:00
|
|
|
pub fn new(size: usize) -> PasteID<'static> {
|
|
|
|
let mut id = String::with_capacity(size);
|
|
|
|
let mut rng = rand::thread_rng();
|
|
|
|
for _ in 0..size {
|
|
|
|
id.push(BASE62[rng.gen::<usize>() % 62] as char);
|
|
|
|
}
|
|
|
|
|
|
|
|
PasteID(Cow::Owned(id))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-23 10:38:50 +00:00
|
|
|
impl<'a> fmt::Display for PasteID<'a> {
|
2019-06-13 02:41:29 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2016-12-23 10:38:50 +00:00
|
|
|
write!(f, "{}", self.0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `true` if `id` is a valid paste ID and `false` otherwise.
|
|
|
|
fn valid_id(id: &str) -> bool {
|
|
|
|
id.chars().all(|c| {
|
|
|
|
(c >= 'a' && c <= 'z')
|
|
|
|
|| (c >= 'A' && c <= 'Z')
|
|
|
|
|| (c >= '0' && c <= '9')
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns an instance of `PasteID` if the path segment is a valid ID.
|
|
|
|
/// Otherwise returns the invalid ID as the `Err` value.
|
2016-12-10 03:56:49 +00:00
|
|
|
impl<'a> FromParam<'a> for PasteID<'a> {
|
2017-03-31 07:18:58 +00:00
|
|
|
type Error = &'a RawStr;
|
2016-12-10 03:56:49 +00:00
|
|
|
|
2017-03-31 07:18:58 +00:00
|
|
|
fn from_param(param: &'a RawStr) -> Result<PasteID<'a>, &'a RawStr> {
|
2016-12-10 03:56:49 +00:00
|
|
|
match valid_id(param) {
|
|
|
|
true => Ok(PasteID(Cow::Borrowed(param))),
|
|
|
|
false => Err(param)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|