year_helper/
lib.rs

1/*!
2# Year Helper
3
4This library provides some useful functions to deal with years.
5
6## Usage
7
8```rust
9let year = 2020;
10let month = 2;
11
12let leap_year = year_helper::is_leap_year(year);
13
14let days_in_month = year_helper::get_days_in_month(year, month);
15let days_in_year = year_helper::get_days_in_year(year);
16
17// or use the following functions if the year has been determined whether it is a leap year
18let days_in_month = year_helper::get_days_in_month_2(leap_year, month);
19let days_in_year = year_helper::get_days_in_year_2(leap_year);
20```
21 */
22
23#![no_std]
24
25/// Determine whether a year is a leap year or not.
26///
27/// A year is a leap year if following conditions are satisfied:
28///
29/// * Year is multiple of 400.
30/// * Year is multiple of 4 and not multiple of 100.
31#[inline]
32pub const fn is_leap_year(year: i32) -> bool {
33    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
34}
35
36/// Calculate how many days in a month.
37///
38/// If the input `month` is not between `1` and `12`, this function will return `None`.
39#[inline]
40pub const fn get_days_in_month(year: i32, month: u8) -> Option<u8> {
41    match month {
42        1 | 3 | 5 | 7 | 8 | 10 | 12 => Some(31),
43        4 | 6 | 9 | 11 => Some(30),
44        2 => {
45            if is_leap_year(year) {
46                Some(29)
47            } else {
48                Some(28)
49            }
50        }
51        _ => None,
52    }
53}
54
55/// Calculate how many days in a month.
56///
57/// If the input `month` is not between `1` and `12`, this function will return `None`.
58#[inline]
59pub const fn get_days_in_month_2(leap_year: bool, month: u8) -> Option<u8> {
60    match month {
61        1 | 3 | 5 | 7 | 8 | 10 | 12 => Some(31),
62        4 | 6 | 9 | 11 => Some(30),
63        2 => {
64            if leap_year {
65                Some(29)
66            } else {
67                Some(28)
68            }
69        }
70        _ => None,
71    }
72}
73
74/// Calculate how many days in a year.
75#[inline]
76pub const fn get_days_in_year(year: i32) -> u16 {
77    if is_leap_year(year) {
78        366
79    } else {
80        365
81    }
82}
83
84/// Calculate how many days in a year.
85#[inline]
86pub const fn get_days_in_year_2(leap_year: bool) -> u16 {
87    if leap_year {
88        366
89    } else {
90        365
91    }
92}