From 4cf8f8fff49c5fcf160fd1c602479e7cfb4de1ab Mon Sep 17 00:00:00 2001 From: Yuxuan Shui Date: Sun, 28 May 2023 08:06:36 +0100 Subject: [PATCH] Add FromStr for FixedOffset Closes #314 --- src/format/mod.rs | 12 +++++++++++- src/format/scan.rs | 4 ++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/format/mod.rs b/src/format/mod.rs index 7c9c3b7dd0..39627999ea 100644 --- a/src/format/mod.rs +++ b/src/format/mod.rs @@ -47,8 +47,9 @@ use std::error::Error; #[cfg(any(feature = "alloc", feature = "std", test))] use crate::naive::{NaiveDate, NaiveTime}; +use crate::offset::FixedOffset; #[cfg(any(feature = "alloc", feature = "std", test))] -use crate::offset::{FixedOffset, Offset}; +use crate::offset::Offset; #[cfg(any(feature = "alloc", feature = "std", test))] use crate::{Datelike, Timelike}; use crate::{Month, ParseMonthError, ParseWeekdayError, Weekday}; @@ -991,6 +992,15 @@ impl FromStr for Weekday { } } +/// Parsing a `str` into a `FixedOffset` uses the format [`%z`](./format/strftime/index.html). +impl FromStr for FixedOffset { + type Err = ParseError; + fn from_str(s: &str) -> Result { + let (_, offset) = scan::timezone_offset(s, scan::colon_or_space)?; + Self::east_opt(offset).ok_or(OUT_OF_RANGE) + } +} + /// Formats single formatting item #[cfg(feature = "unstable-locales")] #[cfg_attr(docsrs, doc(cfg(feature = "unstable-locales")))] diff --git a/src/format/scan.rs b/src/format/scan.rs index 2273dec7d6..00e06c7c13 100644 --- a/src/format/scan.rs +++ b/src/format/scan.rs @@ -197,7 +197,7 @@ pub(super) fn space(s: &str) -> ParseResult<&str> { } /// Consumes any number (including zero) of colon or spaces. -pub(super) fn colon_or_space(s: &str) -> ParseResult<&str> { +pub(crate) fn colon_or_space(s: &str) -> ParseResult<&str> { Ok(s.trim_start_matches(|c: char| c == ':' || c.is_whitespace())) } @@ -205,7 +205,7 @@ pub(super) fn colon_or_space(s: &str) -> ParseResult<&str> { /// /// The additional `colon` may be used to parse a mandatory or optional `:` /// between hours and minutes, and should return either a new suffix or `Err` when parsing fails. -pub(super) fn timezone_offset(s: &str, consume_colon: F) -> ParseResult<(&str, i32)> +pub(crate) fn timezone_offset(s: &str, consume_colon: F) -> ParseResult<(&str, i32)> where F: FnMut(&str) -> ParseResult<&str>, {