Rocket/examples/pastebin/src/paste_id.rs

58 lines
1.7 KiB
Rust
Raw Normal View History

2016-12-10 03:56:49 +00:00
use std::fmt;
use std::borrow::Cow;
use rocket::request::FromParam;
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
/// 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> {
type Error = &'a RawStr;
2016-12-10 03:56:49 +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)
}
}
}