fuzzy_datetime/
date_order.rs

1use std::ops::Range;
2
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum DateOrder {
6  YMD,
7  DMY,
8  MDY,
9}
10
11impl DateOrder {
12  /// render date format as indices for year, month and day
13  pub fn to_ymd_indices(&self) -> (usize, usize, usize) {
14    match self {
15      DateOrder::YMD => (0, 1, 2),
16      DateOrder::DMY => (2, 1, 0),
17      DateOrder::MDY => (2, 0, 1),
18    }
19  }
20
21  pub fn fixed_offsets(&self, length: u8) -> (Range<usize>, Range<usize>, Range<usize>) {
22    let short_date = length < 8;
23    match self {
24      DateOrder::YMD => {
25        if short_date {
26          (0..2, 2..4, 4..6)
27        } else {
28          (0..4, 4..6, 6..8)
29        }
30      },
31      DateOrder::DMY => {
32        if short_date {
33          (4..6, 2..4, 0..2)
34        } else {
35          (4..8, 2..4, 0..2)
36        }
37      },
38      DateOrder::MDY => {
39        if short_date {
40          (4..6, 0..2, 2..4)
41        } else {
42          (4..8, 0..2, 2..4)
43        }
44      }
45    }
46  }
47
48}
49
50
51/// Options for parsing the date component of strings
52pub struct DateOptions(pub DateOrder, pub Option<char>);
53
54impl DateOptions {
55  pub fn order(&self) -> DateOrder {
56    self.0
57  }
58
59  pub fn splitter(&self) -> Option<char> {
60    self.1
61  }
62}
63
64impl Default for DateOptions {
65  fn default() -> Self {
66    DateOptions(DateOrder::YMD, Some('-'))
67  }
68}
69
70/// instantiate options with three common orders + split character
71/// e.g. DateOptions::dmy('.')
72impl DateOptions {
73  pub fn ymd(splitter: char) -> Self {
74    DateOptions(DateOrder::YMD, Some(splitter))
75  }
76
77  pub fn ymd_fixed() -> Self {
78    DateOptions(DateOrder::YMD, None)
79  }
80
81  pub fn dmy(splitter: char) -> Self {
82    DateOptions(DateOrder::DMY, Some(splitter))
83  }
84
85  pub fn dmy_fixed() -> Self {
86    DateOptions(DateOrder::DMY, None)
87  }
88
89  pub fn mdy(splitter: char) -> Self {
90    DateOptions(DateOrder::MDY, Some(splitter))
91  }
92  
93  pub fn mdy_fixed() -> Self {
94    DateOptions(DateOrder::MDY, None)
95  }
96}
97