File: wasm32-datetime.rs

package info (click to toggle)
rust-ulid 1.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 252 kB
  • sloc: makefile: 19; sh: 1
file content (78 lines) | stat: -rw-r--r-- 1,879 bytes parent folder | download | duplicates (3)
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
#![cfg(all(target_arch = "wasm32", target_os = "unknown"))]

use ulid::Ulid;

use wasm_bindgen_test::*;
use web_time::web::SystemTimeExt;

use std::time::{Duration, SystemTime};

fn now() -> std::time::SystemTime {
    return web_time::SystemTime::now().to_std();
}

#[wasm_bindgen_test]
fn test_dynamic() {
    let ulid = Ulid::new();
    let encoded = ulid.to_string();
    let ulid2 = Ulid::from_string(&encoded).expect("failed to deserialize");

    println!("{}", encoded);
    println!("{:?}", ulid);
    println!("{:?}", ulid2);
    assert_eq!(ulid, ulid2);
}

#[wasm_bindgen_test]
fn test_source() {
    use rand::rngs::mock::StepRng;
    let mut source = StepRng::new(123, 0);

    let u1 = Ulid::with_source(&mut source);
    let dt = now() + Duration::from_millis(1);
    let u2 = Ulid::from_datetime_with_source(dt, &mut source);
    let u3 = Ulid::from_datetime_with_source(dt, &mut source);

    assert!(u1 < u2);
    assert_eq!(u2, u3);
}

#[wasm_bindgen_test]
fn test_order() {
    let dt = now();
    let ulid1 = Ulid::from_datetime(dt);
    let ulid2 = Ulid::from_datetime(dt + Duration::from_millis(1));
    assert!(ulid1 < ulid2);
}

#[wasm_bindgen_test]
fn test_datetime() {
    let dt = now();
    let ulid = Ulid::from_datetime(dt);

    println!("{:?}, {:?}", dt, ulid.datetime());
    assert!(ulid.datetime() <= dt);
    assert!(ulid.datetime() + Duration::from_millis(1) >= dt);
}

#[wasm_bindgen_test]
fn test_timestamp() {
    let dt = now();
    let ulid = Ulid::from_datetime(dt);
    let ts = dt
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_millis();

    assert_eq!(u128::from(ulid.timestamp_ms()), ts);
}

#[wasm_bindgen_test]
fn default_is_nil() {
    assert_eq!(Ulid::default(), Ulid::nil());
}

#[wasm_bindgen_test]
fn nil_is_at_unix_epoch() {
    assert_eq!(Ulid::nil().datetime(), SystemTime::UNIX_EPOCH);
}