collision/
collision.rs

1// Copyright (c) 2023 Tony Barbitta
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use tinyid::TinyId;
8
9fn main() {
10    println!("Generating TinyIds until a collision occurs...");
11    let start = std::time::Instant::now();
12    let iters = get_collision();
13    let elapsed = start.elapsed();
14    let pretty_iters = iters
15        .to_string()
16        .as_bytes()
17        .rchunks(3)
18        .rev()
19        .map(std::str::from_utf8)
20        .collect::<Result<Vec<&str>, _>>()
21        .unwrap()
22        .join(","); // separator
23    println!("Collision after {pretty_iters} iterations.");
24    println!("Elapsed time: {elapsed:#?}");
25}
26
27fn get_collision() -> usize {
28    let mut ids = std::collections::HashSet::new();
29    loop {
30        let id = TinyId::random();
31        if !ids.insert(id) {
32            break;
33        }
34    }
35    ids.len()
36}