Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: no panic when formatting with %#z #1140

Merged
merged 1 commit into from
Jun 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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");
}
}