Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions include/tscpp/util/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ library_include_HEADERS = \
Strerror.h \
TextView.h \
TsSharedMutex.h \
ts_unit_parser.h \
ts_time_parser.h \
YamlCfg.h
43 changes: 43 additions & 0 deletions include/tscpp/util/ts_time_parser.h
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
103 changes: 103 additions & 0 deletions include/tscpp/util/ts_unit_parser.h
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
3 changes: 2 additions & 1 deletion src/tscpp/util/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
add_library(tscpputil SHARED
TextView.cc
YamlCfg.cc
)
ts_unit_parser.cc)
target_link_libraries(tscpputil PRIVATE yaml-cpp libswoc)

add_executable(test_tscpputil
Expand All @@ -28,6 +28,7 @@ add_executable(test_tscpputil
unit_tests/test_TextView.cc
unit_tests/test_Strerror.cc
unit_tests/test_ts_meta.cc
unit_tests/test_time_parser.cc
unit_tests/unit_test_main.cc
)
target_link_libraries(test_tscpputil PRIVATE tscpputil libswoc)
Expand Down
6 changes: 4 additions & 2 deletions src/tscpp/util/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ libtscpputil_la_LDFLAGS = @AM_LDFLAGS@ -no-undefined -version-info @TS_LIBTOOL_V
libtscpputil_la_LIBADD = @SWOC_LIBS@ @YAMLCPP_LIBS@

libtscpputil_la_SOURCES = \
ts_diags.cc ts_ip.cc TextView.cc YamlCfg.cc
ts_diags.cc ts_ip.cc TextView.cc YamlCfg.cc ts_unit_parser.cc

test_tscpputil_CPPFLAGS = $(AM_CPPFLAGS)\
-I$(abs_top_srcdir)/tests/include @SWOC_INCLUDES@
Expand All @@ -43,7 +43,9 @@ test_tscpputil_SOURCES = \
unit_tests/test_PostScript.cc \
unit_tests/test_Strerror.cc \
unit_tests/test_TextView.cc \
unit_tests/test_ts_meta.cc
unit_tests/test_ts_meta.cc \
unit_tests/test_time_parser.cc


clean-local:
rm -f ParseRulesCType ParseRulesCTypeToLower ParseRulesCTypeToUpper
Expand Down
91 changes: 91 additions & 0 deletions src/tscpp/util/ts_unit_parser.cc
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
Copy link
Contributor

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?

Copy link
Member Author

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,

UnitParser const time_parser{ ... };

which declares a static instance of UnitParser.

Copy link
Contributor

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_parser be a function and just return a UnitParser and if a program wants one call. Then the programmer can decide its lifetime.

Copy link
Member Author

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?

43 changes: 43 additions & 0 deletions src/tscpp/util/unit_tests/test_time_parser.cc
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));
}
}