Skip to content

Commit

Permalink
Add FromStr for FixedOffset
Browse files Browse the repository at this point in the history
  • Loading branch information
yshui authored and mcronce committed Jun 28, 2023
1 parent ea9398e commit 4cf8f8f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
12 changes: 11 additions & 1 deletion src/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<Self, Self::Err> {
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")))]
Expand Down
4 changes: 2 additions & 2 deletions src/format/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,15 +197,15 @@ 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()))
}

/// Tries to parse `[-+]\d\d` continued by `\d\d`. Return an offset in seconds if possible.
///
/// 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<F>(s: &str, consume_colon: F) -> ParseResult<(&str, i32)>
pub(crate) fn timezone_offset<F>(s: &str, consume_colon: F) -> ParseResult<(&str, i32)>
where
F: FnMut(&str) -> ParseResult<&str>,
{
Expand Down

0 comments on commit 4cf8f8f

Please sign in to comment.