af_core/time/
zone.rs

1// Copyright © 2020 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use crate::prelude::*;
8use chrono_tz::{Tz, TZ_VARIANTS};
9
10/// The local time zone.
11pub const LOCAL: Zone = Zone::Local;
12
13/// The UTC time zone.
14pub const UTC: Zone = Zone::Tz(Tz::UTC);
15
16/// A time zone.
17#[derive(Debug, Clone, Copy, Eq, PartialEq)]
18pub enum Zone {
19  Local,
20  Tz(Tz),
21}
22
23impl Zone {
24  /// Returns a time zone from the given name, or `None` if no such timezone
25  /// exists.
26  pub fn from_name(name: impl AsRef<str>) -> Result<Zone, Unrecognized> {
27    name.as_ref().parse()
28  }
29
30  /// Returns an iterator over all time zones.
31  pub fn all() -> impl Iterator<Item = Self> {
32    TZ_VARIANTS.iter().cloned().map(Zone::Tz)
33  }
34
35  /// Returns the name of the time zone.
36  pub fn name(&self) -> &'static str {
37    match &self {
38      Self::Local => "Local",
39      Self::Tz(tz) => tz.name(),
40    }
41  }
42}
43
44impl FromStr for Zone {
45  type Err = Unrecognized;
46
47  fn from_str(s: &str) -> Result<Self, Self::Err> {
48    match s.parse() {
49      Ok(tz) => Ok(Zone::Tz(tz)),
50      Err(_) => Err(Unrecognized),
51    }
52  }
53}
54
55/// An error returned when a time zone name is not recognized.
56#[derive(Debug, Error)]
57#[error("Unrecognized time zone.")]
58pub struct Unrecognized;