id_manager/
time.rs

1use chrono::prelude::*;
2
3/// Generates a random ID with the prefix followed by a
4/// timestamp and random characters.
5pub fn with_prefix(pfx: &str) -> String {
6    format!(
7        "{}-{}-{}",
8        pfx,
9        timestamp(6),
10        random_manager::secure_string(6)
11    )
12}
13
14/// RUST_LOG=debug cargo test --all-features --package id-manager --lib -- time::test_with_prefix --exact --show-output
15#[test]
16fn test_with_prefix() {
17    use log::info;
18    use std::{thread, time};
19    let _ = env_logger::builder()
20        .filter_level(log::LevelFilter::Info)
21        .is_test(true)
22        .try_init();
23
24    let ts1 = with_prefix("hello");
25    thread::sleep(time::Duration::from_millis(1001));
26    let ts2 = with_prefix("hello");
27    assert_ne!(ts1, ts2);
28
29    info!("ts1: {:?}", ts1);
30    info!("ts2: {:?}", ts2);
31}
32
33/// Gets the current timestamp in concatenated string format.
34pub fn timestamp(n: usize) -> String {
35    let local: DateTime<Local> = Local::now();
36    let mut d = format!(
37        "{}{:02}{:02}{:02}{:02}",
38        local.year(),
39        local.month(),
40        local.day(),
41        local.hour(),
42        local.second(),
43    );
44    if d.len() > n {
45        d.truncate(n);
46    }
47    d
48}
49
50/// RUST_LOG=debug cargo test --all-features --package id-manager --lib -- time::test_timestamp --exact --show-output
51#[test]
52fn test_timestamp() {
53    use log::info;
54    use std::{thread, time};
55    let _ = env_logger::builder()
56        .filter_level(log::LevelFilter::Info)
57        .is_test(true)
58        .try_init();
59
60    let ts1 = timestamp(12);
61    thread::sleep(time::Duration::from_millis(1001));
62    let ts2 = timestamp(12);
63    assert_ne!(ts1, ts2);
64
65    info!("ts1: {:?}", ts1);
66    info!("ts2: {:?}", ts2);
67}