-
Notifications
You must be signed in to change notification settings - Fork 845
Unit parser #9485
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Unit parser #9485
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| /** @file | ||
|
|
||
| Parse strings with units. | ||
|
|
||
| @section license License | ||
|
|
||
| Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. | ||
| See the NOTICE file distributed with this work for additional information regarding copyright | ||
| ownership. The ASF licenses this file to you 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. | ||
| */ | ||
|
|
||
| #pragma once | ||
|
|
||
| #include "tscpp/util/ts_unit_parser.h" | ||
|
|
||
| namespace ts | ||
| { | ||
|
|
||
| namespace detail | ||
| { | ||
| extern UnitParser const time_parser_ns; | ||
| } | ||
| /** Parse duration string. | ||
| * | ||
| * @param text Input text to parse. | ||
| * @return A return value containing the time in nanoseconds or parsing errors. | ||
| */ | ||
| inline swoc::Rv<std::chrono::nanoseconds> | ||
| time_parser(swoc::TextView text) | ||
| { | ||
| auto &&[duration, errata] = detail::time_parser_ns(text); | ||
| return {std::chrono::nanoseconds(duration), std::move(errata)}; | ||
| } | ||
| } // namespace ts |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| /** @file | ||
|
|
||
| Parse strings with units. | ||
|
|
||
| @section license License | ||
|
|
||
| Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. | ||
| See the NOTICE file distributed with this work for additional information regarding copyright | ||
| ownership. The ASF licenses this file to you 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. | ||
| */ | ||
|
|
||
| #pragma once | ||
|
|
||
| #include <cstdint> | ||
|
|
||
| #include "swoc/Lexicon.h" | ||
| #include "swoc/Errata.h" | ||
|
|
||
| namespace ts | ||
| { | ||
|
|
||
| using swoc::TextView; | ||
| using swoc::Lexicon; | ||
| using swoc::Errata; | ||
| using swoc::Rv; | ||
|
|
||
| /** Parse a string that consists of counts and units. | ||
| * | ||
| * Give a set of units, each of which is a list of names and a multiplier, parse a string. The | ||
| * string contents must consist of (optional whitespace) with alternating counts and units, | ||
| * starting with a count. Each count is multiplied by the value of the subsequent unit. Optionally | ||
| * the parser can be set to allow counts without units, which are not multiplied. | ||
| * | ||
| * For example, if the units were [ "X", 10 ] , [ "L", 50 ] , [ "C", 100 ] , [ "M", 1000 ] | ||
| * then the following strings would be parsed as | ||
| * | ||
| * - "1X" : 10 | ||
| * - "1L3X" : 80 | ||
| * - "2C" : 200 | ||
| * - "1M 4C 4X" : 1,440 | ||
| * - "3M 5 C3 X" : 3,530 | ||
| */ | ||
| class UnitParser | ||
| { | ||
| using self_type = UnitParser; ///< Self reference type. | ||
| public: | ||
| using value_type = uintmax_t; ///< Integral type returned. | ||
| using Units = swoc::Lexicon<value_type>; ///< Unit definition type. | ||
|
|
||
| /// Symbolic name for setting whether units are required. | ||
| static constexpr bool UNITS_REQUIRED = true; | ||
| /// Symbolic name for setting whether units are required. | ||
| static constexpr bool UNITS_NOT_REQUIRED = false; | ||
|
|
||
| /** Constructor. | ||
| * | ||
| * @param units A @c Lexicon of unit definitions. | ||
| * @param unit_required_p Whether valid input requires units on all values. | ||
| */ | ||
| UnitParser(Units &&units, bool unit_required_p = true) noexcept; | ||
|
|
||
| /** Set whether a unit is required. | ||
| * | ||
| * @param flag @c true if a unit is required, @c false if not. | ||
| * @return @a this. | ||
| */ | ||
| self_type &unit_required(bool flag); | ||
|
|
||
| /** Parse a string. | ||
| * | ||
| * @param src Input string. | ||
| * @return The computed value if the input is valid, or an error report. | ||
| */ | ||
| Rv<value_type> operator()(swoc::TextView const &src) const noexcept; | ||
|
|
||
| protected: | ||
| bool _unit_required_p = true; ///< Whether unitless values are allowed. | ||
| Units _units; ///< Unit definitions. | ||
| }; | ||
|
|
||
| inline UnitParser::UnitParser(UnitParser::Units &&units, bool unit_required_p) noexcept | ||
| : _unit_required_p(unit_required_p), _units(std::move(units)) | ||
| { | ||
| _units.set_default(value_type{0}); // Used to check for bad unit names. | ||
| } | ||
|
|
||
| inline UnitParser::self_type & | ||
| UnitParser::unit_required(bool flag) | ||
| { | ||
| _unit_required_p = false; | ||
| return *this; | ||
| } | ||
|
|
||
| } // namespace ts |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| /** @file Support for common diagnostics between core, plugins, and libswoc. | ||
|
|
||
| This enables specifying the set of methods usable by a user agent based on the remove IP address | ||
| for a user agent connection. | ||
|
|
||
| @section license License | ||
|
|
||
| Licensed to the Apache Software Foundation (ASF) under one | ||
| or more contributor license agreements. See the NOTICE file | ||
| distributed with this work for additional information | ||
| regarding copyright ownership. The ASF licenses this file | ||
| to you 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. | ||
| */ | ||
|
|
||
| #include <chrono> | ||
|
|
||
| #include "tscpp/util/ts_unit_parser.h" | ||
| #include "tscpp/util/ts_time_parser.h" | ||
|
|
||
| namespace ts | ||
| { | ||
|
|
||
| auto | ||
| UnitParser::operator()(swoc::TextView const &src) const noexcept -> Rv<value_type> | ||
| { | ||
| value_type zret = 0; | ||
| TextView text = src; // Keep @a src around to report error offsets. | ||
|
|
||
| while (text.ltrim_if(&isspace)) { | ||
| TextView parsed; | ||
| auto n = swoc::svtou(text, &parsed); | ||
| if (parsed.empty()) { | ||
| return Errata("Required count not found at offset {}", text.data() - src.data()); | ||
| } else if (n == std::numeric_limits<decltype(n)>::max()) { | ||
| return Errata("Count at offset {} was out of bounds", text.data() - src.data()); | ||
| } | ||
| text.remove_prefix(parsed.size()); | ||
| auto ptr = text.ltrim_if(&isspace).data(); // save for error reporting. | ||
| // Everything up to the next digit or whitespace. | ||
| auto unit = text.clip_prefix_of([](char c) { return !(isspace(c) || isdigit(c)); }); | ||
| if (unit.empty()) { | ||
| if (_unit_required_p) { | ||
| return Errata("Required unit not found at offset {}", ptr - src.data()); | ||
| } | ||
| } else { | ||
| auto mult = _units[unit]; // What's the multiplier? | ||
| if (mult == 0) { | ||
| return Errata("Unknown unit \"{}\" at offset {}", unit, ptr - src.data()); | ||
| } | ||
| n *= mult; | ||
| } | ||
| zret += n; | ||
| } | ||
| return zret; | ||
| } | ||
|
|
||
| // Concrete unit parsers. | ||
|
|
||
| using namespace std::chrono; | ||
|
|
||
| namespace detail | ||
| { | ||
| /** Functor to parse duration strings. | ||
| * @c time_parser is a functor and is used like a function. | ||
| * @code | ||
| * TextView text = "12 hours 30 minutes"; | ||
| * auto duration = std::chrono::nanoseconds(ts::time_parser_ns(text)); | ||
| * @endcode | ||
| */ | ||
| UnitParser const time_parser_ns{UnitParser::Units{{{nanoseconds{1}.count(), {"ns", "nanosec", "nanoseconds"}}, | ||
| {nanoseconds{microseconds{1}}.count(), {"us", "microsec", "microseconds"}}, | ||
| {nanoseconds{milliseconds{1}}.count(), {"ms", "millisec", "milliseconds"}}, | ||
| {nanoseconds{seconds{1}}.count(), {"s", "sec", "seconds"}}, | ||
| {nanoseconds{minutes{1}}.count(), {"m", "min", "minutes"}}, | ||
| {nanoseconds{hours{1}}.count(), {"h", "hour", "hours"}}, | ||
| {nanoseconds{hours{24}}.count(), {"d", "day", "days"}}, | ||
| {nanoseconds{hours{168}}.count(), {"w", "week", "weeks"}}}}}; | ||
|
|
||
| } // namespace detail | ||
|
|
||
| } // namespace ts | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| /** @file | ||
|
|
||
| Unit tests for time parsing. | ||
|
|
||
| @section license License | ||
|
|
||
| Licensed to the Apache Software Foundation (ASF) under one | ||
| or more contributor license agreements. See the NOTICE file | ||
| distributed with this work for additional information | ||
| regarding copyright ownership. The ASF licenses this file | ||
| to you 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. | ||
| */ | ||
|
|
||
| #include <chrono> | ||
|
|
||
| #include "catch.hpp" | ||
| #include "tscpp/util/ts_time_parser.h" | ||
|
|
||
| using namespace std::chrono; | ||
|
|
||
| TEST_CASE("Time Parsing", "[libts][time_parser]") | ||
| { | ||
| SECTION("1") | ||
| { | ||
| auto [dt, errata] = ts::time_parser("11 hours 30m"); | ||
| REQUIRE(dt == minutes(690)); | ||
| } | ||
| SECTION("2") | ||
| { | ||
| auto [dt, errata] = ts::time_parser("30 minutes 11h"); | ||
| REQUIRE(dt == minutes(690)); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just curious, is all of this constexpr resolved to data at compile time or is there static initializer setup here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, there's still computation that occurs to initialize the parser data structure. I'm not sure what you mean by "static initializer" other than the parser being a static data structure which is constructed at process start time. That is,
which declares a static instance of
UnitParser.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I mean the static setup at process start time. It's not called "static initializing"?
I'd rather see
time_parserbe a function and just return a UnitParser and if a program wants one call. Then the programmer can decide its lifetime.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why? It seems more performant to construct a single instance at process start and use that everywhere. Then there is no runtime construction / destruction cost. What's the benefit of multiple instances?