iso8601-0.4.0/.gitignore010064400007660000024000000000301331615603500130300ustar0000000000000000target Cargo.lock *.swp iso8601-0.4.0/.travis.yml010064400007660000024000000003311342457562600131700ustar0000000000000000language: rust sudo: false rust: - stable - beta - nightly script: - cargo test --all - rustup component add rustfmt - cargo fmt --all -- --check - cargo build --release notifications: email: false iso8601-0.4.0/Cargo.toml.orig010064400007660000024000000007031362575463700137550ustar0000000000000000[package] name = "iso8601" version = "0.4.0" authors = ["Jan-Erik Rediger ", "Hendrik Sollich "] description = "Parsing ISO8601 dates using nom" repository = "https://github.com/badboy/iso8601" documentation = "https://docs.rs/iso8601/" license = "MIT" readme = "README.md" edition = "2018" [dependencies] nom = { version = "5.0.0", default-features = false } [features] default = ["std"] std = ["nom/std"] iso8601-0.4.0/Cargo.toml0000644000000017051362575464100102620ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "iso8601" version = "0.4.0" authors = ["Jan-Erik Rediger ", "Hendrik Sollich "] description = "Parsing ISO8601 dates using nom" documentation = "https://docs.rs/iso8601/" readme = "README.md" license = "MIT" repository = "https://github.com/badboy/iso8601" [dependencies.nom] version = "5.0.0" default-features = false [features] default = ["std"] std = ["nom/std"] iso8601-0.4.0/CHANGELOG.md010064400007660000024000000017741362575463700127100ustar0000000000000000# Changelog ## [Unreleased](https://github.com/badboy/iso8601/compare/v0.4.0...master) - ReleaseDate ## [0.4.0](https://github.com/badboy/iso8601/compare/v0.3.0...v0.4.0) - 2020-02-27 * Upgrade to [nom 5](http://unhandledexpression.com/general/2019/06/17/nom-5-is-here.html), getting rid of all parser macros ([#22](https://github.com/badboy/iso8601/pull/22)). * Added support for ISO 8601 Durations ([#24](https://github.com/badboy/iso8601/pull/24), thanks to @zoewithabang). ## [0.3.0](https://github.com/badboy/iso8601/compare/v0.2.0...v0.3.0) - 2019-01-31 * Add `Display` implementations for exported structures * Implemented `FromStr` for `Date`, `Time` and `DateTime` * Upgraded to nom 4 * Formatted everything with `rustfmt` ## [0.2.0](https://github.com/badboy/iso8601/compare/v0.1.0...v0.2.0) - 2017-11-06 * Upgraded nom * Added fuzzing targets * Correctly overwrite hours and minutes in `Time#set_tz` * Correct small error in README example ## 0.1.0 - 2017-11-06 Initial release iso8601-0.4.0/docs/parsing-iso8601-dates-using-nom.md010064400007660000024000000447111342410232000200760ustar0000000000000000# omnomnom - Parsing ISO8601 dates using nom -- Authors: - Jan-Erik Rediger - Chris Couzens History: - 2015-07-16: [Original blog article](https://fnordig.de/2015/07/16/omnomnom-parsing-iso8601-dates-using-nom/) - 2018-07-01: Imported into crate repository & updated article to work with nom 4. -- There are thousands of ways to note down a date and time. The international date format is standardized as [ISO8601][iso], though it still allows a widespread of different formats. The basic format looks like this: > 2015-07-02T19:45:00+0100 And that's what we will parse today using [nom][nom], a parser combinator library created by [Geoffroy Couprie][gcouprie]. The idea is that you write small self-contained parsers, which all do only one simple thing, like parsing the year in our string, and then combine these small parsers to a bigger one to parse the full format. `nom` comes with a wide variety of small parsers: handling different integers, reading simple byte arrays, optional fields, mapping parsed data over a function, ... Most of them are provided as combinable macros. It's very easy to implement your own small parsers, either by providing a method that handles a short byte buffer or by combining existing parsers. So let's dive right in and see how to use nom in real code. ### Analysis This is what we want to parse: > 2015-07-02T19:45:00+0100 It has several parts we need to parse: > YYYY-MM-DDTHH:MM:SS+OOOO with the following meaning: | Characters | Meaning | | ---------- | ------- | | YYYY | The year, can be negative or null and can be extended if necessary | | MM | Month from 1 to 12 (0-prefixed) | | DD | Day from 1 to 31 (0-prefixed) | | T | Separator between date and time | | HH | Hour, 0-23 (0-prefixed) | | MM | Minutes, 0-59 (0-prefixed) | | SS | Seconds, 0-59 (0-prefixed) | | OOOO | Timezone offset, separated by a `+` or `-` sign or `Z` for UTC | Parts like the seconds and the timezone offset are optional. Datetime strings without them will default to a zero value for that field. The date parts are separated by a dash (`-`) and the time parts by a colon (`:`). We will built a small parser for each of these parts and at the end combine them to parse a full date time string. ### Boiler Plate We will need to make a lib project. ~~~bash cargo new --lib date_parse ~~~ Edit `Cargo.toml` and `src/lib.rs` so that our project depends on nom. ~~~toml [dependencies] nom = "^4.0" ~~~ ~~~rust #[macro_use] extern crate nom; ~~~ ### Parsing the date: 2015-07-16 Let's start with the sign. As we need it several times, we create its own parser for that. Parsers are created by giving them a name, stating the return value (or defaulting to a byte slice) and the parser combinators to handle the input. ~~~rust named!(sign <&[u8], i32>, alt!( tag!("-") => { |_| -1 } | tag!("+") => { |_| 1 } ) ); #[cfg(test)] mod tests { use nom::Context::Code; use nom::Err::Error; use nom::Err::Incomplete; use nom::ErrorKind::Alt; use nom::Needed::Size; use sign; #[test] fn parse_sign() { assert_eq!(sign(b"-"), Ok((&[][..], -1))); assert_eq!(sign(b"+"), Ok((&[][..], 1))); assert_eq!(sign(b""), Err(Incomplete(Size(1)))); assert_eq!(sign(b" "), Err(Error(Code(&b" "[..], Alt)))); } } ~~~ First, we parse either a plus or a minus sign. This combines two already existing parsers: `tag!`, which will match the given byte array (in our case a single character) and `alt!`, which will try a list of parsers, returning on the first successful one. We can directly map the result of the sub-parsers to either `-1` or `1`, so we don't need to deal with the byte slice later. Next we parse the year, which consists of an optional sign and 4 digits (I know, I know, it is possible to extend this to more digits, but let's keep it simple for now). ~~~rust use std::ops::{AddAssign, MulAssign}; fn buf_to_int(s: &[u8]) -> T where T: AddAssign + MulAssign + From, { let mut sum = T::from(0); for digit in s { sum *= T::from(10); sum += T::from(*digit - b'0'); } sum } named!(positive_year <&[u8], i32>, map!(take_while_m_n!(4, 4, nom::is_digit), buf_to_int)); named!(pub year <&[u8], i32>, do_parse!( pref: opt!(sign) >> y: positive_year >> (pref.unwrap_or(1) * y) )); #[cfg(test)] mod tests { use positive_year; use year; #[test] fn parse_positive_year() { assert_eq!(positive_year(b"2018"), Ok((&[][..], 2018))); } #[test] fn parse_year() { assert_eq!(year(b"2018"), Ok((&[][..], 2018))); assert_eq!(year(b"+2018"), Ok((&[][..], 2018))); assert_eq!(year(b"-2018"), Ok((&[][..], -2018))); } } ~~~ A lot of additional stuff here. So let's separate it. ~~~rust named!(positive_year <&[u8], i32>, map!(take_while_m_n!(4, 4, nom::is_digit), buf_to_int)); ~~~ This creates a new named parser, that again returns the remaining input and an 32-bit integer. To work, it first calls `take_4_digits` and then maps that result to the corresponding integer. `take_while_m_n` is another small helper parser. We will also use one for 2 digits: ~~~rust take_while_m_n!(4, 4, nom::is_digit) take_while_m_n!(2, 2, nom::is_digit) ~~~ This takes 4 (or 2) characters from the input and checks that each character is a digit. ~~~rust named!(pub year <&[u8], i32>, do_parse!( ~~~ The year is also returned as a 32-bit integer (there's a pattern!). Using the `do_parse!` macro, we can chain together multiple parsers and work with the sub-results. ~~~rust pref: opt!(sign) >> y: positive_year >> ~~~ Our sign is directly followed by 4 digits. It's optional though, that's why we use `opt!`. `>>` is the concatenation operator in the `chain!` macro. We save the sub-results to variables (`pref` and `y`). ~~~rust (pref.unwrap_or(1) * y) ~~~ To get the final result, we multiply the prefix (which comes back as either `1` or `-1`) with the year. We can now successfully parse a year: ~~~rust assert_eq!(year(b"2018"), Ok((&[][..], 2018))); assert_eq!(year(b"-0333"), Ok((&[][..], -0333))); ~~~ Our nom parser will return an `IResult`. ~~~rust type IResult = Result<(I, O), Err>; pub enum Err { Incomplete(Needed), Error(Context), Failure(Context), } ~~~ If all went well, we get `Ok(I,O)` with `I` and `O` being the appropriate types. For our case `I` is the same as the input, a buffer slice (`&[u8]`), and `O` is the output of the parser itself, an integer (`i32`). The return value could also be an `Err(Failure)`, if something went completely wrong, or `Err(Incomplete(Needed))`, requesting more data to be able to satisfy the parser (you can't parse a 4-digit year with only 3 characters input). Parsing the month and day is a bit easier now: we simply take the digits and map them to an integer: ~~~rust named!(month <&[u8], u8>, map!(take_while_m_n!(2, 2, nom::is_digit), buf_to_int)); named!(day <&[u8], u8>, map!(take_while_m_n!(2, 2, nom::is_digit), buf_to_int)); #[cfg(test)] mod tests { use day; use month; #[test] fn parse_month() { assert_eq!(month(b"06"), Ok((&[][..], 06))); } #[test] fn parse_day() { assert_eq!(day(b"18"), Ok((&[][..], 18))); } } ~~~ All that's left is combining these 3 parts to parse a full date. Again we can chain the different parsers and map it to some useful value: ~~~rust #[derive(Eq, PartialEq, Debug)] pub struct Date { year: i32, month: u8, day: u8, } named!(pub date <&[u8], Date>, do_parse!( year: year >> tag!("-") >> month: month >> tag!("-") >> day: day >> (Date { year, month, day}) )); #[cfg(test)] mod tests { use date; use Date; #[test] fn parse_date() { assert_eq!( Ok(( &[][..], Date { year: 2015, month: 7, day: 16 } )), date(b"2015-07-16") ); assert_eq!( Ok(( &[][..], Date { year: -333, month: 6, day: 11 } )), date(b"-0333-06-11") ); } } ~~~ And running the tests shows it already works! ### Parsing the time: 16:43:52 Next, we parse the time. The individual parts are really simple, just some digits: ~~~rust named!(pub hour <&[u8], u8>, map!(take_while_m_n!(2, 2, nom::is_digit), buf_to_int)); named!(pub minute <&[u8], u8>, map!(take_while_m_n!(2, 2, nom::is_digit), buf_to_int)); named!(pub second <&[u8], u8>, map!(take_while_m_n!(2, 2, nom::is_digit), buf_to_int)); ~~~ Putting them together becomes a bit more complex, as the `second` part is optional: ~~~rust #[derive(Eq, PartialEq, Debug)] pub struct Time { hour: u8, minute: u8, second: u8, tz_offset: i32, } named!(pub time <&[u8], Time>, do_parse!( hour: hour >> tag!(":") >> minute: minute >> second: opt!(complete!(do_parse!( tag!(":") >> second: second >> (second) ))) >> (Time {hour, minute, second: second.unwrap_or(0), tz_offset: 0}) )); #[cfg(test)] mod tests { use time; use Time; #[test] fn parse_time() { assert_eq!( Ok(( &[][..], Time { hour: 16, minute: 43, second: 52, tz_offset: 0 } )), time(b"16:43:52") ); assert_eq!( Ok(( &[][..], Time { hour: 16, minute: 43, second: 0, tz_offset: 0 } )), time(b"16:43") ); } } ~~~ As you can see, even `do_parse!` parsers can be nested. The sub-parts then must be mapped once for the inner parser and once into the final value of the outer parser. `opt!` returns an `Option`. Either `None` if there is no input left or it applies the nested parser. If this parser doesn't fail, `Some(value)` is returned. Our parser now works for simple time information. But it leaves out one important bit: the timezone. ### Parsing the timezone: +0100 ~~~ 2015-07-02T19:45:00-0500 2015-07-02T19:45:00Z 2015-07-02T19:45:00+01 ~~~ Above are three variants of valid dates with timezones. The timezone in an ISO8601 string is either an appended `Z`, indicating UTC, or it's separated using a sign (`+` or `-`) and appends the offset from UTC in hours and minutes (with the minutes being optional). Let's cover the UTC special case first: ~~~rust named!(timezone_utc <&[u8], i32>, map!(tag!("Z"), |_| 0)); ~~~ This should look familiar by now. It's a simple `Z` character, which we map to `0`. The other case is the sign-separated hour and minute offset. ~~~rust named!(timezone_hour <&[u8], i32>, do_parse!( sign: sign >> hour: hour >> minute: opt!(complete!(do_parse!( opt!(tag!(":")) >> minute: minute >> (minute) ))) >> ((sign * (hour as i32 * 3600 + minute.unwrap_or(0) as i32 * 60))) )); ~~~ We can re-use our already existing parsers and once again chain them to get what we want. The minutes are optional (and might be separated using a colon). Instead of keeping this as is, we're mapping it to the offset in seconds. We will see why later. We could also just map it to a tuple like
`(sign, hour, minute.unwrap_or(0))` and handle conversion at a later point. Combined we get ~~~rust named!(timezone <&[u8], i32>, alt!(timezone_utc | timezone_hour)); ~~~ Putting this back into time we get: ~~~rust named!(pub time <&[u8], Time>, do_parse!( hour: hour >> tag!(":") >> minute: minute >> second: opt!(complete!(do_parse!( tag!(":") >> second: second >> (second) ))) >> tz_offset: opt!(complete!(timezone)) >> (Time {hour, minute, second: second.unwrap_or(0), tz_offset: tz_offset.unwrap_or(0)}) )); #[cfg(test)] mod tests { use time; use Time; #[test] fn parse_time_with_offset() { assert_eq!( Ok(( &[][..], Time { hour: 16, minute: 43, second: 52, tz_offset: 0 } )), time(b"16:43:52Z") ); assert_eq!( Ok(( &[][..], Time { hour: 16, minute: 43, second: 0, tz_offset: 5 * 3600 } )), time(b"16:43+05") ); assert_eq!( Ok(( &[][..], Time { hour: 16, minute: 43, second: 15, tz_offset: 5 * 3600 } )), time(b"16:43:15+0500") ); assert_eq!( Ok(( &[][..], Time { hour: 16, minute: 43, second: 0, tz_offset: -(5 * 3600 + 30 * 60) } )), time(b"16:43-05:30") ); } } ~~~ ### Putting it all together We now got individual parsers for the date, the time and the timezone offset. Putting it all together, our final datetime parser looks quite small and easy to understand: ~~~rust #[derive(Eq, PartialEq, Debug)] pub struct DateTime { date: Date, time: Time, } named!(pub datetime <&[u8], DateTime>, do_parse!( date: date >> tag!("T") >> time: time >> ( DateTime{ date, time } ) )); #[cfg(test)] mod tests { use datetime; use DateTime; #[test] fn parse_datetime() { assert_eq!( Ok(( &[][..], DateTime { date: Date { year: 2007, month: 08, day: 31 }, time: Time { hour: 16, minute: 47, second: 22, tz_offset: 5 * 3600 } } )), datetime(b"2007-08-31T16:47:22+05:00") ); } } ~~~ Nothing special anymore. We can now parse all kinds of date strings: ~~~rust datetime("2007-08-31T16:47+00:00"); datetime("2007-12-24T18:21Z"); datetime("2008-02-01T09:00:22+05"); ~~~ But it will also parse invalid dates and times: ~~~rust datetime("2234-13-42T25:70Z"); ~~~ But this is fine for now. We can handle the actual validation in a later step. For example, we could use [chrono][], a time library, [to handle this for us][chrono-convert]. Using chrono it's obvious why we already multiplied our timezone offset to be in seconds: this time we can just hand it off to chrono as is. The full code for the previous version of this ISO8601 parser is available in [easy.rs][easy.rs]. The repository also includes [a more complex parser][lib.rs], that does some validation while parsing (it checks that the time and date are reasonable values, but it does not check that it is a valid date for example) ### What's left? These simple parsers or even some more complex ones are already usable. At least if you already got all the data at hand and if a simple return value satisfies your needs. But especially for larger and more complex formats like media files reading everything into memory and spitting out a single large value isn't sufficient at all. nom is prepared for that. Soon it will become as easy as using an object from which nom can [`Read`][read]. For most things you shouldn't worry about that, as a simple `BufReader` will work. For the other end of the chain, nom has [Consumers][consumer]. A Consumer handles the complex part of actually requesting data, calling the right sub-parsers and holding the necessary state. This is what you need to build yourself. Internally it's best abstracted using some kind of state machine, so you always know which part of the format to expect next, how to parse it, what to return to the user and so on. Take a look at [the MP4 parser][mp4], which has an `MP4Consumer` handling the different parts of the format. Soon my own library, [rdb-rs][rdb-rs], will have this as well. Small thing aside: Geoffroy created [machine][] to define a state machine and I got [microstate][] for this. ### Why am I doing this? I'm currently developing [rdb-rs][rdb-rs], a library to parse and analyze Redis dump files. It's currently limited to parsing and reformatting into several formats and can be mainly used as a CLI utility. But [there are projects][rsedis] that could benefit from a nicer API to integrate it into another tool. The current parser is hand-made. It's fast, it's working, but it provides a limited, not very extensible API. I hope to get a proper parser done with nom, that I can build on to provide all necessary methods, while still being super-fast and memory-safe. Work [already started][rdb-rs-nom], but I'm far from done for now -- Thanks to [Geoffroy][gcouprie] for the discussions, the help and for reading a draft of this post. [iso]: https://en.wikipedia.org/wiki/ISO_8601 [repo]: https://github.com/badboy/iso8601 [nom]: https://github.com/Geal/nom [gcouprie]: https://twitter.com/gcouprie [taken]: https://github.com/badboy/iso8601/blob/master/src/macros.rs#L20-L39 [rdb-rs]: http://rdb.fnordig.de/ [rsedis]: https://github.com/seppo0010/rsedis [rdb-rs-nom]: https://github.com/badboy/rdb-rs/tree/nom-parser [mp4]: https://github.com/Geal/nom/blob/master/tests/mp4.rs [chrono]: https://crates.io/crates/chrono [chrono-convert]: https://github.com/badboy/iso8601/blob/master/src/lib.rs#L65-L71 [easy.rs]: https://github.com/badboy/iso8601/blob/master/src/easy.rs [lib.rs]: https://github.com/badboy/iso8601/blob/master/src/lib.rs [consumer]: https://github.com/Geal/nom#consumers [machine]: https://github.com/Geal/machine [microstate]: https://github.com/badboy/microstate [read]: http://doc.rust-lang.org/nightly/std/io/trait.Read.html iso8601-0.4.0/LICENSE010064400007660000024000000020651331615603500120570ustar0000000000000000Copyright (c) 2015 Jan-Erik Rediger, Hendrik Sollich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. iso8601-0.4.0/Makefile010064400007660000024000000000501362575161000125050ustar0000000000000000check: @RUST_TEST_THREADS=1 cargo test iso8601-0.4.0/README.md010064400007660000024000000020341342434746100123320ustar0000000000000000# omnomnom - ~~Eating~~ Parsing [ISO8601][iso] dates using [nom][] [![crates.io](http://meritbadge.herokuapp.com/iso8601)](https://crates.io/crates/iso8601) [![Build Status](https://travis-ci.org/badboy/iso8601.svg?branch=master)](https://travis-ci.org/badboy/iso8601) [iso]: https://en.wikipedia.org/wiki/ISO_8601 [nom]: https://github.com/Geal/nom ![omnomnom](http://24.media.tumblr.com/tumblr_lttcbyLaoP1r44hlho1_400.gif) ```rust,ignore let datetime = iso8601::datetime("2015-06-26T16:43:23+0200").unwrap(); // the above will give you: DateTime { date: Date::YMD { year: 2015, month: 6, day: 26, }, time: Time { hour: 16, minute: 43, second: 23, tz_offset_hours: 2, tz_offset_minutes: 0, }, }; ``` Still rough around the edges, though it won't fail with timezone offsets of half an hour anymore. It's also safe for kittens now. # [Documentation][docs] [Documentation][docs] is online. # License MIT Licensed. See [LICENSE]() [docs]: https://docs.rs/iso8601/ iso8601-0.4.0/release.toml010064400007660000024000000007461362575435600134100ustar0000000000000000pre-release-replacements = [ {file="CHANGELOG.md", search="Unreleased", replace="{{version}}"}, {file="CHANGELOG.md", search="\\.\\.\\.master", replace="...v{{version}}", exactly=1}, {file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}"}, {file="CHANGELOG.md", search="", replace="\n\n## [Unreleased](https://github.com/badboy/iso8601/compare/v{{version}}...master) - ReleaseDate", exactly=1} ] tag-name = "v{{version}}" iso8601-0.4.0/src/display.rs010064400007660000024000000021431362575161200136560ustar0000000000000000use core::fmt::{self, Display}; use super::{Date, DateTime, Time}; impl Display for Date { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { // like `2015-11-02` Date::YMD { year, month, day } => write!(f, "{:04}-{:02}-{:02}", year, month, day), // like `2015-W45-01` Date::Week { year, ww, d } => write!(f, "{:04}-{:02}-{:02}", year, ww, d), // like `2015-306` Date::Ordinal { year, ddd } => write!(f, "{:04}-{:03}", year, ddd), } } } impl Display for Time { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // like `16:43:16.123+00:00` write!( f, "{:02}:{:02}:{:02}.{}+{:02}:{:02}", self.hour, self.minute, self.second, self.millisecond, self.tz_offset_hours, self.tz_offset_hours ) } } impl Display for DateTime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // like `16:43:16.123+00:00` write!(f, "{}T{}", self.date, self.time) } } iso8601-0.4.0/src/lib.rs010064400007660000024000000133261362575161200127640ustar0000000000000000//! ISO8601 is a parser library for the //! [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) format //! and partially RFC3339. //! //! Validity of a given date is not guaranteed, this parser will happily parse //! `"2015-02-29"` as a valid date, //! even though 2015 was no leap year. //! //! # Example //! //! ```rust //! let datetime = iso8601::datetime("2015-06-26T16:43:23+0200").unwrap(); //! ``` #![no_std] #[cfg(any(feature = "std", test))] #[macro_use] extern crate std; #[macro_use] extern crate alloc; use alloc::string::String; use core::default::Default; use core::str::FromStr; mod display; mod parsers; /// A date, can hold three different formats. #[derive(Eq, PartialEq, Debug, Copy, Clone)] pub enum Date { /// consists of year, month and day of month YMD { year: i32, month: u32, day: u32 }, /// consists of year, week and day of week Week { year: i32, ww: u32, d: u32 }, /// consists of year and day of year Ordinal { year: i32, ddd: u32 }, } /// A time object #[derive(Eq, PartialEq, Debug, Copy, Clone, Default)] pub struct Time { /// a 24th of a day pub hour: u32, /// 60 discrete parts of an hour pub minute: u32, /// a minute are 60 of these pub second: u32, /// everything after a `.` pub millisecond: u32, /// depends on where you're at pub tz_offset_hours: i32, pub tz_offset_minutes: i32, } /// Compound struct, holds Date and Time #[derive(Eq, PartialEq, Debug, Copy, Clone, Default)] pub struct DateTime { pub date: Date, pub time: Time, } /// A time duration. #[derive(Eq, PartialEq, Debug, Copy, Clone)] pub enum Duration { /// consists of year, month, day, hour, minute and second units YMDHMS { year: u32, month: u32, day: u32, hour: u32, minute: u32, second: u32, millisecond: u32, }, /// consists of week units Weeks(u32), } impl Time { pub fn set_tz(&self, tzo: (i32, i32)) -> Time { let mut t = *self; t.tz_offset_hours = tzo.0; t.tz_offset_minutes = tzo.1; t } } impl Default for Date { fn default() -> Date { Date::YMD { year: 0, month: 0, day: 0, } } } impl FromStr for Date { type Err = String; fn from_str(s: &str) -> Result { date(s) } } impl FromStr for Time { type Err = String; fn from_str(s: &str) -> Result { time(s) } } impl FromStr for DateTime { type Err = String; fn from_str(s: &str) -> Result { datetime(s) } } impl Default for Duration { fn default() -> Duration { Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, } } } impl FromStr for Duration { type Err = String; fn from_str(s: &str) -> Result { duration(s) } } /// Parses a date string. /// /// A string can have one of the following formats: /// /// * `2015-11-02` or `20151102` /// * `2015-W45-01` or `2015W451` /// * `2015-306` or `2015306` /// /// ## Example /// /// ```rust /// let date = iso8601::date("2015-11-02").unwrap(); /// ``` pub fn date(string: &str) -> Result { if let Ok((_, parsed)) = parsers::parse_date(string.as_bytes()) { Ok(parsed) } else { Err(format!("Parser Error: {}", string)) } } /// Parses a time string. /// /// A string can have one of the following formats: /// /// * `07:35:[00][.123]` or `0735[00][.123]` /// * `07:35:[00][.123][(Z|(+|-)00:00)]` /// * `0735[00][.123][(Z|(+|-)00:00)]` /// * `0735[00][.123][(Z|(+|-)0000)]` /// /// ## Example /// /// ```rust /// let time = iso8601::time("21:56:42").unwrap(); /// ``` pub fn time(string: &str) -> Result { if let Ok((_, parsed)) = parsers::parse_time(string.as_bytes()) { Ok(parsed) } else { Err(format!("Parser Error: {}", string)) } } /// Parses a datetime string. /// /// A datetime string is a combination of the valid formats for the date and time, /// separated by a literal `T`. /// See the respective functions for the correct format. /// /// ## Example /// /// ```rust /// let dt = iso8601::datetime("2015-11-03T21:56").unwrap(); /// ``` pub fn datetime(string: &str) -> Result { if let Ok((_left_overs, parsed)) = parsers::parse_datetime(string.as_bytes()) { Ok(parsed) } else { Err(format!("Parser Error: {}", string)) } } /// Parses a duration string. /// /// A string starts with `P` and can have one of the following formats: /// /// * Fully-specified duration: `P1Y2M3DT4H5M6S` /// * Duration in weekly intervals: `P1W` /// * Fully-specified duration in [DateTime](struct.DateTime.html) format: `P` /// /// Both fully-specified formats get parsed into the YMDHMS Duration variant. /// The weekly interval format gets parsed into the Weeks Duration variant. /// /// The ranges for each of the individual units are not expected to exceed /// the next largest unit. /// /// These ranges (inclusive) are as follows: /// /// * Year (any valid u32) /// * Month 0 - 12 /// * Week 0 - 52 /// * Day 0 - 31 /// * Hour 0 - 24 /// * Minute 0 - 60 /// * Second 0 - 60 /// /// ## Examples /// /// ```rust /// let duration = iso8601::duration("P1Y2M3DT4H5M6S").unwrap(); /// let duration = iso8601::duration("P1W").unwrap(); /// let duration = iso8601::duration("P2015-11-03T21:56").unwrap(); /// ``` pub fn duration(string: &str) -> Result { if let Ok((_left_overs, parsed)) = parsers::parse_duration(string.as_bytes()) { Ok(parsed) } else { Err(format!("Parser Error: {}", string)) } } iso8601-0.4.0/src/parsers.rs010064400007660000024000000232471362575161200137000ustar0000000000000000//! This module is strictly internal. //! //! These functions are used by `date()`, `time()` and `datetime()`. //! They are currently not private, because the need to be accessible, //! but are not useful by themselves. //! //! Please refer to the top-level functions instead, as they offer a better abstraction. //! //! **These functions may be made private later.** use core::str; use nom::{ branch::alt, bytes::complete::{tag, take_while, take_while_m_n}, character::complete::one_of, character::is_digit, combinator::{map, not, opt}, sequence::{preceded, terminated}, IResult, }; use crate::{Date, DateTime, Duration, Time}; #[cfg(test)] mod tests; // UTILITY fn take_digits(i: &[u8]) -> IResult<&[u8], u32> { let (i, digits) = take_while(is_digit)(i)?; if digits.is_empty() { return Err(nom::Err::Error((i, nom::error::ErrorKind::Eof))); } let s = str::from_utf8(digits).expect("Invalid data, expected UTF-8 string"); let res = s .parse() .expect("Invalid string, expected ASCII representation of a number"); Ok((i, res)) } fn take_n_digits(i: &[u8], n: usize) -> IResult<&[u8], u32> { let (i, digits) = take_while_m_n(n, n, is_digit)(i)?; let s = str::from_utf8(digits).expect("Invalid data, expected UTF-8 string"); let res = s .parse() .expect("Invalid string, expected ASCII representation of a number"); Ok((i, res)) } fn take_m_to_n_digits(i: &[u8], m: usize, n: usize) -> IResult<&[u8], u32> { let (i, digits) = take_while_m_n(m, n, is_digit)(i)?; let s = str::from_utf8(digits).expect("Invalid data, expected UTF-8 string"); let res = s .parse() .expect("Invalid string, expected ASCII representation of a number"); Ok((i, res)) } fn n_digit_in_range( i: &[u8], n: usize, range: impl core::ops::RangeBounds, ) -> IResult<&[u8], u32> { let (new_i, number) = take_n_digits(i, n)?; if range.contains(&number) { Ok((new_i, number)) } else { Err(nom::Err::Error((i, nom::error::ErrorKind::Eof))) } } fn m_to_n_digit_in_range( i: &[u8], m: usize, n: usize, range: impl core::ops::RangeBounds, ) -> IResult<&[u8], u32> { let (new_i, number) = take_m_to_n_digits(i, m, n)?; if range.contains(&number) { Ok((new_i, number)) } else { Err(nom::Err::Error((i, nom::error::ErrorKind::Eof))) } } fn sign(i: &[u8]) -> IResult<&[u8], i32> { map(alt((tag(b"-"), tag(b"+"))), |s: &[u8]| match s { b"-" => -1, _ => 1, })(i) } fn fractions(i: &[u8]) -> IResult<&[u8], f32> { let (i, digits) = take_while(is_digit)(i)?; let digits = str::from_utf8(digits).unwrap(); // This can't panic, `digits` will only include digits. let f = format!("0.{}", digits).parse().unwrap(); // This can't panic, the string is a valid `f32`. Ok((i, f)) } // DATE // [+/-]YYYY fn date_year(i: &[u8]) -> IResult<&[u8], i32> { // The sign is optional, but defaults to `+` let (i, s) = sign(i).unwrap_or((i, 1)); let (i, year) = take_n_digits(i, 4)?; let year = s * year as i32; Ok((i, year)) } // MM fn date_month(i: &[u8]) -> IResult<&[u8], u32> { n_digit_in_range(i, 2, 1..=12) } // DD fn date_day(i: &[u8]) -> IResult<&[u8], u32> { n_digit_in_range(i, 2, 1..=31) } // WW fn date_week(i: &[u8]) -> IResult<&[u8], u32> { n_digit_in_range(i, 2, 1..=52) } fn date_week_day(i: &[u8]) -> IResult<&[u8], u32> { n_digit_in_range(i, 1, 1..=7) } // ordinal DDD fn date_ord_day(i: &[u8]) -> IResult<&[u8], u32> { n_digit_in_range(i, 3, 1..=366) } // YYYY-MM-DD fn date_ymd(i: &[u8]) -> IResult<&[u8], Date> { let (i, y) = date_year(i)?; let (i, _) = opt(tag(b"-"))(i)?; let (i, m) = date_month(i)?; let (i, _) = opt(tag(b"-"))(i)?; let (i, d) = date_day(i)?; Ok(( i, Date::YMD { year: y, month: m, day: d, }, )) } // YYYY-DDD fn date_ordinal(i: &[u8]) -> IResult<&[u8], Date> { let (i, y) = date_year(i)?; let (i, _) = opt(tag(b"-"))(i)?; let (i, d) = date_ord_day(i)?; Ok((i, Date::Ordinal { year: y, ddd: d })) } // YYYY-"W"WW-D fn date_iso_week(i: &[u8]) -> IResult<&[u8], Date> { let (i, y) = date_year(i)?; let (i, _) = opt(tag(b"-"))(i)?; let (i, _) = tag(b"W")(i)?; let (i, w) = date_week(i)?; let (i, _) = opt(tag(b"-"))(i)?; let (i, d) = date_week_day(i)?; Ok(( i, Date::Week { year: y, ww: w, d: d, }, )) } pub fn parse_date(i: &[u8]) -> IResult<&[u8], Date> { alt((date_ymd, date_iso_week, date_ordinal))(i) } // TIME // HH fn time_hour(i: &[u8]) -> IResult<&[u8], u32> { n_digit_in_range(i, 2, 0..=24) } // MM fn time_minute(i: &[u8]) -> IResult<&[u8], u32> { n_digit_in_range(i, 2, 0..=59) } // SS fn time_second(i: &[u8]) -> IResult<&[u8], u32> { n_digit_in_range(i, 2, 0..=60) } fn time_millisecond(fraction: f32) -> u32 { (1000.0 * fraction) as u32 } // HH:MM:[SS][.(m*)][(Z|+...|-...)] pub fn parse_time(i: &[u8]) -> IResult<&[u8], Time> { let (i, h) = time_hour(i)?; let (i, _) = opt(tag(b":"))(i)?; let (i, m) = time_minute(i)?; let (i, s) = opt(preceded(opt(tag(b":")), time_second))(i)?; let (i, ms) = opt(map(preceded(one_of(",."), fractions), time_millisecond))(i)?; let (i, z) = match opt(alt((timezone_hour, timezone_utc)))(i) { Ok(ok) => ok, Err(nom::Err::Incomplete(_)) => (i, None), Err(e) => return Err(e), }; let (tz_offset_hours, tz_offset_minutes) = z.unwrap_or((0, 0)); Ok(( i, Time { hour: h, minute: m, second: s.unwrap_or(0), millisecond: ms.unwrap_or(0), tz_offset_hours, tz_offset_minutes, }, )) } fn timezone_hour(i: &[u8]) -> IResult<&[u8], (i32, i32)> { let (i, s) = sign(i)?; let (i, h) = time_hour(i)?; let (i, m) = if i.is_empty() { (i, 0) } else { let (i, _) = opt(tag(b":"))(i)?; time_minute(i)? }; Ok((i, ((s * (h as i32), s * (m as i32))))) } fn timezone_utc(i: &[u8]) -> IResult<&[u8], (i32, i32)> { map(tag(b"Z"), |_| (0, 0))(i) } // Full ISO8601 datetime pub fn parse_datetime(i: &[u8]) -> IResult<&[u8], DateTime> { let (i, d) = parse_date(i)?; let (i, _) = tag(b"T")(i)?; let (i, t) = parse_time(i)?; Ok((i, DateTime { date: d, time: t })) } // DURATION // Y[YYY...] fn duration_year(i: &[u8]) -> IResult<&[u8], u32> { take_digits(i) } // M[M] fn duration_month(i: &[u8]) -> IResult<&[u8], u32> { m_to_n_digit_in_range(i, 1, 2, 0..=12) } // W[W] fn duration_week(i: &[u8]) -> IResult<&[u8], u32> { m_to_n_digit_in_range(i, 1, 2, 0..=52) } // D[D] fn duration_day(i: &[u8]) -> IResult<&[u8], u32> { m_to_n_digit_in_range(i, 1, 2, 0..=31) } // H[H] fn duration_hour(i: &[u8]) -> IResult<&[u8], u32> { m_to_n_digit_in_range(i, 1, 2, 0..=24) } // M[M] fn duration_minute(i: &[u8]) -> IResult<&[u8], u32> { m_to_n_digit_in_range(i, 1, 2, 0..=60) } // S[S][[,.][MS]] fn duration_second_and_millisecond(i: &[u8]) -> IResult<&[u8], (u32, u32)> { let (i, s) = m_to_n_digit_in_range(i, 1, 2, 0..=60)?; let (i, ms) = opt(map(preceded(one_of(",."), fractions), duration_millisecond))(i)?; Ok((i, (s, ms.unwrap_or(0)))) } fn duration_millisecond(fraction: f32) -> u32 { (1000.0 * fraction) as u32 } fn duration_time(i: &[u8]) -> IResult<&[u8], (u32, u32, u32, u32)> { let (i, h) = opt(terminated(duration_hour, tag(b"H")))(i)?; let (i, m) = opt(terminated(duration_minute, tag(b"M")))(i)?; let (i, s) = opt(terminated(duration_second_and_millisecond, tag(b"S")))(i)?; let (s, ms) = s.unwrap_or((0, 0)); Ok((i, (h.unwrap_or(0), m.unwrap_or(0), s, ms))) } fn duration_ymdhms(i: &[u8]) -> IResult<&[u8], Duration> { let (i, _) = tag(b"P")(i)?; let (i, y) = opt(terminated(duration_year, tag(b"Y")))(i)?; let (i, mo) = opt(terminated(duration_month, tag(b"M")))(i)?; let (i, d) = opt(terminated(duration_day, tag(b"D")))(i)?; let (i, time) = opt(preceded(tag(b"T"), duration_time))(i)?; // at least one element must be present for a valid duration representation if y.is_none() && mo.is_none() && d.is_none() && time.is_none() { return Err(nom::Err::Error((i, nom::error::ErrorKind::Eof))); } let (h, mi, s, ms) = time.unwrap_or((0, 0, 0, 0)); Ok(( i, Duration::YMDHMS { year: y.unwrap_or(0), month: mo.unwrap_or(0), day: d.unwrap_or(0), hour: h, minute: mi, second: s, millisecond: ms, }, )) } fn duration_weeks(i: &[u8]) -> IResult<&[u8], Duration> { let (i, _) = tag(b"P")(i)?; let (i, w) = terminated(duration_week, tag(b"W"))(i)?; Ok((i, Duration::Weeks(w))) } // YYYY, no sign fn duration_datetime_year(i: &[u8]) -> IResult<&[u8], u32> { take_n_digits(i, 4) } fn duration_datetime(i: &[u8]) -> IResult<&[u8], Duration> { let (i, _) = tag(b"P")(i)?; let (i, _) = not(sign)(i)?; let (i, y) = duration_datetime_year(i)?; let (i, _) = opt(tag(b"-"))(i)?; let (i, m) = date_month(i)?; let (i, _) = opt(tag(b"-"))(i)?; let (i, d) = date_day(i)?; let (i, _) = tag(b"T")(i)?; let (i, t) = parse_time(i)?; Ok(( i, Duration::YMDHMS { year: y, month: m, day: d, hour: t.hour, minute: t.minute, second: t.second, millisecond: t.millisecond, }, )) } pub fn parse_duration(i: &[u8]) -> IResult<&[u8], Duration> { alt((duration_ymdhms, duration_weeks, duration_datetime))(i) } iso8601-0.4.0/src/parsers/tests.rs010064400007660000024000000222371352322120600150240ustar0000000000000000use super::*; #[test] fn test_date_year() { assert_eq!(Ok((&[][..], 2015)), date_year(b"2015")); assert_eq!(Ok((&[][..], -0333)), date_year(b"-0333")); assert_eq!(Ok((&b"-"[..], 2015)), date_year(b"2015-")); assert!(date_year(b"abcd").is_err()); assert!(date_year(b"2a03").is_err()); } #[test] fn test_date_month() { assert_eq!(Ok((&[][..], 1)), date_month(b"01")); assert_eq!(Ok((&[][..], 6)), date_month(b"06")); assert_eq!(Ok((&[][..], 12)), date_month(b"12")); assert_eq!(Ok((&b"-"[..], 12)), date_month(b"12-")); assert!(date_month(b"13").is_err()); assert!(date_month(b"00").is_err()); } #[test] fn test_date_day() { assert_eq!(Ok((&[][..], 1)), date_day(b"01")); assert_eq!(Ok((&[][..], 12)), date_day(b"12")); assert_eq!(Ok((&[][..], 20)), date_day(b"20")); assert_eq!(Ok((&[][..], 28)), date_day(b"28")); assert_eq!(Ok((&[][..], 30)), date_day(b"30")); assert_eq!(Ok((&[][..], 31)), date_day(b"31")); assert_eq!(Ok((&b"-"[..], 31)), date_day(b"31-")); assert!(date_day(b"00").is_err()); assert!(date_day(b"32").is_err()); } #[test] fn test_time_hour() { assert_eq!(Ok((&[][..], 0)), time_hour(b"00")); assert_eq!(Ok((&[][..], 1)), time_hour(b"01")); assert_eq!(Ok((&[][..], 6)), time_hour(b"06")); assert_eq!(Ok((&[][..], 12)), time_hour(b"12")); assert_eq!(Ok((&[][..], 13)), time_hour(b"13")); assert_eq!(Ok((&[][..], 20)), time_hour(b"20")); assert_eq!(Ok((&[][..], 24)), time_hour(b"24")); assert!(time_hour(b"25").is_err()); assert!(time_hour(b"30").is_err()); assert!(time_hour(b"ab").is_err()); } #[test] fn test_time_minute() { assert_eq!(Ok((&[][..], 0)), time_minute(b"00")); assert_eq!(Ok((&[][..], 1)), time_minute(b"01")); assert_eq!(Ok((&[][..], 30)), time_minute(b"30")); assert_eq!(Ok((&[][..], 59)), time_minute(b"59")); assert!(time_minute(b"60").is_err()); assert!(time_minute(b"61").is_err()); assert!(time_minute(b"ab").is_err()); } #[test] fn test_time_second() { assert_eq!(Ok((&[][..], 0)), time_second(b"00")); assert_eq!(Ok((&[][..], 1)), time_second(b"01")); assert_eq!(Ok((&[][..], 30)), time_second(b"30")); assert_eq!(Ok((&[][..], 59)), time_second(b"59")); assert_eq!(Ok((&[][..], 60)), time_second(b"60")); assert!(time_second(b"61").is_err()); assert!(time_second(b"ab").is_err()); } #[test] fn test_date() { assert!(parse_date(b"201").is_err()); assert!(parse_date(b"2015p00p00").is_err()); assert!(parse_date(b"pppp").is_err()); } #[test] fn test_time() { assert!(parse_time(b"20:").is_err()); assert!(parse_time(b"20p42p16").is_err()); assert!(parse_time(b"pppp").is_err()); } #[test] fn test_time_with_timezone() { assert!(parse_time(b"20:").is_err()); assert!(parse_time(b"20p42p16").is_err()); assert!(parse_time(b"pppp").is_err()); } #[test] fn test_date_iso_week_date() { assert!(date_iso_week(b"2015-W06-8").is_err()); assert!(date_iso_week(b"2015-W068").is_err()); assert!(date_iso_week(b"2015-W06-0").is_err()); assert!(date_iso_week(b"2015-W00-2").is_err()); assert!(date_iso_week(b"2015-W54-2").is_err()); assert!(date_iso_week(b"2015-W542").is_err()); } #[test] fn test_date_ordinal_date() { // not valid here either assert!(date_ordinal(b"2015-400").is_err()); } #[test] fn format_equivalence() { assert_eq!( parse_datetime(b"2001-02-03T04:05:06+07:00"), parse_datetime(b"20010203T040506+0700") ); assert_eq!( parse_datetime(b"2001-02-03T04:05:06+07:00"), parse_datetime(b"20010203T04:05:06+0700") ); assert_eq!( parse_datetime(b"2001-02-03T04:05:00+07:00"), parse_datetime(b"20010203T0405+0700") ); assert_eq!( parse_datetime(b"20010203T0405+0700"), parse_datetime(b"2001-02-03T0405+0700") ); assert_eq!( parse_datetime(b"20010203T040506+0700"), parse_datetime(b"2001-02-03T040506+0700") ); assert_eq!( parse_datetime(b"20010203T040506+0000"), parse_datetime(b"20010203T040506Z") ); assert_eq!( parse_datetime(b"2015W056T04:05:06+07:00"), parse_datetime(b"2015-W05-6T04:05:06+07:00") ); } #[test] fn test_datetime_error() { let test_datetimes = vec!["ppp", "dumd-di-duTmd:iu:m"]; for iso_string in test_datetimes { let res = parse_datetime(iso_string.as_bytes()); assert!(res.is_err()); } } #[test] fn disallows_notallowed() { assert!(parse_time(b"30:90:90").is_err()); assert!(parse_date(b"0000-20-40").is_err()); assert!(parse_datetime(b"2001-w05-6t04:05:06.123z").is_err()); } #[test] fn test_duration_year() { assert_eq!(Ok((&[][..], 2019)), duration_year(b"2019")); assert_eq!(Ok((&[][..], 0)), duration_year(b"0")); assert_eq!(Ok((&[][..], 10000)), duration_year(b"10000")); assert!(duration_year(b"abcd").is_err()); assert!(duration_year(b"-1").is_err()); } #[test] fn test_duration_month() { assert_eq!(Ok((&[][..], 6)), duration_month(b"6")); assert_eq!(Ok((&[][..], 0)), duration_month(b"0")); assert_eq!(Ok((&[][..], 12)), duration_month(b"12")); assert!(duration_month(b"ab").is_err()); assert!(duration_month(b"-1").is_err()); assert!(duration_month(b"13").is_err()); } #[test] fn test_duration_week() { assert_eq!(Ok((&[][..], 26)), duration_week(b"26")); assert_eq!(Ok((&[][..], 0)), duration_week(b"0")); assert_eq!(Ok((&[][..], 52)), duration_week(b"52")); assert!(duration_week(b"ab").is_err()); assert!(duration_week(b"-1").is_err()); assert!(duration_week(b"53").is_err()); } #[test] fn test_duration_day() { assert_eq!(Ok((&[][..], 16)), duration_day(b"16")); assert_eq!(Ok((&[][..], 0)), duration_day(b"0")); assert_eq!(Ok((&[][..], 31)), duration_day(b"31")); assert!(duration_day(b"ab").is_err()); assert!(duration_day(b"-1").is_err()); assert!(duration_day(b"32").is_err()); } #[test] fn test_duration_hour() { assert_eq!(Ok((&[][..], 12)), duration_hour(b"12")); assert_eq!(Ok((&[][..], 0)), duration_hour(b"0")); assert_eq!(Ok((&[][..], 24)), duration_hour(b"24")); assert!(duration_hour(b"ab").is_err()); assert!(duration_hour(b"-1").is_err()); assert!(duration_hour(b"25").is_err()); } #[test] fn test_duration_minute() { assert_eq!(Ok((&[][..], 30)), duration_minute(b"30")); assert_eq!(Ok((&[][..], 0)), duration_minute(b"0")); assert_eq!(Ok((&[][..], 60)), duration_minute(b"60")); assert!(duration_minute(b"ab").is_err()); assert!(duration_minute(b"-1").is_err()); assert!(duration_minute(b"61").is_err()); } #[test] fn test_duration_second_and_millisecond() { assert_eq!( Ok((&[][..], (30, 0))), duration_second_and_millisecond(b"30") ); assert_eq!(Ok((&[][..], (0, 0))), duration_second_and_millisecond(b"0")); assert_eq!( Ok((&[][..], (60, 0))), duration_second_and_millisecond(b"60") ); assert_eq!( Ok((&[][..], (1, 230))), duration_second_and_millisecond(b"1,23") ); assert_eq!( Ok((&[][..], (1, 230))), duration_second_and_millisecond(b"1.23") ); assert!(duration_second_and_millisecond(b"ab").is_err()); assert!(duration_second_and_millisecond(b"-1").is_err()); assert!(duration_second_and_millisecond(b"61").is_err()); } #[test] fn test_duration_time() { assert_eq!(Ok((&[][..], (1, 2, 3, 0))), duration_time(b"1H2M3S")); assert_eq!(Ok((&[][..], (1, 0, 3, 0))), duration_time(b"1H3S")); assert_eq!(Ok((&[][..], (0, 2, 0, 0))), duration_time(b"2M")); assert_eq!(Ok((&[][..], (1, 2, 3, 400))), duration_time(b"1H2M3,4S")); assert_eq!(Ok((&[][..], (1, 2, 3, 400))), duration_time(b"1H2M3.4S")); assert_eq!(Ok((&[][..], (0, 0, 0, 123))), duration_time(b"0,123S")); assert_eq!(Ok((&[][..], (0, 0, 0, 123))), duration_time(b"0.123S")); } #[test] fn test_duration_ymdhms_error() { assert!(duration_ymdhms(b"").is_err()); assert!(duration_ymdhms(b"P").is_err()); // empty duration is not 0 seconds assert!(duration_ymdhms(b"1Y2M3DT4H5M6S").is_err()); // missing P at start assert!(duration_ymdhms(b"T4H5M6S").is_err()); // missing P, required even if no YMD part } #[test] fn test_duration_weeks_error() { assert!(duration_weeks(b"").is_err()); assert!(duration_weeks(b"P").is_err()); // empty duration is not 0 seconds assert!(duration_weeks(b"P1").is_err()); // missing W after number assert!(duration_weeks(b"PW").is_err()); // missing number } #[test] fn test_duration_datetime_error() { assert!(duration_datetime(b"").is_err()); assert!(duration_datetime(b"P").is_err()); // empty duration is not 0 seconds assert!(duration_datetime(b"0001-02-03T04:05:06").is_err()); // missing P at start } // #[test] // fn corner_cases() { // // how to deal with left overs? // assert!(parse_datetime((b"2015-06-26T22:57:09Z00:00").is_done()); // assert!(date("2015-06-26T22:57:09Z00:00").is_err()); // // assert!(parse_datetime((b"2015-06-26T22:57:09Z+00:00").is_done()); // assert!(datetime("2015-06-26T22:57:09Z+00:00").is_err()); // assert!(parse_datetime((b"2001-W05-6T04:05:06.123455Z").is_err()); // assert!(parse_datetime((b"2015-06-26TZ").is_err()); // } iso8601-0.4.0/tests/lib.rs010064400007660000024000000607641352322120600133330ustar0000000000000000use iso8601::*; #[test] fn test_date() { assert_eq!( Ok(Date::YMD { year: 2015, month: 6, day: 26, }), date("2015-06-26") ); assert_eq!( Ok(Date::YMD { year: -333, month: 7, day: 11, }), date("-0333-07-11") ); } #[test] fn test_millisecond() { assert_eq!( Ok(Time { hour: 16, minute: 43, second: 0, millisecond: 100, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:00.1") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 0, millisecond: 120, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:00.12") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 0, millisecond: 123, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:00.123") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 0, millisecond: 432, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:00.4321") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 0, millisecond: 432, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43.4321") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 11, millisecond: 432, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:11.4321") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 0, millisecond: 100, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:00,1") ); assert_eq!( Ok(Time { hour: 04, minute: 05, second: 06, millisecond: 123, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("04:05:06.12345") ); assert_eq!( Ok(DateTime { date: Date::Week { year: 2001, ww: 05, d: 6 }, time: Time { hour: 04, minute: 05, second: 06, millisecond: 123, tz_offset_hours: 0, tz_offset_minutes: 0 } }), datetime("2001-W05-6T04:05:06.12345Z") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 123, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:16.123") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 123, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:16.123+00:00") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 123, tz_offset_hours: 0, tz_offset_minutes: 0 }), time("16:43:16.123-00:00") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 123, tz_offset_hours: 5, tz_offset_minutes: 0 }), time("16:43:16.123+05:00") ); } #[test] fn test_time() { assert_eq!( time("16:43:16"), Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); assert_eq!( time("16:43"), Ok(Time { hour: 16, minute: 43, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); assert!(time("20:").is_err()); assert!(time("20p42p16").is_err()); assert!(time("pppp").is_err()); } #[test] fn test_time_set_tz() { let original = Time { hour: 0, minute: 0, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }; let expected = Time { hour: 0, minute: 0, second: 0, millisecond: 0, tz_offset_hours: 2, tz_offset_minutes: 30, }; assert_eq!(expected, original.set_tz((2, 30))); } #[test] fn short_time1() { assert_eq!( time("1648"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_time2() { assert_eq!( time("16:48"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_time3() { assert_eq!( time("16:48Z"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_time4() { assert_eq!( time("164800"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_time5() { assert_eq!( time("164800.1"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 100, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_time6() { assert_eq!( time("164800.1Z"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 100, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_time7() { assert_eq!( time("16:48:00"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_twtz1() { assert_eq!( time("1648Z"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_twtz2() { assert_eq!( time("16:48Z"), Ok(Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }) ); } #[test] fn short_dtim1() { assert_eq!( datetime("20070831T1648"), Ok(DateTime { date: Date::YMD { year: 2007, month: 08, day: 31, }, time: Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, } }) ); } #[test] fn short_dtim2() { assert_eq!( datetime("20070831T1648Z"), Ok(DateTime { date: Date::YMD { year: 2007, month: 08, day: 31, }, time: Time { hour: 16, minute: 48, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }, }) ); } #[test] fn short_dtim3() { assert_eq!( datetime("2008-12-24T18:21Z"), Ok(DateTime { date: Date::YMD { year: 2008, month: 12, day: 24, }, time: Time { hour: 18, minute: 21, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }, }) ); } #[test] fn test_time_with_timezone() { assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }), time("16:43:16") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }), time("16:43:16Z") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }), time("16:43:16+00:00") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0, }), time("16:43:16-00:00") ); assert_eq!( Ok(Time { hour: 16, minute: 43, second: 16, millisecond: 0, tz_offset_hours: 5, tz_offset_minutes: 0, }), time("16:43:16+05:00") ); assert!(time("20:").is_err()); assert!(time("20p42p16").is_err()); assert!(time("pppp").is_err()); } #[test] fn test_iso_week_date() { assert_eq!( Ok(Date::Week { year: 2015, ww: 5, d: 7, }), date("2015-W05-7") ); assert_eq!( Ok(Date::Week { year: 2015, ww: 6, d: 6, }), date("2015-W06-6") ); assert_eq!( Ok(Date::Week { year: 2015, ww: 6, d: 6, }), date("2015-W066") ); assert_eq!( Ok(Date::Week { year: 2015, ww: 6, d: 6, }), date("2015W066") ); assert_eq!( Ok(Date::Week { year: 2015, ww: 43, d: 6, }), date("2015-W43-6") ); assert!(date("2015-W06-8").is_err()); assert!(date("2015-W068").is_err()); assert!(date("2015-W06-0").is_err()); assert!(date("2015-W00-2").is_err()); assert!(date("2015-W54-2").is_err()); assert!(date("2015-W542").is_err()); } #[test] fn test_ordinal_date() { assert_eq!( Ok(Date::Ordinal { year: 2015, ddd: 57, }), date("2015-057") ); assert_eq!( Ok(Date::Ordinal { year: 2015, ddd: 358, }), date("2015-358") ); assert_eq!( Ok(Date::Ordinal { year: 2015, ddd: 366, }), date("2015-366") ); assert_eq!(Ok(Date::Ordinal { year: 2015, ddd: 1 }), date("2015-001")); // not valid here either assert!(date("2015-400").is_err()); } #[test] fn format_equivalence() { assert_eq!( datetime("2001-02-03T04:05:06+07:00"), datetime("20010203T040506+0700") ); assert_eq!( datetime("2001-02-03T04:05:06+07:00"), datetime("20010203T04:05:06+0700") ); assert_eq!( datetime("2001-02-03T04:05:00+07:00"), datetime("20010203T0405+0700") ); assert_eq!( datetime("20010203T0405+0700"), datetime("2001-02-03T0405+0700") ); assert_eq!( datetime("20010203T040506+0700"), datetime("2001-02-03T040506+0700") ); assert_eq!( datetime("20010203T040506+0000"), datetime("20010203T040506Z") ); assert_eq!( datetime("2015W056T04:05:06+07:00"), datetime("2015-W05-6T04:05:06+07:00") ); } #[test] fn test_datetime_correct() { assert_eq!( datetime("20060831T16:44+00:00"), Ok(DateTime { date: Date::YMD { year: 2006, month: 08, day: 31 }, time: Time { hour: 16, minute: 44, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2007-08-31T16:45+00:00"), Ok(DateTime { date: Date::YMD { year: 2007, month: 08, day: 31 }, time: Time { hour: 16, minute: 45, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("20070831T1646+00:00"), Ok(DateTime { date: Date::YMD { year: 2007, month: 08, day: 31 }, time: Time { hour: 16, minute: 46, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("20070831T1647+0000"), Ok(DateTime { date: Date::YMD { year: 2007, month: 08, day: 31 }, time: Time { hour: 16, minute: 47, second: 0, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2009-02-01T09:00:22+05"), Ok(DateTime { date: Date::YMD { year: 2009, month: 02, day: 01 }, time: Time { hour: 9, minute: 0, second: 22, millisecond: 0, tz_offset_hours: 5, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2010-01-01T12:00:00+01:00"), Ok(DateTime { date: Date::YMD { year: 2010, month: 1, day: 1 }, time: Time { hour: 12, minute: 0, second: 0, millisecond: 0, tz_offset_hours: 1, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2011-06-30T18:30:00+02:00"), Ok(DateTime { date: Date::YMD { year: 2011, month: 06, day: 30 }, time: Time { hour: 18, minute: 30, second: 0, millisecond: 0, tz_offset_hours: 2, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015-06-29T23:07+02:00"), Ok(DateTime { date: Date::YMD { year: 2015, month: 06, day: 29 }, time: Time { hour: 23, minute: 07, second: 0, millisecond: 0, tz_offset_hours: 2, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015-06-26T16:43:16"), Ok(DateTime { date: Date::YMD { year: 2015, month: 06, day: 26 }, time: Time { hour: 16, minute: 43, second: 16, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015-06-26T16:43:16"), Ok(DateTime { date: Date::YMD { year: 2015, month: 06, day: 26 }, time: Time { hour: 16, minute: 43, second: 16, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015-W05-6T04:05:06+07:00"), Ok(DateTime { date: Date::Week { year: 2015, ww: 05, d: 6 }, time: Time { hour: 04, minute: 5, second: 6, millisecond: 0, tz_offset_hours: 7, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015W056T04:05:06+07:00"), Ok(DateTime { date: Date::Week { year: 2015, ww: 05, d: 6 }, time: Time { hour: 04, minute: 5, second: 6, millisecond: 0, tz_offset_hours: 7, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015-056T04:05:06+07:00"), Ok(DateTime { date: Date::Ordinal { year: 2015, ddd: 56 }, time: Time { hour: 04, minute: 5, second: 6, millisecond: 0, tz_offset_hours: 7, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015056T04:05:06+07:00"), Ok(DateTime { date: Date::Ordinal { year: 2015, ddd: 56 }, time: Time { hour: 04, minute: 5, second: 6, millisecond: 0, tz_offset_hours: 7, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015-297T16:30:48Z"), Ok(DateTime { date: Date::Ordinal { year: 2015, ddd: 297 }, time: Time { hour: 16, minute: 30, second: 48, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2015-W43-6T16:30:48Z"), Ok(DateTime { date: Date::Week { year: 2015, ww: 43, d: 6 }, time: Time { hour: 16, minute: 30, second: 48, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2001-W05-6T04:05:06.1234Z"), Ok(DateTime { date: Date::Week { year: 2001, ww: 05, d: 6 }, time: Time { hour: 04, minute: 05, second: 06, millisecond: 123, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); assert_eq!( datetime("2001-W05-6T04:05:06.12345Z"), Ok(DateTime { date: Date::Week { year: 2001, ww: 05, d: 6 }, time: Time { hour: 04, minute: 05, second: 06, millisecond: 123, tz_offset_hours: 0, tz_offset_minutes: 0 } }) ); } #[test] fn issue12_regression_1() { let input = "164801."; assert_eq!( Ok(Time { hour: 16, minute: 48, second: 1, millisecond: 0, tz_offset_hours: 0, tz_offset_minutes: 0 }), time(input) ); } #[test] fn issue12_regression_2() { let input = "04:05:06.1226001015632)*450"; assert_eq!( Ok(Time { hour: 4, minute: 5, second: 6, millisecond: 122, tz_offset_hours: 0, tz_offset_minutes: 0 }), time(input) ); } #[test] fn test_duration_ymdhms() { // full YMDHMS assert_eq!( Ok(Duration::YMDHMS { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6, millisecond: 0, }), duration("P1Y2M3DT4H5M6S") ); // full YMDHMS with milliseconds dot delimiter assert_eq!( Ok(Duration::YMDHMS { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6, millisecond: 700, }), duration("P1Y2M3DT4H5M6.7S") ); // full YMDHMS with milliseconds comma delimiter assert_eq!( Ok(Duration::YMDHMS { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6, millisecond: 700, }), duration("P1Y2M3DT4H5M6,7S") ); // subset YM-HM- assert_eq!( Ok(Duration::YMDHMS { year: 1, month: 2, day: 0, hour: 4, minute: 5, second: 0, millisecond: 0, }), duration("P1Y2MT4H5M") ); // subset Y----- assert_eq!( Ok(Duration::YMDHMS { year: 1, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, }), duration("P1Y") ); // subset ---H-- assert_eq!( Ok(Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 4, minute: 0, second: 0, millisecond: 0, }), duration("PT4H") ); // subset -----S with milliseconds dot delimiter assert_eq!( Ok(Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 6, millisecond: 700, }), duration("PT6.7S") ); // subset -----S with milliseconds comma delimiter assert_eq!( Ok(Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 6, millisecond: 700, }), duration("PT6,700S") ); // empty duration, using Y assert_eq!( Ok(Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, }), duration("P0Y") ); // empty duration, using S assert_eq!( Ok(Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, }), duration("PT0S") ); assert_eq!( Ok(Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 42, second: 30, millisecond: 0, }), duration("PT42M30S") ); assert_eq!( Ok(Duration::YMDHMS { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6, millisecond: 0, }), duration("P0001-02-03T04:05:06") ); assert_eq!( Ok(Duration::YMDHMS { year: 2018, month: 4, day: 27, hour: 0, minute: 0, second: 0, millisecond: 0, }), duration("P2018-04-27T00:00:00") ); } #[test] fn test_duration_weeks() { assert_eq!(Ok(Duration::Weeks(0)), duration("P0W")); assert_eq!(Ok(Duration::Weeks(26)), duration("P26W")); assert_eq!(Ok(Duration::Weeks(52)), duration("P52W")); } iso8601-0.4.0/.cargo_vcs_info.json0000644000000001121362575464100122530ustar00{ "git": { "sha1": "cb16cdcb7e0fe609ba51e87d06ae58dfbf3bc12d" } }