iso8601-0.6.1/.cargo_vcs_info.json0000644000000001360000000000100121510ustar { "git": { "sha1": "c0b5c002c013fd51a559a2cd77e83dc843fe5e15" }, "path_in_vcs": "" }iso8601-0.6.1/.github/workflows/ci.yaml000064400000000000000000000020011046102023000156060ustar 00000000000000name: CI on: [push, pull_request] env: RUSTFLAGS: -Dwarnings jobs: fmt_and_docs: name: Check fmt & build docs runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: Install Rust uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable components: rustfmt override: true - name: rustfmt run: cargo fmt --all -- --check - name: docs run: cargo doc --no-deps build_and_test: name: Build & Test runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: Install Rust uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - name: Run tests run: cargo test --all --verbose - name: Run tests (chrono feature) run: cargo test --lib chrono --features chrono - name: Run tests (serde feature) run: cargo test --lib serde --features serde iso8601-0.6.1/.gitignore000064400000000000000000000000301046102023000127220ustar 00000000000000target Cargo.lock *.swp iso8601-0.6.1/CHANGELOG.md000064400000000000000000000037631046102023000125630ustar 00000000000000# Changelog ## [Unreleased](https://github.com/badboy/iso8601/compare/v0.6.1...main) - ReleaseDate ## [0.6.1](https://github.com/badboy/iso8601/compare/v0.6.0...v0.6.1) - 2023-02-12 ## [0.6.0](https://github.com/badboy/iso8601/compare/v0.5.1...v0.6.0) - 2023-02-12 * add serde (de)serializer implementations * add conversion to chrono as a feature ## [0.5.1](https://github.com/badboy/iso8601/compare/v0.5.0...v0.5.1) - 2022-11-09 * Fix accepted duration representations ## [0.5.0](https://github.com/badboy/iso8601/compare/v0.4.2...v0.5.0) - 2022-07-29 * Replace rounding-error prone floating point code with robust integer code ([#36](https://github.com/badboy/iso8601/pull/36) by @plugwash) * Make low-level parsers public ([c80b169](https://github.com/badboy/iso8601/commit/c80b169c53716d63e4d56a9c10775a931d6ce0be)) ## [0.4.2](https://github.com/badboy/iso8601/compare/v0.4.1...v0.4.2) - 2022-06-01 * Fix TZ offset minutes being replaced by hours ## [0.4.1](https://github.com/badboy/iso8601/compare/v0.4.0...v0.4.1) - 2021-11-21 * Add `Display` implementations for more exported structures (Duration) ## [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.6.1/Cargo.toml0000644000000022640000000000100101530ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "iso8601" version = "0.6.1" 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.chrono] version = "0.4" optional = true default-features = false [dependencies.nom] version = "7" default-features = false [dependencies.num-traits] version = "0.2" optional = true [dependencies.serde] version = "1.0" optional = true [dev-dependencies.serde_json] version = "1.0" [features] chrono = [ "dep:chrono", "num-traits", ] default = ["std"] std = ["nom/std"] iso8601-0.6.1/Cargo.toml.orig000064400000000000000000000012771046102023000136370ustar 00000000000000[package] name = "iso8601" version = "0.6.1" 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 = "7", default-features = false } chrono = { version = "0.4", default-features = false, optional = true } num-traits = { version = "0.2", optional = true } serde = { version = "1.0", optional = true } [dev-dependencies ] serde_json = "1.0" [features] default = ["std"] std = ["nom/std"] chrono = ["dep:chrono", "num-traits"] iso8601-0.6.1/LICENSE000064400000000000000000000020651046102023000117510ustar 00000000000000Copyright (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.6.1/Makefile000064400000000000000000000000501046102023000123740ustar 00000000000000check: @RUST_TEST_THREADS=1 cargo test iso8601-0.6.1/README.md000064400000000000000000000024721046102023000122250ustar 00000000000000# omnomnom - ~~Eating~~ Parsing [ISO8601][iso] dates using [nom][] [![crates.io](https://img.shields.io/crates/v/iso8601?style=flat-square)](https://crates.io/crates/iso8601) [![docs.rs docs](https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square)](https://docs.rs/iso8601) [![License: MIT](https://img.shields.io/github/license/badboy/iso8601?style=flat-square)](LICENSE) [![Build status](https://img.shields.io/github/actions/workflow/status/badboy/iso8601/ci.yaml?branch=main)](https://github.com/badboy/iso8601/actions/workflows/ci.yaml) [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.6.1/docs/parsing-iso8601-dates-using-nom.md000064400000000000000000000447111046102023000200040ustar 00000000000000# 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.6.1/release.toml000064400000000000000000000007421046102023000132610ustar 00000000000000pre-release-replacements = [ {file="CHANGELOG.md", search="Unreleased", replace="{{version}}"}, {file="CHANGELOG.md", search="\\.\\.\\.main", 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}}...main) - ReleaseDate", exactly=1} ] tag-name = "v{{version}}" iso8601-0.6.1/src/assert.rs000064400000000000000000000015731046102023000134050ustar 00000000000000use std::fmt; pub fn print_result(input: &str, rest: &[u8], result: &T) { println!( "INPUT: {:?}\nLEFT: {:?}\nRESULT: {:#?}", input, rest, result ); } #[macro_export] macro_rules! assert_parser { ($parser:ident, $line:expr, $expectation:expr) => {{ use std::string::ToString; let (rest, parsed) = $parser($line.as_bytes()).unwrap(); if std::env::var("VERBOSE_TEST_OUTPUT").is_ok() { $crate::assert::print_result($line, &rest, &parsed); } assert_eq!( parsed, $expectation, "{:?} not parsed as expected (leftover: {:?})", $line, rest ); assert!(rest.is_empty(), "not parsed completely"); let serialized = parsed.to_string(); assert_eq!($line, serialized, "does not reserialize correctly"); println!("✅"); }}; } iso8601-0.6.1/src/chrono.rs000064400000000000000000000130421046102023000133660ustar 00000000000000use chrono::TimeZone; use core::convert::TryFrom; use num_traits::FromPrimitive; // TODO: we already do validity checks on our own, // would be nice if we could use the unsafe versions of these conversions impl TryFrom for chrono::NaiveDate { type Error = (); fn try_from(iso: crate::Date) -> Result { let maybe = match iso { crate::Date::YMD { year, month, day } => { chrono::NaiveDate::from_ymd_opt(year, month, day) } crate::Date::Week { year, ww, d } => chrono::Weekday::from_u32(d) .and_then(|d| chrono::NaiveDate::from_isoywd_opt(year, ww, d)), crate::Date::Ordinal { year, ddd } => chrono::NaiveDate::from_yo_opt(year, ddd), }; maybe.ok_or(()) } } impl crate::Date { /// create a [`chrono::NativeDate`] if possible pub fn into_naive(&self) -> Option { chrono::NaiveDate::try_from(*self).ok() } } #[cfg(test)] mod test_date { use chrono::Datelike; use core::convert::TryFrom; #[test] fn naivedate_from_ymd() { let iso = crate::date("2023-02-08").unwrap(); let naive = chrono::NaiveDate::try_from(iso).unwrap(); assert_eq!(naive.year(), 2023); assert_eq!(naive.month(), 2); assert_eq!(naive.day(), 8); } #[test] fn naivedate_from_ywd() { let iso = crate::date("2023-W06-2").unwrap(); let naive = chrono::NaiveDate::try_from(iso).unwrap(); assert_eq!(naive.year(), 2023); assert_eq!(naive.month(), 2); assert_eq!(naive.day(), 8); } #[test] fn naivedate_from_ordinal() { let iso = crate::date("2023-039").unwrap(); let naive = chrono::NaiveDate::try_from(iso).unwrap(); assert_eq!(naive.year(), 2023); assert_eq!(naive.month(), 2); assert_eq!(naive.day(), 8); } } impl TryFrom for chrono::NaiveTime { type Error = (); fn try_from(iso: crate::Time) -> Result { chrono::NaiveTime::from_hms_opt(iso.hour, iso.minute, iso.second).ok_or(()) } } impl crate::Time { /// create a [`chrono::NaiveTime`] if possible pub fn into_naive(self) -> Option { chrono::NaiveTime::try_from(self).ok() } } impl TryFrom for chrono::DateTime { type Error = (); fn try_from(iso: crate::DateTime) -> Result { let crate::Time { tz_offset_hours, tz_offset_minutes, .. } = iso.time; let offset_minutes = tz_offset_hours * 3600 + tz_offset_minutes; let offset = chrono::FixedOffset::east_opt(offset_minutes).ok_or(())?; let naive_time = chrono::NaiveTime::try_from(iso.time)?; let naive_date_time = chrono::NaiveDate::try_from(iso.date)?.and_time(naive_time); offset .from_local_datetime(&naive_date_time) .single() .ok_or(()) } } impl crate::DateTime { /// create a [`chrono::DateTime`] if possible pub fn into_fixed_offset(self) -> Option> { chrono::DateTime::::try_from(self).ok() } /// create a [`chrono::NativeDateTime`] if possible pub fn into_naive(self) -> Option { self.into_fixed_offset().map(|fxed| fxed.naive_local()) } } #[cfg(test)] mod test_datetime { use chrono::{Datelike, Offset, Timelike}; use core::convert::TryFrom; #[test] fn datetime_from_iso_ymd_offset() { let iso = crate::datetime("2023-02-08T23:40:00+01:23").unwrap(); let datetime = chrono::DateTime::try_from(iso).unwrap(); assert_eq!(datetime.year(), 2023); assert_eq!(datetime.month(), 2); assert_eq!(datetime.day(), 8); assert_eq!(datetime.hour(), 23); assert_eq!(datetime.minute(), 40); assert_eq!(datetime.second(), 00); assert_eq!(datetime.offset().fix().local_minus_utc(), 3623); } #[test] fn datetime_from_iso_ymd_utc() { let iso = crate::datetime("2023-02-08T23:40:00Z").unwrap(); let datetime = chrono::DateTime::try_from(iso).unwrap(); assert_eq!(datetime.year(), 2023); assert_eq!(datetime.month(), 2); assert_eq!(datetime.day(), 8); assert_eq!(datetime.hour(), 23); assert_eq!(datetime.minute(), 40); assert_eq!(datetime.second(), 00); assert_eq!(datetime.offset().fix().local_minus_utc(), 0); } #[test] fn datetime_from_iso_ymd_no_offset() { let iso = crate::datetime("2023-02-08T23:40:00").unwrap(); let datetime = chrono::DateTime::try_from(iso).unwrap(); assert_eq!(datetime.year(), 2023); assert_eq!(datetime.month(), 2); assert_eq!(datetime.day(), 8); assert_eq!(datetime.hour(), 23); assert_eq!(datetime.minute(), 40); assert_eq!(datetime.second(), 00); assert_eq!(datetime.offset().fix().local_minus_utc(), 0); } #[test] fn datetime_from_iso_ywd() { let iso = crate::datetime("2023-W06-2T23:40:00+01:23").unwrap(); let datetime = chrono::DateTime::try_from(iso).unwrap(); assert_eq!(datetime.year(), 2023); assert_eq!(datetime.month(), 2); assert_eq!(datetime.day(), 8); assert_eq!(datetime.hour(), 23); assert_eq!(datetime.minute(), 40); assert_eq!(datetime.second(), 00); assert_eq!(datetime.offset().fix().local_minus_utc(), 3623); } } iso8601-0.6.1/src/display.rs000064400000000000000000000070271046102023000135510ustar 00000000000000use core::fmt::{self, Display}; use super::{Date, DateTime, Duration, 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_minutes ) } } 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) } } impl Display for Duration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Duration::YMDHMS { year, month, day, hour, minute, second, millisecond, } => { if self.is_zero() { write!(f, "P0D")?; return Ok(()); } write!(f, "P")?; if *year > 0 { write!(f, "{}Y", year)? } if *month > 0 { write!(f, "{}M", month)? } if *day > 0 { write!(f, "{}D", day)? } if *hour > 0 || *minute > 0 || *second > 0 || *millisecond > 0 { write!(f, "T")? } if *hour > 0 { write!(f, "{}H", hour)? } if *minute > 0 { write!(f, "{}M", minute)? } if *millisecond > 0 { write!(f, "{}.{}S", second, millisecond)? } else if *second > 0 { write!(f, "{}S", second)? } Ok(()) } Duration::Weeks(w) => write!(f, "P{}W", w), } } } #[cfg(test)] mod tests { use crate::parsers::parse_duration; use super::*; fn test_duration_reparse(duration: Duration) { let serialized = format!("{}", duration); let reparsed = parse_duration(serialized.as_bytes()).unwrap().1; assert_eq!(duration, reparsed); } #[test] fn display_duration_0() { let duration = Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 23, minute: 26, second: 59, millisecond: 0, }; test_duration_reparse(duration); } #[test] fn display_duration_1() { let duration = Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 23, minute: 26, second: 59, millisecond: 123, }; test_duration_reparse(duration); } #[test] fn display_duration_2() { let duration = Duration::Weeks(50); test_duration_reparse(duration); } } iso8601-0.6.1/src/lib.rs000064400000000000000000000207251046102023000126520ustar 00000000000000//! 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(); //! ``` #![allow(clippy::uninlined_format_args)] #![deny( missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces, unused_qualifications, missing_docs )] #![warn(clippy::doc_markdown)] #![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; pub mod parsers; #[cfg(feature = "chrono")] mod chrono; #[cfg(feature = "serde")] mod serde; #[cfg(test)] mod assert; /// A date, can hold three different formats. #[allow(missing_docs)] #[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, /// the hour part of the timezone offset from UTC pub tz_offset_hours: i32, /// the minute part of the timezone offset from UTC pub tz_offset_minutes: i32, } /// Compound struct, holds Date and Time. #[derive(Eq, PartialEq, Debug, Copy, Clone, Default)] pub struct DateTime { /// The date part pub date: Date, /// The time part pub time: Time, } /// A time duration. /// Durations: /// /// dur-second = 1*DIGIT "S" /// dur-minute = 1*DIGIT "M" [dur-second] /// dur-hour = 1*DIGIT "H" [dur-minute] /// dur-time = "T" (dur-hour / dur-minute / dur-second) /// dur-day = 1*DIGIT "D" /// dur-week = 1*DIGIT "W" /// dur-month = 1*DIGIT "M" [dur-day] /// dur-year = 1*DIGIT "Y" [dur-month] /// dur-date = (dur-day / dur-month / dur-year) [dur-time] /// duration = "P" (dur-date / dur-time / dur-week) #[derive(Eq, PartialEq, Debug, Copy, Clone)] pub enum Duration { /// A duration specified by year, month, day, hour, minute and second units YMDHMS { /// Number of calendar years year: u32, /// Number of months month: u32, /// Number of days day: u32, /// Number of hours hour: u32, /// Number of minutes minute: u32, /// Number of seconds second: u32, /// Number of milliseconds millisecond: u32, }, /// consists of week units Weeks(u32), } impl Duration { /// Whether this duration represents a zero duration. pub fn is_zero(&self) -> bool { *self == Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, } || *self == Duration::Weeks(0) } } impl Time { /// Change this time's timezone offset. /// /// # Arguments /// /// * `tzo` - A tuple of `(hours, minutes)` specifying the timezone offset from UTC. 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) } } impl From for ::core::time::Duration { fn from(duration: Duration) -> Self { match duration { Duration::YMDHMS { year, month, day, hour, minute, second, millisecond, } => { let secs = u64::from(year) * 365 * 86_400 + u64::from(month) * 30 * 86_400 + u64::from(day) * 86_400 + u64::from(hour) * 3600 + u64::from(minute) * 60 + u64::from(second); let nanos = millisecond * 1_000_000; Self::new(secs, nanos) } Duration::Weeks(week) => { let secs = u64::from(week) * 7 * 86_400; Self::from_secs(secs) } } } } /// 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!("Failed to parse date: {}", 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!("Failed to parse time: {}", 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!("Failed to parse datetime: {}", 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`] 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!("Failed to parse duration: {}", string)) } } iso8601-0.6.1/src/parsers/tests.rs000064400000000000000000000326011046102023000147210ustar 00000000000000use super::*; use crate::assert_parser; #[test] fn test_date_year() { assert_eq!(Ok((&[][..], 2015)), date_year(b"2015")); assert_eq!(Ok((&[][..], -333)), 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"2019Y")); assert_eq!(Ok((&[][..], 0)), duration_year(b"0Y")); assert_eq!(Ok((&[][..], 10000)), duration_year(b"10000Y")); 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"6M")); assert_eq!(Ok((&[][..], 0)), duration_month(b"0M")); assert_eq!(Ok((&[][..], 12)), duration_month(b"12M")); 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"26W")); assert_eq!(Ok((&[][..], 0)), duration_week(b"0W")); assert_eq!(Ok((&[][..], 52)), duration_week(b"52W")); 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"16D")); assert_eq!(Ok((&[][..], 0)), duration_day(b"0D")); assert_eq!(Ok((&[][..], 31)), duration_day(b"31D")); 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"12H")); assert_eq!(Ok((&[][..], 0)), duration_hour(b"0H")); assert_eq!(Ok((&[][..], 24)), duration_hour(b"24H")); 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"30M")); assert_eq!(Ok((&[][..], 0)), duration_minute(b"0M")); assert_eq!(Ok((&[][..], 60)), duration_minute(b"60M")); 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_millisecond1() { assert_eq!( Ok((&[][..], (30, 0))), duration_second_and_millisecond(b"30S") ); assert_eq!( Ok((&[][..], (0, 0))), duration_second_and_millisecond(b"0S") ); assert_eq!( Ok((&[][..], (60, 0))), duration_second_and_millisecond(b"60S") ); assert_eq!( Ok((&[][..], (1, 230))), duration_second_and_millisecond(b"1,23S") ); assert_eq!( Ok((&[][..], (2, 340))), duration_second_and_millisecond(b"2.34S") ); assert!(duration_second_and_millisecond(b"abS").is_err()); assert!(duration_second_and_millisecond(b"-1S").is_err()); } #[test] fn test_duration_time() { assert_eq!(Ok((&[][..], (1, 2, 3, 0))), duration_time(b"1H2M3S")); assert_eq!(Ok((&[][..], (10, 12, 30, 0))), duration_time(b"10H12M30S")); 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 } #[rustfmt::skip] #[test] fn test_duration_second_and_millisecond2() { assert_parser!( parse_duration, "PT30S", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 30, millisecond: 0 } ); assert_parser!( parse_duration, "PT30.123S", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 30, millisecond: 123 } ); assert_parser!( parse_duration, "P2021Y11M16DT23H26M59.123S", Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 23, minute: 26, second: 59, millisecond: 123 } ); } #[rustfmt::skip] #[test] fn duration_roundtrip() { assert_parser!( parse_duration, "P0W", Duration::Weeks(0) ); assert_parser!( parse_duration, "P2021Y11M16DT23H26M59.123S", Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 23, minute: 26, second: 59, millisecond: 123 } ); assert_parser!( parse_duration, "P2021Y11M16DT23H26M59S", Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 23, minute: 26, second: 59, millisecond: 0 } ); assert_parser!( parse_duration, "P2021Y11M16DT23H26M", Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 23, minute: 26, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "P2021Y11M16DT23H", Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 23, minute: 0, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "P2021Y11M16D", Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 0, minute: 0, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "P2021Y11M16DT1S", Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 0, minute: 0, second: 1, millisecond: 0 } ); assert_parser!( parse_duration, "P2021Y11M16DT0.471S", Duration::YMDHMS { year: 2021, month: 11, day: 16, hour: 0, minute: 0, second: 0, millisecond: 471 } ); assert_parser!( parse_duration, "P2021Y11M", Duration::YMDHMS { year: 2021, month: 11, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "P11M", Duration::YMDHMS { year: 0, month: 11, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "P16D", Duration::YMDHMS { year: 0, month: 0, day: 16, hour: 0, minute: 0, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "P0D", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0 } ); } #[rustfmt::skip] #[test] fn duration_multi_digit_hour() { assert_parser!( parse_duration, "PT12H", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 12, minute: 0, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "PT8760H", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 365*24, minute: 0, second: 0, millisecond: 0 } ); } #[rustfmt::skip] #[test] fn duration_multi_digit_minute() { assert_parser!( parse_duration, "PT15M", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 15, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "PT600M", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 600, second: 0, millisecond: 0 } ); } #[rustfmt::skip] #[test] fn duration_multi_digit_second() { assert_parser!( parse_duration, "PT16S", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 16, millisecond: 0 } ); assert_parser!( parse_duration, "PT900S", Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 900, millisecond: 0 } ); } #[rustfmt::skip] #[test] fn duration_multi_digit_day() { assert_parser!( parse_duration, "P365D", Duration::YMDHMS { year: 0, month: 0, day: 365, hour: 0, minute: 0, second: 0, millisecond: 0 } ); assert_parser!( parse_duration, "P36500D", Duration::YMDHMS { year: 0, month: 0, day: 36500, hour: 0, minute: 0, second: 0, millisecond: 0 } ); } // #[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.6.1/src/parsers.rs000064400000000000000000000245731046102023000135700ustar 00000000000000//! The low-level parsers for date, datetime, duration and time. //! //! The top-level functions [`date`][`crate::date`], [`datetime`][`crate::datetime`], //! [`duration`][`crate::duration`] and [`time`][`crate::time`] //! provide convenient wrappers around the low-level parsers, //! but throw away leftover input on success. //! //! Using the low-level functions provided here allows to recover leftover input //! or to combine these parsers with other parser combinators. 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, map_res, not, opt}, error::Error, sequence::{preceded, separated_pair, terminated, tuple}, Err, 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(Err::Error(Error::new(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 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(Err::Error(Error::new(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) } // DATE // [+/-]YYYY fn date_year(i: &[u8]) -> IResult<&[u8], i32> { // The sign is optional, but defaults to `+` map( tuple(( opt(sign), // [+/-] |i| take_n_digits(i, 4), // year )), |(s, year)| s.unwrap_or(1) * year as i32, )(i) } // 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> { map( tuple(( date_year, // YYYY opt(tag(b"-")), // - date_month, // MM opt(tag(b"-")), // - date_day, //DD )), |(year, _, month, _, day)| Date::YMD { year, month, day }, )(i) } // YYYY-DDD fn date_ordinal(i: &[u8]) -> IResult<&[u8], Date> { map( separated_pair(date_year, opt(tag(b"-")), date_ord_day), |(year, ddd)| Date::Ordinal { year, ddd }, )(i) } // YYYY-"W"WW-D fn date_iso_week(i: &[u8]) -> IResult<&[u8], Date> { map( tuple(( date_year, // y tuple((opt(tag(b"-")), tag(b"W"))), // [-]W date_week, // w opt(tag(b"-")), // [-] date_week_day, // d )), |(year, _, ww, _, d)| Date::Week { year, ww, d }, )(i) } /// Parses a date string. /// /// See [`date`][`crate::date`] for the supported formats. 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) } // Converts the fractional part if-any of a number of seconds to milliseconds // truncating towards zero if there are more than three digits. // e.g. "" -> 0, "1" -> 100, "12" -> 120, "123" -> 123, "1234" -> 123 fn fraction_millisecond(i: &[u8]) -> IResult<&[u8], u32> { let (i, mut digits) = take_while(is_digit)(i)?; let mut l = digits.len(); if l > 3 { digits = digits.get(0..3).unwrap(); } let mut result = 0; if l > 0 { let digits = str::from_utf8(digits).unwrap(); // This can't panic, `digits` will only include digits. result = digits.parse().unwrap(); } while l < 3 { result *= 10; l += 1; } Ok((i, result)) } /// Parses a time string. /// /// See [`time`][`crate::time`] for the supported formats. // HH:MM:[SS][.(m*)][(Z|+...|-...)] pub fn parse_time(i: &[u8]) -> IResult<&[u8], Time> { map( tuple(( time_hour, // HH opt(tag(b":")), // : time_minute, // MM opt(preceded(opt(tag(b":")), time_second)), // [SS] opt(preceded(one_of(",."), fraction_millisecond)), // [.(m*)] opt(alt((timezone_hour, timezone_utc))), // [(Z|+...|-...)] )), |(h, _, m, s, ms, z)| { let (tz_offset_hours, tz_offset_minutes) = z.unwrap_or((0, 0)); Time { hour: h, minute: m, second: s.unwrap_or(0), millisecond: ms.unwrap_or(0), tz_offset_hours, tz_offset_minutes, } }, )(i) } fn timezone_hour(i: &[u8]) -> IResult<&[u8], (i32, i32)> { map( tuple((sign, time_hour, opt(preceded(opt(tag(b":")), time_minute)))), |(s, h, m)| (s * (h as i32), s * (m.unwrap_or(0) as i32)), )(i) } fn timezone_utc(i: &[u8]) -> IResult<&[u8], (i32, i32)> { map(tag(b"Z"), |_| (0, 0))(i) } /// Parses a datetime string. /// /// See [`datetime`][`crate::datetime`] for supported formats. // Full ISO8601 datetime pub fn parse_datetime(i: &[u8]) -> IResult<&[u8], DateTime> { map( separated_pair(parse_date, tag(b"T"), parse_time), |(d, t)| DateTime { date: d, time: t }, )(i) } // DURATION /// dur-year = 1*DIGIT "Y" [dur-month] fn duration_year(i: &[u8]) -> IResult<&[u8], u32> { terminated(take_digits, tag(b"Y"))(i) } /// dur-month = 1*DIGIT "M" [dur-day] fn duration_month(i: &[u8]) -> IResult<&[u8], u32> { terminated(take_digits, tag(b"M"))(i) } /// dur-week = 1*DIGIT "W" fn duration_week(i: &[u8]) -> IResult<&[u8], u32> { terminated(take_digits, tag(b"W"))(i) } // dur-day = 1*DIGIT "D" fn duration_day(i: &[u8]) -> IResult<&[u8], u32> { terminated(take_digits, tag(b"D"))(i) } /// dur-hour = 1*DIGIT "H" [dur-minute] /// dur-time = "T" (dur-hour / dur-minute / dur-second) fn duration_hour(i: &[u8]) -> IResult<&[u8], u32> { terminated(take_digits, tag(b"H"))(i) } /// dur-minute = 1*DIGIT "M" [dur-second] fn duration_minute(i: &[u8]) -> IResult<&[u8], u32> { terminated(take_digits, tag(b"M"))(i) } //// dur-second = 1*DIGIT "S" fn duration_second(i: &[u8]) -> IResult<&[u8], u32> { terminated(take_digits, tag(b"S"))(i) } /// dur-second-ext = 1*DIGIT (,|.) 1*DIGIT "S" fn duration_second_and_millisecond(i: &[u8]) -> IResult<&[u8], (u32, u32)> { alt(( // no milliseconds map(duration_second, |m| (m, 0)), terminated( // with milliseconds separated_pair(take_digits, one_of(",."), fraction_millisecond), tag(b"S"), ), ))(i) } fn duration_time(i: &[u8]) -> IResult<&[u8], (u32, u32, u32, u32)> { map( tuple(( opt(duration_hour), opt(duration_minute), opt(duration_second_and_millisecond), )), |(h, m, s)| { let (s, ms) = s.unwrap_or((0, 0)); (h.unwrap_or(0), m.unwrap_or(0), s, ms) }, )(i) } fn duration_ymdhms(i: &[u8]) -> IResult<&[u8], Duration> { map_res( preceded( tag(b"P"), tuple(( opt(duration_year), opt(duration_month), opt(duration_day), opt(preceded(tag(b"T"), duration_time)), )), ), |(y, mo, d, time)| { // 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(Err::Error((i, nom::error::ErrorKind::Eof))); } let (h, mi, s, ms) = time.unwrap_or((0, 0, 0, 0)); Ok(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, }) }, )(i) } fn duration_weeks(i: &[u8]) -> IResult<&[u8], Duration> { map(preceded(tag(b"P"), duration_week), Duration::Weeks)(i) } // 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> { map( preceded( tuple((tag(b"P"), not(sign))), tuple(( duration_datetime_year, opt(tag(b"-")), date_month, opt(tag(b"-")), date_day, tag(b"T"), parse_time, )), ), |(year, _, month, _, day, _, t)| Duration::YMDHMS { year, month, day, hour: t.hour, minute: t.minute, second: t.second, millisecond: t.millisecond, }, )(i) } /// Parses a duration string. /// /// See [`duration`][`crate::duration`] for supported formats. pub fn parse_duration(i: &[u8]) -> IResult<&[u8], Duration> { alt((duration_ymdhms, duration_weeks, duration_datetime))(i) } iso8601-0.6.1/src/serde.rs000064400000000000000000000161771046102023000132140ustar 00000000000000use alloc::{fmt, string::ToString}; use core::str::FromStr; use serde::{ de::{self, Visitor}, Deserialize, Deserializer, Serialize, Serializer, }; mod date { use super::*; impl<'de> Deserialize<'de> for crate::Date { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_str(DateVisitor) } } impl Serialize for crate::Date { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(&self.to_string()) } } struct DateVisitor; impl<'de> Visitor<'de> for DateVisitor { type Value = crate::Date; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a string that follows iso8601 date format") } fn visit_str(self, s: &str) -> Result where E: de::Error, { match Self::Value::from_str(s) { Ok(p) => Ok(p), Err(_) => Err(de::Error::invalid_value(de::Unexpected::Str(s), &self)), } } } #[test] fn serialize() { let date_json = r#""2023-02-10""#; let date = crate::date("2023-02-10").unwrap(); let serialized_date = serde_json::to_string(&date).unwrap(); assert_eq!(serialized_date, date_json); } #[test] fn deserialize() { let date_json = r#""2023-02-10""#; let date = crate::date("2023-02-10").unwrap(); let deserialized_date = serde_json::from_str::(date_json).unwrap(); assert_eq!(deserialized_date, date); } } mod time { use super::*; impl<'de> Deserialize<'de> for crate::Time { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_str(TimeVisitor) } } impl Serialize for crate::Time { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(&self.to_string()) } } struct TimeVisitor; impl<'de> Visitor<'de> for TimeVisitor { type Value = crate::Time; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a string that follows iso8601 time format") } fn visit_str(self, s: &str) -> Result where E: de::Error, { match Self::Value::from_str(s) { Ok(p) => Ok(p), Err(_) => Err(de::Error::invalid_value(de::Unexpected::Str(s), &self)), } } } #[test] fn serialize() { let time_json = r#""18:12:15.0+00:00""#; let deserialized_time = serde_json::from_str::(time_json).unwrap(); let serialized_time = serde_json::to_string(&deserialized_time).unwrap(); assert_eq!(serialized_time, time_json); } #[test] fn deserialize() { let time_json = r#""18:12:15""#; let expected_time = crate::time("18:12:15").unwrap(); let deserialized_time = serde_json::from_str::(time_json).unwrap(); assert_eq!(deserialized_time, expected_time); } } mod datetime { use super::*; impl<'de> Deserialize<'de> for crate::DateTime { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_str(DateTimeVisitor) } } impl Serialize for crate::DateTime { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(&self.to_string()) } } struct DateTimeVisitor; impl<'de> Visitor<'de> for DateTimeVisitor { type Value = crate::DateTime; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a string that follows iso8601 Datetime format") } fn visit_str(self, s: &str) -> Result where E: de::Error, { match Self::Value::from_str(s) { Ok(p) => Ok(p), Err(_) => Err(de::Error::invalid_value(de::Unexpected::Str(s), &self)), } } } #[test] fn serialize() { let datetime_json = r#""2023-02-10T18:12:15.0+00:00""#; let datetime = crate::datetime("2023-02-10T18:12:15.0+00:00").unwrap(); let serialized_datetime = serde_json::to_string(&datetime).unwrap(); assert_eq!(serialized_datetime, datetime_json); } #[test] fn deserialize() { let datetime_json = r#""2023-02-10T18:12:15""#; let datetime = crate::datetime("2023-02-10T18:12:15").unwrap(); let deserialized_datetime = serde_json::from_str::(datetime_json).unwrap(); assert_eq!(deserialized_datetime, datetime); } #[test] fn deserialize_short() { let datetime_json = r#""2023-02-10T18:12""#; let datetime = crate::datetime("2023-02-10T18:12").unwrap(); let deserialized_datetime = serde_json::from_str::(datetime_json).unwrap(); assert_eq!(deserialized_datetime, datetime); } } mod duration { use super::*; impl<'de> Deserialize<'de> for crate::Duration { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_str(DurationVisitor) } } impl Serialize for crate::Duration { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(&self.to_string()) } } struct DurationVisitor; impl<'de> Visitor<'de> for DurationVisitor { type Value = crate::Duration; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a string that follows iso8601 Duration format") } fn visit_str(self, s: &str) -> Result where E: de::Error, { match Self::Value::from_str(s) { Ok(p) => Ok(p), Err(_) => Err(de::Error::invalid_value(de::Unexpected::Str(s), &self)), } } } #[test] fn serialize() { let duration_json = r#""P1Y2M3DT4H5M6S""#; let duration = crate::duration("P1Y2M3DT4H5M6S").unwrap(); let serialized_duration = serde_json::to_string(&duration).unwrap(); assert_eq!(serialized_duration, duration_json); } #[test] fn deserialize() { let duration_json = r#""P1Y2M3DT4H5M6S""#; let duration = crate::duration("P1Y2M3DT4H5M6S").unwrap(); let deserialized_duration = serde_json::from_str::(duration_json).unwrap(); assert_eq!(deserialized_duration, duration); } } iso8601-0.6.1/tests/lib.rs000064400000000000000000000647501046102023000132330ustar 00000000000000use 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() { let mut i = 0; while i < 1000 { //regression test for pull request 36. assert_eq!( Ok(Time { hour: 16, minute: 43, second: 0, millisecond: i, tz_offset_hours: 0, tz_offset_minutes: 0 }), time(format!("16:43:00.{:0>3}", i).as_str()) ); i += 1; } 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: 4, minute: 5, second: 6, 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: 5, d: 6 }, time: Time { hour: 4, minute: 5, second: 6, 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: 8, 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: 8, 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: 8, 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: 8, 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: 8, 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: 8, 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: 2, day: 1 }, 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: 6, 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: 6, day: 29 }, time: Time { hour: 23, minute: 7, 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: 6, 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: 6, 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: 5, d: 6 }, time: Time { hour: 4, 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: 5, d: 6 }, time: Time { hour: 4, 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: 4, 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: 4, 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: 5, d: 6 }, time: Time { hour: 4, minute: 5, second: 6, 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: 5, d: 6 }, time: Time { hour: 4, minute: 5, second: 6, 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() { use core::time::Duration as StdDuration; // full YMDHMS let dur = duration("P1Y2M3DT4H5M6S").unwrap(); assert_eq!( Duration::YMDHMS { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(36993906, 0)); // full YMDHMS with milliseconds dot delimiter let dur = duration("P1Y2M3DT4H5M6.7S").unwrap(); assert_eq!( Duration::YMDHMS { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6, millisecond: 700, }, dur ); assert_eq!( StdDuration::from(dur), StdDuration::new(36993906, 700000000) ); // full YMDHMS with milliseconds comma delimiter let dur = duration("P1Y2M3DT4H5M6,7S").unwrap(); assert_eq!( Duration::YMDHMS { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6, millisecond: 700, }, dur ); assert_eq!( StdDuration::from(dur), StdDuration::new(36993906, 700000000) ); // subset YM-HM- let dur = duration("P1Y2MT4H5M").unwrap(); assert_eq!( Duration::YMDHMS { year: 1, month: 2, day: 0, hour: 4, minute: 5, second: 0, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(36734700, 0)); // subset Y----- let dur = duration("P1Y").unwrap(); assert_eq!( Duration::YMDHMS { year: 1, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(31536000, 0)); // subset ---H-- let dur = duration("PT4H").unwrap(); assert_eq!( Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 4, minute: 0, second: 0, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(14400, 0)); // subset -----S with milliseconds dot delimiter let dur = duration("PT6.7S").unwrap(); assert_eq!( Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 6, millisecond: 700, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(6, 700000000)); // subset -----S with milliseconds comma delimiter let dur = duration("PT6,700S").unwrap(); assert_eq!( Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 6, millisecond: 700, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(6, 700000000)); // empty duration, using Y let dur = duration("P0Y").unwrap(); assert_eq!( Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(0, 0)); // empty duration, using S let dur = duration("PT0S").unwrap(); assert_eq!( Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(0, 0)); let dur = duration("PT42M30S").unwrap(); assert_eq!( Duration::YMDHMS { year: 0, month: 0, day: 0, hour: 0, minute: 42, second: 30, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(2550, 0)); let dur = duration("P0001-02-03T04:05:06").unwrap(); assert_eq!( Duration::YMDHMS { year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(36993906, 0)); let dur = duration("P2018-04-27T00:00:00").unwrap(); assert_eq!( Duration::YMDHMS { year: 2018, month: 4, day: 27, hour: 0, minute: 0, second: 0, millisecond: 0, }, dur ); assert_eq!(StdDuration::from(dur), StdDuration::new(63652348800, 0)); } #[test] fn test_duration_weeks() { use core::time::Duration as StdDuration; let dur = duration("P0W").unwrap(); assert_eq!(Duration::Weeks(0), dur); assert_eq!(StdDuration::from(dur), StdDuration::new(0, 0)); let dur = duration("P26W").unwrap(); assert_eq!(Duration::Weeks(26), dur); assert_eq!(StdDuration::from(dur), StdDuration::new(15724800, 0)); let dur = duration("P52W").unwrap(); assert_eq!(Duration::Weeks(52), dur); assert_eq!(StdDuration::from(dur), StdDuration::new(31449600, 0)); }