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