satkit 0.16.2

Satellite Toolkit
Documentation
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//!
//! Interaction of Instant class with strings
//!

use crate::time::InstantError;
use crate::Instant;

use anyhow::Result;

/// Collect characters from a `Peekable<Chars>` while `pred` holds, leaving the
/// first non-matching character available for the next read (unlike std's
/// `take_while`, which consumes and discards it).
fn take_while_peek(
    chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
    mut pred: impl FnMut(char) -> bool,
) -> String {
    let mut out = String::new();
    while let Some(&c) = chars.peek() {
        if !pred(c) {
            break;
        }
        out.push(c);
        chars.next();
    }
    out
}

/// Full month names
const MONTH_NAMES: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

/// Abbreviated month names
const MONTH_ABBRS: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

#[derive(PartialEq, Debug)]
enum ParseVal {
    Str(String),
    Num(i32),
}

impl Instant {
    /// Parse a string into an Instant object
    ///
    /// Attempts to guess the string format.
    /// Use sparingly and with caution.  This is
    /// probably not what you want.
    ///
    /// # Arguments:
    ///   s (str): The string to parse
    ///
    /// # Returns:
    ///  Instant: The instant object
    ///
    /// # Raises:
    /// SCErr: If the string cannot be parsed
    pub fn from_string(s: &str) -> Result<Self> {
        // Try RFC 3339 first — it's unambiguous and common
        if let Ok(r) = Self::from_rfc3339(s) {
            return Ok(r);
        }

        let mut chars = s.chars().peekable();
        let mut year = -1;
        let mut month = -1;
        let mut day = -1;
        let mut hour = -1;
        let mut minute = -1;
        let mut second = -1;
        let mut microsecond = 0i32;
        let mut microsecond_set = false;

        let mut thelist = Vec::<ParseVal>::new();

        let mut isperiod: bool = false;
        while let Some(c) = chars.peek() {
            if c.is_ascii_digit() {
                let cstr = take_while_peek(&mut chars, |c| c.is_ascii_digit());
                // If following a period, allow for trailing zeros up to 6 digits
                let val = match isperiod {
                    true => match cstr.len() {
                        1 => cstr.parse::<i32>()? * 100_000,
                        2 => cstr.parse::<i32>()? * 10_000,
                        3 => cstr.parse::<i32>()? * 1_000,
                        4 => cstr.parse::<i32>()? * 100,
                        5 => cstr.parse::<i32>()? * 10,
                        6 => cstr.parse::<i32>()?,
                        _ => {
                            return Err(
                                InstantError::InvalidMicrosecond(cstr.parse::<i32>()?).into()
                            );
                        }
                    },
                    false => cstr.parse::<i32>()?,
                };
                thelist.push(ParseVal::Num(val));
            } else if c.is_alphabetic() {
                thelist.push(ParseVal::Str(take_while_peek(&mut chars, |c| {
                    c.is_alphabetic()
                })));
            } else if let Some(c) = chars.next() {
                isperiod = c == '.';
            }
        }

        // Look for month names (full or abbreviated)
        let mut to_remove = Vec::new();
        thelist.iter().enumerate().for_each(|(idx, x)| match x {
            ParseVal::Num(_) => {}
            ParseVal::Str(s) => {
                if month == -1 {
                    let found = MONTH_NAMES
                        .iter()
                        .position(|&m| m == *s)
                        .or_else(|| MONTH_ABBRS.iter().position(|&m| m == *s));
                    if let Some(m) = found {
                        if idx < thelist.len() - 1 {
                            if let ParseVal::Num(n) = thelist[idx + 1] {
                                day = n;
                                to_remove.push(idx + 1);
                            }
                        }
                        to_remove.push(idx);
                        month = m as i32 + 1;
                    }
                }
            }
        });
        // Remove in reverse order so indices stay valid
        to_remove.sort_unstable_by(|a, b| b.cmp(a));
        for idx in to_remove {
            thelist.remove(idx);
        }

        // Look for HH:MM:SS[.ffffff] time pattern
        if let Some(p) = thelist
            .iter()
            .position(|x| *x == ParseVal::Str(String::from(":")))
        {
            if (p > 0)
                && (p < thelist.len() - 4)
                && (thelist[p + 2] == ParseVal::Str(String::from(":")))
            {
                if let ParseVal::Num(h) = thelist[p - 1] {
                    hour = h;
                }
                if let ParseVal::Num(m) = thelist[p + 1] {
                    minute = m;
                }
                if let ParseVal::Num(s) = thelist[p + 3] {
                    second = s;
                }
                // Microseconds follow seconds (period is not tokenized)
                if p + 4 < thelist.len() {
                    if let ParseVal::Num(m) = thelist[p + 4] {
                        microsecond = m;
                        microsecond_set = true;
                    }
                }
            }
        }

        // Helper: extract date from a separator pattern like ??/??/???? or ??-??-????
        let extract_date = |thelist: &[ParseVal], sep: &str| -> Option<(i32, i32, i32, Vec<usize>)> {
            let p = thelist
                .iter()
                .position(|x| *x == ParseVal::Str(String::from(sep)))?;
            if p == 0 || p >= thelist.len() - 4 {
                return None;
            }
            if thelist[p + 2] != ParseVal::Str(String::from(sep)) {
                return None;
            }
            let mut y = -1i32;
            let mut m = -1i32;
            let mut d = -1i32;
            let mut remove = Vec::new();
            if let ParseVal::Num(n) = thelist[p + 3] {
                y = n;
                remove.push(p + 3);
            }
            if let ParseVal::Num(n) = thelist[p + 1] {
                d = n;
                remove.push(p + 1);
            }
            if let ParseVal::Num(n) = thelist[p - 1] {
                if n > 1900 {
                    // First field is a year (YYYY-MM-DD)
                    let tmp = y;
                    y = n;
                    // What was in position 3 is actually day
                    if d != -1 {
                        m = d;
                        d = tmp;
                    }
                } else {
                    m = n;
                }
                remove.push(p - 1);
            }
            // Also remove the separators
            remove.push(p + 2);
            remove.push(p);
            Some((y, m, d, remove))
        };

        // Look for ??/??/???? for date
        if year == -1 || month == -1 || day == -1 {
            if let Some((y, m, d, remove)) = extract_date(&thelist, "/") {
                if year == -1 && y != -1 { year = y; }
                if month == -1 && m != -1 { month = m; }
                if day == -1 && d != -1 { day = d; }
                let mut remove = remove;
                remove.sort_unstable_by(|a, b| b.cmp(a));
                for idx in remove {
                    if idx < thelist.len() {
                        thelist.remove(idx);
                    }
                }
            }
        }

        // Look for ??-??-???? for date
        if year == -1 || month == -1 || day == -1 {
            if let Some((y, m, d, remove)) = extract_date(&thelist, "-") {
                if year == -1 && y != -1 { year = y; }
                if month == -1 && m != -1 { month = m; }
                if day == -1 && d != -1 { day = d; }
                let mut remove = remove;
                remove.sort_unstable_by(|a, b| b.cmp(a));
                for idx in remove {
                    if idx < thelist.len() {
                        thelist.remove(idx);
                    }
                }
            }
        }

        // Fill remaining fields from leftover numbers
        thelist.iter().for_each(|x| match x {
            ParseVal::Num(x) => {
                if year == -1 {
                    year = *x;
                } else if month == -1 {
                    month = *x;
                } else if day == -1 {
                    day = *x;
                } else if hour == -1 {
                    hour = *x;
                } else if minute == -1 {
                    minute = *x;
                } else if second == -1 {
                    second = *x;
                } else if !microsecond_set {
                    microsecond = *x;
                    microsecond_set = true;
                }
            }
            ParseVal::Str(_) => {}
        });

        if year == -1 || month == -1 || day == -1 {
            return Err(InstantError::InvalidString(s.to_string()).into());
        }
        if hour == -1 || minute == -1 || second < 0 {
            hour = 0;
            minute = 0;
            second = 0;
            microsecond = 0;
        }
        Self::from_datetime(
            year,
            month,
            day,
            hour,
            minute,
            second as f64 + microsecond as f64 / 1_000_000.0,
        )
    }

    /// Parse a string into an Instant object
    ///
    /// # Notes:
    /// * The format string is a subset of the Python datetime module
    ///
    /// # Arguments:
    /// * s (str): The string to parse
    /// * format (str): The format string
    ///
    /// # Format Codes:
    /// * %Y - Year with century as a decimal number
    /// * %m - Month as a zero-padded decimal number [01, 12]
    /// * %B - Full month name (January, February, etc.)
    /// * %b - Abbreviated month name (Jan, Feb, etc.)
    /// * %d - Day of the month as a zero-padded decimal number [01, 31]
    /// * %H - Hour (24-hour clock) as a zero-padded decimal number
    /// * %M - Minute as a zero-padded decimal number
    /// * %S - Second as a zero-padded decimal number
    /// * %f - Microsecond as a decimal number, allowing for trailing zeros
    /// * %z - UTC offset in the form +HHMM or -HHMM or 'Z' for UTC
    ///
    /// # Returns:
    /// Instant: The instant object
    ///
    pub fn strptime(s: &str, format: &str) -> Result<Self> {
        let mut chars = format.chars();
        let mut s_chars = s.chars().peekable();
        let mut year = 0;
        let mut month: i32 = 0;
        let mut day = 0;
        let mut hour = 0;
        let mut minute = 0;
        let mut second = 0;
        let mut microsecond = 0;
        let mut offset = 0;

        while let Some(c) = chars.next() {
            match c {
                '%' => match chars.next() {
                    Some('Y') => year = s_chars.by_ref().take(4).collect::<String>().parse()?,
                    Some('m') => month = s_chars.by_ref().take(2).collect::<String>().parse()?,
                    Some('B') => {
                        let month_name =
                            take_while_peek(&mut s_chars, |c| c.is_alphabetic());
                        month = MONTH_NAMES
                            .iter()
                            .position(|&m| m == month_name)
                            .map(|m| m as i32 + 1)
                            .ok_or(InstantError::InvalidMonthString(month_name))?;
                    }
                    Some('b') => {
                        let month_abbr =
                            take_while_peek(&mut s_chars, |c| c.is_alphabetic());
                        month = MONTH_ABBRS
                            .iter()
                            .position(|&m| m == month_abbr)
                            .map(|m| m as i32 + 1)
                            .ok_or(InstantError::InvalidMonthString(month_abbr))?;
                    }
                    Some('d') => day = s_chars.by_ref().take(2).collect::<String>().parse()?,
                    Some('H') => hour = s_chars.by_ref().take(2).collect::<String>().parse()?,
                    Some('M') => minute = s_chars.by_ref().take(2).collect::<String>().parse()?,
                    Some('S') => second = s_chars.by_ref().take(2).collect::<String>().parse()?,
                    Some('f') => {
                        let smicro =
                            take_while_peek(&mut s_chars, |c| c.is_ascii_digit());
                        // This is a little strange ... formating convention allows
                        // for trailing zeros to be omitted.  So we need to determine
                        // the number of digits and multiply by the appropriate factor
                        microsecond = match smicro.len() {
                            1 => smicro.parse::<i32>()? * 100_000,
                            2 => smicro.parse::<i32>()? * 10_000,
                            3 => smicro.parse::<i32>()? * 1_000,
                            4 => smicro.parse::<i32>()? * 100,
                            5 => smicro.parse::<i32>()? * 10,
                            6 => smicro.parse::<i32>()?,
                            _ => {
                                return Err(InstantError::InvalidMicrosecond(
                                    smicro.parse::<i32>().unwrap(),
                                )
                                .into());
                            }
                        }
                    }
                    Some('z') => {
                        let z = s_chars.by_ref().take(1).collect::<String>();
                        if z == "Z" {
                            // UTC
                        } else {
                            let sign = if z == "-" { -1 } else { 1 };
                            let h = s_chars
                                .by_ref()
                                .take(2)
                                .collect::<String>()
                                .parse::<i32>()?;
                            // take the colon if it is there (it appears to be optional)
                            if s_chars.peek() == Some(&':') {
                                s_chars.next();
                            }
                            let m = s_chars
                                .by_ref()
                                .take(2)
                                .collect::<String>()
                                .parse::<i32>()?;
                            offset = sign * (h * 60 + m);
                        }
                    }
                    Some(t) => {
                        return Err(InstantError::InvalidFormat(t).into());
                    }
                    None => {
                        return Err(InstantError::InvalidFormat('%').into());
                    }
                },
                _ => {
                    let n = s_chars.next().unwrap_or('_');
                    if c != n {
                        return Err(InstantError::InvalidString(format!(
                            "{} doesn't match {}",
                            c, n
                        ))
                        .into());
                    }
                }
            }
        }

        let mut instant = Self::from_datetime(
            year,
            month,
            day,
            hour,
            minute,
            second as f64 + microsecond as f64 / 1_000_000.0,
        )?;
        if offset != 0 {
            instant += crate::Duration::from_minutes(offset as f64);
        }
        Ok(instant)
    }

    /// Parse a string in RFC3339 format
    ///
    /// # Arguments:
    ///    rfc3339 (str): The string in RFC3339 format
    ///
    /// # Notes:
    /// * Only allows a subset of the RFC3339 format: "YYYY-MM-DDTHH:MM:SS.sssZ"
    ///
    /// # Returns:
    ///   Instant: The instant object
    pub fn from_rfc3339(rfc3339: &str) -> std::result::Result<Self, InstantError> {
        // Try formats ending with 'Z' (UTC) first
        if let Ok(r) = Self::strptime(rfc3339, "%Y-%m-%dT%H:%M:%S.%fZ") {
            return Ok(r);
        }
        if let Ok(r) = Self::strptime(rfc3339, "%Y-%m-%dT%H:%M:%SZ") {
            return Ok(r);
        }

        // Try formats with timezone offset (+HH:MM or -HH:MM)
        // RFC 3339 allows offsets like +00:00, -05:00, etc.
        let s = rfc3339.trim();
        if s.len() >= 6 {
            let offset_start = s.len() - 6;
            let maybe_offset = &s[offset_start..];
            if (maybe_offset.starts_with('+') || maybe_offset.starts_with('-'))
                && maybe_offset.chars().nth(3) == Some(':')
            {
                let sign: f64 = if maybe_offset.starts_with('+') {
                    1.0
                } else {
                    -1.0
                };
                if let (Ok(offset_hours), Ok(offset_mins)) = (
                    maybe_offset[1..3].parse::<f64>(),
                    maybe_offset[4..6].parse::<f64>(),
                ) {
                    let offset_seconds = sign * (offset_hours * 3600.0 + offset_mins * 60.0);
                    let base = &s[..offset_start];
                    let r = Self::strptime(base, "%Y-%m-%dT%H:%M:%S.%f")
                        .or_else(|_| Self::strptime(base, "%Y-%m-%dT%H:%M:%S"));
                    if let Ok(r) = r {
                        return Ok(r - crate::Duration::from_seconds(offset_seconds));
                    }
                }
            }
        }

        // Try bare formats (no timezone indicator — assume UTC)
        if let Ok(r) = Self::strptime(rfc3339, "%Y-%m-%dT%H:%M:%S.%f") {
            return Ok(r);
        }
        if let Ok(r) = Self::strptime(rfc3339, "%Y-%m-%dT%H:%M:%S") {
            return Ok(r);
        }
        Err(InstantError::InvalidString(rfc3339.to_string()))
    }

    /// Format the Instant object as a string in RFC3339 format
    ///
    /// # Returns:
    /// str: The formatted string in RFC3339 format: "YYYY-MM-DDTHH:MM:SS.sssZ"
    ///
    /// # Notes:
    /// * This is the same as ISO8601 format
    pub fn as_rfc3339(&self) -> String {
        self.strftime("%Y-%m-%dT%H:%M:%S.%fZ").unwrap()
    }

    /// Format the Instant object as a string in ISO8601 format
    ///
    /// # Returns:
    /// str: The formatted string in ISO8601 format: "YYYY-MM-DDTHH:MM:SS.sssZ"
    ///
    /// # Notes:
    /// * This is the same as RFC3339 format
    pub fn as_iso8601(&self) -> String {
        self.strftime("%Y-%m-%dT%H:%M:%S.%fZ").unwrap()
    }

    /// Format the Instant object as a string
    ///
    /// # Notes:
    /// * The format string is a subset of the Python datetime module
    ///
    /// # Arguments:
    ///  format (str): The format string
    ///
    /// # Format Codes:
    /// * %Y - Year with century as a decimal number
    /// * %m - Month as a zero-padded decimal number [01, 12]
    /// * %B - Full month name (January, February, etc.)
    /// * %b - Abbreviated month name (Jan, Feb, etc.)
    /// * %d - Day of the month as a zero-padded decimal number [01, 31]
    /// * %H - Hour (24-hour clock) as a zero-padded decimal number
    /// * %M - Minute as a zero-padded decimal number
    /// * %S - Second as a zero-padded decimal number
    /// * %f - Microsecond as a decimal number
    /// * %A - Full weekday name (Sunday, Monday, etc.)
    /// * %w - Weekday as a decimal number [0(Sunday), 6(Saturday)]
    ///
    /// # Returns:
    /// str: The formatted string
    ///
    pub fn strftime(&self, format: &str) -> std::result::Result<String, InstantError> {
        let mut result = String::new();
        let mut chars = format.chars();

        let (year, month, day, hour, minute, fsecond) = self.as_datetime();
        let second = fsecond as i32;
        let microsecond = (fsecond.fract() * 1_000_000.0).round() as u32;

        while let Some(c) = chars.next() {
            if c == '%' {
                match chars.next() {
                    Some('Y') => {
                        result.push_str(&year.to_string());
                    }
                    Some('m') => {
                        result.push_str(&format!("{:02}", month));
                    }
                    Some('d') => {
                        result.push_str(&format!("{:02}", day));
                    }
                    Some('H') => {
                        result.push_str(&format!("{:02}", hour));
                    }
                    Some('M') => {
                        result.push_str(&format!("{:02}", minute));
                    }
                    Some('S') => {
                        result.push_str(&format!("{:02}", second));
                    }
                    Some('f') => {
                        result.push_str(&format!("{:06}", microsecond));
                    }
                    Some('B') => {
                        result.push_str(MONTH_NAMES[(month - 1) as usize]);
                    }
                    Some('b') => {
                        result.push_str(MONTH_ABBRS[(month - 1) as usize]);
                    }
                    Some('A') => {
                        let weekday = self.day_of_week();
                        result.push_str(&weekday.to_string());
                    }
                    Some('w') => {
                        let weekday = self.day_of_week();
                        result.push_str(&format!("{:02}", weekday as i32));
                    }
                    Some(c) => {
                        return Err(InstantError::InvalidFormat(c));
                    }
                    None => {
                        return Err(InstantError::InvalidString(
                            "Expected a format character".to_string(),
                        ));
                    }
                }
            } else {
                result.push(c);
            }
        }
        Ok(result)
    }
}