1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
|
use rand::{seq::SliceRandom, thread_rng};
use serde::{Deserializer, Serializer};
use sqlx::encode::IsNull;
use sqlx::{Database, Decode, Encode, Type};
use std::fmt;
// Make IDs that:
//
// * Do not require escaping in URLs
// * Do not require escaping in hostnames
// * Are unique up to case conversion
// * Are relatively unlikely to contain cursewords
// * Are relatively unlikely to contain visually similar characters in most
// typefaces
// * Are not sequential
//
// This leaves 23 ASCII characters, or about 4.52 bits of entropy per character
// if generated with uniform probability.
const ALPHABET: [char; 23] = [
'1', '2', '3', '4', '6', '7', '8', '9', 'b', 'c', 'd', 'f', 'h', 'j', 'k', 'n', 'p', 'r', 's',
't', 'w', 'x', 'y',
];
// Pick enough characters per ID to make accidental collisions "acceptably"
// unlikely without also making them _too_ unwieldy. This gives a fraction under
// 68 bits per ID.
const ID_SIZE: usize = 15;
// Intended to be wrapped in a type aliases that specalizes Id on a type that
// implements Prefix, both so that IDs are type-wise distinct within the server
// and so that IDs are readily distinguishable from one another outside of it.
//
// By convention, the prefix should be UPPERCASE - note that the alphabet for
// this is entirely lowercase.
//
// To build a new ID type, create a "marker" type that implements this trait, plus the following list of derives:
//
// ```
// #[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
// pub struct Person;
//
// impl crate::id::Prefix for Person {
// fn prefix(&self) -> &str {
// "P" // try not to conflict with other prefixes
// }
// }
// ```
//
// Then provide a type alias of the form
//
// ```
// pub type Id = crate::id::Id<Person>;
// ```
//
// The `Id` type will provide a `generate()` method that can generate new random IDs, and the
// resulting type alias can be serialized to and deserialized from strings, and stored in string
// compatible database columns.
#[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub struct Id<T>(String, T);
impl<T> fmt::Display for Id<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub trait Prefix {
fn prefix(&self) -> &str;
}
impl<T> Id<T>
where
T: Prefix + Default,
{
pub fn generate() -> Self {
let instance = T::default();
let prefix = instance.prefix();
let random_part = (0..ID_SIZE)
.filter_map(|_| ALPHABET.choose(&mut thread_rng()))
.copied();
let id = prefix.chars().chain(random_part).collect();
Self(id, instance)
}
}
impl<T> serde::ser::Serialize for Id<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let Self(id, _) = self;
id.serialize(serializer)
}
}
impl<'de, T> serde::de::Deserialize<'de> for Id<T>
where
T: Default,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let instance = T::default();
let id = String::deserialize(deserializer)?;
Ok(Self(id, instance))
}
}
// Type is manually implemented so that we can implement Decode to do
// recover the type token on read. Implementation is otherwise based on
// `#[derive(sqlx::Type)]` with the `#[sqlx(transparent)]` attribute.
impl<DB, T> Type<DB> for Id<T>
where
DB: Database,
String: Type<DB>,
{
fn type_info() -> <DB as Database>::TypeInfo {
<String as Type<DB>>::type_info()
}
fn compatible(ty: &<DB as Database>::TypeInfo) -> bool {
<String as Type<DB>>::compatible(ty)
}
}
impl<'r, DB, T> Decode<'r, DB> for Id<T>
where
DB: Database,
String: Decode<'r, DB>,
T: Default,
{
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
let instance = T::default();
let id = String::decode(value)?;
Ok(Self(id, instance))
}
}
impl<'q, DB, T> Encode<'q, DB> for Id<T>
where
DB: Database,
String: Encode<'q, DB>,
{
fn encode(
self,
buf: &mut <DB as Database>::ArgumentBuffer<'q>,
) -> Result<IsNull, sqlx::error::BoxDynError> {
let Self(id, _) = self;
id.encode(buf)
}
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer<'q>,
) -> Result<IsNull, sqlx::error::BoxDynError> {
let Self(id, _) = self;
id.encode_by_ref(buf)
}
fn produces(&self) -> Option<<DB as Database>::TypeInfo> {
let Self(id, _) = self;
id.produces()
}
fn size_hint(&self) -> usize {
let Self(id, _) = self;
id.size_hint()
}
}
|