Switch to 2024 style

This commit is contained in:
Dirkjan Ochtman 2025-02-21 10:32:44 +01:00
parent 11d227a22b
commit 7f6cf5e504
33 changed files with 136 additions and 155 deletions

View File

@ -1,12 +1,12 @@
//! Benchmarks for chrono that just depend on std //! Benchmarks for chrono that just depend on std
use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; use criterion::{BenchmarkId, Criterion, black_box, criterion_group, criterion_main};
use chrono::format::StrftimeItems;
use chrono::prelude::*;
#[cfg(feature = "unstable-locales")] #[cfg(feature = "unstable-locales")]
use chrono::Locale; use chrono::Locale;
use chrono::{DateTime, FixedOffset, Local, TimeDelta, Utc, __BenchYearFlags}; use chrono::format::StrftimeItems;
use chrono::prelude::*;
use chrono::{__BenchYearFlags, DateTime, FixedOffset, Local, TimeDelta, Utc};
fn bench_date_from_ymd(c: &mut Criterion) { fn bench_date_from_ymd(c: &mut Criterion) {
c.bench_function("bench_date_from_ymd", |b| { c.bench_function("bench_date_from_ymd", |b| {

View File

@ -1,4 +1,4 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use criterion::{Criterion, black_box, criterion_group, criterion_main};
use chrono::NaiveDateTime; use chrono::NaiveDateTime;

View File

@ -1 +1,2 @@
style_edition = "2024"
use_small_heuristics = "Max" use_small_heuristics = "Max"

View File

@ -14,22 +14,22 @@ use core::{fmt, hash, str};
#[cfg(feature = "std")] #[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
#[allow(deprecated)]
use crate::Date;
#[cfg(all(feature = "unstable-locales", feature = "alloc"))] #[cfg(all(feature = "unstable-locales", feature = "alloc"))]
use crate::format::Locale; use crate::format::Locale;
use crate::format::{
parse, parse_and_remainder, parse_rfc3339, Fixed, Item, ParseError, ParseResult, Parsed,
StrftimeItems, TOO_LONG,
};
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
use crate::format::{write_rfc2822, write_rfc3339, DelayedFormat, SecondsFormat}; use crate::format::{DelayedFormat, SecondsFormat, write_rfc2822, write_rfc3339};
use crate::format::{
Fixed, Item, ParseError, ParseResult, Parsed, StrftimeItems, TOO_LONG, parse,
parse_and_remainder, parse_rfc3339,
};
use crate::naive::{Days, IsoWeek, NaiveDate, NaiveDateTime, NaiveTime}; use crate::naive::{Days, IsoWeek, NaiveDate, NaiveDateTime, NaiveTime};
#[cfg(feature = "clock")] #[cfg(feature = "clock")]
use crate::offset::Local; use crate::offset::Local;
use crate::offset::{FixedOffset, LocalResult, Offset, TimeZone, Utc}; use crate::offset::{FixedOffset, LocalResult, Offset, TimeZone, Utc};
#[allow(deprecated)]
use crate::Date;
use crate::{expect, try_opt};
use crate::{Datelike, Months, TimeDelta, Timelike, Weekday}; use crate::{Datelike, Months, TimeDelta, Timelike, Weekday};
use crate::{expect, try_opt};
#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))] #[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
use rkyv::{Archive, Deserialize, Serialize}; use rkyv::{Archive, Deserialize, Serialize};
@ -1849,11 +1849,7 @@ impl From<SystemTime> for DateTime<Utc> {
// unlikely but should be handled // unlikely but should be handled
let dur = e.duration(); let dur = e.duration();
let (sec, nsec) = (dur.as_secs() as i64, dur.subsec_nanos()); let (sec, nsec) = (dur.as_secs() as i64, dur.subsec_nanos());
if nsec == 0 { if nsec == 0 { (-sec, 0) } else { (-sec - 1, 1_000_000_000 - nsec) }
(-sec, 0)
} else {
(-sec - 1, 1_000_000_000 - nsec)
}
} }
}; };
Utc.timestamp_opt(sec, nsec).unwrap() Utc.timestamp_opt(sec, nsec).unwrap()

View File

@ -2,7 +2,7 @@ use core::fmt;
use serde::{de, ser}; use serde::{de, ser};
use super::DateTime; use super::DateTime;
use crate::format::{write_rfc3339, SecondsFormat}; use crate::format::{SecondsFormat, write_rfc3339};
#[cfg(feature = "clock")] #[cfg(feature = "clock")]
use crate::offset::Local; use crate::offset::Local;
use crate::offset::{FixedOffset, Offset, TimeZone, Utc}; use crate::offset::{FixedOffset, Offset, TimeZone, Utc};
@ -1289,7 +1289,9 @@ mod tests {
} }
assert!(serde_json::from_str::<DateTime<Utc>>(r#""2014-07-32T12:34:06Z""#).is_err()); assert!(serde_json::from_str::<DateTime<Utc>>(r#""2014-07-32T12:34:06Z""#).is_err());
assert!(serde_json::from_str::<DateTime<FixedOffset>>(r#""2014-07-32T12:34:06Z""#).is_err()); assert!(
serde_json::from_str::<DateTime<FixedOffset>>(r#""2014-07-32T12:34:06Z""#).is_err()
);
} }
#[test] #[test]

View File

@ -734,10 +734,7 @@ fn test_datetime_rfc2822() {
"Thu,\n\t13\n Feb\n 1969\n 23:32\n -0330 (Newfoundland Time)" "Thu,\n\t13\n Feb\n 1969\n 23:32\n -0330 (Newfoundland Time)"
), ),
Ok( Ok(
ymdhms( ymdhms(&FixedOffset::east_opt(-3 * 60 * 60 - 30 * 60).unwrap(), 1969, 2, 13, 23, 32, 0,)
&FixedOffset::east_opt(-3 * 60 * 60 - 30 * 60).unwrap(),
1969, 2, 13, 23, 32, 0,
)
) )
); );
// example from RFC 2822 Appendix A.5. without trailing " (Newfoundland Time)" // example from RFC 2822 Appendix A.5. without trailing " (Newfoundland Time)"
@ -1099,8 +1096,10 @@ fn test_parse_from_str() {
Ok(ymdhms(&edt, 2014, 5, 7, 12, 34, 56)) Ok(ymdhms(&edt, 2014, 5, 7, 12, 34, 56))
); // ignore offset ); // ignore offset
assert!(DateTime::parse_from_str("20140507000000", "%Y%m%d%H%M%S").is_err()); // no offset assert!(DateTime::parse_from_str("20140507000000", "%Y%m%d%H%M%S").is_err()); // no offset
assert!(DateTime::parse_from_str("Fri, 09 Aug 2013 23:54:35 GMT", "%a, %d %b %Y %H:%M:%S GMT") assert!(
.is_err()); DateTime::parse_from_str("Fri, 09 Aug 2013 23:54:35 GMT", "%a, %d %b %Y %H:%M:%S GMT")
.is_err()
);
assert_eq!( assert_eq!(
DateTime::parse_from_str("0", "%s").unwrap(), DateTime::parse_from_str("0", "%s").unwrap(),
DateTime::from_timestamp(0, 0).unwrap().fixed_offset() DateTime::from_timestamp(0, 0).unwrap().fixed_offset()

View File

@ -638,8 +638,8 @@ mod tests {
#[cfg(all(feature = "std", feature = "unstable-locales", feature = "alloc"))] #[cfg(all(feature = "std", feature = "unstable-locales", feature = "alloc"))]
#[test] #[test]
fn test_with_locale_delayed_write_to() { fn test_with_locale_delayed_write_to() {
use crate::format::locales::Locale;
use crate::DateTime; use crate::DateTime;
use crate::format::locales::Locale;
let dt = DateTime::from_timestamp(1643723400, 123456789).unwrap(); let dt = DateTime::from_timestamp(1643723400, 123456789).unwrap();
let df = dt.format_localized("%A, %B %d, %Y", Locale::ja_JP); let df = dt.format_localized("%A, %B %d, %Y", Locale::ja_JP);

View File

@ -1,6 +1,6 @@
#[cfg(feature = "unstable-locales")] #[cfg(feature = "unstable-locales")]
mod localized { mod localized {
use pure_rust_locales::{locale_match, Locale}; use pure_rust_locales::{Locale, locale_match};
pub(crate) const fn default_locale() -> Locale { pub(crate) const fn default_locale() -> Locale {
Locale::POSIX Locale::POSIX

View File

@ -54,15 +54,15 @@ pub mod strftime;
// not require `alloc`. // not require `alloc`.
pub(crate) mod locales; pub(crate) mod locales;
pub use formatting::SecondsFormat;
pub(crate) use formatting::write_hundreds; pub(crate) use formatting::write_hundreds;
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
pub(crate) use formatting::write_rfc2822; pub(crate) use formatting::write_rfc2822;
#[cfg(any(feature = "alloc", feature = "serde"))] #[cfg(any(feature = "alloc", feature = "serde"))]
pub(crate) use formatting::write_rfc3339; pub(crate) use formatting::write_rfc3339;
pub use formatting::SecondsFormat;
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
#[allow(deprecated)] #[allow(deprecated)]
pub use formatting::{format, format_item, DelayedFormat}; pub use formatting::{DelayedFormat, format, format_item};
#[cfg(feature = "unstable-locales")] #[cfg(feature = "unstable-locales")]
pub use locales::Locale; pub use locales::Locale;
pub(crate) use parse::parse_rfc3339; pub(crate) use parse::parse_rfc3339;

View File

@ -8,9 +8,9 @@ use core::borrow::Borrow;
use core::str; use core::str;
use super::scan; use super::scan;
use super::{BAD_FORMAT, INVALID, OUT_OF_RANGE, TOO_LONG, TOO_SHORT};
use super::{Fixed, InternalFixed, InternalInternal, Item, Numeric, Pad, Parsed}; use super::{Fixed, InternalFixed, InternalInternal, Item, Numeric, Pad, Parsed};
use super::{ParseError, ParseResult}; use super::{ParseError, ParseResult};
use super::{BAD_FORMAT, INVALID, OUT_OF_RANGE, TOO_LONG, TOO_SHORT};
use crate::{DateTime, FixedOffset, Weekday}; use crate::{DateTime, FixedOffset, Weekday};
fn set_weekday_with_num_days_from_sunday(p: &mut Parsed, v: i64) -> ParseResult<()> { fn set_weekday_with_num_days_from_sunday(p: &mut Parsed, v: i64) -> ParseResult<()> {
@ -640,15 +640,17 @@ mod tests {
// most unicode whitespace characters // most unicode whitespace characters
parses( parses(
"\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}", "\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}",
&[Space("\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}")] &[Space(
"\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}",
)],
); );
// most unicode whitespace characters // most unicode whitespace characters
parses( parses(
"\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}", "\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}",
&[ &[
Space("\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}"), Space("\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}"),
Space("\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}") Space("\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{3000}"),
] ],
); );
check("a", &[Space("")], Err(TOO_LONG)); check("a", &[Space("")], Err(TOO_LONG));
check("a", &[Space(" ")], Err(TOO_LONG)); check("a", &[Space(" ")], Err(TOO_LONG));
@ -1835,8 +1837,10 @@ mod tests {
#[test] #[test]
fn test_issue_1010() { fn test_issue_1010() {
let dt = crate::NaiveDateTime::parse_from_str("\u{c}SUN\u{e}\u{3000}\0m@J\u{3000}\0\u{3000}\0m\u{c}!\u{c}\u{b}\u{c}\u{c}\u{c}\u{c}%A\u{c}\u{b}\0SU\u{c}\u{c}", let dt = crate::NaiveDateTime::parse_from_str(
"\u{c}\u{c}%A\u{c}\u{b}\0SUN\u{c}\u{c}\u{c}SUNN\u{c}\u{c}\u{c}SUN\u{c}\u{c}!\u{c}\u{b}\u{c}\u{c}\u{c}\u{c}%A\u{c}\u{b}%a"); "\u{c}SUN\u{e}\u{3000}\0m@J\u{3000}\0\u{3000}\0m\u{c}!\u{c}\u{b}\u{c}\u{c}\u{c}\u{c}%A\u{c}\u{b}\0SU\u{c}\u{c}",
"\u{c}\u{c}%A\u{c}\u{b}\0SUN\u{c}\u{c}\u{c}SUNN\u{c}\u{c}\u{c}SUN\u{c}\u{c}!\u{c}\u{b}\u{c}\u{c}\u{c}\u{c}%A\u{c}\u{b}%a",
);
assert_eq!(dt, Err(ParseError(ParseErrorKind::Invalid))); assert_eq!(dt, Err(ParseError(ParseErrorKind::Invalid)));
} }
} }

View File

@ -4,7 +4,7 @@
//! A collection of parsed date and time items. //! A collection of parsed date and time items.
//! They can be constructed incrementally while being checked for consistency. //! They can be constructed incrementally while being checked for consistency.
use super::{ParseResult, IMPOSSIBLE, NOT_ENOUGH, OUT_OF_RANGE}; use super::{IMPOSSIBLE, NOT_ENOUGH, OUT_OF_RANGE, ParseResult};
use crate::naive::{NaiveDate, NaiveDateTime, NaiveTime}; use crate::naive::{NaiveDate, NaiveDateTime, NaiveTime};
use crate::offset::{FixedOffset, MappedLocalTime, Offset, TimeZone}; use crate::offset::{FixedOffset, MappedLocalTime, Offset, TimeZone};
use crate::{DateTime, Datelike, TimeDelta, Timelike, Weekday}; use crate::{DateTime, Datelike, TimeDelta, Timelike, Weekday};
@ -176,11 +176,7 @@ pub struct Parsed {
#[inline] #[inline]
fn set_if_consistent<T: PartialEq>(old: &mut Option<T>, new: T) -> ParseResult<()> { fn set_if_consistent<T: PartialEq>(old: &mut Option<T>, new: T) -> ParseResult<()> {
if let Some(ref old) = *old { if let Some(ref old) = *old {
if *old == new { if *old == new { Ok(()) } else { Err(IMPOSSIBLE) }
Ok(())
} else {
Err(IMPOSSIBLE)
}
} else { } else {
*old = Some(new); *old = Some(new);
Ok(()) Ok(())
@ -701,11 +697,7 @@ impl Parsed {
(_, _, _) => return Err(NOT_ENOUGH), (_, _, _) => return Err(NOT_ENOUGH),
}; };
if verified { if verified { Ok(parsed_date) } else { Err(IMPOSSIBLE) }
Ok(parsed_date)
} else {
Err(IMPOSSIBLE)
}
} }
/// Returns a parsed naive time out of given fields. /// Returns a parsed naive time out of given fields.
@ -1166,10 +1158,10 @@ fn resolve_week_date(
mod tests { mod tests {
use super::super::{IMPOSSIBLE, NOT_ENOUGH, OUT_OF_RANGE}; use super::super::{IMPOSSIBLE, NOT_ENOUGH, OUT_OF_RANGE};
use super::Parsed; use super::Parsed;
use crate::naive::{NaiveDate, NaiveTime};
use crate::offset::{FixedOffset, TimeZone, Utc};
use crate::Datelike; use crate::Datelike;
use crate::Weekday::*; use crate::Weekday::*;
use crate::naive::{NaiveDate, NaiveTime};
use crate::offset::{FixedOffset, TimeZone, Utc};
#[test] #[test]
fn test_parsed_set_fields() { fn test_parsed_set_fields() {

View File

@ -5,7 +5,7 @@
* Various scanning routines for the parser. * Various scanning routines for the parser.
*/ */
use super::{ParseResult, INVALID, OUT_OF_RANGE, TOO_SHORT}; use super::{INVALID, OUT_OF_RANGE, ParseResult, TOO_SHORT};
use crate::Weekday; use crate::Weekday;
/// Tries to parse the non-negative number from `min` to `max` digits. /// Tries to parse the non-negative number from `min` to `max` digits.
@ -217,11 +217,7 @@ where
const fn digits(s: &str) -> ParseResult<(u8, u8)> { const fn digits(s: &str) -> ParseResult<(u8, u8)> {
let b = s.as_bytes(); let b = s.as_bytes();
if b.len() < 2 { if b.len() < 2 { Err(TOO_SHORT) } else { Ok((b[0], b[1])) }
Err(TOO_SHORT)
} else {
Ok((b[0], b[1]))
}
} }
let negative = match s.chars().next() { let negative = match s.chars().next() {
Some('+') => { Some('+') => {
@ -359,8 +355,8 @@ mod tests {
comment_2822, nanosecond, nanosecond_fixed, short_or_long_month0, short_or_long_weekday, comment_2822, nanosecond, nanosecond_fixed, short_or_long_month0, short_or_long_weekday,
timezone_offset_2822, timezone_offset_2822,
}; };
use crate::format::{INVALID, TOO_SHORT};
use crate::Weekday; use crate::Weekday;
use crate::format::{INVALID, TOO_SHORT};
#[test] #[test]
fn test_rfc2822_comments() { fn test_rfc2822_comments() {

View File

@ -161,12 +161,12 @@ Notes:
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
extern crate alloc; extern crate alloc;
use super::{fixed, internal_fixed, num, num0, nums};
#[cfg(feature = "unstable-locales")]
use super::{locales, Locale};
use super::{Fixed, InternalInternal, Item, Numeric, Pad};
#[cfg(any(feature = "alloc", feature = "std"))] #[cfg(any(feature = "alloc", feature = "std"))]
use super::{ParseError, BAD_FORMAT}; use super::{BAD_FORMAT, ParseError};
use super::{Fixed, InternalInternal, Item, Numeric, Pad};
#[cfg(feature = "unstable-locales")]
use super::{Locale, locales};
use super::{fixed, internal_fixed, num, num0, nums};
#[cfg(all(feature = "alloc", not(feature = "std"), not(test)))] #[cfg(all(feature = "alloc", not(feature = "std"), not(test)))]
use alloc::vec::Vec; use alloc::vec::Vec;
@ -686,8 +686,8 @@ mod tests {
use crate::format::Item::{self, Literal, Space}; use crate::format::Item::{self, Literal, Space};
#[cfg(feature = "unstable-locales")] #[cfg(feature = "unstable-locales")]
use crate::format::Locale; use crate::format::Locale;
use crate::format::{fixed, internal_fixed, num, num0, nums};
use crate::format::{Fixed, InternalInternal, Numeric::*}; use crate::format::{Fixed, InternalInternal, Numeric::*};
use crate::format::{fixed, internal_fixed, num, num0, nums};
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
use crate::{DateTime, FixedOffset, NaiveDate, TimeZone, Timelike, Utc}; use crate::{DateTime, FixedOffset, NaiveDate, TimeZone, Timelike, Utc};

View File

@ -3,8 +3,8 @@ use core::fmt;
#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))] #[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
use rkyv::{Archive, Deserialize, Serialize}; use rkyv::{Archive, Deserialize, Serialize};
use crate::naive::NaiveDate;
use crate::OutOfRange; use crate::OutOfRange;
use crate::naive::NaiveDate;
/// The month of the year. /// The month of the year.
/// ///
@ -395,8 +395,8 @@ mod tests {
#[test] #[test]
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
fn test_serde_serialize() { fn test_serde_serialize() {
use serde_json::to_string;
use Month::*; use Month::*;
use serde_json::to_string;
let cases: Vec<(Month, &str)> = vec![ let cases: Vec<(Month, &str)> = vec![
(January, "\"January\""), (January, "\"January\""),
@ -422,8 +422,8 @@ mod tests {
#[test] #[test]
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
fn test_serde_deserialize() { fn test_serde_deserialize() {
use serde_json::from_str;
use Month::*; use Month::*;
use serde_json::from_str;
let cases: Vec<(&str, Month)> = vec![ let cases: Vec<(&str, Month)> = vec![
("\"january\"", January), ("\"january\"", January),

View File

@ -30,13 +30,13 @@ use pure_rust_locales::Locale;
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
use crate::format::DelayedFormat; use crate::format::DelayedFormat;
use crate::format::{ use crate::format::{
parse, parse_and_remainder, write_hundreds, Item, Numeric, Pad, ParseError, ParseResult, Item, Numeric, Pad, ParseError, ParseResult, Parsed, StrftimeItems, parse, parse_and_remainder,
Parsed, StrftimeItems, write_hundreds,
}; };
use crate::month::Months; use crate::month::Months;
use crate::naive::{Days, IsoWeek, NaiveDateTime, NaiveTime, NaiveWeek}; use crate::naive::{Days, IsoWeek, NaiveDateTime, NaiveTime, NaiveWeek};
use crate::{expect, try_opt};
use crate::{Datelike, TimeDelta, Weekday}; use crate::{Datelike, TimeDelta, Weekday};
use crate::{expect, try_opt};
use super::internals::{Mdf, YearFlags}; use super::internals::{Mdf, YearFlags};

View File

@ -1,5 +1,5 @@
use super::{Days, Months, NaiveDate, MAX_YEAR, MIN_YEAR}; use super::{Days, MAX_YEAR, MIN_YEAR, Months, NaiveDate};
use crate::naive::internals::{YearFlags, A, AG, B, BA, C, CB, D, DC, E, ED, F, FE, G, GF}; use crate::naive::internals::{A, AG, B, BA, C, CB, D, DC, E, ED, F, FE, G, GF, YearFlags};
use crate::{Datelike, TimeDelta, Weekday}; use crate::{Datelike, TimeDelta, Weekday};
// as it is hard to verify year flags in `NaiveDate::MIN` and `NaiveDate::MAX`, // as it is hard to verify year flags in `NaiveDate::MIN` and `NaiveDate::MAX`,

View File

@ -15,14 +15,14 @@ use rkyv::{Archive, Deserialize, Serialize};
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
use crate::format::DelayedFormat; use crate::format::DelayedFormat;
use crate::format::{parse, parse_and_remainder, ParseError, ParseResult, Parsed, StrftimeItems};
use crate::format::{Fixed, Item, Numeric, Pad}; use crate::format::{Fixed, Item, Numeric, Pad};
use crate::format::{ParseError, ParseResult, Parsed, StrftimeItems, parse, parse_and_remainder};
use crate::naive::{Days, IsoWeek, NaiveDate, NaiveTime}; use crate::naive::{Days, IsoWeek, NaiveDate, NaiveTime};
use crate::offset::Utc; use crate::offset::Utc;
use crate::time_delta::NANOS_PER_SEC; use crate::time_delta::NANOS_PER_SEC;
use crate::{ use crate::{
expect, try_opt, DateTime, Datelike, FixedOffset, MappedLocalTime, Months, TimeDelta, TimeZone, DateTime, Datelike, FixedOffset, MappedLocalTime, Months, TimeDelta, TimeZone, Timelike,
Timelike, Weekday, Weekday, expect, try_opt,
}; };
/// Tools to help serializing/deserializing `NaiveDateTime`s /// Tools to help serializing/deserializing `NaiveDateTime`s

View File

@ -199,11 +199,10 @@ fn test_datetime_parse_from_str() {
NaiveDateTime::parse_from_str("Fri, 09 Aug 2013 23:54:35 GMT", "%a, %d %b %Y %H:%M:%S GMT"), NaiveDateTime::parse_from_str("Fri, 09 Aug 2013 23:54:35 GMT", "%a, %d %b %Y %H:%M:%S GMT"),
Ok(ymdhms(2013, 8, 9, 23, 54, 35)) Ok(ymdhms(2013, 8, 9, 23, 54, 35))
); );
assert!(NaiveDateTime::parse_from_str( assert!(
"Sat, 09 Aug 2013 23:54:35 GMT", NaiveDateTime::parse_from_str("Sat, 09 Aug 2013 23:54:35 GMT", "%a, %d %b %Y %H:%M:%S GMT")
"%a, %d %b %Y %H:%M:%S GMT" .is_err()
) );
.is_err());
assert!(NaiveDateTime::parse_from_str("2014-5-7 12:3456", "%Y-%m-%d %H:%M:%S").is_err()); assert!(NaiveDateTime::parse_from_str("2014-5-7 12:3456", "%Y-%m-%d %H:%M:%S").is_err());
assert!(NaiveDateTime::parse_from_str("12:34:56", "%H:%M:%S").is_err()); // insufficient assert!(NaiveDateTime::parse_from_str("12:34:56", "%H:%M:%S").is_err()); // insufficient
assert_eq!( assert_eq!(

View File

@ -381,7 +381,7 @@ impl fmt::Debug for Mdf {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::Mdf; use super::Mdf;
use super::{YearFlags, A, AG, B, BA, C, CB, D, DC, E, ED, F, FE, G, GF}; use super::{A, AG, B, BA, C, CB, D, DC, E, ED, F, FE, G, GF, YearFlags};
const NONLEAP_FLAGS: [YearFlags; 7] = [A, B, C, D, E, F, G]; const NONLEAP_FLAGS: [YearFlags; 7] = [A, B, C, D, E, F, G];
const LEAP_FLAGS: [YearFlags; 7] = [AG, BA, CB, DC, ED, FE, GF]; const LEAP_FLAGS: [YearFlags; 7] = [AG, BA, CB, DC, ED, FE, GF];

View File

@ -164,8 +164,8 @@ impl fmt::Debug for IsoWeek {
mod tests { mod tests {
#[cfg(feature = "rkyv-validation")] #[cfg(feature = "rkyv-validation")]
use super::IsoWeek; use super::IsoWeek;
use crate::naive::date::{self, NaiveDate};
use crate::Datelike; use crate::Datelike;
use crate::naive::date::{self, NaiveDate};
#[test] #[test]
fn test_iso_week_extremes() { fn test_iso_week_extremes() {

View File

@ -6,8 +6,8 @@
use core::ops::RangeInclusive; use core::ops::RangeInclusive;
use crate::expect;
use crate::Weekday; use crate::Weekday;
use crate::expect;
pub(crate) mod date; pub(crate) mod date;
pub(crate) mod datetime; pub(crate) mod datetime;
@ -15,11 +15,11 @@ mod internals;
pub(crate) mod isoweek; pub(crate) mod isoweek;
pub(crate) mod time; pub(crate) mod time;
pub use self::date::{NaiveDate, NaiveDateDaysIterator, NaiveDateWeeksIterator};
#[allow(deprecated)] #[allow(deprecated)]
pub use self::date::{MAX_DATE, MIN_DATE}; pub use self::date::{MAX_DATE, MIN_DATE};
pub use self::date::{NaiveDate, NaiveDateDaysIterator, NaiveDateWeeksIterator};
#[allow(deprecated)] #[allow(deprecated)]
pub use self::datetime::{NaiveDateTime, MAX_DATETIME, MIN_DATETIME}; pub use self::datetime::{MAX_DATETIME, MIN_DATETIME, NaiveDateTime};
pub use self::isoweek::IsoWeek; pub use self::isoweek::IsoWeek;
pub use self::time::NaiveTime; pub use self::time::NaiveTime;

View File

@ -15,11 +15,11 @@ use rkyv::{Archive, Deserialize, Serialize};
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
use crate::format::DelayedFormat; use crate::format::DelayedFormat;
use crate::format::{ use crate::format::{
parse, parse_and_remainder, write_hundreds, Fixed, Item, Numeric, Pad, ParseError, ParseResult, Fixed, Item, Numeric, Pad, ParseError, ParseResult, Parsed, StrftimeItems, parse,
Parsed, StrftimeItems, parse_and_remainder, write_hundreds,
}; };
use crate::{expect, try_opt};
use crate::{FixedOffset, TimeDelta, Timelike}; use crate::{FixedOffset, TimeDelta, Timelike};
use crate::{expect, try_opt};
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
mod serde; mod serde;

View File

@ -10,7 +10,7 @@ use core::str::FromStr;
use rkyv::{Archive, Deserialize, Serialize}; use rkyv::{Archive, Deserialize, Serialize};
use super::{MappedLocalTime, Offset, TimeZone}; use super::{MappedLocalTime, Offset, TimeZone};
use crate::format::{scan, ParseError, OUT_OF_RANGE}; use crate::format::{OUT_OF_RANGE, ParseError, scan};
use crate::naive::{NaiveDate, NaiveDateTime}; use crate::naive::{NaiveDate, NaiveDateTime};
/// The time zone with fixed offset, from UTC-23:59:59 to UTC+23:59:59. /// The time zone with fixed offset, from UTC-23:59:59 to UTC+23:59:59.

View File

@ -11,9 +11,9 @@ use rkyv::{Archive, Deserialize, Serialize};
use super::fixed::FixedOffset; use super::fixed::FixedOffset;
use super::{MappedLocalTime, TimeZone}; use super::{MappedLocalTime, TimeZone};
use crate::naive::{NaiveDate, NaiveDateTime, NaiveTime};
#[allow(deprecated)] #[allow(deprecated)]
use crate::Date; use crate::Date;
use crate::naive::{NaiveDate, NaiveDateTime, NaiveTime};
use crate::{DateTime, Utc}; use crate::{DateTime, Utc};
#[cfg(unix)] #[cfg(unix)]
@ -274,9 +274,9 @@ fn lookup_with_dst_transitions(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::Local; use super::Local;
#[cfg(windows)]
use crate::offset::local::{lookup_with_dst_transitions, Transition};
use crate::offset::TimeZone; use crate::offset::TimeZone;
#[cfg(windows)]
use crate::offset::local::{Transition, lookup_with_dst_transitions};
use crate::{Datelike, Days, Utc}; use crate::{Datelike, Days, Utc};
#[cfg(windows)] #[cfg(windows)]
use crate::{FixedOffset, MappedLocalTime, NaiveDate, NaiveDateTime}; use crate::{FixedOffset, MappedLocalTime, NaiveDate, NaiveDateTime};

View File

@ -3,9 +3,9 @@ use std::iter;
use std::num::ParseIntError; use std::num::ParseIntError;
use std::str::{self, FromStr}; use std::str::{self, FromStr};
use super::Error;
use super::rule::TransitionRule; use super::rule::TransitionRule;
use super::timezone::{LeapSecond, LocalTimeType, TimeZone, Transition}; use super::timezone::{LeapSecond, LocalTimeType, TimeZone, Transition};
use super::Error;
pub(super) fn parse(bytes: &[u8]) -> Result<TimeZone, Error> { pub(super) fn parse(bytes: &[u8]) -> Result<TimeZone, Error> {
let mut cursor = Cursor::new(bytes); let mut cursor = Cursor::new(bytes);
@ -14,7 +14,7 @@ pub(super) fn parse(bytes: &[u8]) -> Result<TimeZone, Error> {
Version::V1 => match cursor.is_empty() { Version::V1 => match cursor.is_empty() {
true => (state, None), true => (state, None),
false => { false => {
return Err(Error::InvalidTzFile("remaining data after end of TZif v1 data block")) return Err(Error::InvalidTzFile("remaining data after end of TZif v1 data block"));
} }
}, },
Version::V2 | Version::V3 => { Version::V2 | Version::V3 => {

View File

@ -1,7 +1,7 @@
use super::parser::Cursor; use super::parser::Cursor;
use super::timezone::{LocalTimeType, SECONDS_PER_WEEK}; use super::timezone::{LocalTimeType, SECONDS_PER_WEEK};
use super::{ use super::{
Error, CUMUL_DAY_IN_MONTHS_NORMAL_YEAR, DAYS_PER_WEEK, DAY_IN_MONTHS_NORMAL_YEAR, CUMUL_DAY_IN_MONTHS_NORMAL_YEAR, DAY_IN_MONTHS_NORMAL_YEAR, DAYS_PER_WEEK, Error,
SECONDS_PER_DAY, SECONDS_PER_DAY,
}; };
use crate::{Datelike, NaiveDateTime}; use crate::{Datelike, NaiveDateTime};
@ -39,7 +39,7 @@ impl TransitionRule {
Some(&b',') => std_offset - 3600, Some(&b',') => std_offset - 3600,
Some(_) => parse_offset(&mut cursor)?, Some(_) => parse_offset(&mut cursor)?,
None => { None => {
return Err(Error::UnsupportedTzString("DST start and end rules must be provided")) return Err(Error::UnsupportedTzString("DST start and end rules must be provided"));
} }
}; };
@ -219,11 +219,7 @@ impl AlternateTime {
} }
}; };
if is_dst { if is_dst { Ok(&self.dst) } else { Ok(&self.std) }
Ok(&self.dst)
} else {
Ok(&self.std)
}
} }
fn find_local_time_type_from_local( fn find_local_time_type_from_local(

View File

@ -1,13 +1,13 @@
//! Types related to a time zone. //! Types related to a time zone.
use super::rule::{AlternateTime, TransitionRule};
use super::{parser, Error, DAYS_PER_WEEK, SECONDS_PER_DAY};
use crate::NaiveDateTime;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::{self, Read}; use std::io::{self, Read};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::{cmp::Ordering, fmt, str}; use std::{cmp::Ordering, fmt, str};
use super::rule::{AlternateTime, TransitionRule};
use super::{DAYS_PER_WEEK, Error, SECONDS_PER_DAY, parser};
use crate::NaiveDateTime;
#[cfg(target_env = "ohos")] #[cfg(target_env = "ohos")]
use crate::offset::local::tz_info::parser::Cursor; use crate::offset::local::tz_info::parser::Cursor;

View File

@ -14,7 +14,7 @@ use std::ptr;
use super::win_bindings::{GetTimeZoneInformationForYear, SYSTEMTIME, TIME_ZONE_INFORMATION}; use super::win_bindings::{GetTimeZoneInformationForYear, SYSTEMTIME, TIME_ZONE_INFORMATION};
use crate::offset::local::{lookup_with_dst_transitions, Transition}; use crate::offset::local::{Transition, lookup_with_dst_transitions};
use crate::{Datelike, FixedOffset, MappedLocalTime, NaiveDate, NaiveDateTime, NaiveTime, Weekday}; use crate::{Datelike, FixedOffset, MappedLocalTime, NaiveDate, NaiveDateTime, NaiveTime, Weekday};
// We don't use `SystemTimeToTzSpecificLocalTime` because it doesn't support the same range of dates // We don't use `SystemTimeToTzSpecificLocalTime` because it doesn't support the same range of dates
@ -213,7 +213,7 @@ fn naive_date_time_from_system_time(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::offset::local::win_bindings::{ use crate::offset::local::win_bindings::{
SystemTimeToFileTime, TzSpecificLocalTimeToSystemTime, FILETIME, SYSTEMTIME, FILETIME, SYSTEMTIME, SystemTimeToFileTime, TzSpecificLocalTimeToSystemTime,
}; };
use crate::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, TimeDelta}; use crate::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, TimeDelta};
use crate::{Datelike, TimeZone, Timelike}; use crate::{Datelike, TimeZone, Timelike};

View File

@ -20,9 +20,9 @@
use core::fmt; use core::fmt;
use crate::format::{parse, ParseResult, Parsed, StrftimeItems};
use crate::naive::{NaiveDate, NaiveDateTime, NaiveTime};
use crate::Weekday; use crate::Weekday;
use crate::format::{ParseResult, Parsed, StrftimeItems, parse};
use crate::naive::{NaiveDate, NaiveDateTime, NaiveTime};
#[allow(deprecated)] #[allow(deprecated)]
use crate::{Date, DateTime}; use crate::{Date, DateTime};

View File

@ -365,8 +365,8 @@ impl std::error::Error for RoundingError {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{DurationRound, RoundingError, SubsecRound, TimeDelta}; use super::{DurationRound, RoundingError, SubsecRound, TimeDelta};
use crate::offset::{FixedOffset, TimeZone, Utc};
use crate::Timelike; use crate::Timelike;
use crate::offset::{FixedOffset, TimeZone, Utc};
use crate::{DateTime, NaiveDate}; use crate::{DateTime, NaiveDate};
#[test] #[test]

View File

@ -301,22 +301,14 @@ impl TimeDelta {
/// Returns the total number of whole seconds in the `TimeDelta`. /// Returns the total number of whole seconds in the `TimeDelta`.
pub const fn num_seconds(&self) -> i64 { pub const fn num_seconds(&self) -> i64 {
// If secs is negative, nanos should be subtracted from the duration. // If secs is negative, nanos should be subtracted from the duration.
if self.secs < 0 && self.nanos > 0 { if self.secs < 0 && self.nanos > 0 { self.secs + 1 } else { self.secs }
self.secs + 1
} else {
self.secs
}
} }
/// Returns the number of nanoseconds such that /// Returns the number of nanoseconds such that
/// `subsec_nanos() + num_seconds() * NANOS_PER_SEC` is the total number of /// `subsec_nanos() + num_seconds() * NANOS_PER_SEC` is the total number of
/// nanoseconds in the `TimeDelta`. /// nanoseconds in the `TimeDelta`.
pub const fn subsec_nanos(&self) -> i32 { pub const fn subsec_nanos(&self) -> i32 {
if self.secs < 0 && self.nanos > 0 { if self.secs < 0 && self.nanos > 0 { self.nanos - NANOS_PER_SEC } else { self.nanos }
self.nanos - NANOS_PER_SEC
} else {
self.nanos
}
} }
/// Returns the total number of whole milliseconds in the `TimeDelta`. /// Returns the total number of whole milliseconds in the `TimeDelta`.
@ -642,7 +634,7 @@ impl arbitrary::Arbitrary<'_> for TimeDelta {
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
mod serde { mod serde {
use super::TimeDelta; use super::TimeDelta;
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
impl Serialize for TimeDelta { impl Serialize for TimeDelta {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
@ -683,7 +675,7 @@ mod serde {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::OutOfRangeError; use super::OutOfRangeError;
use super::{TimeDelta, MAX, MIN}; use super::{MAX, MIN, TimeDelta};
use crate::expect; use crate::expect;
use core::time::Duration; use core::time::Duration;
@ -803,10 +795,12 @@ mod tests {
fn test_duration_milliseconds_max_overflow() { fn test_duration_milliseconds_max_overflow() {
// Here we ensure that trying to add one millisecond to the maximum storable // Here we ensure that trying to add one millisecond to the maximum storable
// value will fail. // value will fail.
assert!(TimeDelta::try_milliseconds(i64::MAX) assert!(
.unwrap() TimeDelta::try_milliseconds(i64::MAX)
.checked_add(&TimeDelta::try_milliseconds(1).unwrap()) .unwrap()
.is_none()); .checked_add(&TimeDelta::try_milliseconds(1).unwrap())
.is_none()
);
} }
#[test] #[test]
@ -826,10 +820,12 @@ mod tests {
fn test_duration_milliseconds_min_underflow() { fn test_duration_milliseconds_min_underflow() {
// Here we ensure that trying to subtract one millisecond from the minimum // Here we ensure that trying to subtract one millisecond from the minimum
// storable value will fail. // storable value will fail.
assert!(TimeDelta::try_milliseconds(-i64::MAX) assert!(
.unwrap() TimeDelta::try_milliseconds(-i64::MAX)
.checked_sub(&TimeDelta::try_milliseconds(1).unwrap()) .unwrap()
.is_none()); .checked_sub(&TimeDelta::try_milliseconds(1).unwrap())
.is_none()
);
} }
#[test] #[test]
@ -905,10 +901,12 @@ mod tests {
); );
// Here we ensure that trying to add one microsecond to the maximum storable // Here we ensure that trying to add one microsecond to the maximum storable
// value will fail. // value will fail.
assert!(TimeDelta::try_milliseconds(i64::MAX) assert!(
.unwrap() TimeDelta::try_milliseconds(i64::MAX)
.checked_add(&TimeDelta::microseconds(1)) .unwrap()
.is_none()); .checked_add(&TimeDelta::microseconds(1))
.is_none()
);
} }
#[test] #[test]
fn test_duration_microseconds_min_allowed() { fn test_duration_microseconds_min_allowed() {
@ -944,10 +942,12 @@ mod tests {
); );
// Here we ensure that trying to subtract one microsecond from the minimum // Here we ensure that trying to subtract one microsecond from the minimum
// storable value will fail. // storable value will fail.
assert!(TimeDelta::try_milliseconds(-i64::MAX) assert!(
.unwrap() TimeDelta::try_milliseconds(-i64::MAX)
.checked_sub(&TimeDelta::microseconds(1)) .unwrap()
.is_none()); .checked_sub(&TimeDelta::microseconds(1))
.is_none()
);
} }
#[test] #[test]
@ -1009,10 +1009,12 @@ mod tests {
); );
// Here we ensure that trying to add one nanosecond to the maximum storable // Here we ensure that trying to add one nanosecond to the maximum storable
// value will fail. // value will fail.
assert!(TimeDelta::try_milliseconds(i64::MAX) assert!(
.unwrap() TimeDelta::try_milliseconds(i64::MAX)
.checked_add(&TimeDelta::nanoseconds(1)) .unwrap()
.is_none()); .checked_add(&TimeDelta::nanoseconds(1))
.is_none()
);
} }
#[test] #[test]
@ -1049,10 +1051,12 @@ mod tests {
); );
// Here we ensure that trying to subtract one nanosecond from the minimum // Here we ensure that trying to subtract one nanosecond from the minimum
// storable value will fail. // storable value will fail.
assert!(TimeDelta::try_milliseconds(-i64::MAX) assert!(
.unwrap() TimeDelta::try_milliseconds(-i64::MAX)
.checked_sub(&TimeDelta::nanoseconds(1)) .unwrap()
.is_none()); .checked_sub(&TimeDelta::nanoseconds(1))
.is_none()
);
} }
#[test] #[test]

View File

@ -37,11 +37,7 @@ pub trait Datelike: Sized {
#[inline] #[inline]
fn year_ce(&self) -> (bool, u32) { fn year_ce(&self) -> (bool, u32) {
let year = self.year(); let year = self.year();
if year < 1 { if year < 1 { (false, (1 - year) as u32) } else { (true, year as u32) }
(false, (1 - year) as u32)
} else {
(true, year as u32)
}
} }
/// Returns the month number starting from 1. /// Returns the month number starting from 1.

View File

@ -161,11 +161,7 @@ impl Weekday {
pub const fn days_since(&self, other: Weekday) -> u32 { pub const fn days_since(&self, other: Weekday) -> u32 {
let lhs = *self as u32; let lhs = *self as u32;
let rhs = other as u32; let rhs = other as u32;
if lhs < rhs { if lhs < rhs { 7 + lhs - rhs } else { lhs - rhs }
7 + lhs - rhs
} else {
lhs - rhs
}
} }
} }
@ -344,8 +340,8 @@ mod tests {
#[test] #[test]
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
fn test_serde_serialize() { fn test_serde_serialize() {
use serde_json::to_string;
use Weekday::*; use Weekday::*;
use serde_json::to_string;
let cases: Vec<(Weekday, &str)> = vec![ let cases: Vec<(Weekday, &str)> = vec![
(Mon, "\"Mon\""), (Mon, "\"Mon\""),
@ -366,8 +362,8 @@ mod tests {
#[test] #[test]
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
fn test_serde_deserialize() { fn test_serde_deserialize() {
use serde_json::from_str;
use Weekday::*; use Weekday::*;
use serde_json::from_str;
let cases: Vec<(&str, Weekday)> = vec![ let cases: Vec<(&str, Weekday)> = vec![
("\"mon\"", Mon), ("\"mon\"", Mon),