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
use chrono::{Duration, NaiveDateTime, Utc};

pub struct TimestampBuilder {
    pub ts_fmt: String,
    start: i64,
    end: i64,
    step: i64,
    interval: String,
    pub limit: i64,
}

impl Default for TimestampBuilder {
    fn default() -> Self {
        Self {
            ts_fmt: "%Y-%m-%d %H:%M".into(),
            start: 0,
            end: 0,
            step: 900000,
            interval: "15m".into(),
            limit: 499,
        }
    }
}

impl TimestampBuilder {
    pub fn new<S1, S2, S3>(
        start: S1,
        end: Option<S2>,
        step: S3,
    ) -> Result<Self, Box<dyn std::error::Error>>
    where
        S1: AsRef<str>,
        S2: AsRef<str>,
        S3: AsRef<str>,
    {
        let mut builder = TimestampBuilder::default();
        builder.start = NaiveDateTime::parse_from_str(start.as_ref(), builder.ts_fmt.as_ref())?
            .timestamp_millis();
        builder.end = match end {
            Some(end) => NaiveDateTime::parse_from_str(end.as_ref(), builder.ts_fmt.as_ref())?
                .timestamp_millis(),
            None => Utc::now().naive_utc().timestamp_millis(),
        };
        if builder.start >= builder.end {
            return Err("start is later than end".into());
        }
        builder.interval = step.as_ref().into();
        builder.step = match step.as_ref() {
            "15m" => Duration::minutes(15).num_milliseconds(),
            _ => todo!(),
        };
        Ok(builder)
    }

    pub fn build(&self) -> Vec<i64> {
        let mut list: Vec<i64> = (self.start..self.end)
            .step_by((self.step * self.limit) as usize)
            // .map(|ts| NaiveDateTime::from_timestamp_millis(ts).unwrap())
            .collect();
        list.push(self.end);
        list
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic]
    fn ts_same_start_end() {
        TimestampBuilder::new("2023-02-22 00:00", Some("2023-02-22 00:00"), "15m").unwrap();
    }
    #[test]
    fn ts_under_limit() -> Result<(), Box<dyn std::error::Error>> {
        let ts =
            TimestampBuilder::new("2023-02-22 00:00", Some("2023-02-27 04:44"), "15m")?.build();
        assert_eq!(ts.len(), 2);
        let ts: Vec<_> = ts.windows(2).collect();
        assert_eq!(ts.len(), 1);
        Ok(())
    }
    #[test]
    fn ts_as_same_as_limit() -> Result<(), Box<dyn std::error::Error>> {
        let ts =
            TimestampBuilder::new("2023-02-22 00:00", Some("2023-02-27 04:45"), "15m")?.build();
        assert_eq!(ts.len(), 2);
        let ts: Vec<_> = ts.windows(2).collect();
        assert_eq!(ts.len(), 1);
        Ok(())
    }
    #[test]
    fn ts_exceed_limit() -> Result<(), Box<dyn std::error::Error>> {
        let ts =
            TimestampBuilder::new("2023-02-22 00:00", Some("2023-02-27 04:46"), "15m")?.build();
        assert_eq!(ts.len(), 3);
        let ts: Vec<_> = ts.windows(2).collect();
        assert_eq!(ts.len(), 2);
        Ok(())
    }
    #[test]
    #[should_panic]
    #[allow(unused)]
    fn ts_panic_parse_str() {
        TimestampBuilder::new("2023-02-22 00:00:00", None::<String>, "15m").unwrap();
    }
    #[test]
    #[should_panic]
    #[allow(unused)]
    fn ts_panic_parse_step() {
        TimestampBuilder::new("2023-02-22 00:00", None::<String>, "1d");
    }
    #[test]
    fn ts_too_long_span() -> Result<(), Box<dyn std::error::Error>> {
        let ts =
            TimestampBuilder::new("2020-01-01 00:00", Some("2023-03-01 00:00"), "15m")?.build();
        assert_eq!(ts.len(), 224);
        let ts: Vec<_> = ts.windows(2).collect();
        assert_eq!(ts.len(), 223);
        Ok(())
    }
    #[test]
    #[should_panic]
    fn ts_start_later_than_end() {
        TimestampBuilder::new("2023-03-01 01:00", Some("2023-03-01 00:00"), "15m").unwrap();
    }
}