basic/
basic.rs

1use std::str::FromStr;
2
3use tinyid::TinyId;
4
5fn main() {
6    // Create a random ID
7    let rand_id = TinyId::random();
8
9    // Parse a string into a Result<TinyId, TinyIdError> for possibly unsafe / invalid ID strings
10    let maybe = TinyId::from_str("AAAABBBB");
11    assert!(maybe.is_ok());
12    let bad = TinyId::from_str("AAAABBB");
13    assert!(bad.is_err());
14
15    // Parse a string you **KNOW** is safe into a TinyId
16    let parsed = TinyId::from_str_unchecked("AAAABBBB");
17
18    // All expected operations are available on TinyIds
19    // Equality is a simple byte comparison so it should be fast and cheap!
20    assert_eq!(maybe.unwrap(), parsed);
21
22    // IDs may be printed using Display or Debug
23    println!("Random ID: {rand_id}");
24    println!("Parsed ID: {parsed}");
25    println!(" Debug ID: {parsed:?}");
26
27    // IDs are small!
28    println!("TinyID Size: {}", std::mem::size_of::<TinyId>());
29
30    // IDs are case-sensitive
31    let parsed2 = TinyId::from_str_unchecked("aaaaBBBB");
32    assert_ne!(parsed, parsed2);
33
34    // Check whether an ID starts with a given string. Example use case would be providing a
35    // list of IDs to a user, and asking for a partial string to match against so the user
36    // doesn't have to type the entire thing.
37    assert!(parsed.starts_with("AAAA"));
38    assert!(parsed.ends_with("BBBB"));
39    assert!(!parsed.starts_with("BBBB"));
40
41    // IDs are copied when assigned.
42    let mut switched = parsed;
43    assert_eq!(switched, parsed);
44
45    // Validity can be checked, and a "marker" exists for null / invalid IDs.
46    assert!(switched.is_valid());
47    assert!(!switched.is_null());
48    assert_ne!(switched, TinyId::null());
49    // Mutable IDs can be made null. This change has no effect on the `parsed` variable.
50    switched.make_null();
51    assert!(!switched.is_valid());
52    assert!(switched.is_null());
53    assert_eq!(switched, TinyId::null());
54}