From 83cd6074b88fc88dd05992f516ba144118b5d5d0 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Tue, 19 Mar 2019 17:09:03 +1100 Subject: [PATCH] parse/time: add consuming and non-consuming parsers --- parse/time.cpp | 21 ++++++++++++++++++++- parse/time.hpp | 13 +++++++++++-- test/parse/time.cpp | 5 ++--- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/parse/time.cpp b/parse/time.cpp index 923b7fb6..a0665a00 100644 --- a/parse/time.cpp +++ b/parse/time.cpp @@ -91,7 +91,7 @@ try_consume_prefix ( /////////////////////////////////////////////////////////////////////////////// cruft::expected -cruft::parse::duration (cruft::view &remain) +cruft::parse::duration::consume (cruft::view &remain) { auto const count = value (remain); if (remain.empty ()) @@ -128,3 +128,22 @@ cruft::parse::duration (cruft::view &remain) return cruft::unexpected (std::errc::invalid_argument); } + + +//----------------------------------------------------------------------------- +cruft::expected +cruft::parse::duration::from (cruft::view const &str) +{ + auto remain = str; + + // Try to parse from the temporary view. + auto res = ::cruft::parse::duration::consume (remain); + if (!res) + return res; + + // Ensure it was totally consumed. + if (!remain.empty ()) + return cruft::unexpected (std::errc::invalid_argument); + + return res; +} diff --git a/parse/time.hpp b/parse/time.hpp index fff460ef..e4b156f2 100644 --- a/parse/time.hpp +++ b/parse/time.hpp @@ -14,14 +14,23 @@ #include #include -namespace cruft::parse { +namespace cruft::parse::duration { /// Parse a number that represents a duration. eg, "1s", "5 minutes". /// + /// The data view is updated to indicate the unused data. + /// /// When there is no suffix it is assumed the quantity is in second. /// /// Note: The quantities are as defined by the standard std::chrono /// durations. This means that "1 month" will equal just under 30.5 days. /// Thus the utility is not universally useful for offsetting. expected - duration (cruft::view &); + consume (cruft::view &); + + + /// Parse a number that represent a duration (as with `consume`). + /// + /// The operation will fail if the entire input is not consumed. + expected + from (cruft::view const&); } diff --git a/test/parse/time.cpp b/test/parse/time.cpp index 0cd71967..666f3458 100644 --- a/test/parse/time.cpp +++ b/test/parse/time.cpp @@ -36,9 +36,8 @@ int main () cruft::TAP::logger tap; for (auto const &[str,val,msg]: TESTS) { - cruft::view src (str); - auto res = cruft::parse::duration (src); - tap.expect (src.empty () && res && val == *res, "%! %! == %!", msg, val.count (), res->count()); + auto res = cruft::parse::duration::from (str); + tap.expect (res && val == *res, "%! %! == %!", msg, val.count (), res->count()); } return tap.status ();