Skip to content

Commit

Permalink
Add FromStr for FixedOffset
Browse files Browse the repository at this point in the history
  • Loading branch information
yshui committed May 28, 2023
1 parent 083d3bf commit f92e979
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 @@ -986,6 +987,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::consume_colon_maybe)?;
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 @@ -221,7 +221,7 @@ pub(super) fn trim1(s: &str) -> &str {

/// Consumes one colon char `:` if it is at the front of `s`.
/// Always returns `Ok(s)`.
pub(super) fn consume_colon_maybe(mut s: &str) -> ParseResult<&str> {
pub(crate) fn consume_colon_maybe(mut s: &str) -> ParseResult<&str> {
if s.is_empty() {
// nothing consumed
return Ok(s);
Expand All @@ -239,7 +239,7 @@ pub(super) fn consume_colon_maybe(mut 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<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 f92e979

Please sign in to comment.