/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright 2017-2018, 2022 Danny Robson */ #pragma once #include "../view.hpp" #include "enum.hpp" namespace cruft::parse { /////////////////////////////////////////////////////////////////////////// /// Extracts an instance of a native type T from the string [first, last). /// /// Throws std::invalid_argument when the type cannot be parsed. /// /// The view is modified in place to reflect the unused data. template T value (cruft::view &); template T value (cruft::view< char *> &); template T value (std::string_view &str) { cruft::view wrapper (str); T res = value (wrapper); str = str.substr (str.size () - wrapper.size ()); return res; } /// Parses a prefix string to obtain an instance of T. /// /// This only differs from `parse` in that it throws if the entire string /// isn't consumed during the parse, rather than reporting the remaining /// data. template T from_string (cruft::view data) { if constexpr (std::is_enum_v) { return enumeration::from_string (data); } else { T res = value (data); if (!data.empty ()) throw std::invalid_argument ("unable to parse"); return res; } } /////////////////////////////////////////////////////////////////////////// template T from_string (const char *data) { return from_string (cruft::view (data)); } //------------------------------------------------------------------------- template T from_string (std::string const &data) { return from_string (cruft::view (data)); } //------------------------------------------------------------------------- template T from_string (std::string_view data) { return from_string (cruft::view (data)); } }