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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
|
use std::fmt;
use rand::{seq::SliceRandom, thread_rng};
use serde::{Deserializer, Serializer};
use sqlx::{Database, Decode, Encode, Type, encode::IsNull};
// 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);
// Implementations of prefix provide type tokens for IDs where a new value can be generated, with a
// known prefix. Most implementations should also implement Default and be zero-sized types without
// state, as many of the operations on Ids will discard or re-create type tokens (using
// `Default::default()`) when converting between an ID type and some external form.
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> Id<T> {
pub fn as_str(&self) -> &str {
let Self(value, _) = self;
value
}
fn inner(&self) -> &String {
let Self(value, _) = self;
value
}
}
// Any ID can be converted to a string. Its type token is discarded during the conversion.
impl<T> From<Id<T>> for String {
fn from(value: Id<T>) -> Self {
let Id(value, _) = value;
value
}
}
// If the type token implements `Default`, then the corresponding ID type can be converted from a
// string. A new type token will be generated using `T::default()`.
impl<T> From<String> for Id<T>
where
T: Default,
{
fn from(value: String) -> Self {
Self(value, T::default())
}
}
// IDs are printable, exactly as their contained string is printable.
impl<T> fmt::Display for Id<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner().fmt(f)
}
}
// IDs are serializable, exactly as their contained string is serializable. The type token is
// discarded during serialization.
impl<T> serde::ser::Serialize for Id<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.inner().serialize(serializer)
}
}
// If the type token implements `Default`, then the corresponding ID type is deserializable as a
// String. A new type token will be generated using `T::default()` during deserialization.
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 id = String::deserialize(deserializer)?;
Ok(id.into())
}
}
// An ID is an sqlx database type for any database where String is a database type. In practice,
// that's all of them.
//
// This is largely cribbed from the implementation generated by `#[sqlx::transparent]`, but we
// implement it by hand here in order to handle the fact that an ID has two contained values,
// rather than one.
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)
}
}
// If the type token implements Default, then the corresponding ID type can be decoded as a String
// from a database record. A new type token will be generated using `T::default()` during decoding.
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 id = String::decode(value)?;
Ok(id.into())
}
}
// An ID is encodeable to a database value whenever String is encodeable. The type token is
// discarded during encoding.
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> {
self.inner().encode(buf)
}
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer<'q>,
) -> Result<IsNull, sqlx::error::BoxDynError> {
self.inner().encode_by_ref(buf)
}
fn produces(&self) -> Option<<DB as Database>::TypeInfo> {
self.inner().produces()
}
fn size_hint(&self) -> usize {
self.inner().size_hint()
}
}
|