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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use rand::{thread_rng, Rng};
use serde::{de::Visitor, Deserialize};
use std::{
    fmt::{Debug, Display},
    str::FromStr,
};
use uuid::Uuid;

/// By the Hull-Dobell theorem, the period of a linear congruential generator
/// with c=1 will have a period of m iff the multiplier `a` satisfies:
/// - a - 1 is divisible by all prime factors of m
/// - a - 1 is divisible by 4 if m is divisible by 4
///
/// Our LCG is used to pick sequences of n > 3 letters, for which there are
/// 26^n possibilities. The prime factors of m are therefore 2 and 13, and
/// m is divisible by 4 for n>1. 52 is the lowest number that divides 2, 13,
/// and 4, so we use 52+1 = 53 as the multiplier.
const LCG_MULTIPLIER: u64 = 53;

const ASCII_A: u32 = 0x41;

const SHORTEST_SHORT_NAME: u32 = 3;
const LONGEST_SHORT_NAME: u32 = 13;

/// Trait for objects capable of generating a user ID.
pub trait RoomIdGenerator: Debug + Send + Sync {
    fn generate(&mut self) -> String;
}

/// Generates short, upper-case alphabetical IDs of a given length.
///
/// The ID generation algorithm is designed not to reuse an ID until
/// all potential IDs have been exhausted.
#[derive(Debug)]
pub struct ShortRoomIdGenerator {
    state: u64,
    offset: u64,
    m: u64,
    length: u32,
}

impl RoomIdGenerator for ShortRoomIdGenerator {
    fn generate(&mut self) -> String {
        self.state = (LCG_MULTIPLIER * self.state + 1) % self.m;
        let mut val = (self.state + self.offset) % self.m;

        let mut chars: Vec<char> = Vec::with_capacity(self.length as usize);

        for _ in 0..self.length {
            #[allow(clippy::cast_possible_truncation)]
            let c = (val % 26) as u32;
            chars.push(
                char::from_u32(c + ASCII_A).expect("Should always be a valid ASCII character."),
            );
            val /= 26;
        }

        chars.iter().collect()
    }
}

impl ShortRoomIdGenerator {
    /// Construct a ShortRoomIdGenerator for the given length.
    ///
    /// Calls to this constructor are non-deterministic, because
    /// some random entropy is baked into the generator.
    #[must_use]
    pub fn new(length: u32) -> Self {
        let mut rng = thread_rng();
        let m = 26_u64.pow(length as u32);
        let offset = rng.gen_range(0..m);
        let seed_state = rng.gen_range(0..m);

        Self {
            state: seed_state,
            offset,
            m,
            length,
        }
    }
}

/// Factory for creating a [[ShortRoomIdGenerator]].
#[derive(Debug)]
pub struct ShortRoomIdGeneratorFactory(pub u32);

impl ShortRoomIdGeneratorFactory {
    #[must_use]
    pub fn new(length: u32) -> Self {
        ShortRoomIdGeneratorFactory(length)
    }
}

impl RoomIdGeneratorFactory for ShortRoomIdGeneratorFactory {
    fn build(&self) -> Box<dyn RoomIdGenerator> {
        let generator = ShortRoomIdGenerator::new(self.0);
        Box::new(generator)
    }
}

#[derive(Debug)]
pub struct UuidRoomIdGeneratorFactory;

impl RoomIdGeneratorFactory for UuidRoomIdGeneratorFactory {
    fn build(&self) -> Box<dyn RoomIdGenerator> {
        Box::new(UuidRoomIdGenerator)
    }
}

/// Assigns a user ID from a UUID.
#[derive(Debug)]
pub struct UuidRoomIdGenerator;

pub trait RoomIdGeneratorFactory: Debug {
    fn build(&self) -> Box<dyn RoomIdGenerator>;
}

impl RoomIdGenerator for UuidRoomIdGenerator {
    fn generate(&mut self) -> String {
        let my_uuid = Uuid::new_v4();
        my_uuid.to_string()
    }
}

/// Determines how new rooms are assigned an id.
#[derive(Debug)]
pub enum RoomIdStrategy {
    /// Rooms are created when they are first accessed.
    Implicit,
    /// Rooms are created with an explicit API call that provides an ID.
    Explicit,
    /// Room IDs are created by an endpoint, which returns an ID
    /// generated by the provided generator.
    Generator(Box<dyn RoomIdGeneratorFactory + Send + Sync>),
}

struct RoomIdStrategyVisitor;

impl<'de> Visitor<'de> for RoomIdStrategyVisitor {
    type Value = RoomIdStrategy;

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        RoomIdStrategy::from_str(v)
            .map_err(|_| serde::de::Error::custom("Could not parse RoomIdStrategy."))
    }

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("A string like {short, uuid, api, implicit}.")
    }
}

impl<'de> Deserialize<'de> for RoomIdStrategy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(RoomIdStrategyVisitor)
    }
}

impl RoomIdStrategy {
    #[must_use]
    pub fn explicit_room_creation_allowed(&self) -> bool {
        match self {
            RoomIdStrategy::Explicit | RoomIdStrategy::Implicit => true,
            RoomIdStrategy::Generator(_) => false,
        }
    }

    #[must_use]
    pub fn implicit_room_creation_allowed(&self) -> bool {
        match self {
            RoomIdStrategy::Explicit | RoomIdStrategy::Generator(_) => false,
            RoomIdStrategy::Implicit => true,
        }
    }

    #[must_use]
    pub fn try_generator(&self) -> Option<Box<dyn RoomIdGenerator>> {
        match self {
            RoomIdStrategy::Explicit => None,
            RoomIdStrategy::Implicit => Some(UuidRoomIdGeneratorFactory.build()),
            RoomIdStrategy::Generator(factory) => Some(factory.build()),
        }
    }
}

impl Default for RoomIdStrategy {
    fn default() -> Self {
        RoomIdStrategy::Implicit
    }
}

#[derive(Debug)]
pub struct BadGeneratorName(String);

impl Display for BadGeneratorName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Bad room ID generator '{}', expected one of {{singleton,short,uuid,api,implicit}}.",
            self.0
        )
    }
}

impl std::error::Error for BadGeneratorName {}

impl FromStr for RoomIdStrategy {
    type Err = BadGeneratorName;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "api" => Ok(RoomIdStrategy::Explicit),
            "implicit" => Ok(RoomIdStrategy::Implicit),
            "short" => Ok(RoomIdStrategy::Generator(Box::new(
                ShortRoomIdGeneratorFactory(4),
            ))),
            "uuid" => Ok(RoomIdStrategy::Generator(Box::new(
                UuidRoomIdGeneratorFactory,
            ))),
            _ if s.starts_with("short") => {
                if let Some(num) = s.strip_prefix("short") {
                    let n: u32 = num.parse().map_err(|_| BadGeneratorName(s.to_string()))?;

                    if !(SHORTEST_SHORT_NAME..LONGEST_SHORT_NAME).contains(&n) {
                        return Err(BadGeneratorName(s.to_string()));
                    }

                    Ok(RoomIdStrategy::Generator(Box::new(
                        ShortRoomIdGeneratorFactory(n),
                    )))
                } else {
                    panic!() // Should never get here.
                }
            }
            _ => Err(BadGeneratorName(s.to_string())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use matches::assert_matches;

    #[test]
    fn test_parse_room_id_strategy() {
        assert_matches!(
            RoomIdStrategy::from_str("api").unwrap(),
            RoomIdStrategy::Explicit
        );
        assert_matches!(
            RoomIdStrategy::from_str("implicit").unwrap(),
            RoomIdStrategy::Implicit
        );
        assert_matches!(
            RoomIdStrategy::from_str("short").unwrap(),
            RoomIdStrategy::Generator(_)
        );
        assert_matches!(
            RoomIdStrategy::from_str("short5").unwrap(),
            RoomIdStrategy::Generator(_)
        );
        assert_matches!(
            RoomIdStrategy::from_str("uuid").unwrap(),
            RoomIdStrategy::Generator(_)
        );
    }

    #[test]
    fn test_length() {
        if let RoomIdStrategy::Generator(g) = RoomIdStrategy::from_str("uuid").unwrap() {
            let result = g.build().generate();
            assert_eq!(36, result.len())
        } else {
            panic!("Expected RoomIdStrategy::Generator.")
        }

        if let RoomIdStrategy::Generator(g) = RoomIdStrategy::from_str("short6").unwrap() {
            let result = g.build().generate();
            assert_eq!(6, result.len())
        } else {
            panic!("Expected RoomIdStrategy::Generator.")
        }

        if let RoomIdStrategy::Generator(g) = RoomIdStrategy::from_str("short").unwrap() {
            let result = g.build().generate();
            assert_eq!(4, result.len())
        } else {
            panic!("Expected RoomIdStrategy::Generator.")
        }
    }
}