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
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use date_tuple::DateTuple;
use date_utils;
use regex::Regex;
use std::cmp::Ordering;
use std::convert::From;
use std::fmt;
use std::str::FromStr;

const MONTH_STRINGS: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

pub type Month = MonthTuple;

/// A container for a month of a specific year.
///
/// **NOTE:** MonthTuple's `m` field is one-based (one represents January) as of version 2.0.0.
///
/// Only handles values between Jan 0000 and Dec 9999 (inclusive).
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub struct MonthTuple {
    y: u16,
    m: u8,
}

impl MonthTuple {
    /// Produces a new MonthTuple.
    ///
    /// Only accepts a valid month value (`1 <= m <= 12`).
    ///
    /// Only accepts a valid year value (`0 <= y <= 9999`).
    pub fn new(y: u16, m: u8) -> Result<MonthTuple, String> {
        if 1 <= m && m <= 12 {
            if y <= 9999 {
                Ok(MonthTuple { y, m })
            } else {
                Err(format!(
                    "Invalid year in MonthTuple: {:?}\nYear must be <= 9999.",
                    MonthTuple { y, m }
                ))
            }
        } else {
            Err(format!(
                "Invalid month in MonthTuple: {:?}\nMonth must be between 1 and 12; Note that months are ONE-BASED since version 2.0.0.",
                MonthTuple { y, m }
            ))
        }
    }

    /// Returns a `MonthTuple` of the current month according to the system clock.
    pub fn this_month() -> MonthTuple {
        date_utils::now_as_monthtuple()
    }

    pub fn get_year(&self) -> u16 {
        self.y
    }

    /// Retrieves the month component of the tuple.
    ///
    /// Note this month is **ONE-BASED** (one represents January).
    pub fn get_month(&self) -> u8 {
        self.m
    }

    /// Gets a MonthTuple representing the month immediately following
    /// the current one. Will not go past Dec 9999.
    pub fn next_month(self) -> MonthTuple {
        if self.y == 9999 && self.m == 12 {
            return self;
        }
        if self.m == 12 {
            MonthTuple {
                y: self.y + 1,
                m: 1,
            }
        } else {
            MonthTuple {
                y: self.y,
                m: self.m + 1,
            }
        }
    }

    /// Gets a MonthTuple representing the month immediately preceding
    /// the current one. Will not go past Jan 0000.
    pub fn previous_month(self) -> MonthTuple {
        if self.y == 0 && self.m == 1 {
            return self;
        }
        if self.m == 1 {
            MonthTuple {
                y: self.y - 1,
                m: 12,
            }
        } else {
            MonthTuple {
                y: self.y,
                m: self.m - 1,
            }
        }
    }

    /// Adds a number of months to a MonthTuple.
    pub fn add_months(&mut self, months: u32) {
        for _ in 0..months {
            *self = self.next_month();
        }
    }

    /// Subtracts a number of months from a MonthTuple.
    pub fn subtract_months(&mut self, months: u32) {
        for _ in 0..months {
            *self = self.previous_month();
        }
    }

    /// Adds a number of years to a MonthTuple.
    pub fn add_years(&mut self, years: u16) {
        let mut new_years = self.y + years;
        if new_years > 9999 {
            new_years = 9999;
        }
        self.y = new_years;
    }

    /// Subtracts a number of years from a MonthTuple.
    pub fn subtract_years(&mut self, years: u16) {
        let mut new_years = self.y as i32 - years as i32;
        if new_years < 0 {
            new_years = 0;
        }
        self.y = new_years as u16;
    }

    /// Returns the month formatted to be human-readable.
    ///
    /// ## Examples
    /// * Jan 2018
    /// * Dec 1994
    pub fn to_readable_string(&self) -> String {
        match MONTH_STRINGS.iter().skip(self.m as usize - 1).next() {
            Some(s) => return format!("{} {:04}", s, self.y),
            None => panic!("Invalid MonthTuple: {:?}", self),
        }
    }
}

impl fmt::Display for MonthTuple {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:04}-{:02}", self.y, self.m)
    }
}

impl FromStr for MonthTuple {
    type Err = String;

    fn from_str(s: &str) -> Result<MonthTuple, Self::Err> {
        let valid_format = Regex::new(r"^\d{4}-\d{2}$").unwrap();
        let legacy_format = Regex::new(r"^\d{6}$").unwrap();
        if valid_format.is_match(s) {
            match MonthTuple::new(
                u16::from_str(&s[0..4]).unwrap(),
                u8::from_str(&s[5..7]).unwrap(),
            ) {
                Ok(m) => Ok(m),
                Err(e) => Err(format!("Invalid month passed to from_str: {}", e)),
            }
        } else if legacy_format.is_match(s) {
            let (s1, s2) = s.split_at(4);
            match MonthTuple::new(u16::from_str(s1).unwrap(), u8::from_str(s2).unwrap()) {
                Ok(m) => Ok(m),
                Err(e) => Err(format!("Invalid month passed to from_str: {}", e)),
            }
        } else {
            Err(format!(
                "Invalid str formatting of MonthTuple: {}\nExpects a string formatted like 2018-11",
                s
            ))
        }
    }
}

impl PartialOrd for MonthTuple {
    fn partial_cmp(&self, other: &MonthTuple) -> Option<Ordering> {
        if self.y == other.y {
            self.m.partial_cmp(&other.m)
        } else {
            self.y.partial_cmp(&other.y)
        }
    }
}

impl Ord for MonthTuple {
    fn cmp(&self, other: &MonthTuple) -> Ordering {
        if self.y == other.y {
            self.m.cmp(&other.m)
        } else {
            self.y.cmp(&other.y)
        }
    }
}

impl From<DateTuple> for MonthTuple {
    fn from(date: DateTuple) -> Self {
        MonthTuple {
            y: date.get_year(),
            m: date.get_month(),
        }
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_component_too_large() {
        assert!(super::MonthTuple::new(2000, 12).is_ok());
        assert!(super::MonthTuple::new(2000, 13).is_err());
        assert!(super::MonthTuple::new(10000, 5).is_err());
    }

    #[test]
    fn test_next_month() {
        let tuple1 = super::MonthTuple::new(2000, 5).unwrap();
        let tuple2 = super::MonthTuple::new(2000, 12).unwrap();
        let tuple3 = super::MonthTuple::new(9999, 12).unwrap();
        assert_eq!(super::MonthTuple { y: 2000, m: 6 }, tuple1.next_month());
        assert_eq!(super::MonthTuple { y: 2001, m: 1 }, tuple2.next_month());
        assert_eq!(tuple3, tuple3.next_month());
    }

    #[test]
    fn test_previous_month() {
        let tuple1 = super::MonthTuple::new(2000, 5).unwrap();
        let tuple2 = super::MonthTuple::new(2000, 1).unwrap();
        let tuple3 = super::MonthTuple::new(0, 1).unwrap();
        assert_eq!(super::MonthTuple { y: 2000, m: 4 }, tuple1.previous_month());
        assert_eq!(
            super::MonthTuple { y: 1999, m: 12 },
            tuple2.previous_month()
        );
        assert_eq!(tuple3, tuple3.previous_month());
    }

    #[test]
    fn test_to_readable_string() {
        let tuple = super::MonthTuple::new(2000, 5).unwrap();
        assert_eq!(String::from("May 2000"), tuple.to_readable_string());
    }

    #[test]
    #[should_panic]
    fn test_to_readable_string_panic() {
        let tuple = super::MonthTuple { y: 2000, m: 13 };
        tuple.to_readable_string();
    }

    #[test]
    fn test_to_string() {
        let tuple = super::MonthTuple::new(2000, 5).unwrap();
        assert_eq!(String::from("2000-05"), tuple.to_string());
    }

    #[test]
    fn test_equals() {
        let tuple1 = super::MonthTuple::new(2000, 5).unwrap();
        let tuple2 = super::MonthTuple::new(2000, 5).unwrap();
        assert_eq!(tuple1, tuple2);
    }

    #[test]
    fn test_comparisons() {
        let tuple1 = super::MonthTuple::new(2000, 5).unwrap();
        let tuple2 = super::MonthTuple::new(2000, 5).unwrap();
        let tuple3 = super::MonthTuple::new(2000, 6).unwrap();
        let tuple4 = super::MonthTuple::new(2001, 1).unwrap();
        assert!(tuple1 <= tuple2);
        assert!(!(tuple1 < tuple2));
        assert!(tuple1 >= tuple2);
        assert!(tuple1 < tuple3);
        assert!(tuple3 < tuple4);
        assert!(tuple4 > tuple2);
    }

    #[test]
    fn test_from_date() {
        let date = ::date_tuple::DateTuple::new(2000, 5, 10).unwrap();
        assert_eq!(
            super::MonthTuple { y: 2000, m: 5 },
            super::MonthTuple::from(date)
        );
    }

    #[test]
    fn test_from_string() {
        let tuple = super::MonthTuple::new(2000, 5).unwrap();
        assert_eq!(tuple, str::parse("2000-05").unwrap());
        assert_eq!(tuple, str::parse("200005").unwrap());
        assert!(str::parse::<super::MonthTuple>("2000-15").is_err());
        assert!(str::parse::<super::MonthTuple>("200015").is_err());
        assert!(str::parse::<super::MonthTuple>("200O05").is_err());
    }

    #[test]
    fn test_add_months() {
        let mut tuple1 = super::MonthTuple::new(2000, 6).unwrap();
        let tuple1_orig = super::MonthTuple::new(2000, 6).unwrap();
        let mut tuple2 = super::MonthTuple::new(2000, 12).unwrap();
        let tuple2_orig = super::MonthTuple::new(2000, 12).unwrap();
        tuple1.add_months(1);
        assert_eq!(tuple1, tuple1_orig.next_month());
        tuple2.add_months(2);
        assert_eq!(tuple2, tuple2_orig.next_month().next_month());
    }

    #[test]
    fn test_subtract_months() {
        let mut tuple1 = super::MonthTuple::new(2000, 6).unwrap();
        let tuple1_orig = super::MonthTuple::new(2000, 6).unwrap();
        let mut tuple2 = super::MonthTuple::new(2000, 12).unwrap();
        let tuple2_orig = super::MonthTuple::new(2000, 12).unwrap();
        tuple1.subtract_months(1);
        assert_eq!(tuple1, tuple1_orig.previous_month());
        tuple2.subtract_months(2);
        assert_eq!(tuple2, tuple2_orig.previous_month().previous_month());
    }

}