Skip to content

Commit

Permalink
fix: no panic when formatting with %#z
Browse files Browse the repository at this point in the history
This changes the "don't use me" panic into an error when using the
parsing-only "%#z" formatter, consistent with other invalid formatters.
  • Loading branch information
domodwyer authored and djc committed Jun 8, 2023
1 parent 2665e30 commit aa8a237
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,7 @@ fn format_inner(
off.map(|&(_, off)| write_local_minus_utc(result, off, true, Colons::None))
}
Internal(InternalFixed { val: InternalInternal::TimezoneOffsetPermissive }) => {
panic!("Do not try to write %#z it is undefined")
return Err(fmt::Error);
}
RFC2822 =>
// same as `%a, %d %b %Y %H:%M:%S %z`
Expand Down
24 changes: 24 additions & 0 deletions src/format/strftime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -718,4 +718,28 @@ mod tests {
assert_eq!(nd.format_localized("%F", Locale::de_DE).to_string(), "2001-07-08");
assert_eq!(nd.format_localized("%v", Locale::de_DE).to_string(), " 8-Jul-2001");
}

/// Ensure parsing a timestamp with the parse-only stftime formatter "%#z" does
/// not cause a panic.
///
/// See <https://github.com/chronotope/chrono/issues/1139>.
#[test]
fn test_parse_only_timezone_offset_permissive_no_panic() {
use crate::NaiveDate;
use crate::{FixedOffset, TimeZone};
use std::fmt::Write;

let dt = FixedOffset::east_opt(34200)
.unwrap()
.from_local_datetime(
&NaiveDate::from_ymd_opt(2001, 7, 8)
.unwrap()
.and_hms_nano_opt(0, 34, 59, 1_026_490_708)
.unwrap(),
)
.unwrap();

let mut buf = String::new();
let _ = write!(buf, "{}", dt.format("%#z")).expect_err("parse-only formatter should fail");
}
}

0 comments on commit aa8a237

Please sign in to comment.