summaryrefslogtreecommitdiff
path: root/src/dateparse.rs
blob: 42fd214f248aebbbedfe68b8e900cca7a5372257 (plain)
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
use std::simd::{
    cmp::{SimdPartialEq, SimdPartialOrd},
    simd_swizzle, u8x16 as V,
};

macro_rules! A {
    [$a: ident; $($b: expr),+] => {
        const $a: V = V::from_array(*concat_bytes!($($b),+));
    };
}

#[must_use]
pub fn dateparse(s: &str) -> Option<(usize, usize, usize)> {
    // inf and sup for indiv. values
    A![LO; b"00/00/00", [0; 8]];
    A![HI; b"19/39/99", [0xFF; 8]];
    A![INTMSK; [b'0'; 16]];
    A![SLHMSK; [b'/'; 16]];
    // as_flattened wont work with concat_bytes!()
    //           m  m  /     d  d  /     y  y
    A![NUMMSK; [10, 1, 0], [10, 1, 0], [10, 1], [0; 8]];
    let b = s.as_bytes();
    let v = V::load_or_default(b);
    let mut valid = true;
    // index 16 for swizzles with INTMSK is b'0'
    // index 15 is \0
    // this will compile to a shuffle, but a relaxed_laneselect would be cool
    const Z: usize = 16;
    const N: usize = 15;
    macro_rules! X { [$($b: expr),+] => {
        simd_swizzle!(v, INTMSK, [$($b),+, N, N, N, N, N, N, N, N])
        //               [b'0'; 16]        we need better syntax for this
    }; }
    // normalize values by filling blanks, find through indexes of slashes
    let mut v = match (b.len(), v.simd_eq(SLHMSK).to_bitmask()) {
        //    yy/d/m  ->   '0' m  / '0' d  /  y  y
        (6, 0b001010) => X![Z, 0, 1, Z, 2, 3, 4, 5],
        //   yy/dd/m  ->   '0' m  /  d  d  /  y  y
        (7, 0b010010) => X![Z, 0, 1, 2, 3, 4, 5, 6],
        //   yy/d/mm  ->    m  m  / '0' d  /  y  y
        (7, 0b010100) => X![0, 1, 2, Z, 3, 4, 5, 6],
        //  yy/dd/mm
        (8, 0b100100) => v,
        _ => {
            valid = false;
            v
        },
    };

    // est-ce numerique?
    valid &= (v.simd_ge(LO) & v.simd_le(HI)).all();

    // parse
    //   '0' '3' '/' '3' '1' '/' '2' '6'
    // - '0' '0' '0' '0' '0' '0' '0' '0'
    // ---------------------------------
    //    0   3   .   3   1   .   2   6
    // * 10   1   0  10   1   0  10   1
    // ---------------------------------
    //    0   3   0  30   1   0  20   6
    // +  3   0  30   1   0  20   6<<<<
    // ---------------------------------
    //    3   .   .  31   .   .  26
    v -= INTMSK;
    v *= NUMMSK;
    v += v.rotate_elements_left::<1>();

    let n = v.to_array();
    let (m, d, y) = (n[0], n[3], n[6]);

    (valid & (1..=12).contains(&m) & (1..=31).contains(&d))
        .then(|| (m.into(), d.into(), y.into()))
}