time-fmt-0.3.8/.cargo_vcs_info.json0000644000000001360000000000100125660ustar { "git": { "sha1": "56772929d792efc629514e3d98c21ef9366bdfb7" }, "path_in_vcs": "" }time-fmt-0.3.8/.gitignore000064400000000000000000000000231046102023000133410ustar 00000000000000/target Cargo.lock time-fmt-0.3.8/Cargo.toml0000644000000020330000000000100105620ustar # 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 = "2021" name = "time-fmt" version = "0.3.8" authors = ["mi_sawa "] exclude = [ ".github", "release.toml", ] description = "A strftime/strptime-like time formatter/parser for time-rs" readme = "README.md" license = "MIT/Apache-2.0" repository = "https://github.com/MiSawa/time-fmt" [dependencies.thiserror] version = "1.0.30" [dependencies.time] version = "0.3.7" features = [ "parsing", "formatting", ] [dev-dependencies.time] version = "0.3.7" features = [ "large-dates", "macros", ] [features] default = [] time-fmt-0.3.8/Cargo.toml.orig000064400000000000000000000010351046102023000142440ustar 00000000000000[package] name = "time-fmt" version = "0.3.8" authors = ["mi_sawa "] edition = "2021" description = "A strftime/strptime-like time formatter/parser for time-rs" license = "MIT/Apache-2.0" repository = "https://github.com/MiSawa/time-fmt" readme = "README.md" exclude = [".github", "release.toml"] [features] default = [] [dependencies] thiserror = "1.0.30" time = { version = "0.3.7", features = ["parsing", "formatting"] } [dev-dependencies] time = { version = "0.3.7", features = ["large-dates", "macros"] } time-fmt-0.3.8/LICENSE-APACHE000064400000000000000000000261351046102023000133110ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. time-fmt-0.3.8/LICENSE-MIT000064400000000000000000000020471046102023000130150ustar 00000000000000MIT License Copyright (c) 2022 MiSawa 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. time-fmt-0.3.8/README.md000064400000000000000000000136771046102023000126530ustar 00000000000000[![CI](https://github.com/MiSawa/time-fmt/actions/workflows/ci.yml/badge.svg)](https://github.com/MiSawa/time-fmt/actions/workflows/ci.yml) [![crates.io](https://img.shields.io/crates/v/time-fmt.svg)](https://crates.io/crates/time-fmt) # time-fmt This is a library that formats/parses datetime of the [time crate](https://github.com/time-rs/time) with _somewhat_ more `strftime`/`strptime`-compatible format specification. **You should really use the format of the time crate**, if there's no strong reason not to. ## Features - ANSI/ISO C `strftime`-like function. - `%C`, `%d`, `%D`, `%e`, `%F`, `%g`, `%G`, `%h`, `%H`, `%I`, `%j`, `%k`, `%l`, `%m`, `%M`, `%n`, `%R`, `%S`, `%t`, `%T`, `%u`, `%U`, `%V`, `%w`, `%W`, `%y`, `%Y`, `%%`. - Those treated as if you were in C/POSIX locale: `%a`, `%A`, `%b`, `%B`, `%c`, `%p`, `%P`, `%r`, `%x`, `%X`. - Available-ish (see: incompatibilities section): `%z`, `%Z`. - POSIX C `strptime`-like function. - `%C`, `%d`, `%D`, `%e`, `%F`, `%h`, `%H`, `%I`, `%j`, `%k`, `%l`, `%m`, `%M`, `%n`, `%R`, `%S`, `%t`, `%T`, `%W`, `%y`, `%Y`, `%%`. - Those treated as if you were in C/POSIX locale: `%b`, `%B`, `%c`, `%p`, `%P`, `%r`, `%x`, `%X` - Available-ish but the way handling the parsed value is delegated to the user: `%z`, `%Z`. - Those parsed (as if you were in C/POSIX locale) but ignored: `%a`, `%A`, `%U`, `%w`. - A function that converts `strftime`-like conversion specification to `Vec` of the time crate. - A function that converts `strptime`-like conversion description to `Vec` of the time crate. ## *Non*-features ...yet. Contributions are welcomed! - Not well-tested. Obviously require a lot more tests. - Compiling format specifications to an intermediate representation is unsupported. Convert them to `Vec` instead. - `%E*` and `%O*` should be implemented as if it were in the C/POSIX locale; i.e. fall back to the normal ones. - Minimum field width (should be applicable to `C`, `F`, `G`, `Y`) and flags (`0`, `+`). ## Incompatibilities / Cautions - `strftime`-like ones - Those require `nl_langinfo` lookups, namely `%a`, `%A`, `%b`, `%h`, `%B`, `%c`, `%p`, `%P`, `%r`, `%x`, and `%X` are not implemented to do so. Instead, they are hardcoded to use that of C/POSIX locale. - Era-based formats, namely those starts with `%E` are unsupported. - Alternative numeric symbols, namely those starts with `%O` are unsupported. - `%z` doesn't work if you passed `PrimitiveDateTime`. It'll be substituted to the empty string, as if "no time zone is determinable". - `%Z` works only if you used a function that takes a zone name. Otherwise substituted to the empty string, as if "no time zone is determinable". - `%` followed by a character that doesn't compose a conversion specifier that *we* support will result into an error. - `strptime`-like ones - Years has to fit in 4 bytes, i.e. before the year -999 or after the year 9999 are unsupported. - Day of week specifiers, week of year specifiers, namely `%a`, `%A`, `%U`, and `%w` are matched to the input but ignored. - Since our structure that represents date/time are not something like `struct tm` of C language, inconsistent input will result in an unspecified behavior. - For example, one can specify the month, the day of the month, and the day of the year. But it's unclear what to do if the day of the year doesn't match what (month, day of the month) pair says. Currently it choose what day of the year says, it may be changed to do something else, for example returning `Result::Err` in a future release *without bumping the major version*. - Offset/timezone info given by `%z`, `%Z` are not refleted to the returned date time. Instead, we return a pair of `PrimitiveDateTime` and the parsed offset / timezone name. - If `Z` was given for `%z`, it will be treated as same as `+00:00`. - Convertion from `strftime`-like conversion specification to `Vec` - `%C` (century) and `%Z` (timezone name) are unsupported as no corresponding `FormatItem` exists. - Convertion from `strptime`-like conversion description to `Vec` - `%C` (century) and `%Z` (timezone name) are unsupported as no corresponding `FormatItem` exists. - `%z` (timezone specifier) can't be `Z`, as we can't seem to do it with `FormatItem`. - Whitespaces won't eat more than one white space, as there's no repetitions in `FormatItem`. ## Examples ```rust use time::{macros::{datetime, offset}, UtcOffset}; use time_fmt::{format::*, parse::*}; let dt = datetime!(2022-03-06 12:34:56); // Format primitive date time assert_eq!( format_date_time("%Y-%m-%d %H:%M:%S", dt).unwrap(), "2022-03-06 12:34:56" ); // Format offset date time assert_eq!( format_offset_date_time("%Y-%m-%d %H:%M:%S %z", dt.assume_offset(offset!(+9:00))).unwrap(), "2022-03-06 12:34:56 +0900" ); // With timezone_name feature assert_eq!( format_zoned_date_time("%Y-%m-%d %H:%M:%S %Z", dt, offset!(+9:00), "JST").unwrap(), "2022-03-06 12:34:56 JST" ); // Parse date time assert_eq!( parse_date_time_maybe_with_zone("%Y-%m-%d %H:%M:%S %z", "2022-03-06 12:34:56 +0900") .unwrap(), ( dt, Some(TimeZoneSpecifier::Offset( UtcOffset::from_hms(9, 0, 0).unwrap() )) ) ); ``` ## Publish new version Note for myself. ```shell $ git switch master # make sure you're on the master branch $ cargo release patch # to dry-run the release $ cargo release patch --execute # to actually execute the release ``` ## License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. time-fmt-0.3.8/src/format/spec_parser.rs000064400000000000000000000237141046102023000163200ustar 00000000000000use std::slice::SliceIndex; /// E and O are not implemented. /// Those require `nl-langinfo` lookup is default-implemented as if it were a POSIX locale. /// If you'd want to implement it properly, it's your responsibility to recursively parse /// the format you get from `nl-langinfo`, and prevent infinite recursion. pub(crate) trait Collector { type Output; type Error; /// `%a`. `nl_langinfo`-dependent. fn day_of_week_name_short(&mut self) -> Result<(), Self::Error>; /// `%A`. `nl_langinfo`-dependent. fn day_of_week_name_long(&mut self) -> Result<(), Self::Error>; /// `%b` and `%h`. `nl_langinfo`-dependent. fn month_name_short(&mut self) -> Result<(), Self::Error>; /// `%B`. `nl_langinfo`-dependent. fn month_name_long(&mut self) -> Result<(), Self::Error>; /// `%c`. Same as `%a %b %e %T %Y` in POSIX locale. `nl_langinfo`-dependent. #[inline] fn preferred_date_time(&mut self) -> Result<(), Self::Error> { self.day_of_week_name_short()?; self.static_str(" ")?; self.month_name_short()?; self.static_str(" ")?; self.day_of_month_blank()?; self.static_str(" ")?; self.time_of_day()?; self.static_str(" ")?; self.year() } /// `%C`. `00` to unbounded number. fn year_prefix(&mut self) -> Result<(), Self::Error>; /// `%d`. `01` to `31`. fn day_of_month(&mut self) -> Result<(), Self::Error>; /// `%D`. `%m/%d/%y` (American......). #[inline] fn date_mmddyy_slash(&mut self) -> Result<(), Self::Error> { self.month_of_year()?; self.static_str("/")?; self.day_of_month()?; self.static_str("/")?; self.year_suffix() } /// `%e`. ` 1` to `31`. fn day_of_month_blank(&mut self) -> Result<(), Self::Error>; /// `%F`. `%Y-%m-%d`. #[inline] fn date_yyyymmdd_hyphen(&mut self) -> Result<(), Self::Error> { self.year()?; self.static_str("-")?; self.month_of_year()?; self.static_str("-")?; self.day_of_month() } /// `%g`. ISO 8601 week-based year modulo 100. fn iso8601_week_based_year_suffix(&mut self) -> Result<(), Self::Error>; /// `%G`. ISO 8601 week-based year. fn iso8601_week_based_year(&mut self) -> Result<(), Self::Error>; /// `%H`. `00` to `23`. fn hour_of_day(&mut self) -> Result<(), Self::Error>; /// `%I`. `01` to `12`. fn hour_of_day_12(&mut self) -> Result<(), Self::Error>; /// `%j`. `001` to `336`. fn day_of_year(&mut self) -> Result<(), Self::Error>; /// `%k`. ` 0` to `23`. fn hour_of_day_blank(&mut self) -> Result<(), Self::Error>; /// `%l`. ` 1` to `12`. fn hour_of_day_12_blank(&mut self) -> Result<(), Self::Error>; /// `%m`. `01` to `12`. fn month_of_year(&mut self) -> Result<(), Self::Error>; /// `%M`. `00` to `59`. fn minute_of_hour(&mut self) -> Result<(), Self::Error>; /// `%n`. #[inline] fn new_line(&mut self) -> Result<(), Self::Error> { self.static_str("\n") } /// `%p`. `AM` or `PM`. `nl_langinfo`-dependent. fn ampm(&mut self) -> Result<(), Self::Error>; /// `%P`. `am` or `pm`. `nl_langinfo`-dependent. fn ampm_lower(&mut self) -> Result<(), Self::Error>; /// `%r`. Same as `%I:%M:%S %p` in POSIX locale. `nl_langinfo`-dependent. #[inline] fn time_ampm(&mut self) -> Result<(), Self::Error> { self.hour_of_day_12()?; self.static_str(":")?; self.minute_of_hour()?; self.static_str(":")?; self.second_of_minute()?; self.static_str(" ")?; self.ampm() } /// `%R`. Same as `%H:%M`. #[inline] fn hour_minute_of_day(&mut self) -> Result<(), Self::Error> { self.hour_of_day()?; self.static_str(":")?; self.minute_of_hour() } /// `%S`. `00` to `60`. fn second_of_minute(&mut self) -> Result<(), Self::Error>; /// `%f`. `000000000` to `999999999`. fn nanosecond_of_second(&mut self) -> Result<(), Self::Error>; /// `%t`. #[inline] fn tab(&mut self) -> Result<(), Self::Error> { self.static_str("\t") } /// `%T`. Same as `%H:%M:%S`. #[inline] fn time_of_day(&mut self) -> Result<(), Self::Error> { self.hour_of_day()?; self.static_str(":")?; self.minute_of_hour()?; self.static_str(":")?; self.second_of_minute() } /// `%u`. `1` to `7` fn day_of_week_from_monday_as_1(&mut self) -> Result<(), Self::Error>; /// `%U`. `00` to `53`. fn week_number_of_current_year_start_sunday(&mut self) -> Result<(), Self::Error>; /// `%V`. `01` to `53`. fn iso8601_week_number(&mut self) -> Result<(), Self::Error>; /// `%w`. fn day_of_week_from_sunday_as_0(&mut self) -> Result<(), Self::Error>; /// `%W`. `00` to `53`. fn week_number_of_current_year_start_monday(&mut self) -> Result<(), Self::Error>; /// `%x`. `%m/%d/%y` in POSIX locale. `nl_langinfo`-dependent. #[inline] fn preferred_date(&mut self) -> Result<(), Self::Error> { self.month_of_year()?; self.static_str("/")?; self.day_of_month()?; self.static_str("/")?; self.year_suffix() } /// `%X`. `%H:%M:%S` in POSIX locale. `nl_langinfo`-dependent. #[inline] fn preferred_time_of_day(&mut self) -> Result<(), Self::Error> { self.hour_of_day()?; self.static_str(":")?; self.minute_of_hour()?; self.static_str(":")?; self.second_of_minute() } /// `%y`. `00` to `99`. fn year_suffix(&mut self) -> Result<(), Self::Error>; /// `%Y`. fn year(&mut self) -> Result<(), Self::Error>; /// `%z`. `+hhmm` or `-hhmm`. fn timezone(&mut self) -> Result<(), Self::Error>; /// `%Z`. Timezone name or abbreviation. fn timezone_name(&mut self) -> Result<(), Self::Error>; /// `%%`. #[inline] fn percent(&mut self) -> Result<(), Self::Error> { self.static_str("%") } /// Escaped character or seprators in formatted string like `:` or `/`. /// It's just a character but we'd want a &'static str. fn static_str(&mut self, s: &'static str) -> Result<(), Self::Error>; /// Other literals. /// The byte range of the original format `fmt_span` is passed so that you can internally store /// the original format and index that to get the same content with `lit` with your favorite /// lifetime. fn literal( &mut self, lit: &str, fmt_span: impl SliceIndex<[u8], Output = [u8]>, ) -> Result<(), Self::Error>; /// `%(something else)`. fn unknown(&mut self, specifier: char) -> Result<(), Self::Error>; /// Construct the final result from what you've collected. fn output(self) -> Result; } pub(crate) fn parse_conversion_specifications( mut format: &str, mut collector: C, ) -> Result { let original_len = format.len(); while !format.is_empty() { let i = format .bytes() .position(|c| c == b'%') .unwrap_or(format.len()); if i > 0 { let start = original_len - format.len(); let (lit, rest) = format.split_at(i); collector.literal(lit, start..(start + i))?; format = rest; if format.is_empty() { break; } } assert_eq!(format.as_bytes()[0], b'%'); format = &format[1..]; if let Some(b) = format.bytes().next() { match b { b'a' => collector.day_of_week_name_short()?, b'A' => collector.day_of_week_name_long()?, b'b' | b'h' => collector.month_name_short()?, b'B' => collector.month_name_long()?, b'c' => collector.preferred_date_time()?, b'C' => collector.year_prefix()?, b'd' => collector.day_of_month()?, b'D' => collector.date_mmddyy_slash()?, b'e' => collector.day_of_month_blank()?, b'F' => collector.date_yyyymmdd_hyphen()?, b'g' => collector.iso8601_week_based_year_suffix()?, b'G' => collector.iso8601_week_based_year()?, b'H' => collector.hour_of_day()?, b'I' => collector.hour_of_day_12()?, b'j' => collector.day_of_year()?, b'k' => collector.hour_of_day_blank()?, b'l' => collector.hour_of_day_12_blank()?, b'm' => collector.month_of_year()?, b'M' => collector.minute_of_hour()?, b'n' => collector.new_line()?, b'p' => collector.ampm()?, b'P' => collector.ampm_lower()?, b'r' => collector.time_ampm()?, b'R' => collector.hour_minute_of_day()?, b'S' => collector.second_of_minute()?, b'f' => collector.nanosecond_of_second()?, b't' => collector.tab()?, b'T' => collector.time_of_day()?, b'u' => collector.day_of_week_from_monday_as_1()?, b'U' => collector.week_number_of_current_year_start_sunday()?, b'V' => collector.iso8601_week_number()?, b'w' => collector.day_of_week_from_sunday_as_0()?, b'W' => collector.week_number_of_current_year_start_monday()?, b'x' => collector.preferred_date()?, b'X' => collector.preferred_time_of_day()?, b'y' => collector.year_suffix()?, b'Y' => collector.year()?, b'z' => collector.timezone()?, b'Z' => collector.timezone_name()?, b'%' => collector.percent()?, _ => { let c = format.chars().next().unwrap(); collector.unknown(c)?; format = &format[c.len_utf8()..]; continue; } } format = &format[1..]; } else { collector.percent()?; } } collector.output() } time-fmt-0.3.8/src/format/time_format_item.rs000064400000000000000000000253011046102023000173300ustar 00000000000000use std::slice::SliceIndex; use thiserror::Error; use time::format_description::{modifier, Component, FormatItem}; use super::spec_parser::Collector; #[derive(Error, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] #[non_exhaustive] pub enum Error { #[error("Unknown specifier `%{0}`")] UnknownSpecifier(char), #[error("No FormatItem that represent {0}")] NoCorrespondingFormatItem(&'static str), } struct ToFormatItemCollector<'a> { fmt: &'a [u8], items: Vec>, } impl<'a> ToFormatItemCollector<'a> { fn new(fmt: &'a [u8]) -> Self { Self { fmt, items: Default::default(), } } } impl<'a> Collector for ToFormatItemCollector<'a> { type Output = Vec>; type Error = Error; #[inline] fn day_of_week_name_short(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Weekday::default(); modifier.repr = modifier::WeekdayRepr::Short; self.items .push(FormatItem::Component(Component::Weekday(modifier))); Ok(()) } #[inline] fn day_of_week_name_long(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Weekday::default(); modifier.repr = modifier::WeekdayRepr::Long; self.items .push(FormatItem::Component(Component::Weekday(modifier))); Ok(()) } #[inline] fn month_name_short(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Month::default(); modifier.repr = modifier::MonthRepr::Short; self.items .push(FormatItem::Component(Component::Month(modifier))); Ok(()) } #[inline] fn month_name_long(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Month::default(); modifier.repr = modifier::MonthRepr::Long; self.items .push(FormatItem::Component(Component::Month(modifier))); Ok(()) } #[inline] fn year_prefix(&mut self) -> Result<(), Self::Error> { Err(Self::Error::NoCorrespondingFormatItem("%C")) } #[inline] fn day_of_month(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Day::default(); modifier.padding = modifier::Padding::Zero; self.items .push(FormatItem::Component(Component::Day(modifier))); Ok(()) } #[inline] fn day_of_month_blank(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Day::default(); modifier.padding = modifier::Padding::Space; self.items .push(FormatItem::Component(Component::Day(modifier))); Ok(()) } #[inline] fn iso8601_week_based_year_suffix(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Year::default(); modifier.iso_week_based = true; modifier.repr = modifier::YearRepr::LastTwo; self.items .push(FormatItem::Component(Component::Year(modifier))); Ok(()) } #[inline] fn iso8601_week_based_year(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Year::default(); modifier.iso_week_based = true; self.items .push(FormatItem::Component(Component::Year(modifier))); Ok(()) } #[inline] fn hour_of_day(&mut self) -> Result<(), Self::Error> { let modifier = modifier::Hour::default(); self.items .push(FormatItem::Component(Component::Hour(modifier))); Ok(()) } #[inline] fn hour_of_day_12(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Hour::default(); modifier.is_12_hour_clock = true; self.items .push(FormatItem::Component(Component::Hour(modifier))); Ok(()) } #[inline] fn day_of_year(&mut self) -> Result<(), Self::Error> { let modifier = modifier::Ordinal::default(); self.items .push(FormatItem::Component(Component::Ordinal(modifier))); Ok(()) } #[inline] fn hour_of_day_blank(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Hour::default(); modifier.padding = modifier::Padding::Space; self.items .push(FormatItem::Component(Component::Hour(modifier))); Ok(()) } #[inline] fn hour_of_day_12_blank(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Hour::default(); modifier.padding = modifier::Padding::Space; modifier.is_12_hour_clock = true; self.items .push(FormatItem::Component(Component::Hour(modifier))); Ok(()) } #[inline] fn month_of_year(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Month::default(); modifier.repr = modifier::MonthRepr::Numerical; self.items .push(FormatItem::Component(Component::Month(modifier))); Ok(()) } #[inline] fn minute_of_hour(&mut self) -> Result<(), Self::Error> { let modifier = modifier::Minute::default(); self.items .push(FormatItem::Component(Component::Minute(modifier))); Ok(()) } #[inline] fn ampm(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Period::default(); modifier.is_uppercase = true; self.items .push(FormatItem::Component(Component::Period(modifier))); Ok(()) } #[inline] fn ampm_lower(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Period::default(); modifier.is_uppercase = false; self.items .push(FormatItem::Component(Component::Period(modifier))); Ok(()) } #[inline] fn second_of_minute(&mut self) -> Result<(), Self::Error> { let modifier = modifier::Second::default(); self.items .push(FormatItem::Component(Component::Second(modifier))); Ok(()) } #[inline] fn nanosecond_of_second(&mut self) -> Result<(), Self::Error> { let modifier = modifier::Subsecond::default(); self.items .push(FormatItem::Component(Component::Subsecond(modifier))); Ok(()) } #[inline] fn day_of_week_from_monday_as_1(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Weekday::default(); modifier.repr = modifier::WeekdayRepr::Monday; modifier.one_indexed = true; self.items .push(FormatItem::Component(Component::Weekday(modifier))); Ok(()) } #[inline] fn week_number_of_current_year_start_sunday(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::WeekNumber::default(); modifier.repr = modifier::WeekNumberRepr::Sunday; self.items .push(FormatItem::Component(Component::WeekNumber(modifier))); Ok(()) } #[inline] fn iso8601_week_number(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::WeekNumber::default(); modifier.repr = modifier::WeekNumberRepr::Iso; self.items .push(FormatItem::Component(Component::WeekNumber(modifier))); Ok(()) } #[inline] fn day_of_week_from_sunday_as_0(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Weekday::default(); modifier.repr = modifier::WeekdayRepr::Sunday; modifier.one_indexed = false; self.items .push(FormatItem::Component(Component::Weekday(modifier))); Ok(()) } #[inline] fn week_number_of_current_year_start_monday(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::WeekNumber::default(); modifier.repr = modifier::WeekNumberRepr::Monday; self.items .push(FormatItem::Component(Component::WeekNumber(modifier))); Ok(()) } #[inline] fn year_suffix(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Year::default(); modifier.repr = modifier::YearRepr::LastTwo; self.items .push(FormatItem::Component(Component::Year(modifier))); Ok(()) } #[inline] fn year(&mut self) -> Result<(), Self::Error> { let modifier = modifier::Year::default(); self.items .push(FormatItem::Component(Component::Year(modifier))); Ok(()) } #[inline] fn timezone(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::OffsetHour::default(); modifier.sign_is_mandatory = true; self.items .push(FormatItem::Component(Component::OffsetHour(modifier))); let modifier = modifier::OffsetMinute::default(); self.items .push(FormatItem::Component(Component::OffsetMinute(modifier))); Ok(()) } #[inline] fn timezone_name(&mut self) -> Result<(), Self::Error> { Err(Self::Error::NoCorrespondingFormatItem("timezone name")) } #[inline] fn static_str(&mut self, s: &'static str) -> Result<(), Self::Error> { self.items.push(FormatItem::Literal(s.as_bytes())); Ok(()) } #[inline] fn literal( &mut self, _lit: &str, fmt_span: impl SliceIndex<[u8], Output = [u8]>, ) -> Result<(), Self::Error> { self.items.push(FormatItem::Literal(&self.fmt[fmt_span])); Ok(()) } #[inline] fn unknown(&mut self, specifier: char) -> Result<(), Self::Error> { Err(Self::Error::UnknownSpecifier(specifier)) } #[inline] fn output(self) -> Result { Ok(self.items) } } pub fn parse_to_format_item(fmt: &str) -> Result, Error> { let collector = ToFormatItemCollector::new(fmt.as_bytes()); super::spec_parser::parse_conversion_specifications(fmt, collector) } #[cfg(test)] mod tests { use time::macros::datetime; use super::parse_to_format_item; #[test] fn it_works() -> Result<(), super::Error> { assert_eq!( parse_to_format_item("%Y-%m-%d")?, parse_to_format_item("%F")?, ); Ok(()) } #[test] fn parse_primitive_datetime() -> Result<(), Box> { let format_items = parse_to_format_item("%Y-%m-%d %H:%M:%S")?; assert_eq!( datetime!(2012-05-21 12:09:14).format(&format_items)?, "2012-05-21 12:09:14" ); Ok(()) } #[test] fn parse_offset_datetime() -> Result<(), Box> { let format_items = parse_to_format_item("%Y-%m-%d %H:%M:%S %z")?; assert_eq!( datetime!(2012-05-21 12:09:14 +9:00).format(&format_items)?, "2012-05-21 12:09:14 +0900" ); Ok(()) } } time-fmt-0.3.8/src/format.rs000064400000000000000000000433411046102023000140100ustar 00000000000000use std::fmt::Write; use thiserror::Error; use time::{Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}; use crate::{format::spec_parser::Collector, util}; mod spec_parser; pub mod time_format_item; #[derive(Error, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum FormatError { #[error("Unknown specifier `%{0}`")] UnknownSpecifier(char), #[error(transparent)] Format(#[from] std::fmt::Error), } struct FormatCollector<'a, W: Write> { date: Date, time: Time, offset: Option, zone_name: Option<&'a str>, write: &'a mut W, } impl<'a, W: Write> FormatCollector<'a, W> { fn from_date_time(date_time: PrimitiveDateTime, write: &'a mut W) -> Self { Self { date: date_time.date(), time: date_time.time(), offset: None, zone_name: None, write, } } fn from_offset_date_time(date_time: OffsetDateTime, write: &'a mut W) -> Self { Self { date: date_time.date(), time: date_time.time(), offset: Some(date_time.offset()), zone_name: None, write, } } fn from_zoned_date_time( date_time: PrimitiveDateTime, offset: UtcOffset, zone_name: &'a str, write: &'a mut W, ) -> Self { Self { date: date_time.date(), time: date_time.time(), offset: Some(offset), zone_name: Some(zone_name), write, } } fn from_zoned_offset_date_time( date_time: OffsetDateTime, zone_name: &'a str, write: &'a mut W, ) -> Self { Self { date: date_time.date(), time: date_time.time(), offset: Some(date_time.offset()), zone_name: Some(zone_name), write, } } } impl<'a, W: Write> Collector for FormatCollector<'a, W> { type Output = (); type Error = FormatError; #[inline] fn day_of_week_name_short(&mut self) -> Result<(), Self::Error> { self.write .write_str(util::weekday_short_str(self.date.weekday()))?; Ok(()) } #[inline] fn day_of_week_name_long(&mut self) -> Result<(), Self::Error> { self.write .write_str(util::weekday_long_str(self.date.weekday()))?; Ok(()) } #[inline] fn month_name_short(&mut self) -> Result<(), Self::Error> { self.write .write_str(util::month_short_str(self.date.month()))?; Ok(()) } #[inline] fn month_name_long(&mut self) -> Result<(), Self::Error> { self.write .write_str(util::month_long_str(self.date.month()))?; Ok(()) } #[inline] fn year_prefix(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.date.year().div_euclid(100)))?; Ok(()) } #[inline] fn day_of_month(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.date.day()))?; Ok(()) } #[inline] fn day_of_month_blank(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:2}", self.date.day()))?; Ok(()) } #[inline] fn iso8601_week_based_year_suffix(&mut self) -> Result<(), Self::Error> { let (year, _, _) = self.date.to_iso_week_date(); self.write .write_fmt(format_args!("{:02}", year.rem_euclid(100)))?; Ok(()) } #[inline] fn iso8601_week_based_year(&mut self) -> Result<(), Self::Error> { let (year, _, _) = self.date.to_iso_week_date(); self.write.write_fmt(format_args!("{:4}", year))?; Ok(()) } #[inline] fn hour_of_day(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.time.hour()))?; Ok(()) } #[inline] fn hour_of_day_12(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", (self.time.hour() + 11) % 12 + 1))?; Ok(()) } #[inline] fn day_of_year(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:03}", self.date.ordinal()))?; Ok(()) } #[inline] fn hour_of_day_blank(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:2}", self.time.hour()))?; Ok(()) } #[inline] fn hour_of_day_12_blank(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:2}", (self.time.hour() + 11) % 12 + 1))?; Ok(()) } #[inline] fn month_of_year(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.date.month() as u8))?; Ok(()) } #[inline] fn minute_of_hour(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.time.minute()))?; Ok(()) } #[inline] fn ampm(&mut self) -> Result<(), Self::Error> { self.write.write_str(util::ampm_upper(self.time.hour()))?; Ok(()) } #[inline] fn ampm_lower(&mut self) -> Result<(), Self::Error> { self.write.write_str(util::ampm_lower(self.time.hour()))?; Ok(()) } #[inline] fn second_of_minute(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.time.second()))?; Ok(()) } #[inline] fn nanosecond_of_second(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:0>9}", self.time.nanosecond()))?; Ok(()) } #[inline] fn day_of_week_from_monday_as_1(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{}", self.date.weekday().number_from_monday()))?; Ok(()) } #[inline] fn week_number_of_current_year_start_sunday(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.date.sunday_based_week()))?; Ok(()) } #[inline] fn iso8601_week_number(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.date.iso_week()))?; Ok(()) } #[inline] fn day_of_week_from_sunday_as_0(&mut self) -> Result<(), Self::Error> { self.write.write_fmt(format_args!( "{}", self.date.weekday().number_days_from_sunday() ))?; Ok(()) } #[inline] fn week_number_of_current_year_start_monday(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:02}", self.date.monday_based_week()))?; Ok(()) } #[inline] fn year_suffix(&mut self) -> Result<(), Self::Error> { let year = self.date.year(); self.write .write_fmt(format_args!("{:02}", year.abs() % 100))?; Ok(()) } #[inline] fn year(&mut self) -> Result<(), Self::Error> { self.write .write_fmt(format_args!("{:04}", self.date.year()))?; Ok(()) } #[inline] fn timezone(&mut self) -> Result<(), Self::Error> { if let Some(offset) = self.offset { let (h, m, _) = offset.as_hms(); if offset.is_negative() { self.write.write_fmt(format_args!("-{:02}{:02}", -h, -m))?; } else { self.write.write_fmt(format_args!("+{:02}{:02}", h, m))?; } } // No bytes if no timezone is determinable. Ok(()) } #[inline] fn timezone_name(&mut self) -> Result<(), Self::Error> { if let Some(zone_name) = &self.zone_name { self.write.write_str(zone_name)?; } // No bytes if no timezone information exists. Ok(()) } #[inline] fn static_str(&mut self, s: &'static str) -> Result<(), Self::Error> { self.write.write_str(s)?; Ok(()) } #[inline] fn literal( &mut self, lit: &str, _fmt_span: impl std::slice::SliceIndex<[u8], Output = [u8]>, ) -> Result<(), Self::Error> { self.write.write_str(lit)?; Ok(()) } #[inline] fn unknown(&mut self, specifier: char) -> Result<(), Self::Error> { Err(Self::Error::UnknownSpecifier(specifier)) } #[inline] fn output(self) -> Result { Ok(()) } } pub fn format_date_time(fmt: &str, date_time: PrimitiveDateTime) -> Result { let mut ret = String::new(); let collector = FormatCollector::from_date_time(date_time, &mut ret); spec_parser::parse_conversion_specifications(fmt, collector)?; Ok(ret) } pub fn format_offset_date_time( fmt: &str, date_time: OffsetDateTime, ) -> Result { let mut ret = String::new(); let collector = FormatCollector::from_offset_date_time(date_time, &mut ret); spec_parser::parse_conversion_specifications(fmt, collector)?; Ok(ret) } pub fn format_zoned_date_time( fmt: &str, date_time: PrimitiveDateTime, offset: UtcOffset, zone_name: &str, ) -> Result { let mut ret = String::new(); let collector = FormatCollector::from_zoned_date_time(date_time, offset, zone_name, &mut ret); spec_parser::parse_conversion_specifications(fmt, collector)?; Ok(ret) } pub fn format_zoned_offset_date_time( fmt: &str, date_time: OffsetDateTime, zone_name: &str, ) -> Result { let mut ret = String::new(); let collector = FormatCollector::from_zoned_offset_date_time(date_time, zone_name, &mut ret); spec_parser::parse_conversion_specifications(fmt, collector)?; Ok(ret) } #[cfg(test)] mod tests { use super::{format_date_time, format_offset_date_time}; use time::{ macros::{datetime, offset}, PrimitiveDateTime, }; #[test] fn test_simple() -> Result<(), super::FormatError> { fn test_datetime( fmt: &str, dt: PrimitiveDateTime, expected: &str, ) -> Result<(), super::FormatError> { assert_eq!(format_date_time(fmt, dt)?, expected); assert_eq!( format_offset_date_time(fmt, dt.assume_offset(offset!(+9:00)))?, expected ); assert_eq!( super::format_zoned_date_time(fmt, dt, offset!(+9:00), "JST")?, expected ); assert_eq!( super::format_zoned_offset_date_time(fmt, dt.assume_offset(offset!(+9:00)), "JST")?, expected ); Ok(()) } let datetime = datetime!(2022-03-06 12:34:56); let datetime2 = datetime!(2022-03-06 02:04:06); test_datetime("%a %A", datetime, "Sun Sunday")?; test_datetime("%b %h %B", datetime, "Mar Mar March")?; test_datetime("%c", datetime, "Sun Mar 6 12:34:56 2022")?; test_datetime("%C", datetime, "20")?; test_datetime("%d", datetime, "06")?; test_datetime("%D", datetime, "03/06/22")?; test_datetime("%e", datetime, " 6")?; test_datetime("%F", datetime, "2022-03-06")?; test_datetime("%g", datetime, "22")?; test_datetime("%G", datetime, "2022")?; test_datetime("%H", datetime, "12")?; test_datetime("%H", datetime2, "02")?; test_datetime("%I", datetime, "12")?; test_datetime("%I", datetime2, "02")?; test_datetime("%j", datetime, "065")?; test_datetime("%k", datetime2, " 2")?; test_datetime("%l", datetime, "12")?; test_datetime("%l", datetime2, " 2")?; test_datetime("%m", datetime, "03")?; test_datetime("%M", datetime, "34")?; test_datetime("%n", datetime, "\n")?; test_datetime("%p", datetime, "PM")?; test_datetime("%P", datetime, "pm")?; test_datetime("%r", datetime, "12:34:56 PM")?; test_datetime("%r", datetime2, "02:04:06 AM")?; test_datetime("%R", datetime, "12:34")?; test_datetime("%R", datetime2, "02:04")?; test_datetime("%S", datetime, "56")?; test_datetime("%t", datetime, "\t")?; test_datetime("%T", datetime, "12:34:56")?; test_datetime("%u", datetime, "7")?; test_datetime("%U", datetime, "10")?; test_datetime("%V", datetime, "09")?; test_datetime("%w", datetime, "0")?; test_datetime("%W", datetime, "09")?; test_datetime("%x", datetime, "03/06/22")?; test_datetime("%X", datetime, "12:34:56")?; test_datetime("%y", datetime, "22")?; test_datetime("%Y", datetime, "2022")?; test_datetime("%%", datetime, "%")?; let datetime_ms0 = datetime!(2022-03-06 02:04:06); let datetime_ms1 = datetime!(2022-03-06 02:04:06.1); let datetime_ms2 = datetime!(2022-03-06 02:04:06.12); let datetime_ms3 = datetime!(2022-03-06 02:04:06.123); let datetime_ms4 = datetime!(2022-03-06 02:04:06.1234); let datetime_ms5 = datetime!(2022-03-06 02:04:06.12345); let datetime_ms6 = datetime!(2022-03-06 02:04:06.123456); let datetime_ms7 = datetime!(2022-03-06 02:04:06.1234567); let datetime_ms8 = datetime!(2022-03-06 02:04:06.12345678); let datetime_ms9 = datetime!(2022-03-06 02:04:06.123456789); test_datetime("%f", datetime_ms0, "000000000")?; test_datetime("%f", datetime_ms1, "100000000")?; test_datetime("%f", datetime_ms2, "120000000")?; test_datetime("%f", datetime_ms3, "123000000")?; test_datetime("%f", datetime_ms4, "123400000")?; test_datetime("%f", datetime_ms5, "123450000")?; test_datetime("%f", datetime_ms6, "123456000")?; test_datetime("%f", datetime_ms7, "123456700")?; test_datetime("%f", datetime_ms8, "123456780")?; test_datetime("%f", datetime_ms9, "123456789")?; let datetime_ms1 = datetime!(2022-03-06 02:04:06.900000000); let datetime_ms2 = datetime!(2022-03-06 02:04:06.980000000); let datetime_ms3 = datetime!(2022-03-06 02:04:06.987000000); let datetime_ms4 = datetime!(2022-03-06 02:04:06.987600000); let datetime_ms5 = datetime!(2022-03-06 02:04:06.987650000); let datetime_ms6 = datetime!(2022-03-06 02:04:06.987654000); let datetime_ms7 = datetime!(2022-03-06 02:04:06.987654300); let datetime_ms8 = datetime!(2022-03-06 02:04:06.987654320); test_datetime("%f", datetime_ms1, "900000000")?; test_datetime("%f", datetime_ms2, "980000000")?; test_datetime("%f", datetime_ms3, "987000000")?; test_datetime("%f", datetime_ms4, "987600000")?; test_datetime("%f", datetime_ms5, "987650000")?; test_datetime("%f", datetime_ms6, "987654000")?; test_datetime("%f", datetime_ms7, "987654300")?; test_datetime("%f", datetime_ms8, "987654320")?; let datetime_ms1 = datetime!(2022-03-06 02:04:06.000000002); let datetime_ms2 = datetime!(2022-03-06 02:04:06.000000022); let datetime_ms3 = datetime!(2022-03-06 02:04:06.000000222); let datetime_ms4 = datetime!(2022-03-06 02:04:06.000002222); let datetime_ms5 = datetime!(2022-03-06 02:04:06.000022222); let datetime_ms6 = datetime!(2022-03-06 02:04:06.000222222); let datetime_ms7 = datetime!(2022-03-06 02:04:06.002222222); let datetime_ms8 = datetime!(2022-03-06 02:04:06.022222222); test_datetime("%f", datetime_ms1, "000000002")?; test_datetime("%f", datetime_ms2, "000000022")?; test_datetime("%f", datetime_ms3, "000000222")?; test_datetime("%f", datetime_ms4, "000002222")?; test_datetime("%f", datetime_ms5, "000022222")?; test_datetime("%f", datetime_ms6, "000222222")?; test_datetime("%f", datetime_ms7, "002222222")?; test_datetime("%f", datetime_ms8, "022222222")?; Ok(()) } #[test] fn test_year_prefix() -> Result<(), super::FormatError> { let fmt = "%C"; assert_eq!( format_offset_date_time(fmt, datetime!(410-01-01 01:01:01 UTC))?, "04".to_string() ); assert_eq!( format_offset_date_time(fmt, datetime!(2021-01-01 01:01:01 UTC))?, "20".to_string() ); assert_eq!( format_offset_date_time(fmt, datetime!(+99999-01-01 01:01:01 UTC))?, "999".to_string() ); assert_eq!( format_offset_date_time(fmt, datetime!(-1-01-01 01:01:01 UTC))?, "-1".to_string() ); assert_eq!( format_offset_date_time(fmt, datetime!(-1000-01-01 01:01:01 UTC))?, "-10".to_string() ); Ok(()) } #[test] fn test_offset() -> Result<(), super::FormatError> { let fmt = "%z"; assert_eq!( format_offset_date_time(fmt, datetime!(410-01-01 01:01:01 UTC))?, "+0000".to_string() ); assert_eq!( format_offset_date_time(fmt, datetime!(2022-02-02 01:01:01 -1:23))?, "-0123".to_string() ); Ok(()) } #[test] fn test_timezone_name() -> Result<(), super::FormatError> { use super::{format_zoned_date_time, format_zoned_offset_date_time}; assert_eq!( format_zoned_date_time( "%z %Z", datetime!(2022-02-02 02:02:02), offset!(+9:00), "JST" )?, "+0900 JST".to_string() ); assert_eq!( format_zoned_offset_date_time( "%T %z %Z", datetime!(2022-02-02 02:02:02 UTC).to_offset(offset!(+9:00)), "JST" )?, "11:02:02 +0900 JST".to_string() ); Ok(()) } } time-fmt-0.3.8/src/lib.rs000064400000000000000000000000511046102023000132550ustar 00000000000000pub mod format; pub mod parse; mod util; time-fmt-0.3.8/src/parse/desc_parser.rs000064400000000000000000000221571046102023000161260ustar 00000000000000use std::slice::SliceIndex; /// E and O are not implemented. /// Those require `nl-langinfo` lookup is default-implemented as if it were a POSIX locale. /// If you'd want to implement it properly, it's your responsibility to recursively parse /// the format you get from `nl-langinfo`, and prevent infinite recursion. pub(crate) trait Collector { type Output; type Error; /// Skips sequence of whitespaces. fn spaces(&mut self) -> Result<(), Self::Error>; /// `%a` or `%A`. `nl_langinfo`-dependent. fn day_of_week_name(&mut self) -> Result<(), Self::Error>; /// `%b`, `%B` or `%h`. `nl_langinfo`-dependent. fn month_name(&mut self) -> Result<(), Self::Error>; /// `%c`. Same as `%a %b %e %T %Y` in POSIX locale. `nl_langinfo`-dependent. #[inline] fn preferred_date_time(&mut self) -> Result<(), Self::Error> { self.day_of_week_name()?; self.spaces()?; self.month_name()?; self.spaces()?; self.day_of_month()?; self.spaces()?; self.time_of_day()?; self.spaces()?; self.year() } /// `%C`. `0` to `99`. fn year_prefix(&mut self) -> Result<(), Self::Error>; /// `%d`, `%e`. `01` to `31`. fn day_of_month(&mut self) -> Result<(), Self::Error>; /// `%D`. `%m / %d / %y` (American......). #[inline] fn date_mmddyy_slash(&mut self) -> Result<(), Self::Error> { self.month_of_year()?; self.spaces()?; self.static_str("/")?; self.spaces()?; self.day_of_month()?; self.spaces()?; self.static_str("/")?; self.spaces()?; self.year_suffix() } /// `%F`. `%Y-%m-%d`. #[inline] fn date_yyyymmdd_hyphen(&mut self) -> Result<(), Self::Error> { self.year()?; self.static_str("-")?; self.month_of_year()?; self.static_str("-")?; self.day_of_month() } /// `%H`, `%k`. `00` to `23`. fn hour_of_day(&mut self) -> Result<(), Self::Error>; /// `%I`, `%l`. `01` to `12`. fn hour_of_day_12(&mut self) -> Result<(), Self::Error>; /// `%j`. `001` to `336`. fn day_of_year(&mut self) -> Result<(), Self::Error>; /// `%m`. `01` to `12`. fn month_of_year(&mut self) -> Result<(), Self::Error>; /// `%M`. `00` to `59`. fn minute_of_hour(&mut self) -> Result<(), Self::Error>; /// `%n`. #[inline] fn new_line(&mut self) -> Result<(), Self::Error> { self.spaces() } /// `%p`, `%P`. `AM` or `PM`. `nl_langinfo`-dependent. fn ampm(&mut self) -> Result<(), Self::Error>; /// `%r`. Same as `%I : %M : %S %p` in POSIX locale. `nl_langinfo`-dependent. #[inline] fn time_ampm(&mut self) -> Result<(), Self::Error> { self.hour_of_day_12()?; self.spaces()?; self.static_str(":")?; self.spaces()?; self.minute_of_hour()?; self.spaces()?; self.static_str(":")?; self.spaces()?; self.second_of_minute()?; self.spaces()?; self.ampm() } /// `%R`. Same as `%H : %M`. #[inline] fn hour_minute_of_day(&mut self) -> Result<(), Self::Error> { self.hour_of_day()?; self.spaces()?; self.static_str(":")?; self.spaces()?; self.minute_of_hour() } /// `%S`. `00` to `60`. fn second_of_minute(&mut self) -> Result<(), Self::Error>; /// `%f`. `000000000` to `999999999`. fn nanosecond_of_second(&mut self) -> Result<(), Self::Error>; /// `%t`. #[inline] fn tab(&mut self) -> Result<(), Self::Error> { self.spaces() } /// `%T`. Same as `%H : %M : %S`. #[inline] fn time_of_day(&mut self) -> Result<(), Self::Error> { self.hour_of_day()?; self.spaces()?; self.static_str(":")?; self.spaces()?; self.minute_of_hour()?; self.spaces()?; self.static_str(":")?; self.spaces()?; self.second_of_minute() } /// `%U`. `00` to `53`. fn week_number_of_current_year_start_sunday(&mut self) -> Result<(), Self::Error>; /// `%w`. fn day_of_week_from_sunday_as_0(&mut self) -> Result<(), Self::Error>; /// `%W`. `00` to `53`. fn week_number_of_current_year_start_monday(&mut self) -> Result<(), Self::Error>; /// `%x`. `%m/%d/%y` in POSIX locale. `nl_langinfo`-dependent. #[inline] fn preferred_date(&mut self) -> Result<(), Self::Error> { self.month_of_year()?; self.static_str("/")?; self.day_of_month()?; self.static_str("/")?; self.year_suffix() } /// `%X`. `%H:%M:%S` in POSIX locale. `nl_langinfo`-dependent. #[inline] fn preferred_time_of_day(&mut self) -> Result<(), Self::Error> { self.hour_of_day()?; self.static_str(":")?; self.minute_of_hour()?; self.static_str(":")?; self.second_of_minute() } /// `%y`. `00` to `99`. fn year_suffix(&mut self) -> Result<(), Self::Error>; /// `%Y`. fn year(&mut self) -> Result<(), Self::Error>; /// `%z`. `+hhmm` or `-hhmm`. fn timezone(&mut self) -> Result<(), Self::Error>; /// `%Z`. Timezone name or abbreviation. fn timezone_name(&mut self) -> Result<(), Self::Error>; /// `%%`. #[inline] fn percent(&mut self) -> Result<(), Self::Error> { self.static_str("%") } /// Escaped character or seprators in formatted string like `:` or `/`. /// It's just a character but we'd want a &'static str. fn static_str(&mut self, s: &'static str) -> Result<(), Self::Error>; /// Other literals. /// The byte range of the original format `fmt_span` is passed so that you can internally store /// the original format and index that to get the same content with `lit` with your favorite /// lifetime. fn literal( &mut self, lit: &str, fmt_span: impl SliceIndex<[u8], Output = [u8]>, ) -> Result<(), Self::Error>; /// `%(something else)`. fn unknown(&mut self, specifier: char) -> Result<(), Self::Error>; /// Check for remaining unconsumed input. fn unconsumed_input(&self) -> Result<(), Self::Error>; /// Construct the final result from what you've collected. fn output(self) -> Result; } pub(crate) fn parse_format_specifications( mut format: &str, mut collector: C, strict: bool, ) -> Result { let original_len = format.len(); while !format.is_empty() { let i = format .find(|c: char| c == '%' || c.is_whitespace()) .unwrap_or(format.len()); if i > 0 { let start = original_len - format.len(); let (lit, rest) = format.split_at(i); collector.literal(lit, start..(start + i))?; format = rest; if format.is_empty() { break; } } if format.starts_with(char::is_whitespace) { collector.spaces()?; format = format.trim_start(); continue; } assert_eq!(format.as_bytes()[0], b'%'); format = &format[1..]; if let Some(b) = format.bytes().next() { match b { b'a' | b'A' => collector.day_of_week_name()?, b'b' | b'B' | b'h' => collector.month_name()?, b'c' => collector.preferred_date_time()?, b'C' => collector.year_prefix()?, b'd' | b'e' => collector.day_of_month()?, b'D' => collector.date_mmddyy_slash()?, b'F' => collector.date_yyyymmdd_hyphen()?, b'H' | b'k' => collector.hour_of_day()?, b'I' | b'l' => collector.hour_of_day_12()?, b'j' => collector.day_of_year()?, b'm' => collector.month_of_year()?, b'M' => collector.minute_of_hour()?, b'n' => collector.new_line()?, b'p' | b'P' => collector.ampm()?, b'r' => collector.time_ampm()?, b'R' => collector.hour_minute_of_day()?, b'S' => collector.second_of_minute()?, b'f' => collector.nanosecond_of_second()?, b't' => collector.tab()?, b'T' => collector.time_of_day()?, b'U' => collector.week_number_of_current_year_start_sunday()?, b'w' => collector.day_of_week_from_sunday_as_0()?, b'W' => collector.week_number_of_current_year_start_monday()?, b'x' => collector.preferred_date()?, b'X' => collector.preferred_time_of_day()?, b'y' => collector.year_suffix()?, b'Y' => collector.year()?, b'z' => collector.timezone()?, b'Z' => collector.timezone_name()?, b'%' => collector.percent()?, _ => { let c = format.chars().next().unwrap(); collector.unknown(c)?; format = &format[c.len_utf8()..]; continue; } } format = &format[1..]; } else { collector.percent()?; } } if strict { collector.unconsumed_input()?; }; collector.output() } time-fmt-0.3.8/src/parse/time_format_item.rs000064400000000000000000000232271046102023000171570ustar 00000000000000use std::slice::SliceIndex; use thiserror::Error; use time::format_description::{modifier, Component, FormatItem}; use super::desc_parser::Collector; #[derive(Error, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] #[non_exhaustive] pub enum Error { #[error("Unknown specifier `%{0}`")] UnknownSpecifier(char), #[error("No FormatItem that represent {0}")] NoCorrespondingFormatItem(&'static str), } struct ToFormatItemCollector<'a> { fmt: &'a [u8], items: Vec>, } impl<'a> ToFormatItemCollector<'a> { fn new(fmt: &'a [u8]) -> Self { Self { fmt, items: Default::default(), } } } macro_rules! all_paddings { ($ret: expr, $create_base: expr, $component_builder: expr) => { const fn with_padding(pad: modifier::Padding) -> Component { let mut m = $create_base; m.padding = pad; $component_builder(m) } static ITEMS: [FormatItem; 3] = [ FormatItem::Component(with_padding(modifier::Padding::Zero)), FormatItem::Component(with_padding(modifier::Padding::Space)), FormatItem::Component(with_padding(modifier::Padding::None)), ]; $ret.push(FormatItem::First(&ITEMS)); }; } impl<'a> Collector for ToFormatItemCollector<'a> { type Output = Vec>; type Error = Error; #[inline] fn spaces(&mut self) -> Result<(), Self::Error> { // TODO: How to allow more than one? self.items.push(FormatItem::Optional(&FormatItem::First(&[ FormatItem::Literal(b" "), FormatItem::Literal(b"\n"), FormatItem::Literal(b"\t"), ]))); Ok(()) } #[inline] fn day_of_week_name(&mut self) -> Result<(), Self::Error> { const fn short() -> FormatItem<'static> { let mut short = modifier::Weekday::default(); short.repr = modifier::WeekdayRepr::Short; short.case_sensitive = false; FormatItem::Component(Component::Weekday(short)) } const fn long() -> FormatItem<'static> { let mut long = modifier::Weekday::default(); long.repr = modifier::WeekdayRepr::Long; long.case_sensitive = false; FormatItem::Component(Component::Weekday(long)) } static ITEMS: [FormatItem; 2] = [long(), short()]; self.items.push(FormatItem::First(&ITEMS)); Ok(()) } #[inline] fn month_name(&mut self) -> Result<(), Self::Error> { const fn short() -> FormatItem<'static> { let mut short = modifier::Month::default(); short.repr = modifier::MonthRepr::Short; short.case_sensitive = false; FormatItem::Component(Component::Month(short)) } const fn long() -> FormatItem<'static> { let mut long = modifier::Month::default(); long.repr = modifier::MonthRepr::Long; long.case_sensitive = false; FormatItem::Component(Component::Month(long)) } static ITEMS: [FormatItem; 2] = [long(), short()]; self.items.push(FormatItem::First(&ITEMS)); Ok(()) } #[inline] fn year_prefix(&mut self) -> Result<(), Self::Error> { Err(Self::Error::NoCorrespondingFormatItem("%C")) } #[inline] fn day_of_month(&mut self) -> Result<(), Self::Error> { all_paddings!(self.items, modifier::Day::default(), Component::Day); Ok(()) } #[inline] fn hour_of_day(&mut self) -> Result<(), Self::Error> { all_paddings!(self.items, modifier::Hour::default(), Component::Hour); Ok(()) } #[inline] fn hour_of_day_12(&mut self) -> Result<(), Self::Error> { all_paddings!( self.items, { let mut base = modifier::Hour::default(); base.is_12_hour_clock = true; base }, Component::Hour ); Ok(()) } #[inline] fn day_of_year(&mut self) -> Result<(), Self::Error> { all_paddings!(self.items, modifier::Ordinal::default(), Component::Ordinal); Ok(()) } #[inline] fn month_of_year(&mut self) -> Result<(), Self::Error> { all_paddings!(self.items, modifier::Month::default(), Component::Month); Ok(()) } #[inline] fn minute_of_hour(&mut self) -> Result<(), Self::Error> { all_paddings!(self.items, modifier::Minute::default(), Component::Minute); Ok(()) } #[inline] fn ampm(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Period::default(); modifier.case_sensitive = false; self.items .push(FormatItem::Component(Component::Period(modifier))); Ok(()) } #[inline] fn second_of_minute(&mut self) -> Result<(), Self::Error> { all_paddings!(self.items, modifier::Second::default(), Component::Second); Ok(()) } #[inline] fn nanosecond_of_second(&mut self) -> Result<(), Self::Error> { let modifier = modifier::Subsecond::default(); self.items .push(FormatItem::Component(Component::Subsecond(modifier))); Ok(()) } #[inline] fn tab(&mut self) -> Result<(), Self::Error> { self.spaces() } #[inline] fn week_number_of_current_year_start_sunday(&mut self) -> Result<(), Self::Error> { all_paddings!( self.items, { let mut base = modifier::WeekNumber::default(); base.repr = modifier::WeekNumberRepr::Sunday; base }, Component::WeekNumber ); Ok(()) } #[inline] fn day_of_week_from_sunday_as_0(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::Weekday::default(); modifier.repr = modifier::WeekdayRepr::Sunday; modifier.one_indexed = false; self.items .push(FormatItem::Component(Component::Weekday(modifier))); Ok(()) } #[inline] fn week_number_of_current_year_start_monday(&mut self) -> Result<(), Self::Error> { all_paddings!( self.items, { let mut base = modifier::WeekNumber::default(); base.repr = modifier::WeekNumberRepr::Monday; base }, Component::WeekNumber ); Ok(()) } #[inline] fn year_suffix(&mut self) -> Result<(), Self::Error> { all_paddings!( self.items, { let mut base = modifier::Year::default(); base.repr = modifier::YearRepr::LastTwo; base }, Component::Year ); Ok(()) } #[inline] fn year(&mut self) -> Result<(), Self::Error> { all_paddings!(self.items, modifier::Year::default(), Component::Year); Ok(()) } #[inline] fn timezone(&mut self) -> Result<(), Self::Error> { let mut modifier = modifier::OffsetHour::default(); modifier.sign_is_mandatory = true; self.items .push(FormatItem::Component(Component::OffsetHour(modifier))); self.items .push(FormatItem::Optional(&FormatItem::Literal(b":"))); let modifier = modifier::OffsetMinute::default(); self.items .push(FormatItem::Component(Component::OffsetMinute(modifier))); Ok(()) } #[inline] fn timezone_name(&mut self) -> Result<(), Self::Error> { Err(Self::Error::NoCorrespondingFormatItem("timezone name")) } #[inline] fn static_str(&mut self, s: &'static str) -> Result<(), Self::Error> { self.items.push(FormatItem::Literal(s.as_bytes())); Ok(()) } #[inline] fn literal( &mut self, _lit: &str, fmt_span: impl SliceIndex<[u8], Output = [u8]>, ) -> Result<(), Self::Error> { self.items.push(FormatItem::Literal(&self.fmt[fmt_span])); Ok(()) } #[inline] fn unknown(&mut self, specifier: char) -> Result<(), Self::Error> { Err(Self::Error::UnknownSpecifier(specifier)) } #[inline] fn unconsumed_input(&self) -> Result<(), Self::Error> { Ok(()) } #[inline] fn output(self) -> Result { Ok(self.items) } } pub fn parse_to_format_item(fmt: &str) -> Result, Error> { let collector = ToFormatItemCollector::new(fmt.as_bytes()); super::desc_parser::parse_format_specifications(fmt, collector, false) } #[cfg(test)] mod tests { use time::{macros::datetime, OffsetDateTime, PrimitiveDateTime}; use super::parse_to_format_item; #[test] fn it_works() -> Result<(), super::Error> { assert_eq!( parse_to_format_item("%Y-%m-%d")?, parse_to_format_item("%F")?, ); Ok(()) } #[test] fn parse_primitive_datetime() -> Result<(), Box> { let format_items = parse_to_format_item("%Y-%m-%d %H:%M:%S")?; assert_eq!( PrimitiveDateTime::parse("2012-05-21 12:09:14", &format_items)?, datetime!(2012-05-21 12:09:14) ); Ok(()) } #[test] fn parse_offset_datetime() -> Result<(), Box> { let format_items = parse_to_format_item("%Y-%m-%d %H:%M:%S %z")?; assert_eq!( OffsetDateTime::parse("2012-05-21 12:09:14 +0900", &format_items)?, datetime!(2012-05-21 12:09:14 +9:00) ); assert_eq!( OffsetDateTime::parse("2012-05-21 12:09:14 +09:00", &format_items)?, datetime!(2012-05-21 12:09:14 +9:00) ); Ok(()) } } time-fmt-0.3.8/src/parse.rs000064400000000000000000000643341046102023000136370ustar 00000000000000use thiserror::Error; use time::{Date, Month, PrimitiveDateTime, Time, UtcOffset, Weekday}; use crate::{parse::desc_parser::Collector, util}; mod desc_parser; pub mod time_format_item; #[derive(Error, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum ParseError { #[error("Unknown specifier `%{0}`")] UnknownSpecifier(char), #[error("Expected {0} but got a byte {1}")] UnexpectedByte(&'static str, u8), #[error("Expected {0} but reached to the end")] UnexpectedEnd(&'static str), #[error("Expected {0} but doesn't have a match")] NotMatch(&'static str), #[error("Out-of-range for {0} component")] ComponentOutOfRange(&'static str), #[error("Unconverted data remains: {0}")] UnconvertedDataRemains(String), #[error(transparent)] ComponentRange(#[from] time::error::ComponentRange), } trait Nat: std::ops::Add + std::ops::Mul where Self: Sized, { const ZERO: Self; const TEN: Self; fn from_u8(_: u8) -> Self; } trait Int: Nat + std::ops::Neg {} impl Nat for u8 { const ZERO: Self = 0; const TEN: Self = 10; fn from_u8(v: u8) -> Self { v } } impl Nat for u16 { const ZERO: Self = 0; const TEN: Self = 10; fn from_u8(v: u8) -> Self { v as u16 } } impl Nat for u32 { const ZERO: Self = 0; const TEN: Self = 10; fn from_u8(v: u8) -> Self { v as u32 } } impl Nat for i16 { const ZERO: Self = 0; const TEN: Self = 10; fn from_u8(v: u8) -> Self { v as i16 } } impl Int for i16 {} impl Nat for i32 { const ZERO: Self = 0; const TEN: Self = 10; fn from_u8(v: u8) -> Self { v as i32 } } impl Int for i32 {} #[derive(Debug)] enum ParsingYear { Unspecified, Year(i32), PrefixSuffix(i32, u8), } #[derive(Debug)] enum ParsingDayOfYear { Unspecified, MonthDay(Month, u8), DayOfYear(u16), } #[derive(Debug)] enum ParsingHour { Unspecified, FullDay(u8), HalfDay(u8, bool), } #[derive(Debug, PartialEq, Eq)] pub enum TimeZoneSpecifier<'a> { Offset(UtcOffset), Name(&'a str), } struct ParseCollector<'a> { s: &'a str, year: ParsingYear, day: ParsingDayOfYear, hour: ParsingHour, minute: u8, second: u8, nanosecond: u32, zone: Option>, } impl<'a> ParseCollector<'a> { fn new(s: &'a str) -> Self { Self { s, year: ParsingYear::Unspecified, day: ParsingDayOfYear::Unspecified, hour: ParsingHour::Unspecified, minute: 0, second: 0, nanosecond: 0, zone: None, } } #[inline] fn skip_whitespaces(&mut self) { self.s = self.s.trim_start(); } #[inline] fn get_until_whitespace(&mut self) -> &'a str { let pos = self.s.find(char::is_whitespace).unwrap_or(self.s.len()); let (res, rest) = self.s.split_at(pos); self.s = rest; res } #[inline] fn peek_byte(&self) -> Option { self.s.bytes().next() } /// Note: Need a change if pass max_len that makes us require checking for overflow. #[inline] fn parse_nat(&mut self, min_len: usize, max_len: usize) -> Result { if self.s.len() < min_len { return Err(ParseError::UnexpectedEnd("digits")); } let bytes = self.s.as_bytes(); let max_len = max_len.min(bytes.len()); let mut res = N::ZERO; let mut bytes_read = 0; for &c in &bytes[..max_len] { if (b'0'..=b'9').contains(&c) { res = (res * N::TEN) + N::from_u8(c - b'0'); } else if bytes_read < min_len { return Err(ParseError::UnexpectedByte("digits", c)); } else { break; } bytes_read += 1; } self.s = &self.s[bytes_read..]; Ok(res) } /// Allows '+'/'-'. /// Note: Need a change if pass max_len that makes us require checking for overflow. #[inline] fn parse_int(&mut self, max_len: usize) -> Result { if self.s.is_empty() { return Err(ParseError::UnexpectedEnd("digits")); } let max_len = max_len.min(self.s.len()); let mut res = Z::ZERO; let mut bytes_read = 0; let mut negate = false; let mut had_digit = false; for &c in &self.s.as_bytes()[..max_len] { if (b'0'..=b'9').contains(&c) { res = (res * Z::TEN) + Z::from_u8(c - b'0'); had_digit = true; } else if bytes_read == 0 { if c == b'+' { // skip it } else if c == b'-' { negate = true; } else { return Err(ParseError::UnexpectedByte("digits or sign", c)); } } else if had_digit { break; } else { return Err(ParseError::UnexpectedByte("digits", c)); } bytes_read += 1; } self.s = &self.s[bytes_read..]; Ok(if negate { -res } else { res }) } #[inline] fn starts_with_ignore_ascii_case(&self, prefix: &str) -> bool { self.s.len() >= prefix.len() && self.s.is_char_boundary(prefix.len()) && self.s[..prefix.len()].eq_ignore_ascii_case(prefix) } } impl<'a> Collector for ParseCollector<'a> { type Output = (PrimitiveDateTime, Option>); type Error = ParseError; #[inline] fn spaces(&mut self) -> Result<(), Self::Error> { self.skip_whitespaces(); Ok(()) } #[inline] fn day_of_week_name(&mut self) -> Result<(), Self::Error> { let mut weekday = Weekday::Monday; for _i in 0..7 { let short = util::weekday_short_str(weekday); if self.starts_with_ignore_ascii_case(short) { let long = util::weekday_long_str(weekday); if self.starts_with_ignore_ascii_case(long) { self.s = &self.s[long.len()..]; } else { self.s = &self.s[short.len()..]; } // Found match. Ignore it! return Ok(()); } weekday = weekday.next(); } Err(Self::Error::NotMatch("day of week name")) } #[inline] fn month_name(&mut self) -> Result<(), Self::Error> { let mut month = Month::January; for _i in 0..12 { let short = util::month_short_str(month); if self.starts_with_ignore_ascii_case(short) { let long = util::month_long_str(month); if self.starts_with_ignore_ascii_case(long) { self.s = &self.s[long.len()..]; } else { self.s = &self.s[short.len()..]; } match &mut self.day { ParsingDayOfYear::Unspecified => { self.day = ParsingDayOfYear::MonthDay(month, 1) } ParsingDayOfYear::MonthDay(current, _) => *current = month, // Prefer day of year over (month, day) ParsingDayOfYear::DayOfYear(_) => {} } return Ok(()); } month = month.next(); } Err(Self::Error::NotMatch("month name")) } #[inline] fn year_prefix(&mut self) -> Result<(), Self::Error> { let prefix = self.parse_int(2)?; match &mut self.year { ParsingYear::Unspecified => self.year = ParsingYear::PrefixSuffix(prefix, 0), // Prefer year over (year prefix, year suffix). ParsingYear::Year(_) => {} ParsingYear::PrefixSuffix(v, _) => *v = prefix, } Ok(()) } #[inline] fn day_of_month(&mut self) -> Result<(), Self::Error> { let day = self.parse_nat(1, 2)?; if (1..=31).contains(&day) { match &mut self.day { ParsingDayOfYear::Unspecified => { self.day = ParsingDayOfYear::MonthDay(Month::January, day) } ParsingDayOfYear::MonthDay(_, current) => *current = day, // Prefer day of year over (month, day) ParsingDayOfYear::DayOfYear(_) => {} } Ok(()) } else { Err(Self::Error::ComponentOutOfRange("day-of-month")) } } #[inline] fn hour_of_day(&mut self) -> Result<(), Self::Error> { let hour = self.parse_nat(1, 2)?; if (0..24).contains(&hour) { match &mut self.hour { ParsingHour::Unspecified => self.hour = ParsingHour::FullDay(hour), ParsingHour::FullDay(current) => *current = hour, // Prefer full day over halfday + am/pm. ParsingHour::HalfDay(_, _) => {} } Ok(()) } else { Err(Self::Error::ComponentOutOfRange("hour-of-day")) } } #[inline] fn hour_of_day_12(&mut self) -> Result<(), Self::Error> { let hour: u8 = self.parse_nat(1, 2)?; if (1..=12).contains(&hour) { let hour = hour % 12; match &mut self.hour { ParsingHour::Unspecified => self.hour = ParsingHour::HalfDay(hour, false), // Prefer full day over halfday + am/pm. ParsingHour::FullDay(_) => {} ParsingHour::HalfDay(current, _) => *current = hour, } Ok(()) } else { Err(Self::Error::ComponentOutOfRange("hour-of-half-day")) } } #[inline] fn day_of_year(&mut self) -> Result<(), Self::Error> { let day = self.parse_nat(1, 3)?; if (1..=366).contains(&day) { // Prefer day of year over (month, day) self.day = ParsingDayOfYear::DayOfYear(day); Ok(()) } else { Err(Self::Error::ComponentOutOfRange("day-of-year")) } } #[inline] fn month_of_year(&mut self) -> Result<(), Self::Error> { let month = self.parse_nat(1, 2)?; if (1..=12).contains(&month) { let month = util::get_month(month).unwrap(); match &mut self.day { ParsingDayOfYear::Unspecified => self.day = ParsingDayOfYear::MonthDay(month, 1), ParsingDayOfYear::MonthDay(current, _) => *current = month, // Prefer day of year over (month, day) ParsingDayOfYear::DayOfYear(_) => {} } Ok(()) } else { Err(Self::Error::ComponentOutOfRange("month")) } } #[inline] fn minute_of_hour(&mut self) -> Result<(), Self::Error> { let minute = self.parse_nat(1, 2)?; if (0..60).contains(&minute) { self.minute = minute; Ok(()) } else { Err(Self::Error::ComponentOutOfRange("munute")) } } #[inline] fn ampm(&mut self) -> Result<(), Self::Error> { for h in [0, 12] { let s = util::ampm_lower(h); if self.starts_with_ignore_ascii_case(s) { match &mut self.hour { ParsingHour::Unspecified => self.hour = ParsingHour::HalfDay(0, h != 0), // Prefer full day over halfday + am/pm. ParsingHour::FullDay(_) => {} ParsingHour::HalfDay(_, current) => *current = h != 0, } // Consume AM/PM substring self.s = &self.s[2..]; return Ok(()); } } Err(Self::Error::NotMatch("am/pm")) } #[inline] fn second_of_minute(&mut self) -> Result<(), Self::Error> { let second = self.parse_nat(1, 2)?; if (0..61).contains(&second) { self.second = second; Ok(()) } else { Err(Self::Error::ComponentOutOfRange("second")) } } #[inline] fn nanosecond_of_second(&mut self) -> Result<(), Self::Error> { let input_length = self.s.len(); let nanosecond: u32 = self.parse_nat(1, 9)?; let digits_consumed = input_length - self.s.len(); static SCALE: [u32; 10] = [ 0, 100_000_000, 10_000_000, 1_000_000, 100_000, 10_000, 1_000, 100, 10, 1, ]; self.nanosecond = nanosecond * SCALE[digits_consumed]; Ok(()) } #[inline] fn week_number_of_current_year_start_sunday(&mut self) -> Result<(), Self::Error> { let w: u8 = self.parse_nat(1, 2)?; if (0..=53).contains(&w) { // Ignore it! Ok(()) } else { Err(Self::Error::ComponentOutOfRange("week-number")) } } #[inline] fn day_of_week_from_sunday_as_0(&mut self) -> Result<(), Self::Error> { let w: u8 = self.parse_nat(1, 1)?; if (0..7).contains(&w) { // Ignore it! Ok(()) } else { Err(Self::Error::ComponentOutOfRange("day-of-week")) } } #[inline] fn week_number_of_current_year_start_monday(&mut self) -> Result<(), Self::Error> { let w: u8 = self.parse_nat(1, 2)?; if (0..=53).contains(&w) { Ok(()) } else { Err(Self::Error::ComponentOutOfRange("week-number")) } } #[inline] fn year_suffix(&mut self) -> Result<(), Self::Error> { let y = self.parse_nat(1, 2)?; if (0..100).contains(&y) { match &mut self.year { ParsingYear::Unspecified => { self.year = ParsingYear::PrefixSuffix(if y < 69 { 20 } else { 19 }, y) } // Prefer year over (year prefix, year suffix). ParsingYear::Year(_) => {} ParsingYear::PrefixSuffix(_, current) => *current = y, } Ok(()) } else { Err(Self::Error::ComponentOutOfRange("year-suffix")) } } #[inline] fn year(&mut self) -> Result<(), Self::Error> { let y = self.parse_int(4)?; // Prefer year over (year prefix, year suffix). self.year = ParsingYear::Year(y); Ok(()) } #[inline] fn timezone(&mut self) -> Result<(), Self::Error> { let negate = match self.peek_byte() { Some(b'Z') => { self.s = &self.s[1..]; // skip Z self.zone = Some(TimeZoneSpecifier::Offset(UtcOffset::UTC)); return Ok(()); } Some(c @ (b'+' | b'-')) => { self.s = &self.s[1..]; // skip sign c == b'-' } Some(b) => return Err(Self::Error::UnexpectedByte("+ or -", b)), None => return Err(Self::Error::UnexpectedEnd("+ or -")), }; let h: u8 = self.parse_nat(2, 2)?; if self.peek_byte() == Some(b':') { self.s = &self.s[1..]; // skip : } let m: u8 = self.parse_nat(2, 2)?; let h: i8 = h .try_into() .map_err(|_| Self::Error::ComponentOutOfRange("offset-hour"))?; let m: i8 = m .try_into() .map_err(|_| Self::Error::ComponentOutOfRange("offset-minute"))?; let (h, m) = if negate { (-h, -m) } else { (h, m) }; self.zone = Some(TimeZoneSpecifier::Offset(UtcOffset::from_hms(h, m, 0)?)); Ok(()) } #[inline] fn timezone_name(&mut self) -> Result<(), Self::Error> { let s = self.get_until_whitespace(); self.zone = Some(TimeZoneSpecifier::Name(s)); Ok(()) } #[inline] fn static_str(&mut self, s: &'static str) -> Result<(), Self::Error> { if let Some(rest) = self.s.strip_prefix(s) { self.s = rest; Ok(()) } else { Err(Self::Error::NotMatch(s)) } } #[inline] fn literal( &mut self, lit: &str, _fmt_span: impl std::slice::SliceIndex<[u8], Output = [u8]>, ) -> Result<(), Self::Error> { if let Some(rest) = self.s.strip_prefix(lit) { self.s = rest; Ok(()) } else { Err(Self::Error::NotMatch("string literal")) } } #[inline] fn unknown(&mut self, specifier: char) -> Result<(), Self::Error> { Err(Self::Error::UnknownSpecifier(specifier)) } #[inline] fn unconsumed_input(&self) -> Result<(), Self::Error> { let unconsumed_input = self.s.to_string(); if unconsumed_input.len() > 0 { Err(Self::Error::UnconvertedDataRemains(unconsumed_input)) } else { Ok(()) } } #[inline] fn output(self) -> Result { let year = match self.year { ParsingYear::Unspecified => 1900, ParsingYear::Year(y) => y, ParsingYear::PrefixSuffix(p, s) => p .checked_mul(100) .and_then(|p| p.checked_add(s as i32)) .ok_or(Self::Error::ComponentOutOfRange("year"))?, }; let date = match self.day { ParsingDayOfYear::Unspecified => Date::from_ordinal_date(year, 1)?, ParsingDayOfYear::MonthDay(month, day) => Date::from_calendar_date(year, month, day)?, ParsingDayOfYear::DayOfYear(day) => Date::from_ordinal_date(year, day)?, }; let hour = match self.hour { ParsingHour::Unspecified => 0, ParsingHour::FullDay(h) => h, ParsingHour::HalfDay(h, ampm) => { if ampm { h + 12 } else { h } } }; let time = Time::from_hms_nano(hour, self.minute, self.second, self.nanosecond)?; let zone = self.zone; Ok((PrimitiveDateTime::new(date, time), zone)) } } pub fn parse_date_time_maybe_with_zone<'a>( fmt: &str, s: &'a str, ) -> Result<(PrimitiveDateTime, Option>), ParseError> { let collector = ParseCollector::new(s); desc_parser::parse_format_specifications(fmt, collector, false) } pub fn parse_strict_date_time_maybe_with_zone<'a>( fmt: &str, s: &'a str, ) -> Result<(PrimitiveDateTime, Option>), ParseError> { let collector = ParseCollector::new(s); desc_parser::parse_format_specifications(fmt, collector, true) } #[cfg(test)] mod tests { use super::{ parse_date_time_maybe_with_zone, parse_strict_date_time_maybe_with_zone, ParseError, TimeZoneSpecifier, }; use time::macros::{datetime, offset}; #[test] fn test_simple_parse() -> Result<(), super::ParseError> { assert_eq!( parse_date_time_maybe_with_zone("%a %A %a", "wED Wed weDnesDay")?, (datetime!(1900-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%b %B %b", "feB FEb feburaRy")?, (datetime!(1900-02-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%c", "Sun Mar 6 12:34:56 2022")?, (datetime!(2022-03-06 12:34:56), None) ); assert_eq!( parse_date_time_maybe_with_zone("%C", "20")?, (datetime!(2000-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%d", "5")?, (datetime!(1900-01-05 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%e", "5")?, (datetime!(1900-01-05 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%D", "3 /6/22")?, (datetime!(2022-03-06 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%F", "2022-03-06")?, (datetime!(2022-03-06 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%H", "2")?, (datetime!(1900-01-01 2:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%k", "2")?, (datetime!(1900-01-01 2:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%I", "2")?, (datetime!(1900-01-01 2:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%l", "12")?, (datetime!(1900-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%j", "38")?, (datetime!(1900-02-07 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%m", "8")?, (datetime!(1900-08-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%M", "8")?, (datetime!(1900-01-01 00:08:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%n%t ", " ")?, (datetime!(1900-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%I %p", "12 AM")?, (datetime!(1900-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%I %p", "1 AM")?, (datetime!(1900-01-01 01:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%I %p", "1 pm")?, (datetime!(1900-01-01 13:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%I %p", "12 pm")?, (datetime!(1900-01-01 12:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%r", "12:34:56 PM")?, (datetime!(1900-01-01 12:34:56), None) ); assert_eq!( parse_date_time_maybe_with_zone("%r", "12:34:56 AM")?, (datetime!(1900-01-01 00:34:56), None) ); assert_eq!( parse_date_time_maybe_with_zone("%r %F", "12:34:56 AM 2022-03-06")?, (datetime!(2022-03-06 00:34:56), None) ); assert_eq!( parse_date_time_maybe_with_zone("%R", "12: 4")?, (datetime!(1900-01-01 12:04:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%S", "01")?, (datetime!(1900-01-01 00:00:01), None) ); assert_eq!( parse_date_time_maybe_with_zone("%T", "01:23:45")?, (datetime!(1900-01-01 01:23:45), None) ); assert_eq!( parse_date_time_maybe_with_zone("%T.%f", "01:23:45.123")?, (datetime!(1900-01-01 01:23:45.123), None) ); assert_eq!( parse_date_time_maybe_with_zone("%T.%f", "01:23:45.12300")?, (datetime!(1900-01-01 01:23:45.123), None) ); assert_eq!( parse_date_time_maybe_with_zone("%T.%f", "01:23:45.000001234")?, (datetime!(1900-01-01 01:23:45.000001234), None) ); assert_eq!( parse_date_time_maybe_with_zone("%U", "1")?, (datetime!(1900-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%w", "1")?, (datetime!(1900-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%W", "1")?, (datetime!(1900-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%x", "3/6/22")?, (datetime!(2022-03-06 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%X", "12:34:5")?, (datetime!(1900-01-01 12:34:05), None) ); assert_eq!( parse_date_time_maybe_with_zone("%y", "12")?, (datetime!(2012-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%y", "70")?, (datetime!(1970-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%Y", "70")?, (datetime!(0070-01-01 00:00:00), None) ); assert_eq!( parse_date_time_maybe_with_zone("%C%y", "2022")?, (datetime!(2022-01-01 00:00:00), None) ); Ok(()) } #[test] fn test_strict() { assert!(matches!( parse_strict_date_time_maybe_with_zone("%F", "2022-03-06T12:34:56Z"), Err(ParseError::UnconvertedDataRemains(_)), )); assert_eq!( parse_strict_date_time_maybe_with_zone("%FT%TZ", "2022-03-06T12:34:56Z"), Ok((datetime!(2022-03-06 12:34:56), None)) ); } #[test] fn test_zone() -> Result<(), super::ParseError> { assert_eq!( parse_date_time_maybe_with_zone("%FT%TZ", "2022-03-06T12:34:56Z")?, (datetime!(2022-03-06 12:34:56), None) ); assert_eq!( parse_date_time_maybe_with_zone("%FT%T%z", "2022-03-06T12:34:56Z")?, ( datetime!(2022-03-06 12:34:56), Some(TimeZoneSpecifier::Offset(offset!(+00:00))) ) ); assert_eq!( parse_date_time_maybe_with_zone("%FT%T%Z", "2022-03-06T12:34:56Z")?, ( datetime!(2022-03-06 12:34:56), Some(TimeZoneSpecifier::Name("Z")) ) ); assert_eq!( parse_date_time_maybe_with_zone("%FT%T %z", "2022-03-06T12:34:56 -1234")?, ( datetime!(2022-03-06 12:34:56), Some(TimeZoneSpecifier::Offset(offset!(-12:34))) ) ); assert_eq!( parse_date_time_maybe_with_zone("%FT%T %Z", "2022-03-06T12:34:56 JST")?, ( datetime!(2022-03-06 12:34:56), Some(TimeZoneSpecifier::Name("JST")) ) ); assert_eq!( parse_date_time_maybe_with_zone("%FT%T %z", "2022-03-06T12:34:56 -12:34")?, ( datetime!(2022-03-06 12:34:56), Some(TimeZoneSpecifier::Offset(offset!(-12:34))) ) ); assert!(parse_date_time_maybe_with_zone("%FT%T %z", "2022-03-06T12:34:56 12:34").is_err()); assert!(parse_date_time_maybe_with_zone("%FT%T %z", "2022-03-06T12:34:56 +2:34").is_err()); assert!(parse_date_time_maybe_with_zone("%FT%T %z", "2022-03-06T12:34:56 +234").is_err()); Ok(()) } } time-fmt-0.3.8/src/util.rs000064400000000000000000000036571046102023000135030ustar 00000000000000use time::{Month, Weekday}; const MONTH_LONG: [&str; 12] = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; const MONTH_SHORT: [&str; 12] = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; const MONTHS0: [Month; 12] = [ Month::January, Month::February, Month::March, Month::April, Month::May, Month::June, Month::July, Month::August, Month::September, Month::October, Month::November, Month::December, ]; const WEEKDAY_LONG: [&str; 7] = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ]; const WEEKDAY_SHORT: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; const AMPM_UPPER: [&str; 2] = ["AM", "PM"]; const AMPM_LOWER: [&str; 2] = ["am", "pm"]; #[inline] pub(crate) const fn ampm_upper(hour: u8) -> &'static str { AMPM_UPPER[if hour < 12 { 0 } else { 1 }] } #[inline] pub(crate) const fn ampm_lower(hour: u8) -> &'static str { AMPM_LOWER[if hour < 12 { 0 } else { 1 }] } #[inline] pub(crate) const fn month_long_str(month: Month) -> &'static str { MONTH_LONG[(month as u8 - 1) as usize] } #[inline] pub(crate) const fn month_short_str(month: Month) -> &'static str { MONTH_SHORT[(month as u8 - 1) as usize] } #[inline] pub(crate) const fn weekday_long_str(weekday: Weekday) -> &'static str { WEEKDAY_LONG[weekday as u8 as usize] } #[inline] pub(crate) const fn weekday_short_str(weekday: Weekday) -> &'static str { WEEKDAY_SHORT[weekday as u8 as usize] } #[inline] pub(crate) const fn get_month(month: u8) -> Option { // TODO: Use MONTHD0.get((month - 1) as usize).copied() once copied() get to a const fn in // stable. if 1 <= month && month <= 12 { Some(MONTHS0[(month - 1) as usize]) } else { None } }