From: Joel Rosdahl Date: Thu, 20 Jul 2023 08:30:06 +0000 (+0200) Subject: refactor: Switch to tl::expected instead of nonstd::expected X-Git-Tag: v4.9~96 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=3960607021f74f143c8ed6fc2a89ec662b22d3d1;p=thirdparty%2Fccache.git refactor: Switch to tl::expected instead of nonstd::expected --- diff --git a/LICENSE.adoc b/LICENSE.adoc index ad274ed79..2958cfa29 100644 --- a/LICENSE.adoc +++ b/LICENSE.adoc @@ -574,14 +574,14 @@ SOFTWARE. ---- -=== src/third_party/nonstd/expected.hpp +=== src/third_party/nonstd/span.hpp This is the single header version of -https://github.com/martinmoene/expected-lite[expected-lite] 0.6.2 with the +https://github.com/martinmoene/span-lite[expected-lite] 0.10.3 with the following license: ---- -Copyright (c) 2016-2020 Martin Moene +Copyright (c) 2018-2021 Martin Moene Boost Software License - Version 1.0 - August 17th, 2003 @@ -609,38 +609,133 @@ DEALINGS IN THE SOFTWARE. ---- -=== src/third_party/nonstd/span.hpp +=== src/third_party/tl/expected.hpp -This is the single header version of -https://github.com/martinmoene/span-lite[expected-lite] 0.10.3 with the -following license: +This is https://github.com/TartanLlama/expected[TartanLlama expected] 1.1.0 with +the following license: ---- -Copyright (c) 2018-2021 Martin Moene +Creative Commons Legal Code -Boost Software License - Version 1.0 - August 17th, 2003 +CC0 1.0 Universal -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. +Statement of Purpose -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, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. ---- diff --git a/src/Hash.cpp b/src/Hash.cpp index 47471a694..0ea8c456c 100644 --- a/src/Hash.cpp +++ b/src/Hash.cpp @@ -107,20 +107,20 @@ Hash::hash(int64_t x) return *this; } -nonstd::expected +tl::expected Hash::hash_fd(int fd) { return util::read_fd( fd, [this](nonstd::span data) { hash(data); }); } -nonstd::expected +tl::expected Hash::hash_file(const std::string& path) { Fd fd(open(path.c_str(), O_RDONLY | O_BINARY)); if (!fd) { LOG("Failed to open {}: {}", path, strerror(errno)); - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } return hash_fd(*fd); diff --git a/src/Hash.hpp b/src/Hash.hpp index 66d6b2781..5fa9f034f 100644 --- a/src/Hash.hpp +++ b/src/Hash.hpp @@ -19,8 +19,8 @@ #pragma once #include "third_party/blake3/blake3.h" -#include #include +#include #include #include @@ -74,13 +74,13 @@ public: // // If hash debugging is enabled, the data is written verbatim to the text // input file. - nonstd::expected hash_file(const std::string& path); + tl::expected hash_file(const std::string& path); // Add contents read from an open file descriptor to the hash. // // If hash debugging is enabled, the data is written verbatim to the text // input file. - nonstd::expected hash_fd(int fd); + tl::expected hash_fd(int fd); private: blake3_hasher m_hasher; diff --git a/src/ccache.cpp b/src/ccache.cpp index f84d4b8db..8f8e405a4 100644 --- a/src/ccache.cpp +++ b/src/ccache.cpp @@ -102,7 +102,7 @@ const char k_ccache_disable_token[] = "ccache:disable"; namespace { -// Return nonstd::make_unexpected if ccache did not succeed in getting +// Return tl::unexpected if ccache did not succeed in getting // or putting a result in the cache. If `exit_code` is set, ccache will just // exit with that code directly, otherwise execute the real compiler and exit // with its exit code. Statistics counters will also be incremented. @@ -473,13 +473,13 @@ print_included_files(const Context& ctx, FILE* fp) // - Makes include file paths for which the base directory is a prefix relative // when computing the hash sum. // - Stores the paths and hashes of included files in ctx.included_files. -static nonstd::expected +static tl::expected process_preprocessed_file(Context& ctx, Hash& hash, const std::string& path) { auto data = util::read_file(path); if (!data) { LOG("Failed to read {}: {}", path, data.error()); - return nonstd::make_unexpected(Statistic::internal_error); + return tl::unexpected(Statistic::internal_error); } std::unordered_map relative_inc_path_cache; @@ -565,7 +565,7 @@ process_preprocessed_file(Context& ctx, Hash& hash, const std::string& path) q++; if (q >= end) { LOG_RAW("Failed to parse included file path"); - return nonstd::make_unexpected(Statistic::internal_error); + return tl::unexpected(Statistic::internal_error); } // q points to the beginning of an include file path hash.hash(p, q - p); @@ -605,8 +605,7 @@ process_preprocessed_file(Context& ctx, Hash& hash, const std::string& path) if (remember_include_file(ctx, inc_path, hash, system, nullptr) == RememberIncludeFileResult::cannot_use_pch) { - return nonstd::make_unexpected( - Statistic::could_not_use_precompiled_header); + return tl::unexpected(Statistic::could_not_use_precompiled_header); } p = q; // Everything of interest between p and q has been hashed now. } else if (strncmp(q, incbin_directive, sizeof(incbin_directive)) == 0 @@ -620,8 +619,7 @@ process_preprocessed_file(Context& ctx, Hash& hash, const std::string& path) LOG_RAW( "Found potential unsupported .inc" "bin directive in source code"); - return nonstd::make_unexpected( - Failure(Statistic::unsupported_code_directive)); + return tl::unexpected(Failure(Statistic::unsupported_code_directive)); } else if (strncmp(q, "___________", 10) == 0 && (q == data->data() || q[-1] == '\n')) { // Unfortunately the distcc-pump wrapper outputs standard output lines: @@ -765,7 +763,7 @@ result_key_from_includes(Context& ctx, Hash& hash, std::string_view stdout_data) // Execute the compiler/preprocessor, with logic to retry without requesting // colored diagnostics messages if that fails. -static nonstd::expected +static tl::expected do_execute(Context& ctx, Args& args, const bool capture_stdout = true) { util::UmaskScope umask_scope(ctx.original_umask); @@ -808,7 +806,7 @@ do_execute(Context& ctx, Args& args, const bool capture_stdout = true) LOG("Failed to read {} (cleanup in progress?): {}", tmp_stdout.path, stdout_data_result.error()); - return nonstd::make_unexpected(Statistic::missing_cache_file); + return tl::unexpected(Statistic::missing_cache_file); } stdout_data = *stdout_data_result; } @@ -818,7 +816,7 @@ do_execute(Context& ctx, Args& args, const bool capture_stdout = true) LOG("Failed to read {} (cleanup in progress?): {}", tmp_stderr.path, stderr_data_result.error()); - return nonstd::make_unexpected(Statistic::missing_cache_file); + return tl::unexpected(Statistic::missing_cache_file); } return DoExecuteResult{status, stdout_data, *stderr_data_result}; @@ -1051,7 +1049,7 @@ rewrite_stdout_from_compiler(const Context& ctx, util::Bytes&& stdout_data) } // Run the real compiler and put the result in cache. Returns the result key. -static nonstd::expected +static tl::expected to_cache(Context& ctx, Args& args, std::optional result_key, @@ -1095,14 +1093,14 @@ to_cache(Context& ctx, if (unlink(ctx.args_info.output_dwo.c_str()) != 0 && errno != ENOENT && errno != ESTALE) { LOG("Failed to unlink {}: {}", ctx.args_info.output_dwo, strerror(errno)); - return nonstd::make_unexpected(Statistic::bad_output_file); + return tl::unexpected(Statistic::bad_output_file); } } LOG_RAW("Running real compiler"); MTR_BEGIN("execute", "compiler"); - nonstd::expected result; + tl::expected result; if (!ctx.config.depend_mode()) { result = do_execute(ctx, args); args.pop_back(3); @@ -1122,7 +1120,7 @@ to_cache(Context& ctx, MTR_END("execute", "compiler"); if (!result) { - return nonstd::make_unexpected(result.error()); + return tl::unexpected(result.error()); } // Merge stderr from the preprocessor (if any) and stderr from the real @@ -1150,7 +1148,7 @@ to_cache(Context& ctx, auto failure = Failure(Statistic::compile_failed); failure.set_exit_code(result->exit_status); - return nonstd::make_unexpected(failure); + return tl::unexpected(failure); } if (ctx.config.depend_mode()) { @@ -1164,7 +1162,7 @@ to_cache(Context& ctx, ASSERT(false); } if (!result_key) { - return nonstd::make_unexpected(Statistic::internal_error); + return tl::unexpected(Statistic::internal_error); } LOG_RAW("Got result key from dependency file"); LOG("Result key: {}", util::format_digest(*result_key)); @@ -1188,17 +1186,17 @@ to_cache(Context& ctx, obj_stat = Stat::stat(ctx.args_info.output_obj); if (!obj_stat) { LOG_RAW("Compiler didn't produce an object file"); - return nonstd::make_unexpected(Statistic::compiler_produced_no_output); + return tl::unexpected(Statistic::compiler_produced_no_output); } else if (obj_stat.size() == 0) { LOG_RAW("Compiler produced an empty object file"); - return nonstd::make_unexpected(Statistic::compiler_produced_empty_output); + return tl::unexpected(Statistic::compiler_produced_empty_output); } } MTR_BEGIN("result", "result_put"); if (!write_result( ctx, *result_key, obj_stat, result->stdout_data, result->stderr_data)) { - return nonstd::make_unexpected(Statistic::compiler_produced_no_output); + return tl::unexpected(Statistic::compiler_produced_no_output); } MTR_END("result", "result_put"); @@ -1217,7 +1215,7 @@ to_cache(Context& ctx, // Find the result key by running the compiler in preprocessor mode and // hashing the result. -static nonstd::expected +static tl::expected get_result_key_from_cpp(Context& ctx, Args& args, Hash& hash) { ctx.time_of_compilation = util::TimePoint::now(); @@ -1268,10 +1266,10 @@ get_result_key_from_cpp(Context& ctx, Args& args, Hash& hash) args.pop_back(args.size() - orig_args_size); if (!result) { - return nonstd::make_unexpected(result.error()); + return tl::unexpected(result.error()); } else if (result->exit_status != 0) { LOG("Preprocessor gave exit status {}", result->exit_status); - return nonstd::make_unexpected(Statistic::preprocessor_error); + return tl::unexpected(Statistic::preprocessor_error); } cpp_stderr_data = result->stderr_data; @@ -1298,7 +1296,7 @@ get_result_key_from_cpp(Context& ctx, Args& args, Hash& hash) // Hash mtime or content of a file, or the output of a command, according to // the CCACHE_COMPILERCHECK setting. -static nonstd::expected +static tl::expected hash_compiler(const Context& ctx, Hash& hash, const Stat& st, @@ -1322,7 +1320,7 @@ hash_compiler(const Context& ctx, hash, ctx.config.compiler_check(), ctx.orig_args[0])) { LOG("Failure running compiler check command: {}", ctx.config.compiler_check()); - return nonstd::make_unexpected(Statistic::compiler_check_failed); + return tl::unexpected(Statistic::compiler_check_failed); } } return {}; @@ -1333,7 +1331,7 @@ hash_compiler(const Context& ctx, // If `ccbin_st` and `ccbin` are set, they refer to a directory or compiler set // with -ccbin/--compiler-bindir. If `ccbin_st` is nullptr or `ccbin` is the // empty string, the compilers are looked up in PATH instead. -static nonstd::expected +static tl::expected hash_nvcc_host_compiler(const Context& ctx, Hash& hash, const Stat* ccbin_st = nullptr, @@ -1382,7 +1380,7 @@ hash_nvcc_host_compiler(const Context& ctx, } // update a hash with information common for the direct and preprocessor modes. -static nonstd::expected +static tl::expected hash_common_info(const Context& ctx, const Args& args, Hash& hash, @@ -1408,7 +1406,7 @@ hash_common_info(const Context& ctx, auto st = Stat::stat(compiler_path, Stat::OnError::log); if (!st) { - return nonstd::make_unexpected(Statistic::could_not_find_compiler); + return tl::unexpected(Statistic::could_not_find_compiler); } // Hash information about the compiler. @@ -1539,7 +1537,7 @@ hash_common_info(const Context& ctx, LOG("Hashing sanitize blacklist {}", sanitize_blacklist); hash.hash_delimiter("sanitizeblacklist"); if (!hash_binary_file(ctx, hash, sanitize_blacklist)) { - return nonstd::make_unexpected(Statistic::error_hashing_extra_file); + return tl::unexpected(Statistic::error_hashing_extra_file); } } @@ -1549,7 +1547,7 @@ hash_common_info(const Context& ctx, LOG("Hashing extra file {}", path); hash.hash_delimiter("extrafile"); if (!hash_binary_file(ctx, hash, path)) { - return nonstd::make_unexpected(Statistic::error_hashing_extra_file); + return tl::unexpected(Statistic::error_hashing_extra_file); } } } @@ -1584,7 +1582,7 @@ get_option_and_value(std::string_view option, const Args& args, size_t& i) } } -static nonstd::expected +static tl::expected hash_argument(const Context& ctx, const Args& args, size_t& i, @@ -1738,7 +1736,7 @@ hash_argument(const Context& ctx, if (eq_pos == std::string::npos) { if (i + 1 >= args.size()) { LOG("missing argument for \"{}\"", args[i]); - return nonstd::make_unexpected(Statistic::bad_compiler_arguments); + return tl::unexpected(Statistic::bad_compiler_arguments); } path = args[i + 1]; i++; @@ -1799,7 +1797,7 @@ hash_argument(const Context& ctx, return {}; } -static nonstd::expected, Failure> +static tl::expected, Failure> get_manifest_key(Context& ctx, Hash& hash) { // Hash environment variables that affect the preprocessor output. @@ -1836,7 +1834,7 @@ get_manifest_key(Context& ctx, Hash& hash) auto ret = hash_source_code_file(ctx, input_file_digest, ctx.args_info.input_file); if (ret.contains(HashSourceCode::error)) { - return nonstd::make_unexpected(Statistic::internal_error); + return tl::unexpected(Statistic::internal_error); } if (ret.contains(HashSourceCode::found_time)) { LOG_RAW("Disabling direct mode"); @@ -1884,7 +1882,7 @@ hash_profile_data_file(const Context& ctx, Hash& hash) return found; } -static nonstd::expected +static tl::expected hash_profiling_related_data(const Context& ctx, Hash& hash) { // For profile generation (-fprofile(-instr)-generate[=path]) @@ -1917,7 +1915,7 @@ hash_profiling_related_data(const Context& ctx, Hash& hash) if (ctx.args_info.profile_use && !hash_profile_data_file(ctx, hash)) { LOG_RAW("No profile data file found"); - return nonstd::make_unexpected(Statistic::no_input_file); + return tl::unexpected(Statistic::no_input_file); } return {}; @@ -1963,7 +1961,7 @@ get_result_key_from_manifest(Context& ctx, const Hash::Digest& manifest_key) // Update a hash sum with information specific to the direct and preprocessor // modes and calculate the result key. Returns the result key on success, and // if direct_mode is true also the manifest key. -static nonstd::expected< +static tl::expected< std::pair, std::optional>, Failure> calculate_result_and_manifest_key(Context& ctx, @@ -2029,7 +2027,7 @@ calculate_result_and_manifest_key(Context& ctx, if (direct_mode) { const auto manifest_key_result = get_manifest_key(ctx, hash); if (!manifest_key_result) { - return nonstd::make_unexpected(manifest_key_result.error()); + return tl::unexpected(manifest_key_result.error()); } manifest_key = *manifest_key_result; if (manifest_key) { @@ -2039,7 +2037,7 @@ calculate_result_and_manifest_key(Context& ctx, } else if (ctx.args_info.arch_args.empty()) { const auto digest = get_result_key_from_cpp(ctx, *preprocessor_args, hash); if (!digest) { - return nonstd::make_unexpected(digest.error()); + return tl::unexpected(digest.error()); } result_key = *digest; LOG_RAW("Got result key from preprocessor"); @@ -2060,7 +2058,7 @@ calculate_result_and_manifest_key(Context& ctx, const auto digest = get_result_key_from_cpp(ctx, *preprocessor_args, hash); if (!digest) { - return nonstd::make_unexpected(digest.error()); + return tl::unexpected(digest.error()); } result_key = *digest; LOG("Got result key from preprocessor with -arch {}", arch); @@ -2081,7 +2079,7 @@ calculate_result_and_manifest_key(Context& ctx, enum class FromCacheCallMode { direct, cpp }; // Try to return the compile result from cache. -static nonstd::expected +static tl::expected from_cache(Context& ctx, FromCacheCallMode mode, const Hash::Digest& result_key) { // The user might be disabling cache hits. @@ -2128,7 +2126,7 @@ from_cache(Context& ctx, FromCacheCallMode mode, const Hash::Digest& result_key) LOG("Write error when retrieving result from {}: {}", util::format_digest(result_key), e.what()); - return nonstd::make_unexpected(Statistic::bad_output_file); + return tl::unexpected(Statistic::bad_output_file); } catch (core::Error& e) { LOG("Failed to get result from {}: {}", util::format_digest(result_key), @@ -2229,14 +2227,14 @@ initialize(Context& ctx, const char* const* argv, bool masquerading_as_compiler) // Make a copy of stderr that will not be cached, so things like distcc can // send networking errors to it. -static nonstd::expected +static tl::expected set_up_uncached_err() { int uncached_fd = dup(STDERR_FILENO); // The file descriptor is intentionally leaked. if (uncached_fd == -1) { LOG("dup(2) failed: {}", strerror(errno)); - return nonstd::make_unexpected(Statistic::internal_error); + return tl::unexpected(Statistic::internal_error); } util::setenv("UNCACHED_ERR_FD", FMT("{}", uncached_fd)); @@ -2245,7 +2243,7 @@ set_up_uncached_err() static int cache_compilation(int argc, const char* const* argv); -static nonstd::expected +static tl::expected do_cache_compilation(Context& ctx); static void @@ -2405,17 +2403,17 @@ cache_compilation(int argc, const char* const* argv) return EXIT_SUCCESS; } -static nonstd::expected +static tl::expected do_cache_compilation(Context& ctx) { if (ctx.config.disable()) { LOG_RAW("ccache is disabled"); - return nonstd::make_unexpected(Statistic::none); + return tl::unexpected(Statistic::none); } if (ctx.actual_cwd.empty()) { LOG("Unable to determine current working directory: {}", strerror(errno)); - return nonstd::make_unexpected(Statistic::internal_error); + return tl::unexpected(Statistic::internal_error); } // Set CCACHE_DISABLE so no process ccache executes from now on will risk @@ -2429,7 +2427,7 @@ do_cache_compilation(Context& ctx) MTR_END("main", "process_args"); if (processed.error) { - return nonstd::make_unexpected(*processed.error); + return tl::unexpected(*processed.error); } TRY(set_up_uncached_err()); @@ -2526,7 +2524,7 @@ do_cache_compilation(Context& ctx) LOG("{} found in {}, disabling ccache", k_ccache_disable_token, ctx.args_info.input_file); - return nonstd::make_unexpected(Statistic::disabled); + return tl::unexpected(Statistic::disabled); } { @@ -2559,7 +2557,7 @@ do_cache_compilation(Context& ctx) ctx, args_to_hash, direct_hash, nullptr); MTR_END("hash", "direct_hash"); if (!result_and_manifest_key) { - return nonstd::make_unexpected(result_and_manifest_key.error()); + return tl::unexpected(result_and_manifest_key.error()); } std::tie(result_key, manifest_key) = *result_and_manifest_key; if (result_key) { @@ -2567,7 +2565,7 @@ do_cache_compilation(Context& ctx) const auto from_cache_result = from_cache(ctx, FromCacheCallMode::direct, *result_key); if (!from_cache_result) { - return nonstd::make_unexpected(from_cache_result.error()); + return tl::unexpected(from_cache_result.error()); } else if (*from_cache_result) { return Statistic::direct_cache_hit; } @@ -2589,7 +2587,7 @@ do_cache_compilation(Context& ctx) if (ctx.config.read_only_direct()) { LOG_RAW("Read-only direct mode; running real compiler"); - return nonstd::make_unexpected(Statistic::cache_miss); + return tl::unexpected(Statistic::cache_miss); } if (!ctx.config.depend_mode()) { @@ -2603,7 +2601,7 @@ do_cache_compilation(Context& ctx) ctx, args_to_hash, cpp_hash, &processed.preprocessor_args); MTR_END("hash", "cpp_hash"); if (!result_and_manifest_key) { - return nonstd::make_unexpected(result_and_manifest_key.error()); + return tl::unexpected(result_and_manifest_key.error()); } result_key = result_and_manifest_key->first; @@ -2636,7 +2634,7 @@ do_cache_compilation(Context& ctx) const auto from_cache_result = from_cache(ctx, FromCacheCallMode::cpp, *result_key); if (!from_cache_result) { - return nonstd::make_unexpected(from_cache_result.error()); + return tl::unexpected(from_cache_result.error()); } else if (*from_cache_result) { if (ctx.config.direct_mode() && manifest_key && put_result_in_manifest) { MTR_SCOPE("cache", "update_manifest"); @@ -2652,7 +2650,7 @@ do_cache_compilation(Context& ctx) if (ctx.config.read_only()) { LOG_RAW("Read-only mode; running real compiler"); - return nonstd::make_unexpected(Statistic::cache_miss); + return tl::unexpected(Statistic::cache_miss); } add_prefix(ctx, processed.compiler_args, ctx.config.prefix_command()); @@ -2669,7 +2667,7 @@ do_cache_compilation(Context& ctx) depend_mode_hash); MTR_END("cache", "to_cache"); if (!digest) { - return nonstd::make_unexpected(digest.error()); + return tl::unexpected(digest.error()); } result_key = *digest; if (ctx.config.direct_mode()) { diff --git a/src/core/mainoptions.cpp b/src/core/mainoptions.cpp index 09cff4225..d83940970 100644 --- a/src/core/mainoptions.cpp +++ b/src/core/mainoptions.cpp @@ -182,7 +182,7 @@ configuration_printer(const std::string& key, PRINT(stdout, "({}) {} = {}\n", origin, key, value); } -static nonstd::expected, std::string> +static tl::expected, std::string> read_from_path_or_stdin(const std::string& path) { if (path == "-") { @@ -192,15 +192,14 @@ read_from_path_or_stdin(const std::string& path) output.insert(output.end(), data.begin(), data.end()); }); if (!result) { - return nonstd::make_unexpected( + return tl::unexpected( FMT("Failed to read from stdin: {}", result.error())); } return output; } else { const auto result = util::read_file>(path); if (!result) { - return nonstd::make_unexpected( - FMT("Failed to read {}: {}", path, result.error())); + return tl::unexpected(FMT("Failed to read {}: {}", path, result.error())); } return *result; } diff --git a/src/storage/remote/FileStorage.cpp b/src/storage/remote/FileStorage.cpp index 57a511917..ca18dd9f6 100644 --- a/src/storage/remote/FileStorage.cpp +++ b/src/storage/remote/FileStorage.cpp @@ -47,14 +47,14 @@ class FileStorageBackend : public RemoteStorage::Backend public: FileStorageBackend(const Params& params); - nonstd::expected, Failure> + tl::expected, Failure> get(const Hash::Digest& key) override; - nonstd::expected put(const Hash::Digest& key, - nonstd::span value, - bool only_if_missing) override; + tl::expected put(const Hash::Digest& key, + nonstd::span value, + bool only_if_missing) override; - nonstd::expected remove(const Hash::Digest& key) override; + tl::expected remove(const Hash::Digest& key) override; private: enum class Layout { flat, subdirs }; @@ -111,7 +111,7 @@ FileStorageBackend::FileStorageBackend(const Params& params) } } -nonstd::expected, RemoteStorage::Backend::Failure> +tl::expected, RemoteStorage::Backend::Failure> FileStorageBackend::get(const Hash::Digest& key) { const auto path = get_entry_path(key); @@ -131,12 +131,12 @@ FileStorageBackend::get(const Hash::Digest& key) auto value = util::read_file(path); if (!value) { LOG("Failed to read {}: {}", path, value.error()); - return nonstd::make_unexpected(Failure::error); + return tl::unexpected(Failure::error); } return std::move(*value); } -nonstd::expected +tl::expected FileStorageBackend::put(const Hash::Digest& key, const nonstd::span value, const bool only_if_missing) @@ -154,7 +154,7 @@ FileStorageBackend::put(const Hash::Digest& key, const auto dir = Util::dir_name(path); if (auto result = fs::create_directories(dir); !result) { LOG("Failed to create directory {}: {}", dir, result.error().message()); - return nonstd::make_unexpected(Failure::error); + return tl::unexpected(Failure::error); } util::create_cachedir_tag(m_dir); @@ -167,19 +167,19 @@ FileStorageBackend::put(const Hash::Digest& key, return true; } catch (const core::Error& e) { LOG("Failed to write {}: {}", path, e.what()); - return nonstd::make_unexpected(Failure::error); + return tl::unexpected(Failure::error); } } } -nonstd::expected +tl::expected FileStorageBackend::remove(const Hash::Digest& key) { auto entry_path = get_entry_path(key); auto result = util::remove_nfs_safe(entry_path); if (!result) { LOG("Failed to remove {}: {}", entry_path, result.error().message()); - return nonstd::make_unexpected(RemoteStorage::Backend::Failure::error); + return tl::unexpected(RemoteStorage::Backend::Failure::error); } return *result; } diff --git a/src/storage/remote/HttpStorage.cpp b/src/storage/remote/HttpStorage.cpp index 84787de9b..a92500799 100644 --- a/src/storage/remote/HttpStorage.cpp +++ b/src/storage/remote/HttpStorage.cpp @@ -42,14 +42,14 @@ class HttpStorageBackend : public RemoteStorage::Backend public: HttpStorageBackend(const Params& params); - nonstd::expected, Failure> + tl::expected, Failure> get(const Hash::Digest& key) override; - nonstd::expected put(const Hash::Digest& key, - nonstd::span value, - bool only_if_missing) override; + tl::expected put(const Hash::Digest& key, + nonstd::span value, + bool only_if_missing) override; - nonstd::expected remove(const Hash::Digest& key) override; + tl::expected remove(const Hash::Digest& key) override; private: enum class Layout { bazel, flat, subdirs }; @@ -153,7 +153,7 @@ HttpStorageBackend::HttpStorageBackend(const Params& params) m_http_client.set_write_timeout(operation_timeout); } -nonstd::expected, RemoteStorage::Backend::Failure> +tl::expected, RemoteStorage::Backend::Failure> HttpStorageBackend::get(const Hash::Digest& key) { const auto url_path = get_entry_path(key); @@ -164,7 +164,7 @@ HttpStorageBackend::get(const Hash::Digest& key) url_path, to_string(result.error()), static_cast(result.error())); - return nonstd::make_unexpected(failure_from_httplib_error(result.error())); + return tl::unexpected(failure_from_httplib_error(result.error())); } if (result->status < 200 || result->status >= 300) { @@ -175,7 +175,7 @@ HttpStorageBackend::get(const Hash::Digest& key) return util::Bytes(result->body.data(), result->body.size()); } -nonstd::expected +tl::expected HttpStorageBackend::put(const Hash::Digest& key, const nonstd::span value, const bool only_if_missing) @@ -190,8 +190,7 @@ HttpStorageBackend::put(const Hash::Digest& key, url_path, to_string(result.error()), static_cast(result.error())); - return nonstd::make_unexpected( - failure_from_httplib_error(result.error())); + return tl::unexpected(failure_from_httplib_error(result.error())); } if (result->status >= 200 && result->status < 300) { @@ -214,20 +213,20 @@ HttpStorageBackend::put(const Hash::Digest& key, url_path, to_string(result.error()), static_cast(result.error())); - return nonstd::make_unexpected(failure_from_httplib_error(result.error())); + return tl::unexpected(failure_from_httplib_error(result.error())); } if (result->status < 200 || result->status >= 300) { LOG("Failed to put {} to http storage: status code: {}", url_path, result->status); - return nonstd::make_unexpected(failure_from_httplib_error(result.error())); + return tl::unexpected(failure_from_httplib_error(result.error())); } return true; } -nonstd::expected +tl::expected HttpStorageBackend::remove(const Hash::Digest& key) { const auto url_path = get_entry_path(key); @@ -238,14 +237,14 @@ HttpStorageBackend::remove(const Hash::Digest& key) url_path, to_string(result.error()), static_cast(result.error())); - return nonstd::make_unexpected(failure_from_httplib_error(result.error())); + return tl::unexpected(failure_from_httplib_error(result.error())); } if (result->status < 200 || result->status >= 300) { LOG("Failed to delete {} from http storage: status code: {}", url_path, result->status); - return nonstd::make_unexpected(failure_from_httplib_error(result.error())); + return tl::unexpected(failure_from_httplib_error(result.error())); } return true; diff --git a/src/storage/remote/RedisStorage.cpp b/src/storage/remote/RedisStorage.cpp index ad1587df7..42fefecd3 100644 --- a/src/storage/remote/RedisStorage.cpp +++ b/src/storage/remote/RedisStorage.cpp @@ -66,14 +66,14 @@ class RedisStorageBackend : public RemoteStorage::Backend public: RedisStorageBackend(const RemoteStorage::Backend::Params& params); - nonstd::expected, Failure> + tl::expected, Failure> get(const Hash::Digest& key) override; - nonstd::expected put(const Hash::Digest& key, - nonstd::span value, - bool only_if_missing) override; + tl::expected put(const Hash::Digest& key, + nonstd::span value, + bool only_if_missing) override; - nonstd::expected remove(const Hash::Digest& key) override; + tl::expected remove(const Hash::Digest& key) override; private: const std::string m_prefix; @@ -83,7 +83,7 @@ private: connect(const Url& url, uint32_t connect_timeout, uint32_t operation_timeout); void select_database(const Url& url); void authenticate(const Url& url); - nonstd::expected redis_command(const char* format, ...); + tl::expected redis_command(const char* format, ...); std::string get_key_string(const Hash::Digest& digest) const; }; @@ -163,25 +163,25 @@ is_timeout(int err) #endif } -nonstd::expected, RemoteStorage::Backend::Failure> +tl::expected, RemoteStorage::Backend::Failure> RedisStorageBackend::get(const Hash::Digest& key) { const auto key_string = get_key_string(key); LOG("Redis GET {}", key_string); const auto reply = redis_command("GET %s", key_string.c_str()); if (!reply) { - return nonstd::make_unexpected(reply.error()); + return tl::unexpected(reply.error()); } else if ((*reply)->type == REDIS_REPLY_STRING) { return util::Bytes((*reply)->str, (*reply)->len); } else if ((*reply)->type == REDIS_REPLY_NIL) { return std::nullopt; } else { LOG("Unknown reply type: {}", (*reply)->type); - return nonstd::make_unexpected(Failure::error); + return tl::unexpected(Failure::error); } } -nonstd::expected +tl::expected RedisStorageBackend::put(const Hash::Digest& key, nonstd::span value, bool only_if_missing) @@ -192,7 +192,7 @@ RedisStorageBackend::put(const Hash::Digest& key, LOG("Redis EXISTS {}", key_string); const auto reply = redis_command("EXISTS %s", key_string.c_str()); if (!reply) { - return nonstd::make_unexpected(reply.error()); + return tl::unexpected(reply.error()); } else if ((*reply)->type != REDIS_REPLY_INTEGER) { LOG("Unknown reply type: {}", (*reply)->type); } else if ((*reply)->integer > 0) { @@ -205,28 +205,28 @@ RedisStorageBackend::put(const Hash::Digest& key, const auto reply = redis_command("SET %s %b", key_string.c_str(), value.data(), value.size()); if (!reply) { - return nonstd::make_unexpected(reply.error()); + return tl::unexpected(reply.error()); } else if ((*reply)->type == REDIS_REPLY_STATUS) { return true; } else { LOG("Unknown reply type: {}", (*reply)->type); - return nonstd::make_unexpected(Failure::error); + return tl::unexpected(Failure::error); } } -nonstd::expected +tl::expected RedisStorageBackend::remove(const Hash::Digest& key) { const auto key_string = get_key_string(key); LOG("Redis DEL {}", key_string); const auto reply = redis_command("DEL %s", key_string.c_str()); if (!reply) { - return nonstd::make_unexpected(reply.error()); + return tl::unexpected(reply.error()); } else if ((*reply)->type == REDIS_REPLY_INTEGER) { return (*reply)->integer > 0; } else { LOG("Unknown reply type: {}", (*reply)->type); - return nonstd::make_unexpected(Failure::error); + return tl::unexpected(Failure::error); } } @@ -320,7 +320,7 @@ RedisStorageBackend::authenticate(const Url& url) } } -nonstd::expected +tl::expected RedisStorageBackend::redis_command(const char* format, ...) { va_list ap; @@ -330,11 +330,11 @@ RedisStorageBackend::redis_command(const char* format, ...) va_end(ap); if (!reply) { LOG("Redis command failed: {}", m_context->errstr); - return nonstd::make_unexpected(is_timeout(m_context->err) ? Failure::timeout - : Failure::error); + return tl::unexpected(is_timeout(m_context->err) ? Failure::timeout + : Failure::error); } else if (reply->type == REDIS_REPLY_ERROR) { LOG("Redis command failed: {}", reply->str); - return nonstd::make_unexpected(Failure::error); + return tl::unexpected(Failure::error); } else { return RedisReply(reply, freeReplyObject); } diff --git a/src/storage/remote/RemoteStorage.hpp b/src/storage/remote/RemoteStorage.hpp index 5e93da362..d71f60ba1 100644 --- a/src/storage/remote/RemoteStorage.hpp +++ b/src/storage/remote/RemoteStorage.hpp @@ -22,8 +22,8 @@ #include #include -#include #include +#include #include #include @@ -79,20 +79,19 @@ public: // Get the value associated with `key`. Returns the value on success or // std::nullopt if the entry is not present. - virtual nonstd::expected, Failure> + virtual tl::expected, Failure> get(const Hash::Digest& key) = 0; // Put `value` associated to `key` in the storage. A true `only_if_missing` // is a hint that the value does not have to be set if already present. // Returns true if the entry was stored, otherwise false. - virtual nonstd::expected - put(const Hash::Digest& key, - nonstd::span value, - bool only_if_missing = false) = 0; + virtual tl::expected put(const Hash::Digest& key, + nonstd::span value, + bool only_if_missing = false) = 0; // Remove `key` and its associated value. Returns true if the entry was // removed, otherwise false. - virtual nonstd::expected remove(const Hash::Digest& key) = 0; + virtual tl::expected remove(const Hash::Digest& key) = 0; // Determine whether an attribute is handled by the remote storage // framework itself. diff --git a/src/third_party/nonstd/expected.hpp b/src/third_party/nonstd/expected.hpp deleted file mode 100644 index f2b7f9402..000000000 --- a/src/third_party/nonstd/expected.hpp +++ /dev/null @@ -1,2520 +0,0 @@ -// This version targets C++11 and later. -// -// Copyright (C) 2016-2020 Martin Moene. -// -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// expected lite is based on: -// A proposal to add a utility class to represent expected monad -// by Vicente J. Botet Escriba and Pierre Talbot. http:://wg21.link/p0323 - -#ifndef NONSTD_EXPECTED_LITE_HPP -#define NONSTD_EXPECTED_LITE_HPP - -#define expected_lite_MAJOR 0 -#define expected_lite_MINOR 6 -#define expected_lite_PATCH 2 - -#define expected_lite_VERSION expected_STRINGIFY(expected_lite_MAJOR) "." expected_STRINGIFY(expected_lite_MINOR) "." expected_STRINGIFY(expected_lite_PATCH) - -#define expected_STRINGIFY( x ) expected_STRINGIFY_( x ) -#define expected_STRINGIFY_( x ) #x - -// expected-lite configuration: - -#define nsel_EXPECTED_DEFAULT 0 -#define nsel_EXPECTED_NONSTD 1 -#define nsel_EXPECTED_STD 2 - -// tweak header support: - -#ifdef __has_include -# if __has_include() -# include -# endif -#define expected_HAVE_TWEAK_HEADER 1 -#else -#define expected_HAVE_TWEAK_HEADER 0 -//# pragma message("expected.hpp: Note: Tweak header not supported.") -#endif - -// expected selection and configuration: - -#if !defined( nsel_CONFIG_SELECT_EXPECTED ) -# define nsel_CONFIG_SELECT_EXPECTED ( nsel_HAVE_STD_EXPECTED ? nsel_EXPECTED_STD : nsel_EXPECTED_NONSTD ) -#endif - -// Proposal revisions: -// -// DXXXXR0: -- -// N4015 : -2 (2014-05-26) -// N4109 : -1 (2014-06-29) -// P0323R0: 0 (2016-05-28) -// P0323R1: 1 (2016-10-12) -// -------: -// P0323R2: 2 (2017-06-15) -// P0323R3: 3 (2017-10-15) -// P0323R4: 4 (2017-11-26) -// P0323R5: 5 (2018-02-08) -// P0323R6: 6 (2018-04-02) -// P0323R7: 7 (2018-06-22) * -// -// expected-lite uses 2 and higher - -#ifndef nsel_P0323R -# define nsel_P0323R 7 -#endif - -// Control presence of C++ exception handling (try and auto discover): - -#ifndef nsel_CONFIG_NO_EXCEPTIONS -# if defined(_MSC_VER) -# include // for _HAS_EXCEPTIONS -# endif -# if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (_HAS_EXCEPTIONS) -# define nsel_CONFIG_NO_EXCEPTIONS 0 -# else -# define nsel_CONFIG_NO_EXCEPTIONS 1 -# endif -#endif - -// at default use SEH with MSVC for no C++ exceptions - -#ifndef nsel_CONFIG_NO_EXCEPTIONS_SEH -# define nsel_CONFIG_NO_EXCEPTIONS_SEH ( nsel_CONFIG_NO_EXCEPTIONS && _MSC_VER ) -#endif - -// C++ language version detection (C++23 is speculative): -// Note: VC14.0/1900 (VS2015) lacks too much from C++14. - -#ifndef nsel_CPLUSPLUS -# if defined(_MSVC_LANG ) && !defined(__clang__) -# define nsel_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) -# else -# define nsel_CPLUSPLUS __cplusplus -# endif -#endif - -#define nsel_CPP98_OR_GREATER ( nsel_CPLUSPLUS >= 199711L ) -#define nsel_CPP11_OR_GREATER ( nsel_CPLUSPLUS >= 201103L ) -#define nsel_CPP14_OR_GREATER ( nsel_CPLUSPLUS >= 201402L ) -#define nsel_CPP17_OR_GREATER ( nsel_CPLUSPLUS >= 201703L ) -#define nsel_CPP20_OR_GREATER ( nsel_CPLUSPLUS >= 202002L ) -#define nsel_CPP23_OR_GREATER ( nsel_CPLUSPLUS >= 202300L ) - -// Use C++23 std::expected if available and requested: - -#if nsel_CPP23_OR_GREATER && defined(__has_include ) -# if __has_include( ) -# define nsel_HAVE_STD_EXPECTED 1 -# else -# define nsel_HAVE_STD_EXPECTED 0 -# endif -#else -# define nsel_HAVE_STD_EXPECTED 0 -#endif - -#define nsel_USES_STD_EXPECTED ( (nsel_CONFIG_SELECT_EXPECTED == nsel_EXPECTED_STD) || ((nsel_CONFIG_SELECT_EXPECTED == nsel_EXPECTED_DEFAULT) && nsel_HAVE_STD_EXPECTED) ) - -// -// in_place: code duplicated in any-lite, expected-lite, expected-lite, value-ptr-lite, variant-lite: -// - -#ifndef nonstd_lite_HAVE_IN_PLACE_TYPES -#define nonstd_lite_HAVE_IN_PLACE_TYPES 1 - -// C++17 std::in_place in : - -#if nsel_CPP17_OR_GREATER - -#include - -namespace nonstd { - -using std::in_place; -using std::in_place_type; -using std::in_place_index; -using std::in_place_t; -using std::in_place_type_t; -using std::in_place_index_t; - -#define nonstd_lite_in_place_t( T) std::in_place_t -#define nonstd_lite_in_place_type_t( T) std::in_place_type_t -#define nonstd_lite_in_place_index_t(K) std::in_place_index_t - -#define nonstd_lite_in_place( T) std::in_place_t{} -#define nonstd_lite_in_place_type( T) std::in_place_type_t{} -#define nonstd_lite_in_place_index(K) std::in_place_index_t{} - -} // namespace nonstd - -#else // nsel_CPP17_OR_GREATER - -#include - -namespace nonstd { -namespace detail { - -template< class T > -struct in_place_type_tag {}; - -template< std::size_t K > -struct in_place_index_tag {}; - -} // namespace detail - -struct in_place_t {}; - -template< class T > -inline in_place_t in_place( detail::in_place_type_tag = detail::in_place_type_tag() ) -{ - return in_place_t(); -} - -template< std::size_t K > -inline in_place_t in_place( detail::in_place_index_tag = detail::in_place_index_tag() ) -{ - return in_place_t(); -} - -template< class T > -inline in_place_t in_place_type( detail::in_place_type_tag = detail::in_place_type_tag() ) -{ - return in_place_t(); -} - -template< std::size_t K > -inline in_place_t in_place_index( detail::in_place_index_tag = detail::in_place_index_tag() ) -{ - return in_place_t(); -} - -// mimic templated typedef: - -#define nonstd_lite_in_place_t( T) nonstd::in_place_t(&)( nonstd::detail::in_place_type_tag ) -#define nonstd_lite_in_place_type_t( T) nonstd::in_place_t(&)( nonstd::detail::in_place_type_tag ) -#define nonstd_lite_in_place_index_t(K) nonstd::in_place_t(&)( nonstd::detail::in_place_index_tag ) - -#define nonstd_lite_in_place( T) nonstd::in_place_type -#define nonstd_lite_in_place_type( T) nonstd::in_place_type -#define nonstd_lite_in_place_index(K) nonstd::in_place_index - -} // namespace nonstd - -#endif // nsel_CPP17_OR_GREATER -#endif // nonstd_lite_HAVE_IN_PLACE_TYPES - -// -// Using std::expected: -// - -#if nsel_USES_STD_EXPECTED - -#include - -namespace nonstd { - - using std::expected; -// ... -} - -#else // nsel_USES_STD_EXPECTED - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// additional includes: - -#if nsel_CONFIG_NO_EXCEPTIONS -# if nsel_CONFIG_NO_EXCEPTIONS_SEH -# include // for ExceptionCodes -# else -// already included: -# endif -#else -# include -#endif - -// C++ feature usage: - -#if nsel_CPP11_OR_GREATER -# define nsel_constexpr constexpr -#else -# define nsel_constexpr /*constexpr*/ -#endif - -#if nsel_CPP14_OR_GREATER -# define nsel_constexpr14 constexpr -#else -# define nsel_constexpr14 /*constexpr*/ -#endif - -#if nsel_CPP17_OR_GREATER -# define nsel_inline17 inline -#else -# define nsel_inline17 /*inline*/ -#endif - -// Compiler versions: -// -// MSVC++ 6.0 _MSC_VER == 1200 nsel_COMPILER_MSVC_VERSION == 60 (Visual Studio 6.0) -// MSVC++ 7.0 _MSC_VER == 1300 nsel_COMPILER_MSVC_VERSION == 70 (Visual Studio .NET 2002) -// MSVC++ 7.1 _MSC_VER == 1310 nsel_COMPILER_MSVC_VERSION == 71 (Visual Studio .NET 2003) -// MSVC++ 8.0 _MSC_VER == 1400 nsel_COMPILER_MSVC_VERSION == 80 (Visual Studio 2005) -// MSVC++ 9.0 _MSC_VER == 1500 nsel_COMPILER_MSVC_VERSION == 90 (Visual Studio 2008) -// MSVC++ 10.0 _MSC_VER == 1600 nsel_COMPILER_MSVC_VERSION == 100 (Visual Studio 2010) -// MSVC++ 11.0 _MSC_VER == 1700 nsel_COMPILER_MSVC_VERSION == 110 (Visual Studio 2012) -// MSVC++ 12.0 _MSC_VER == 1800 nsel_COMPILER_MSVC_VERSION == 120 (Visual Studio 2013) -// MSVC++ 14.0 _MSC_VER == 1900 nsel_COMPILER_MSVC_VERSION == 140 (Visual Studio 2015) -// MSVC++ 14.1 _MSC_VER >= 1910 nsel_COMPILER_MSVC_VERSION == 141 (Visual Studio 2017) -// MSVC++ 14.2 _MSC_VER >= 1920 nsel_COMPILER_MSVC_VERSION == 142 (Visual Studio 2019) - -#if defined(_MSC_VER) && !defined(__clang__) -# define nsel_COMPILER_MSVC_VER (_MSC_VER ) -# define nsel_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900)) ) -#else -# define nsel_COMPILER_MSVC_VER 0 -# define nsel_COMPILER_MSVC_VERSION 0 -#endif - -#define nsel_COMPILER_VERSION( major, minor, patch ) ( 10 * ( 10 * (major) + (minor) ) + (patch) ) - -#if defined(__clang__) -# define nsel_COMPILER_CLANG_VERSION nsel_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) -#else -# define nsel_COMPILER_CLANG_VERSION 0 -#endif - -#if defined(__GNUC__) && !defined(__clang__) -# define nsel_COMPILER_GNUC_VERSION nsel_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) -#else -# define nsel_COMPILER_GNUC_VERSION 0 -#endif - -// half-open range [lo..hi): -//#define nsel_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) - -// Method enabling - -#define nsel_REQUIRES_0(...) \ - template< bool B = (__VA_ARGS__), typename std::enable_if::type = 0 > - -#define nsel_REQUIRES_T(...) \ - , typename std::enable_if< (__VA_ARGS__), int >::type = 0 - -#define nsel_REQUIRES_R(R, ...) \ - typename std::enable_if< (__VA_ARGS__), R>::type - -#define nsel_REQUIRES_A(...) \ - , typename std::enable_if< (__VA_ARGS__), void*>::type = nullptr - -// Presence of language and library features: - -#ifdef _HAS_CPP0X -# define nsel_HAS_CPP0X _HAS_CPP0X -#else -# define nsel_HAS_CPP0X 0 -#endif - -//#define nsel_CPP11_140 (nsel_CPP11_OR_GREATER || nsel_COMPILER_MSVC_VER >= 1900) - -// Clang, GNUC, MSVC warning suppression macros: - -#ifdef __clang__ -# pragma clang diagnostic push -#elif defined __GNUC__ -# pragma GCC diagnostic push -#endif // __clang__ - -#if nsel_COMPILER_MSVC_VERSION >= 140 -# pragma warning( push ) -# define nsel_DISABLE_MSVC_WARNINGS(codes) __pragma( warning(disable: codes) ) -#else -# define nsel_DISABLE_MSVC_WARNINGS(codes) -#endif - -#ifdef __clang__ -# define nsel_RESTORE_WARNINGS() _Pragma("clang diagnostic pop") -#elif defined __GNUC__ -# define nsel_RESTORE_WARNINGS() _Pragma("GCC diagnostic pop") -#elif nsel_COMPILER_MSVC_VERSION >= 140 -# define nsel_RESTORE_WARNINGS() __pragma( warning( pop ) ) -#else -# define nsel_RESTORE_WARNINGS() -#endif - -// Suppress the following MSVC (GSL) warnings: -// - C26409: Avoid calling new and delete explicitly, use std::make_unique instead (r.11) - -nsel_DISABLE_MSVC_WARNINGS( 26409 ) - -// -// expected: -// - -namespace nonstd { namespace expected_lite { - -// type traits C++17: - -namespace std17 { - -#if nsel_CPP17_OR_GREATER - -using std::conjunction; -using std::is_swappable; -using std::is_nothrow_swappable; - -#else // nsel_CPP17_OR_GREATER - -namespace detail { - -using std::swap; - -struct is_swappable -{ - template< typename T, typename = decltype( swap( std::declval(), std::declval() ) ) > - static std::true_type test( int /* unused */); - - template< typename > - static std::false_type test(...); -}; - -struct is_nothrow_swappable -{ - // wrap noexcept(expr) in separate function as work-around for VC140 (VS2015): - - template< typename T > - static constexpr bool satisfies() - { - return noexcept( swap( std::declval(), std::declval() ) ); - } - - template< typename T > - static auto test( int ) -> std::integral_constant()>{} - - template< typename > - static auto test(...) -> std::false_type; -}; -} // namespace detail - -// is [nothow] swappable: - -template< typename T > -struct is_swappable : decltype( detail::is_swappable::test(0) ){}; - -template< typename T > -struct is_nothrow_swappable : decltype( detail::is_nothrow_swappable::test(0) ){}; - -// conjunction: - -template< typename... > struct conjunction : std::true_type{}; -template< typename B1 > struct conjunction : B1{}; - -template< typename B1, typename... Bn > -struct conjunction : std::conditional, B1>::type{}; - -#endif // nsel_CPP17_OR_GREATER - -} // namespace std17 - -// type traits C++20: - -namespace std20 { - -#if defined(__cpp_lib_remove_cvref) - -using std::remove_cvref; - -#else - -template< typename T > -struct remove_cvref -{ - typedef typename std::remove_cv< typename std::remove_reference::type >::type type; -}; - -#endif - -} // namespace std20 - -// forward declaration: - -template< typename T, typename E > -class expected; - -namespace detail { - -/// discriminated union to hold value or 'error'. - -template< typename T, typename E > -class storage_t_impl -{ - template< typename, typename > friend class nonstd::expected_lite::expected; - -public: - using value_type = T; - using error_type = E; - - // no-op construction - storage_t_impl() {} - ~storage_t_impl() {} - - explicit storage_t_impl( bool has_value ) - : m_has_value( has_value ) - {} - - void construct_value( value_type const & e ) - { - new( &m_value ) value_type( e ); - } - - void construct_value( value_type && e ) - { - new( &m_value ) value_type( std::move( e ) ); - } - - template< class... Args > - void emplace_value( Args&&... args ) - { - new( &m_value ) value_type( std::forward(args)...); - } - - template< class U, class... Args > - void emplace_value( std::initializer_list il, Args&&... args ) - { - new( &m_value ) value_type( il, std::forward(args)... ); - } - - void destruct_value() - { - m_value.~value_type(); - } - - void construct_error( error_type const & e ) - { - new( &m_error ) error_type( e ); - } - - void construct_error( error_type && e ) - { - new( &m_error ) error_type( std::move( e ) ); - } - - template< class... Args > - void emplace_error( Args&&... args ) - { - new( &m_error ) error_type( std::forward(args)...); - } - - template< class U, class... Args > - void emplace_error( std::initializer_list il, Args&&... args ) - { - new( &m_error ) error_type( il, std::forward(args)... ); - } - - void destruct_error() - { - m_error.~error_type(); - } - - constexpr value_type const & value() const & - { - return m_value; - } - - value_type & value() & - { - return m_value; - } - - constexpr value_type const && value() const && - { - return std::move( m_value ); - } - - nsel_constexpr14 value_type && value() && - { - return std::move( m_value ); - } - - value_type const * value_ptr() const - { - return &m_value; - } - - value_type * value_ptr() - { - return &m_value; - } - - error_type const & error() const & - { - return m_error; - } - - error_type & error() & - { - return m_error; - } - - constexpr error_type const && error() const && - { - return std::move( m_error ); - } - - nsel_constexpr14 error_type && error() && - { - return std::move( m_error ); - } - - bool has_value() const - { - return m_has_value; - } - - void set_has_value( bool v ) - { - m_has_value = v; - } - -private: - union - { - value_type m_value; - error_type m_error; - }; - - bool m_has_value = false; -}; - -/// discriminated union to hold only 'error'. - -template< typename E > -struct storage_t_impl -{ - template< typename, typename > friend class nonstd::expected_lite::expected; - -public: - using value_type = void; - using error_type = E; - - // no-op construction - storage_t_impl() {} - ~storage_t_impl() {} - - explicit storage_t_impl( bool has_value ) - : m_has_value( has_value ) - {} - - void construct_error( error_type const & e ) - { - new( &m_error ) error_type( e ); - } - - void construct_error( error_type && e ) - { - new( &m_error ) error_type( std::move( e ) ); - } - - template< class... Args > - void emplace_error( Args&&... args ) - { - new( &m_error ) error_type( std::forward(args)...); - } - - template< class U, class... Args > - void emplace_error( std::initializer_list il, Args&&... args ) - { - new( &m_error ) error_type( il, std::forward(args)... ); - } - - void destruct_error() - { - m_error.~error_type(); - } - - error_type const & error() const & - { - return m_error; - } - - error_type & error() & - { - return m_error; - } - - constexpr error_type const && error() const && - { - return std::move( m_error ); - } - - nsel_constexpr14 error_type && error() && - { - return std::move( m_error ); - } - - bool has_value() const - { - return m_has_value; - } - - void set_has_value( bool v ) - { - m_has_value = v; - } - -private: - union - { - char m_dummy; - error_type m_error; - }; - - bool m_has_value = false; -}; - -template< typename T, typename E, bool isConstructable, bool isMoveable > -class storage_t -{ -public: - storage_t() = default; - ~storage_t() = default; - - explicit storage_t( bool has_value ) - : storage_t_impl( has_value ) - {} - - storage_t( storage_t const & other ) = delete; - storage_t( storage_t && other ) = delete; -}; - -template< typename T, typename E > -class storage_t : public storage_t_impl -{ -public: - storage_t() = default; - ~storage_t() = default; - - explicit storage_t( bool has_value ) - : storage_t_impl( has_value ) - {} - - storage_t( storage_t const & other ) - : storage_t_impl( other.has_value() ) - { - if ( this->has_value() ) this->construct_value( other.value() ); - else this->construct_error( other.error() ); - } - - storage_t(storage_t && other ) - : storage_t_impl( other.has_value() ) - { - if ( this->has_value() ) this->construct_value( std::move( other.value() ) ); - else this->construct_error( std::move( other.error() ) ); - } -}; - -template< typename E > -class storage_t : public storage_t_impl -{ -public: - storage_t() = default; - ~storage_t() = default; - - explicit storage_t( bool has_value ) - : storage_t_impl( has_value ) - {} - - storage_t( storage_t const & other ) - : storage_t_impl( other.has_value() ) - { - if ( this->has_value() ) ; - else this->construct_error( other.error() ); - } - - storage_t(storage_t && other ) - : storage_t_impl( other.has_value() ) - { - if ( this->has_value() ) ; - else this->construct_error( std::move( other.error() ) ); - } -}; - -template< typename T, typename E > -class storage_t : public storage_t_impl -{ -public: - storage_t() = default; - ~storage_t() = default; - - explicit storage_t( bool has_value ) - : storage_t_impl( has_value ) - {} - - storage_t( storage_t const & other ) - : storage_t_impl(other.has_value()) - { - if ( this->has_value() ) this->construct_value( other.value() ); - else this->construct_error( other.error() ); - } - - storage_t( storage_t && other ) = delete; -}; - -template< typename E > -class storage_t : public storage_t_impl -{ -public: - storage_t() = default; - ~storage_t() = default; - - explicit storage_t( bool has_value ) - : storage_t_impl( has_value ) - {} - - storage_t( storage_t const & other ) - : storage_t_impl(other.has_value()) - { - if ( this->has_value() ) ; - else this->construct_error( other.error() ); - } - - storage_t( storage_t && other ) = delete; -}; - -template< typename T, typename E > -class storage_t : public storage_t_impl -{ -public: - storage_t() = default; - ~storage_t() = default; - - explicit storage_t( bool has_value ) - : storage_t_impl( has_value ) - {} - - storage_t( storage_t const & other ) = delete; - - storage_t( storage_t && other ) - : storage_t_impl( other.has_value() ) - { - if ( this->has_value() ) this->construct_value( std::move( other.value() ) ); - else this->construct_error( std::move( other.error() ) ); - } -}; - -template< typename E > -class storage_t : public storage_t_impl -{ -public: - storage_t() = default; - ~storage_t() = default; - - explicit storage_t( bool has_value ) - : storage_t_impl( has_value ) - {} - - storage_t( storage_t const & other ) = delete; - - storage_t( storage_t && other ) - : storage_t_impl( other.has_value() ) - { - if ( this->has_value() ) ; - else this->construct_error( std::move( other.error() ) ); - } -}; - -} // namespace detail - -/// x.x.5 Unexpected object type; unexpected_type; C++17 and later can also use aliased type unexpected. - -#if nsel_P0323R <= 2 -template< typename E = std::exception_ptr > -class unexpected_type -#else -template< typename E > -class unexpected_type -#endif // nsel_P0323R -{ -public: - using error_type = E; - - // x.x.5.2.1 Constructors - -// unexpected_type() = delete; - - constexpr unexpected_type( unexpected_type const & ) = default; - constexpr unexpected_type( unexpected_type && ) = default; - - template< typename... Args - nsel_REQUIRES_T( - std::is_constructible::value - ) - > - constexpr explicit unexpected_type( nonstd_lite_in_place_t(E), Args &&... args ) - : m_error( std::forward( args )...) - {} - - template< typename U, typename... Args - nsel_REQUIRES_T( - std::is_constructible, Args&&...>::value - ) - > - constexpr explicit unexpected_type( nonstd_lite_in_place_t(E), std::initializer_list il, Args &&... args ) - : m_error( il, std::forward( args )...) - {} - - template< typename E2 - nsel_REQUIRES_T( - std::is_constructible::value - && !std::is_same< typename std20::remove_cvref::type, nonstd_lite_in_place_t(E2) >::value - && !std::is_same< typename std20::remove_cvref::type, unexpected_type >::value - ) - > - constexpr explicit unexpected_type( E2 && error ) - : m_error( std::forward( error ) ) - {} - - template< typename E2 - nsel_REQUIRES_T( - std::is_constructible< E, E2>::value - && !std::is_constructible & >::value - && !std::is_constructible >::value - && !std::is_constructible const & >::value - && !std::is_constructible const >::value - && !std::is_convertible< unexpected_type &, E>::value - && !std::is_convertible< unexpected_type , E>::value - && !std::is_convertible< unexpected_type const &, E>::value - && !std::is_convertible< unexpected_type const , E>::value - && !std::is_convertible< E2 const &, E>::value /*=> explicit */ - ) - > - constexpr explicit unexpected_type( unexpected_type const & error ) - : m_error( E{ error.value() } ) - {} - - template< typename E2 - nsel_REQUIRES_T( - std::is_constructible< E, E2>::value - && !std::is_constructible & >::value - && !std::is_constructible >::value - && !std::is_constructible const & >::value - && !std::is_constructible const >::value - && !std::is_convertible< unexpected_type &, E>::value - && !std::is_convertible< unexpected_type , E>::value - && !std::is_convertible< unexpected_type const &, E>::value - && !std::is_convertible< unexpected_type const , E>::value - && std::is_convertible< E2 const &, E>::value /*=> explicit */ - ) - > - constexpr /*non-explicit*/ unexpected_type( unexpected_type const & error ) - : m_error( error.value() ) - {} - - template< typename E2 - nsel_REQUIRES_T( - std::is_constructible< E, E2>::value - && !std::is_constructible & >::value - && !std::is_constructible >::value - && !std::is_constructible const & >::value - && !std::is_constructible const >::value - && !std::is_convertible< unexpected_type &, E>::value - && !std::is_convertible< unexpected_type , E>::value - && !std::is_convertible< unexpected_type const &, E>::value - && !std::is_convertible< unexpected_type const , E>::value - && !std::is_convertible< E2 const &, E>::value /*=> explicit */ - ) - > - constexpr explicit unexpected_type( unexpected_type && error ) - : m_error( E{ std::move( error.value() ) } ) - {} - - template< typename E2 - nsel_REQUIRES_T( - std::is_constructible< E, E2>::value - && !std::is_constructible & >::value - && !std::is_constructible >::value - && !std::is_constructible const & >::value - && !std::is_constructible const >::value - && !std::is_convertible< unexpected_type &, E>::value - && !std::is_convertible< unexpected_type , E>::value - && !std::is_convertible< unexpected_type const &, E>::value - && !std::is_convertible< unexpected_type const , E>::value - && std::is_convertible< E2 const &, E>::value /*=> non-explicit */ - ) - > - constexpr /*non-explicit*/ unexpected_type( unexpected_type && error ) - : m_error( std::move( error.value() ) ) - {} - - // x.x.5.2.2 Assignment - - nsel_constexpr14 unexpected_type& operator=( unexpected_type const & ) = default; - nsel_constexpr14 unexpected_type& operator=( unexpected_type && ) = default; - - template< typename E2 = E > - nsel_constexpr14 unexpected_type & operator=( unexpected_type const & other ) - { - unexpected_type{ other.value() }.swap( *this ); - return *this; - } - - template< typename E2 = E > - nsel_constexpr14 unexpected_type & operator=( unexpected_type && other ) - { - unexpected_type{ std::move( other.value() ) }.swap( *this ); - return *this; - } - - // x.x.5.2.3 Observers - - nsel_constexpr14 E & value() & noexcept - { - return m_error; - } - - constexpr E const & value() const & noexcept - { - return m_error; - } - -#if !nsel_COMPILER_GNUC_VERSION || nsel_COMPILER_GNUC_VERSION >= 490 - - nsel_constexpr14 E && value() && noexcept - { - return std::move( m_error ); - } - - constexpr E const && value() const && noexcept - { - return std::move( m_error ); - } - -#endif - - // x.x.5.2.4 Swap - - nsel_REQUIRES_R( void, - std17::is_swappable::value - ) - swap( unexpected_type & other ) noexcept ( - std17::is_nothrow_swappable::value - ) - { - using std::swap; - swap( m_error, other.m_error ); - } - - // TODO: ??? unexpected_type: in-class friend operator==, != - -private: - error_type m_error; -}; - -#if nsel_CPP17_OR_GREATER - -/// template deduction guide: - -template< typename E > -unexpected_type( E ) -> unexpected_type< E >; - -#endif - -/// class unexpected_type, std::exception_ptr specialization (P0323R2) - -#if !nsel_CONFIG_NO_EXCEPTIONS -#if nsel_P0323R <= 2 - -// TODO: Should expected be specialized for particular E types such as exception_ptr and how? -// See p0323r7 2.1. Ergonomics, http://wg21.link/p0323 -template<> -class unexpected_type< std::exception_ptr > -{ -public: - using error_type = std::exception_ptr; - - unexpected_type() = delete; - - ~unexpected_type(){} - - explicit unexpected_type( std::exception_ptr const & error ) - : m_error( error ) - {} - - explicit unexpected_type(std::exception_ptr && error ) - : m_error( std::move( error ) ) - {} - - template< typename E > - explicit unexpected_type( E error ) - : m_error( std::make_exception_ptr( error ) ) - {} - - std::exception_ptr const & value() const - { - return m_error; - } - - std::exception_ptr & value() - { - return m_error; - } - -private: - std::exception_ptr m_error; -}; - -#endif // nsel_P0323R -#endif // !nsel_CONFIG_NO_EXCEPTIONS - -/// x.x.4, Unexpected equality operators - -template< typename E1, typename E2 > -constexpr bool operator==( unexpected_type const & x, unexpected_type const & y ) -{ - return x.value() == y.value(); -} - -template< typename E1, typename E2 > -constexpr bool operator!=( unexpected_type const & x, unexpected_type const & y ) -{ - return ! ( x == y ); -} - -#if nsel_P0323R <= 2 - -template< typename E > -constexpr bool operator<( unexpected_type const & x, unexpected_type const & y ) -{ - return x.value() < y.value(); -} - -template< typename E > -constexpr bool operator>( unexpected_type const & x, unexpected_type const & y ) -{ - return ( y < x ); -} - -template< typename E > -constexpr bool operator<=( unexpected_type const & x, unexpected_type const & y ) -{ - return ! ( y < x ); -} - -template< typename E > -constexpr bool operator>=( unexpected_type const & x, unexpected_type const & y ) -{ - return ! ( x < y ); -} - -#endif // nsel_P0323R - -/// x.x.5 Specialized algorithms - -template< typename E - nsel_REQUIRES_T( - std17::is_swappable::value - ) -> -void swap( unexpected_type & x, unexpected_type & y) noexcept ( noexcept ( x.swap(y) ) ) -{ - x.swap( y ); -} - -#if nsel_P0323R <= 2 - -// unexpected: relational operators for std::exception_ptr: - -inline constexpr bool operator<( unexpected_type const & /*x*/, unexpected_type const & /*y*/ ) -{ - return false; -} - -inline constexpr bool operator>( unexpected_type const & /*x*/, unexpected_type const & /*y*/ ) -{ - return false; -} - -inline constexpr bool operator<=( unexpected_type const & x, unexpected_type const & y ) -{ - return ( x == y ); -} - -inline constexpr bool operator>=( unexpected_type const & x, unexpected_type const & y ) -{ - return ( x == y ); -} - -#endif // nsel_P0323R - -// unexpected: traits - -#if nsel_P0323R <= 3 - -template< typename E> -struct is_unexpected : std::false_type {}; - -template< typename E> -struct is_unexpected< unexpected_type > : std::true_type {}; - -#endif // nsel_P0323R - -// unexpected: factory - -// keep make_unexpected() removed in p0323r2 for pre-C++17: - -template< typename E> -nsel_constexpr14 auto -make_unexpected( E && value ) -> unexpected_type< typename std::decay::type > -{ - return unexpected_type< typename std::decay::type >( std::forward(value) ); -} - -#if nsel_P0323R <= 3 - -/*nsel_constexpr14*/ auto inline -make_unexpected_from_current_exception() -> unexpected_type< std::exception_ptr > -{ - return unexpected_type< std::exception_ptr >( std::current_exception() ); -} - -#endif // nsel_P0323R - -/// x.x.6, x.x.7 expected access error - -template< typename E > -class bad_expected_access; - -/// x.x.7 bad_expected_access: expected access error - -template <> -class bad_expected_access< void > : public std::exception -{ -public: - explicit bad_expected_access() - : std::exception() - {} -}; - -/// x.x.6 bad_expected_access: expected access error - -#if !nsel_CONFIG_NO_EXCEPTIONS - -template< typename E > -class bad_expected_access : public bad_expected_access< void > -{ -public: - using error_type = E; - - explicit bad_expected_access( error_type error ) - : m_error( error ) - {} - - virtual char const * what() const noexcept override - { - return "bad_expected_access"; - } - - nsel_constexpr14 error_type & error() & - { - return m_error; - } - - constexpr error_type const & error() const & - { - return m_error; - } - -#if !nsel_COMPILER_GNUC_VERSION || nsel_COMPILER_GNUC_VERSION >= 490 - - nsel_constexpr14 error_type && error() && - { - return std::move( m_error ); - } - - constexpr error_type const && error() const && - { - return std::move( m_error ); - } - -#endif - -private: - error_type m_error; -}; - -#endif // nsel_CONFIG_NO_EXCEPTIONS - -/// x.x.8 unexpect tag, in_place_unexpected tag: construct an error - -struct unexpect_t{}; -using in_place_unexpected_t = unexpect_t; - -nsel_inline17 constexpr unexpect_t unexpect{}; -nsel_inline17 constexpr unexpect_t in_place_unexpected{}; - -/// class error_traits - -#if nsel_CONFIG_NO_EXCEPTIONS - -namespace detail { - inline bool text( char const * /*text*/ ) { return true; } -} - -template< typename Error > -struct error_traits -{ - static void rethrow( Error const & /*e*/ ) - { -#if nsel_CONFIG_NO_EXCEPTIONS_SEH - RaiseException( EXCEPTION_ACCESS_VIOLATION, EXCEPTION_NONCONTINUABLE, 0, NULL ); -#else - assert( false && detail::text("throw bad_expected_access{ e };") ); -#endif - } -}; - -template<> -struct error_traits< std::exception_ptr > -{ - static void rethrow( std::exception_ptr const & /*e*/ ) - { -#if nsel_CONFIG_NO_EXCEPTIONS_SEH - RaiseException( EXCEPTION_ACCESS_VIOLATION, EXCEPTION_NONCONTINUABLE, 0, NULL ); -#else - assert( false && detail::text("throw bad_expected_access{ e };") ); -#endif - } -}; - -template<> -struct error_traits< std::error_code > -{ - static void rethrow( std::error_code const & /*e*/ ) - { -#if nsel_CONFIG_NO_EXCEPTIONS_SEH - RaiseException( EXCEPTION_ACCESS_VIOLATION, EXCEPTION_NONCONTINUABLE, 0, NULL ); -#else - assert( false && detail::text("throw std::system_error( e );") ); -#endif - } -}; - -#else // nsel_CONFIG_NO_EXCEPTIONS - -template< typename Error > -struct error_traits -{ - static void rethrow( Error const & e ) - { - throw bad_expected_access{ e }; - } -}; - -template<> -struct error_traits< std::exception_ptr > -{ - static void rethrow( std::exception_ptr const & e ) - { - std::rethrow_exception( e ); - } -}; - -template<> -struct error_traits< std::error_code > -{ - static void rethrow( std::error_code const & e ) - { - throw std::system_error( e ); - } -}; - -#endif // nsel_CONFIG_NO_EXCEPTIONS - -} // namespace expected_lite - -// provide nonstd::unexpected_type: - -using expected_lite::unexpected_type; - -namespace expected_lite { - -/// class expected - -#if nsel_P0323R <= 2 -template< typename T, typename E = std::exception_ptr > -class expected -#else -template< typename T, typename E > -class expected -#endif // nsel_P0323R -{ -private: - template< typename, typename > friend class expected; - -public: - using value_type = T; - using error_type = E; - using unexpected_type = nonstd::unexpected_type; - - template< typename U > - struct rebind - { - using type = expected; - }; - - // x.x.4.1 constructors - - nsel_REQUIRES_0( - std::is_default_constructible::value - ) - nsel_constexpr14 expected() - : contained( true ) - { - contained.construct_value( value_type() ); - } - - nsel_constexpr14 expected( expected const & ) = default; - nsel_constexpr14 expected( expected && ) = default; - - template< typename U, typename G - nsel_REQUIRES_T( - std::is_constructible< T, U const &>::value - && std::is_constructible::value - && !std::is_constructible & >::value - && !std::is_constructible && >::value - && !std::is_constructible const & >::value - && !std::is_constructible const && >::value - && !std::is_convertible< expected & , T>::value - && !std::is_convertible< expected &&, T>::value - && !std::is_convertible< expected const & , T>::value - && !std::is_convertible< expected const &&, T>::value - && (!std::is_convertible::value || !std::is_convertible::value ) /*=> explicit */ - ) - > - nsel_constexpr14 explicit expected( expected const & other ) - : contained( other.has_value() ) - { - if ( has_value() ) contained.construct_value( T{ other.contained.value() } ); - else contained.construct_error( E{ other.contained.error() } ); - } - - template< typename U, typename G - nsel_REQUIRES_T( - std::is_constructible< T, U const &>::value - && std::is_constructible::value - && !std::is_constructible & >::value - && !std::is_constructible && >::value - && !std::is_constructible const & >::value - && !std::is_constructible const && >::value - && !std::is_convertible< expected & , T>::value - && !std::is_convertible< expected &&, T>::value - && !std::is_convertible< expected const &, T>::value - && !std::is_convertible< expected const &&, T>::value - && !(!std::is_convertible::value || !std::is_convertible::value ) /*=> non-explicit */ - ) - > - nsel_constexpr14 /*non-explicit*/ expected( expected const & other ) - : contained( other.has_value() ) - { - if ( has_value() ) contained.construct_value( other.contained.value() ); - else contained.construct_error( other.contained.error() ); - } - - template< typename U, typename G - nsel_REQUIRES_T( - std::is_constructible< T, U>::value - && std::is_constructible::value - && !std::is_constructible & >::value - && !std::is_constructible && >::value - && !std::is_constructible const & >::value - && !std::is_constructible const && >::value - && !std::is_convertible< expected & , T>::value - && !std::is_convertible< expected &&, T>::value - && !std::is_convertible< expected const & , T>::value - && !std::is_convertible< expected const &&, T>::value - && (!std::is_convertible::value || !std::is_convertible::value ) /*=> explicit */ - ) - > - nsel_constexpr14 explicit expected( expected && other ) - : contained( other.has_value() ) - { - if ( has_value() ) contained.construct_value( T{ std::move( other.contained.value() ) } ); - else contained.construct_error( E{ std::move( other.contained.error() ) } ); - } - - template< typename U, typename G - nsel_REQUIRES_T( - std::is_constructible< T, U>::value - && std::is_constructible::value - && !std::is_constructible & >::value - && !std::is_constructible && >::value - && !std::is_constructible const & >::value - && !std::is_constructible const && >::value - && !std::is_convertible< expected & , T>::value - && !std::is_convertible< expected &&, T>::value - && !std::is_convertible< expected const & , T>::value - && !std::is_convertible< expected const &&, T>::value - && !(!std::is_convertible::value || !std::is_convertible::value ) /*=> non-explicit */ - ) - > - nsel_constexpr14 /*non-explicit*/ expected( expected && other ) - : contained( other.has_value() ) - { - if ( has_value() ) contained.construct_value( std::move( other.contained.value() ) ); - else contained.construct_error( std::move( other.contained.error() ) ); - } - - template< typename U = T - nsel_REQUIRES_T( - std::is_copy_constructible::value - ) - > - nsel_constexpr14 expected( value_type const & value ) - : contained( true ) - { - contained.construct_value( value ); - } - - template< typename U = T - nsel_REQUIRES_T( - std::is_constructible::value - && !std::is_same::type, nonstd_lite_in_place_t(U)>::value - && !std::is_same< expected , typename std20::remove_cvref::type>::value - && !std::is_same, typename std20::remove_cvref::type>::value - && !std::is_convertible::value /*=> explicit */ - ) - > - nsel_constexpr14 explicit expected( U && value ) noexcept - ( - std::is_nothrow_move_constructible::value && - std::is_nothrow_move_constructible::value - ) - : contained( true ) - { - contained.construct_value( T{ std::forward( value ) } ); - } - - template< typename U = T - nsel_REQUIRES_T( - std::is_constructible::value - && !std::is_same::type, nonstd_lite_in_place_t(U)>::value - && !std::is_same< expected , typename std20::remove_cvref::type>::value - && !std::is_same, typename std20::remove_cvref::type>::value - && std::is_convertible::value /*=> non-explicit */ - ) - > - nsel_constexpr14 /*non-explicit*/ expected( U && value ) noexcept - ( - std::is_nothrow_move_constructible::value && - std::is_nothrow_move_constructible::value - ) - : contained( true ) - { - contained.construct_value( std::forward( value ) ); - } - - // construct error: - - template< typename G = E - nsel_REQUIRES_T( - std::is_constructible::value - && !std::is_convertible< G const &, E>::value /*=> explicit */ - ) - > - nsel_constexpr14 explicit expected( nonstd::unexpected_type const & error ) - : contained( false ) - { - contained.construct_error( E{ error.value() } ); - } - - template< typename G = E - nsel_REQUIRES_T( - std::is_constructible::value - && std::is_convertible< G const &, E>::value /*=> non-explicit */ - ) - > - nsel_constexpr14 /*non-explicit*/ expected( nonstd::unexpected_type const & error ) - : contained( false ) - { - contained.construct_error( error.value() ); - } - - template< typename G = E - nsel_REQUIRES_T( - std::is_constructible::value - && !std::is_convertible< G&&, E>::value /*=> explicit */ - ) - > - nsel_constexpr14 explicit expected( nonstd::unexpected_type && error ) - : contained( false ) - { - contained.construct_error( E{ std::move( error.value() ) } ); - } - - template< typename G = E - nsel_REQUIRES_T( - std::is_constructible::value - && std::is_convertible< G&&, E>::value /*=> non-explicit */ - ) - > - nsel_constexpr14 /*non-explicit*/ expected( nonstd::unexpected_type && error ) - : contained( false ) - { - contained.construct_error( std::move( error.value() ) ); - } - - // in-place construction, value - - template< typename... Args - nsel_REQUIRES_T( - std::is_constructible::value - ) - > - nsel_constexpr14 explicit expected( nonstd_lite_in_place_t(T), Args&&... args ) - : contained( true ) - { - contained.emplace_value( std::forward( args )... ); - } - - template< typename U, typename... Args - nsel_REQUIRES_T( - std::is_constructible, Args&&...>::value - ) - > - nsel_constexpr14 explicit expected( nonstd_lite_in_place_t(T), std::initializer_list il, Args&&... args ) - : contained( true ) - { - contained.emplace_value( il, std::forward( args )... ); - } - - // in-place construction, error - - template< typename... Args - nsel_REQUIRES_T( - std::is_constructible::value - ) - > - nsel_constexpr14 explicit expected( unexpect_t, Args&&... args ) - : contained( false ) - { - contained.emplace_error( std::forward( args )... ); - } - - template< typename U, typename... Args - nsel_REQUIRES_T( - std::is_constructible, Args&&...>::value - ) - > - nsel_constexpr14 explicit expected( unexpect_t, std::initializer_list il, Args&&... args ) - : contained( false ) - { - contained.emplace_error( il, std::forward( args )... ); - } - - // x.x.4.2 destructor - - // TODO: ~expected: triviality - // Effects: If T is not cv void and is_trivially_destructible_v is false and bool(*this), calls val.~T(). If is_trivially_destructible_v is false and !bool(*this), calls unexpect.~unexpected(). - // Remarks: If either T is cv void or is_trivially_destructible_v is true, and is_trivially_destructible_v is true, then this destructor shall be a trivial destructor. - - ~expected() - { - if ( has_value() ) contained.destruct_value(); - else contained.destruct_error(); - } - - // x.x.4.3 assignment - - expected & operator=( expected const & other ) - { - expected( other ).swap( *this ); - return *this; - } - - expected & operator=( expected && other ) noexcept - ( - std::is_nothrow_move_constructible< T>::value - && std::is_nothrow_move_assignable< T>::value - && std::is_nothrow_move_constructible::value // added for missing - && std::is_nothrow_move_assignable< E>::value ) // nothrow above - { - expected( std::move( other ) ).swap( *this ); - return *this; - } - - template< typename U - nsel_REQUIRES_T( - !std::is_same, typename std20::remove_cvref::type>::value - && std17::conjunction, std::is_same> >::value - && std::is_constructible::value - && std::is_assignable< T&,U>::value - && std::is_nothrow_move_constructible::value ) - > - expected & operator=( U && value ) - { - expected( std::forward( value ) ).swap( *this ); - return *this; - } - - template< typename G = E - nsel_REQUIRES_T( - std::is_constructible::value && - std::is_copy_constructible::value // TODO: std::is_nothrow_copy_constructible - && std::is_copy_assignable::value - ) - > - expected & operator=( nonstd::unexpected_type const & error ) - { - expected( unexpect, error.value() ).swap( *this ); - return *this; - } - - template< typename G = E - nsel_REQUIRES_T( - std::is_constructible::value && - std::is_move_constructible::value // TODO: std::is_nothrow_move_constructible - && std::is_move_assignable::value - ) - > - expected & operator=( nonstd::unexpected_type && error ) - { - expected( unexpect, std::move( error.value() ) ).swap( *this ); - return *this; - } - - template< typename... Args - nsel_REQUIRES_T( - std::is_nothrow_constructible::value - ) - > - value_type & emplace( Args &&... args ) - { - expected( nonstd_lite_in_place(T), std::forward(args)... ).swap( *this ); - return value(); - } - - template< typename U, typename... Args - nsel_REQUIRES_T( - std::is_nothrow_constructible&, Args&&...>::value - ) - > - value_type & emplace( std::initializer_list il, Args &&... args ) - { - expected( nonstd_lite_in_place(T), il, std::forward(args)... ).swap( *this ); - return value(); - } - - // x.x.4.4 swap - - template< typename U=T, typename G=E > - nsel_REQUIRES_R( void, - std17::is_swappable< U>::value - && std17::is_swappable::value - && ( std::is_move_constructible::value || std::is_move_constructible::value ) - ) - swap( expected & other ) noexcept - ( - std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value && - std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value - ) - { - using std::swap; - - if ( bool(*this) && bool(other) ) { swap( contained.value(), other.contained.value() ); } - else if ( ! bool(*this) && ! bool(other) ) { swap( contained.error(), other.contained.error() ); } - else if ( bool(*this) && ! bool(other) ) { error_type t( std::move( other.error() ) ); - other.contained.destruct_error(); - other.contained.construct_value( std::move( contained.value() ) ); - contained.destruct_value(); - contained.construct_error( std::move( t ) ); - bool has_value = contained.has_value(); - bool other_has_value = other.has_value(); - other.contained.set_has_value(has_value); - contained.set_has_value(other_has_value); - } - else if ( ! bool(*this) && bool(other) ) { other.swap( *this ); } - } - - // x.x.4.5 observers - - constexpr value_type const * operator ->() const - { - return assert( has_value() ), contained.value_ptr(); - } - - value_type * operator ->() - { - return assert( has_value() ), contained.value_ptr(); - } - - constexpr value_type const & operator *() const & - { - return assert( has_value() ), contained.value(); - } - - value_type & operator *() & - { - return assert( has_value() ), contained.value(); - } - -#if !nsel_COMPILER_GNUC_VERSION || nsel_COMPILER_GNUC_VERSION >= 490 - - constexpr value_type const && operator *() const && - { - return std::move( ( assert( has_value() ), contained.value() ) ); - } - - nsel_constexpr14 value_type && operator *() && - { - return std::move( ( assert( has_value() ), contained.value() ) ); - } - -#endif - - constexpr explicit operator bool() const noexcept - { - return has_value(); - } - - constexpr bool has_value() const noexcept - { - return contained.has_value(); - } - - constexpr value_type const & value() const & - { - return has_value() - ? ( contained.value() ) - : ( error_traits::rethrow( contained.error() ), contained.value() ); - } - - value_type & value() & - { - return has_value() - ? ( contained.value() ) - : ( error_traits::rethrow( contained.error() ), contained.value() ); - } - -#if !nsel_COMPILER_GNUC_VERSION || nsel_COMPILER_GNUC_VERSION >= 490 - - constexpr value_type const && value() const && - { - return std::move( has_value() - ? ( contained.value() ) - : ( error_traits::rethrow( contained.error() ), contained.value() ) ); - } - - nsel_constexpr14 value_type && value() && - { - return std::move( has_value() - ? ( contained.value() ) - : ( error_traits::rethrow( contained.error() ), contained.value() ) ); - } - -#endif - - constexpr error_type const & error() const & - { - return assert( ! has_value() ), contained.error(); - } - - error_type & error() & - { - return assert( ! has_value() ), contained.error(); - } - -#if !nsel_COMPILER_GNUC_VERSION || nsel_COMPILER_GNUC_VERSION >= 490 - - constexpr error_type const && error() const && - { - return std::move( ( assert( ! has_value() ), contained.error() ) ); - } - - error_type && error() && - { - return std::move( ( assert( ! has_value() ), contained.error() ) ); - } - -#endif - - constexpr unexpected_type get_unexpected() const - { - return make_unexpected( contained.error() ); - } - - template< typename Ex > - bool has_exception() const - { - using ContainedEx = typename std::remove_reference< decltype( get_unexpected().value() ) >::type; - return ! has_value() && std::is_base_of< Ex, ContainedEx>::value; - } - - template< typename U - nsel_REQUIRES_T( - std::is_copy_constructible< T>::value - && std::is_convertible::value - ) - > - value_type value_or( U && v ) const & - { - return has_value() - ? contained.value() - : static_cast( std::forward( v ) ); - } - - template< typename U - nsel_REQUIRES_T( - std::is_move_constructible< T>::value - && std::is_convertible::value - ) - > - value_type value_or( U && v ) && - { - return has_value() - ? std::move( contained.value() ) - : static_cast( std::forward( v ) ); - } - - // unwrap() - -// template -// constexpr expected expected,E>::unwrap() const&; - -// template -// constexpr expected expected::unwrap() const&; - -// template -// expected expected, E>::unwrap() &&; - -// template -// template expected expected::unwrap() &&; - - // factories - -// template< typename Ex, typename F> -// expected catch_exception(F&& f); - -// template< typename F> -// expected())),E> map(F&& func) ; - -// template< typename F> -// 'see below' bind(F&& func); - -// template< typename F> -// expected catch_error(F&& f); - -// template< typename F> -// 'see below' then(F&& func); - -private: - detail::storage_t - < - T - ,E - , std::is_copy_constructible::value && std::is_copy_constructible::value - , std::is_move_constructible::value && std::is_move_constructible::value - > - contained; -}; - -/// class expected, void specialization - -template< typename E > -class expected -{ -private: - template< typename, typename > friend class expected; - -public: - using value_type = void; - using error_type = E; - using unexpected_type = nonstd::unexpected_type; - - // x.x.4.1 constructors - - constexpr expected() noexcept - : contained( true ) - {} - - nsel_constexpr14 expected( expected const & other ) = default; - nsel_constexpr14 expected( expected && other ) = default; - - constexpr explicit expected( nonstd_lite_in_place_t(void) ) - : contained( true ) - {} - - template< typename G = E - nsel_REQUIRES_T( - !std::is_convertible::value /*=> explicit */ - ) - > - nsel_constexpr14 explicit expected( nonstd::unexpected_type const & error ) - : contained( false ) - { - contained.construct_error( E{ error.value() } ); - } - - template< typename G = E - nsel_REQUIRES_T( - std::is_convertible::value /*=> non-explicit */ - ) - > - nsel_constexpr14 /*non-explicit*/ expected( nonstd::unexpected_type const & error ) - : contained( false ) - { - contained.construct_error( error.value() ); - } - - template< typename G = E - nsel_REQUIRES_T( - !std::is_convertible::value /*=> explicit */ - ) - > - nsel_constexpr14 explicit expected( nonstd::unexpected_type && error ) - : contained( false ) - { - contained.construct_error( E{ std::move( error.value() ) } ); - } - - template< typename G = E - nsel_REQUIRES_T( - std::is_convertible::value /*=> non-explicit */ - ) - > - nsel_constexpr14 /*non-explicit*/ expected( nonstd::unexpected_type && error ) - : contained( false ) - { - contained.construct_error( std::move( error.value() ) ); - } - - template< typename... Args - nsel_REQUIRES_T( - std::is_constructible::value - ) - > - nsel_constexpr14 explicit expected( unexpect_t, Args&&... args ) - : contained( false ) - { - contained.emplace_error( std::forward( args )... ); - } - - template< typename U, typename... Args - nsel_REQUIRES_T( - std::is_constructible, Args&&...>::value - ) - > - nsel_constexpr14 explicit expected( unexpect_t, std::initializer_list il, Args&&... args ) - : contained( false ) - { - contained.emplace_error( il, std::forward( args )... ); - } - - // destructor - - ~expected() - { - if ( ! has_value() ) - { - contained.destruct_error(); - } - } - - // x.x.4.3 assignment - - expected & operator=( expected const & other ) - { - expected( other ).swap( *this ); - return *this; - } - - expected & operator=( expected && other ) noexcept - ( - std::is_nothrow_move_assignable::value && - std::is_nothrow_move_constructible::value ) - { - expected( std::move( other ) ).swap( *this ); - return *this; - } - - void emplace() - { - expected().swap( *this ); - } - - // x.x.4.4 swap - - template< typename G = E > - nsel_REQUIRES_R( void, - std17::is_swappable::value - && std::is_move_constructible::value - ) - swap( expected & other ) noexcept - ( - std::is_nothrow_move_constructible::value && std17::is_nothrow_swappable::value - ) - { - using std::swap; - - if ( ! bool(*this) && ! bool(other) ) { swap( contained.error(), other.contained.error() ); } - else if ( bool(*this) && ! bool(other) ) { contained.construct_error( std::move( other.error() ) ); - bool has_value = contained.has_value(); - bool other_has_value = other.has_value(); - other.contained.set_has_value(has_value); - contained.set_has_value(other_has_value); - } - else if ( ! bool(*this) && bool(other) ) { other.swap( *this ); } - } - - // x.x.4.5 observers - - constexpr explicit operator bool() const noexcept - { - return has_value(); - } - - constexpr bool has_value() const noexcept - { - return contained.has_value(); - } - - void value() const - { - if ( ! has_value() ) - { - error_traits::rethrow( contained.error() ); - } - } - - constexpr error_type const & error() const & - { - return assert( ! has_value() ), contained.error(); - } - - error_type & error() & - { - return assert( ! has_value() ), contained.error(); - } - -#if !nsel_COMPILER_GNUC_VERSION || nsel_COMPILER_GNUC_VERSION >= 490 - - constexpr error_type const && error() const && - { - return std::move( ( assert( ! has_value() ), contained.error() ) ); - } - - error_type && error() && - { - return std::move( ( assert( ! has_value() ), contained.error() ) ); - } - -#endif - - constexpr unexpected_type get_unexpected() const - { - return make_unexpected( contained.error() ); - } - - template< typename Ex > - bool has_exception() const - { - using ContainedEx = typename std::remove_reference< decltype( get_unexpected().value() ) >::type; - return ! has_value() && std::is_base_of< Ex, ContainedEx>::value; - } - -// template constexpr 'see below' unwrap() const&; -// -// template 'see below' unwrap() &&; - - // factories - -// template< typename Ex, typename F> -// expected catch_exception(F&& f); -// -// template< typename F> -// expected map(F&& func) ; -// -// template< typename F> -// 'see below' bind(F&& func) ; -// -// template< typename F> -// expected catch_error(F&& f); -// -// template< typename F> -// 'see below' then(F&& func); - -private: - detail::storage_t - < - void - , E - , std::is_copy_constructible::value - , std::is_move_constructible::value - > - contained; -}; - -// x.x.4.6 expected<>: comparison operators - -template< typename T1, typename E1, typename T2, typename E2 > -constexpr bool operator==( expected const & x, expected const & y ) -{ - return bool(x) != bool(y) ? false : bool(x) == false ? x.error() == y.error() : *x == *y; -} - -template< typename T1, typename E1, typename T2, typename E2 > -constexpr bool operator!=( expected const & x, expected const & y ) -{ - return !(x == y); -} - -template< typename E1, typename E2 > -constexpr bool operator==( expected const & x, expected const & y ) -{ - return bool(x) != bool(y) ? false : bool(x) == false ? x.error() == y.error() : true; -} - -#if nsel_P0323R <= 2 - -template< typename T, typename E > -constexpr bool operator<( expected const & x, expected const & y ) -{ - return (!y) ? false : (!x) ? true : *x < *y; -} - -template< typename T, typename E > -constexpr bool operator>( expected const & x, expected const & y ) -{ - return (y < x); -} - -template< typename T, typename E > -constexpr bool operator<=( expected const & x, expected const & y ) -{ - return !(y < x); -} - -template< typename T, typename E > -constexpr bool operator>=( expected const & x, expected const & y ) -{ - return !(x < y); -} - -#endif - -// x.x.4.7 expected: comparison with T - -template< typename T1, typename E1, typename T2 > -constexpr bool operator==( expected const & x, T2 const & v ) -{ - return bool(x) ? *x == v : false; -} - -template< typename T1, typename E1, typename T2 > -constexpr bool operator==(T2 const & v, expected const & x ) -{ - return bool(x) ? v == *x : false; -} - -template< typename T1, typename E1, typename T2 > -constexpr bool operator!=( expected const & x, T2 const & v ) -{ - return bool(x) ? *x != v : true; -} - -template< typename T1, typename E1, typename T2 > -constexpr bool operator!=( T2 const & v, expected const & x ) -{ - return bool(x) ? v != *x : true; -} - -#if nsel_P0323R <= 2 - -template< typename T, typename E > -constexpr bool operator<( expected const & x, T const & v ) -{ - return bool(x) ? *x < v : true; -} - -template< typename T, typename E > -constexpr bool operator<( T const & v, expected const & x ) -{ - return bool(x) ? v < *x : false; -} - -template< typename T, typename E > -constexpr bool operator>( T const & v, expected const & x ) -{ - return bool(x) ? *x < v : false; -} - -template< typename T, typename E > -constexpr bool operator>( expected const & x, T const & v ) -{ - return bool(x) ? v < *x : false; -} - -template< typename T, typename E > -constexpr bool operator<=( T const & v, expected const & x ) -{ - return bool(x) ? ! ( *x < v ) : false; -} - -template< typename T, typename E > -constexpr bool operator<=( expected const & x, T const & v ) -{ - return bool(x) ? ! ( v < *x ) : true; -} - -template< typename T, typename E > -constexpr bool operator>=( expected const & x, T const & v ) -{ - return bool(x) ? ! ( *x < v ) : false; -} - -template< typename T, typename E > -constexpr bool operator>=( T const & v, expected const & x ) -{ - return bool(x) ? ! ( v < *x ) : true; -} - -#endif // nsel_P0323R - -// x.x.4.8 expected: comparison with unexpected_type - -template< typename T1, typename E1 , typename E2 > -constexpr bool operator==( expected const & x, unexpected_type const & u ) -{ - return (!x) ? x.get_unexpected() == u : false; -} - -template< typename T1, typename E1 , typename E2 > -constexpr bool operator==( unexpected_type const & u, expected const & x ) -{ - return ( x == u ); -} - -template< typename T1, typename E1 , typename E2 > -constexpr bool operator!=( expected const & x, unexpected_type const & u ) -{ - return ! ( x == u ); -} - -template< typename T1, typename E1 , typename E2 > -constexpr bool operator!=( unexpected_type const & u, expected const & x ) -{ - return ! ( x == u ); -} - -#if nsel_P0323R <= 2 - -template< typename T, typename E > -constexpr bool operator<( expected const & x, unexpected_type const & u ) -{ - return (!x) ? ( x.get_unexpected() < u ) : false; -} - -template< typename T, typename E > -constexpr bool operator<( unexpected_type const & u, expected const & x ) -{ - return (!x) ? ( u < x.get_unexpected() ) : true ; -} - -template< typename T, typename E > -constexpr bool operator>( expected const & x, unexpected_type const & u ) -{ - return ( u < x ); -} - -template< typename T, typename E > -constexpr bool operator>( unexpected_type const & u, expected const & x ) -{ - return ( x < u ); -} - -template< typename T, typename E > -constexpr bool operator<=( expected const & x, unexpected_type const & u ) -{ - return ! ( u < x ); -} - -template< typename T, typename E > -constexpr bool operator<=( unexpected_type const & u, expected const & x) -{ - return ! ( x < u ); -} - -template< typename T, typename E > -constexpr bool operator>=( expected const & x, unexpected_type const & u ) -{ - return ! ( u > x ); -} - -template< typename T, typename E > -constexpr bool operator>=( unexpected_type const & u, expected const & x ) -{ - return ! ( x > u ); -} - -#endif // nsel_P0323R - -/// x.x.x Specialized algorithms - -template< typename T, typename E - nsel_REQUIRES_T( - ( std::is_void::value || std::is_move_constructible::value ) - && std::is_move_constructible::value - && std17::is_swappable::value - && std17::is_swappable::value ) -> -void swap( expected & x, expected & y ) noexcept ( noexcept ( x.swap(y) ) ) -{ - x.swap( y ); -} - -#if nsel_P0323R <= 3 - -template< typename T > -constexpr auto make_expected( T && v ) -> expected< typename std::decay::type > -{ - return expected< typename std::decay::type >( std::forward( v ) ); -} - -// expected specialization: - -auto inline make_expected() -> expected -{ - return expected( in_place ); -} - -template< typename T > -constexpr auto make_expected_from_current_exception() -> expected -{ - return expected( make_unexpected_from_current_exception() ); -} - -template< typename T > -auto make_expected_from_exception( std::exception_ptr v ) -> expected -{ - return expected( unexpected_type( std::forward( v ) ) ); -} - -template< typename T, typename E > -constexpr auto make_expected_from_error( E e ) -> expected::type> -{ - return expected::type>( make_unexpected( e ) ); -} - -template< typename F - nsel_REQUIRES_T( ! std::is_same::type, void>::value ) -> -/*nsel_constexpr14*/ -auto make_expected_from_call( F f ) -> expected< typename std::result_of::type > -{ - try - { - return make_expected( f() ); - } - catch (...) - { - return make_unexpected_from_current_exception(); - } -} - -template< typename F - nsel_REQUIRES_T( std::is_same::type, void>::value ) -> -/*nsel_constexpr14*/ -auto make_expected_from_call( F f ) -> expected -{ - try - { - f(); - return make_expected(); - } - catch (...) - { - return make_unexpected_from_current_exception(); - } -} - -#endif // nsel_P0323R - -} // namespace expected_lite - -using namespace expected_lite; - -// using expected_lite::expected; -// using ... - -} // namespace nonstd - -namespace std { - -// expected: hash support - -template< typename T, typename E > -struct hash< nonstd::expected > -{ - using result_type = std::size_t; - using argument_type = nonstd::expected; - - constexpr result_type operator()(argument_type const & arg) const - { - return arg ? std::hash{}(*arg) : result_type{}; - } -}; - -// TBD - ?? remove? see spec. -template< typename T, typename E > -struct hash< nonstd::expected > -{ - using result_type = std::size_t; - using argument_type = nonstd::expected; - - constexpr result_type operator()(argument_type const & arg) const - { - return arg ? std::hash{}(*arg) : result_type{}; - } -}; - -// TBD - implement -// bool(e), hash>()(e) shall evaluate to the hashing true; -// otherwise it evaluates to an unspecified value if E is exception_ptr or -// a combination of hashing false and hash()(e.error()). - -template< typename E > -struct hash< nonstd::expected > -{ -}; - -} // namespace std - -namespace nonstd { - -// void unexpected() is deprecated && removed in C++17 - -#if nsel_CPP17_OR_GREATER || nsel_COMPILER_MSVC_VERSION > 141 -template< typename E > -using unexpected = unexpected_type; -#endif - -} // namespace nonstd - -#undef nsel_REQUIRES -#undef nsel_REQUIRES_0 -#undef nsel_REQUIRES_T - -nsel_RESTORE_WARNINGS() - -#endif // nsel_USES_STD_EXPECTED - -#endif // NONSTD_EXPECTED_LITE_HPP diff --git a/src/third_party/tl/expected.hpp b/src/third_party/tl/expected.hpp new file mode 100644 index 000000000..afee404d4 --- /dev/null +++ b/src/third_party/tl/expected.hpp @@ -0,0 +1,2444 @@ +/// +// expected - An implementation of std::expected with extensions +// Written in 2017 by Sy Brand (tartanllama@gmail.com, @TartanLlama) +// +// Documentation available at http://tl.tartanllama.xyz/ +// +// To the extent possible under law, the author(s) have dedicated all +// copyright and related and neighboring rights to this software to the +// public domain worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication +// along with this software. If not, see +// . +/// + +#ifndef TL_EXPECTED_HPP +#define TL_EXPECTED_HPP + +#define TL_EXPECTED_VERSION_MAJOR 1 +#define TL_EXPECTED_VERSION_MINOR 1 +#define TL_EXPECTED_VERSION_PATCH 0 + +#include +#include +#include +#include + +#if defined(__EXCEPTIONS) || defined(_CPPUNWIND) +#define TL_EXPECTED_EXCEPTIONS_ENABLED +#endif + +#if (defined(_MSC_VER) && _MSC_VER == 1900) +#define TL_EXPECTED_MSVC2015 +#define TL_EXPECTED_MSVC2015_CONSTEXPR +#else +#define TL_EXPECTED_MSVC2015_CONSTEXPR constexpr +#endif + +#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ + !defined(__clang__)) +#define TL_EXPECTED_GCC49 +#endif + +#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 4 && \ + !defined(__clang__)) +#define TL_EXPECTED_GCC54 +#endif + +#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 5 && \ + !defined(__clang__)) +#define TL_EXPECTED_GCC55 +#endif + +#if !defined(TL_ASSERT) +//can't have assert in constexpr in C++11 and GCC 4.9 has a compiler bug +#if (__cplusplus > 201103L) && !defined(TL_EXPECTED_GCC49) +#include +#define TL_ASSERT(x) assert(x) +#else +#define TL_ASSERT(x) +#endif +#endif + +#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ + !defined(__clang__)) +// GCC < 5 doesn't support overloading on const&& for member functions + +#define TL_EXPECTED_NO_CONSTRR +// GCC < 5 doesn't support some standard C++11 type traits +#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ + std::has_trivial_copy_constructor +#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ + std::has_trivial_copy_assign + +// This one will be different for GCC 5.7 if it's ever supported +#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ + std::is_trivially_destructible + +// GCC 5 < v < 8 has a bug in is_trivially_copy_constructible which breaks +// std::vector for non-copyable types +#elif (defined(__GNUC__) && __GNUC__ < 8 && !defined(__clang__)) +#ifndef TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX +#define TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX +namespace tl { +namespace detail { +template +struct is_trivially_copy_constructible + : std::is_trivially_copy_constructible {}; +#ifdef _GLIBCXX_VECTOR +template +struct is_trivially_copy_constructible> : std::false_type {}; +#endif +} // namespace detail +} // namespace tl +#endif + +#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ + tl::detail::is_trivially_copy_constructible +#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ + std::is_trivially_copy_assignable +#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ + std::is_trivially_destructible +#else +#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ + std::is_trivially_copy_constructible +#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ + std::is_trivially_copy_assignable +#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ + std::is_trivially_destructible +#endif + +#if __cplusplus > 201103L +#define TL_EXPECTED_CXX14 +#endif + +#ifdef TL_EXPECTED_GCC49 +#define TL_EXPECTED_GCC49_CONSTEXPR +#else +#define TL_EXPECTED_GCC49_CONSTEXPR constexpr +#endif + +#if (__cplusplus == 201103L || defined(TL_EXPECTED_MSVC2015) || \ + defined(TL_EXPECTED_GCC49)) +#define TL_EXPECTED_11_CONSTEXPR +#else +#define TL_EXPECTED_11_CONSTEXPR constexpr +#endif + +namespace tl { +template class expected; + +#ifndef TL_MONOSTATE_INPLACE_MUTEX +#define TL_MONOSTATE_INPLACE_MUTEX +class monostate {}; + +struct in_place_t { + explicit in_place_t() = default; +}; +static constexpr in_place_t in_place{}; +#endif + +template class unexpected { +public: + static_assert(!std::is_same::value, "E must not be void"); + + unexpected() = delete; + constexpr explicit unexpected(const E &e) : m_val(e) {} + + constexpr explicit unexpected(E &&e) : m_val(std::move(e)) {} + + template ::value>::type * = nullptr> + constexpr explicit unexpected(Args &&...args) + : m_val(std::forward(args)...) {} + template < + class U, class... Args, + typename std::enable_if &, Args &&...>::value>::type * = nullptr> + constexpr explicit unexpected(std::initializer_list l, Args &&...args) + : m_val(l, std::forward(args)...) {} + + constexpr const E &value() const & { return m_val; } + TL_EXPECTED_11_CONSTEXPR E &value() & { return m_val; } + TL_EXPECTED_11_CONSTEXPR E &&value() && { return std::move(m_val); } + constexpr const E &&value() const && { return std::move(m_val); } + +private: + E m_val; +}; + +#ifdef __cpp_deduction_guides +template unexpected(E) -> unexpected; +#endif + +template +constexpr bool operator==(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() == rhs.value(); +} +template +constexpr bool operator!=(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() != rhs.value(); +} +template +constexpr bool operator<(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() < rhs.value(); +} +template +constexpr bool operator<=(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() <= rhs.value(); +} +template +constexpr bool operator>(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() > rhs.value(); +} +template +constexpr bool operator>=(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() >= rhs.value(); +} + +template +unexpected::type> make_unexpected(E &&e) { + return unexpected::type>(std::forward(e)); +} + +struct unexpect_t { + unexpect_t() = default; +}; +static constexpr unexpect_t unexpect{}; + +namespace detail { +template +[[noreturn]] TL_EXPECTED_11_CONSTEXPR void throw_exception(E &&e) { +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + throw std::forward(e); +#else + (void)e; +#ifdef _MSC_VER + __assume(0); +#else + __builtin_unreachable(); +#endif +#endif +} + +#ifndef TL_TRAITS_MUTEX +#define TL_TRAITS_MUTEX +// C++14-style aliases for brevity +template using remove_const_t = typename std::remove_const::type; +template +using remove_reference_t = typename std::remove_reference::type; +template using decay_t = typename std::decay::type; +template +using enable_if_t = typename std::enable_if::type; +template +using conditional_t = typename std::conditional::type; + +// std::conjunction from C++17 +template struct conjunction : std::true_type {}; +template struct conjunction : B {}; +template +struct conjunction + : std::conditional, B>::type {}; + +#if defined(_LIBCPP_VERSION) && __cplusplus == 201103L +#define TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND +#endif + +// In C++11 mode, there's an issue in libc++'s std::mem_fn +// which results in a hard-error when using it in a noexcept expression +// in some cases. This is a check to workaround the common failing case. +#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND +template +struct is_pointer_to_non_const_member_func : std::false_type {}; +template +struct is_pointer_to_non_const_member_func + : std::true_type {}; +template +struct is_pointer_to_non_const_member_func + : std::true_type {}; +template +struct is_pointer_to_non_const_member_func + : std::true_type {}; +template +struct is_pointer_to_non_const_member_func + : std::true_type {}; +template +struct is_pointer_to_non_const_member_func + : std::true_type {}; +template +struct is_pointer_to_non_const_member_func + : std::true_type {}; + +template struct is_const_or_const_ref : std::false_type {}; +template struct is_const_or_const_ref : std::true_type {}; +template struct is_const_or_const_ref : std::true_type {}; +#endif + +// std::invoke from C++17 +// https://stackoverflow.com/questions/38288042/c11-14-invoke-workaround +template < + typename Fn, typename... Args, +#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND + typename = enable_if_t::value && + is_const_or_const_ref::value)>, +#endif + typename = enable_if_t>::value>, int = 0> +constexpr auto invoke(Fn &&f, Args &&...args) noexcept( + noexcept(std::mem_fn(f)(std::forward(args)...))) + -> decltype(std::mem_fn(f)(std::forward(args)...)) { + return std::mem_fn(f)(std::forward(args)...); +} + +template >::value>> +constexpr auto invoke(Fn &&f, Args &&...args) noexcept( + noexcept(std::forward(f)(std::forward(args)...))) + -> decltype(std::forward(f)(std::forward(args)...)) { + return std::forward(f)(std::forward(args)...); +} + +// std::invoke_result from C++17 +template struct invoke_result_impl; + +template +struct invoke_result_impl< + F, + decltype(detail::invoke(std::declval(), std::declval()...), void()), + Us...> { + using type = + decltype(detail::invoke(std::declval(), std::declval()...)); +}; + +template +using invoke_result = invoke_result_impl; + +template +using invoke_result_t = typename invoke_result::type; + +#if defined(_MSC_VER) && _MSC_VER <= 1900 +// TODO make a version which works with MSVC 2015 +template struct is_swappable : std::true_type {}; + +template struct is_nothrow_swappable : std::true_type {}; +#else +// https://stackoverflow.com/questions/26744589/what-is-a-proper-way-to-implement-is-swappable-to-test-for-the-swappable-concept +namespace swap_adl_tests { +// if swap ADL finds this then it would call std::swap otherwise (same +// signature) +struct tag {}; + +template tag swap(T &, T &); +template tag swap(T (&a)[N], T (&b)[N]); + +// helper functions to test if an unqualified swap is possible, and if it +// becomes std::swap +template std::false_type can_swap(...) noexcept(false); +template (), std::declval()))> +std::true_type can_swap(int) noexcept(noexcept(swap(std::declval(), + std::declval()))); + +template std::false_type uses_std(...); +template +std::is_same(), std::declval())), tag> +uses_std(int); + +template +struct is_std_swap_noexcept + : std::integral_constant::value && + std::is_nothrow_move_assignable::value> {}; + +template +struct is_std_swap_noexcept : is_std_swap_noexcept {}; + +template +struct is_adl_swap_noexcept + : std::integral_constant(0))> {}; +} // namespace swap_adl_tests + +template +struct is_swappable + : std::integral_constant< + bool, + decltype(detail::swap_adl_tests::can_swap(0))::value && + (!decltype(detail::swap_adl_tests::uses_std(0))::value || + (std::is_move_assignable::value && + std::is_move_constructible::value))> {}; + +template +struct is_swappable + : std::integral_constant< + bool, + decltype(detail::swap_adl_tests::can_swap(0))::value && + (!decltype(detail::swap_adl_tests::uses_std( + 0))::value || + is_swappable::value)> {}; + +template +struct is_nothrow_swappable + : std::integral_constant< + bool, + is_swappable::value && + ((decltype(detail::swap_adl_tests::uses_std(0))::value && + detail::swap_adl_tests::is_std_swap_noexcept::value) || + (!decltype(detail::swap_adl_tests::uses_std(0))::value && + detail::swap_adl_tests::is_adl_swap_noexcept::value))> {}; +#endif +#endif + +// Trait for checking if a type is a tl::expected +template struct is_expected_impl : std::false_type {}; +template +struct is_expected_impl> : std::true_type {}; +template using is_expected = is_expected_impl>; + +template +using expected_enable_forward_value = detail::enable_if_t< + std::is_constructible::value && + !std::is_same, in_place_t>::value && + !std::is_same, detail::decay_t>::value && + !std::is_same, detail::decay_t>::value>; + +template +using expected_enable_from_other = detail::enable_if_t< + std::is_constructible::value && + std::is_constructible::value && + !std::is_constructible &>::value && + !std::is_constructible &&>::value && + !std::is_constructible &>::value && + !std::is_constructible &&>::value && + !std::is_convertible &, T>::value && + !std::is_convertible &&, T>::value && + !std::is_convertible &, T>::value && + !std::is_convertible &&, T>::value>; + +template +using is_void_or = conditional_t::value, std::true_type, U>; + +template +using is_copy_constructible_or_void = + is_void_or>; + +template +using is_move_constructible_or_void = + is_void_or>; + +template +using is_copy_assignable_or_void = is_void_or>; + +template +using is_move_assignable_or_void = is_void_or>; + +} // namespace detail + +namespace detail { +struct no_init_t {}; +static constexpr no_init_t no_init{}; + +// Implements the storage of the values, and ensures that the destructor is +// trivial if it can be. +// +// This specialization is for where neither `T` or `E` is trivially +// destructible, so the destructors must be called on destruction of the +// `expected` +template ::value, + bool = std::is_trivially_destructible::value> +struct expected_storage_base { + constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} + + template ::value> * = + nullptr> + constexpr expected_storage_base(in_place_t, Args &&...args) + : m_val(std::forward(args)...), m_has_val(true) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected_storage_base(in_place_t, std::initializer_list il, + Args &&...args) + : m_val(il, std::forward(args)...), m_has_val(true) {} + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&...args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&...args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() { + if (m_has_val) { + m_val.~T(); + } else { + m_unexpect.~unexpected(); + } + } + union { + T m_val; + unexpected m_unexpect; + char m_no_init; + }; + bool m_has_val; +}; + +// This specialization is for when both `T` and `E` are trivially-destructible, +// so the destructor of the `expected` can be trivial. +template struct expected_storage_base { + constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} + + template ::value> * = + nullptr> + constexpr expected_storage_base(in_place_t, Args &&...args) + : m_val(std::forward(args)...), m_has_val(true) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected_storage_base(in_place_t, std::initializer_list il, + Args &&...args) + : m_val(il, std::forward(args)...), m_has_val(true) {} + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&...args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&...args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() = default; + union { + T m_val; + unexpected m_unexpect; + char m_no_init; + }; + bool m_has_val; +}; + +// T is trivial, E is not. +template struct expected_storage_base { + constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} + TL_EXPECTED_MSVC2015_CONSTEXPR expected_storage_base(no_init_t) + : m_no_init(), m_has_val(false) {} + + template ::value> * = + nullptr> + constexpr expected_storage_base(in_place_t, Args &&...args) + : m_val(std::forward(args)...), m_has_val(true) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected_storage_base(in_place_t, std::initializer_list il, + Args &&...args) + : m_val(il, std::forward(args)...), m_has_val(true) {} + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&...args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&...args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() { + if (!m_has_val) { + m_unexpect.~unexpected(); + } + } + + union { + T m_val; + unexpected m_unexpect; + char m_no_init; + }; + bool m_has_val; +}; + +// E is trivial, T is not. +template struct expected_storage_base { + constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} + + template ::value> * = + nullptr> + constexpr expected_storage_base(in_place_t, Args &&...args) + : m_val(std::forward(args)...), m_has_val(true) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected_storage_base(in_place_t, std::initializer_list il, + Args &&...args) + : m_val(il, std::forward(args)...), m_has_val(true) {} + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&...args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&...args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() { + if (m_has_val) { + m_val.~T(); + } + } + union { + T m_val; + unexpected m_unexpect; + char m_no_init; + }; + bool m_has_val; +}; + +// `T` is `void`, `E` is trivially-destructible +template struct expected_storage_base { + #if __GNUC__ <= 5 + //no constexpr for GCC 4/5 bug + #else + TL_EXPECTED_MSVC2015_CONSTEXPR + #endif + expected_storage_base() : m_has_val(true) {} + + constexpr expected_storage_base(no_init_t) : m_val(), m_has_val(false) {} + + constexpr expected_storage_base(in_place_t) : m_has_val(true) {} + + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&...args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&...args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() = default; + struct dummy {}; + union { + unexpected m_unexpect; + dummy m_val; + }; + bool m_has_val; +}; + +// `T` is `void`, `E` is not trivially-destructible +template struct expected_storage_base { + constexpr expected_storage_base() : m_dummy(), m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_dummy(), m_has_val(false) {} + + constexpr expected_storage_base(in_place_t) : m_dummy(), m_has_val(true) {} + + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&...args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&...args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() { + if (!m_has_val) { + m_unexpect.~unexpected(); + } + } + + union { + unexpected m_unexpect; + char m_dummy; + }; + bool m_has_val; +}; + +// This base class provides some handy member functions which can be used in +// further derived classes +template +struct expected_operations_base : expected_storage_base { + using expected_storage_base::expected_storage_base; + + template void construct(Args &&...args) noexcept { + new (std::addressof(this->m_val)) T(std::forward(args)...); + this->m_has_val = true; + } + + template void construct_with(Rhs &&rhs) noexcept { + new (std::addressof(this->m_val)) T(std::forward(rhs).get()); + this->m_has_val = true; + } + + template void construct_error(Args &&...args) noexcept { + new (std::addressof(this->m_unexpect)) + unexpected(std::forward(args)...); + this->m_has_val = false; + } + +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + + // These assign overloads ensure that the most efficient assignment + // implementation is used while maintaining the strong exception guarantee. + // The problematic case is where rhs has a value, but *this does not. + // + // This overload handles the case where we can just copy-construct `T` + // directly into place without throwing. + template ::value> + * = nullptr> + void assign(const expected_operations_base &rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + geterr().~unexpected(); + construct(rhs.get()); + } else { + assign_common(rhs); + } + } + + // This overload handles the case where we can attempt to create a copy of + // `T`, then no-throw move it into place if the copy was successful. + template ::value && + std::is_nothrow_move_constructible::value> + * = nullptr> + void assign(const expected_operations_base &rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + T tmp = rhs.get(); + geterr().~unexpected(); + construct(std::move(tmp)); + } else { + assign_common(rhs); + } + } + + // This overload is the worst-case, where we have to move-construct the + // unexpected value into temporary storage, then try to copy the T into place. + // If the construction succeeds, then everything is fine, but if it throws, + // then we move the old unexpected value back into place before rethrowing the + // exception. + template ::value && + !std::is_nothrow_move_constructible::value> + * = nullptr> + void assign(const expected_operations_base &rhs) { + if (!this->m_has_val && rhs.m_has_val) { + auto tmp = std::move(geterr()); + geterr().~unexpected(); + +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + construct(rhs.get()); + } catch (...) { + geterr() = std::move(tmp); + throw; + } +#else + construct(rhs.get()); +#endif + } else { + assign_common(rhs); + } + } + + // These overloads do the same as above, but for rvalues + template ::value> + * = nullptr> + void assign(expected_operations_base &&rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + geterr().~unexpected(); + construct(std::move(rhs).get()); + } else { + assign_common(std::move(rhs)); + } + } + + template ::value> + * = nullptr> + void assign(expected_operations_base &&rhs) { + if (!this->m_has_val && rhs.m_has_val) { + auto tmp = std::move(geterr()); + geterr().~unexpected(); +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + construct(std::move(rhs).get()); + } catch (...) { + geterr() = std::move(tmp); + throw; + } +#else + construct(std::move(rhs).get()); +#endif + } else { + assign_common(std::move(rhs)); + } + } + +#else + + // If exceptions are disabled then we can just copy-construct + void assign(const expected_operations_base &rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + geterr().~unexpected(); + construct(rhs.get()); + } else { + assign_common(rhs); + } + } + + void assign(expected_operations_base &&rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + geterr().~unexpected(); + construct(std::move(rhs).get()); + } else { + assign_common(std::move(rhs)); + } + } + +#endif + + // The common part of move/copy assigning + template void assign_common(Rhs &&rhs) { + if (this->m_has_val) { + if (rhs.m_has_val) { + get() = std::forward(rhs).get(); + } else { + destroy_val(); + construct_error(std::forward(rhs).geterr()); + } + } else { + if (!rhs.m_has_val) { + geterr() = std::forward(rhs).geterr(); + } + } + } + + bool has_value() const { return this->m_has_val; } + + TL_EXPECTED_11_CONSTEXPR T &get() & { return this->m_val; } + constexpr const T &get() const & { return this->m_val; } + TL_EXPECTED_11_CONSTEXPR T &&get() && { return std::move(this->m_val); } +#ifndef TL_EXPECTED_NO_CONSTRR + constexpr const T &&get() const && { return std::move(this->m_val); } +#endif + + TL_EXPECTED_11_CONSTEXPR unexpected &geterr() & { + return this->m_unexpect; + } + constexpr const unexpected &geterr() const & { return this->m_unexpect; } + TL_EXPECTED_11_CONSTEXPR unexpected &&geterr() && { + return std::move(this->m_unexpect); + } +#ifndef TL_EXPECTED_NO_CONSTRR + constexpr const unexpected &&geterr() const && { + return std::move(this->m_unexpect); + } +#endif + + TL_EXPECTED_11_CONSTEXPR void destroy_val() { get().~T(); } +}; + +// This base class provides some handy member functions which can be used in +// further derived classes +template +struct expected_operations_base : expected_storage_base { + using expected_storage_base::expected_storage_base; + + template void construct() noexcept { this->m_has_val = true; } + + // This function doesn't use its argument, but needs it so that code in + // levels above this can work independently of whether T is void + template void construct_with(Rhs &&) noexcept { + this->m_has_val = true; + } + + template void construct_error(Args &&...args) noexcept { + new (std::addressof(this->m_unexpect)) + unexpected(std::forward(args)...); + this->m_has_val = false; + } + + template void assign(Rhs &&rhs) noexcept { + if (!this->m_has_val) { + if (rhs.m_has_val) { + geterr().~unexpected(); + construct(); + } else { + geterr() = std::forward(rhs).geterr(); + } + } else { + if (!rhs.m_has_val) { + construct_error(std::forward(rhs).geterr()); + } + } + } + + bool has_value() const { return this->m_has_val; } + + TL_EXPECTED_11_CONSTEXPR unexpected &geterr() & { + return this->m_unexpect; + } + constexpr const unexpected &geterr() const & { return this->m_unexpect; } + TL_EXPECTED_11_CONSTEXPR unexpected &&geterr() && { + return std::move(this->m_unexpect); + } +#ifndef TL_EXPECTED_NO_CONSTRR + constexpr const unexpected &&geterr() const && { + return std::move(this->m_unexpect); + } +#endif + + TL_EXPECTED_11_CONSTEXPR void destroy_val() { + // no-op + } +}; + +// This class manages conditionally having a trivial copy constructor +// This specialization is for when T and E are trivially copy constructible +template :: + value &&TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value> +struct expected_copy_base : expected_operations_base { + using expected_operations_base::expected_operations_base; +}; + +// This specialization is for when T or E are not trivially copy constructible +template +struct expected_copy_base : expected_operations_base { + using expected_operations_base::expected_operations_base; + + expected_copy_base() = default; + expected_copy_base(const expected_copy_base &rhs) + : expected_operations_base(no_init) { + if (rhs.has_value()) { + this->construct_with(rhs); + } else { + this->construct_error(rhs.geterr()); + } + } + + expected_copy_base(expected_copy_base &&rhs) = default; + expected_copy_base &operator=(const expected_copy_base &rhs) = default; + expected_copy_base &operator=(expected_copy_base &&rhs) = default; +}; + +// This class manages conditionally having a trivial move constructor +// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it +// doesn't implement an analogue to std::is_trivially_move_constructible. We +// have to make do with a non-trivial move constructor even if T is trivially +// move constructible +#ifndef TL_EXPECTED_GCC49 +template >::value + &&std::is_trivially_move_constructible::value> +struct expected_move_base : expected_copy_base { + using expected_copy_base::expected_copy_base; +}; +#else +template struct expected_move_base; +#endif +template +struct expected_move_base : expected_copy_base { + using expected_copy_base::expected_copy_base; + + expected_move_base() = default; + expected_move_base(const expected_move_base &rhs) = default; + + expected_move_base(expected_move_base &&rhs) noexcept( + std::is_nothrow_move_constructible::value) + : expected_copy_base(no_init) { + if (rhs.has_value()) { + this->construct_with(std::move(rhs)); + } else { + this->construct_error(std::move(rhs.geterr())); + } + } + expected_move_base &operator=(const expected_move_base &rhs) = default; + expected_move_base &operator=(expected_move_base &&rhs) = default; +}; + +// This class manages conditionally having a trivial copy assignment operator +template >::value + &&TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(E)::value + &&TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value + &&TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(E)::value> +struct expected_copy_assign_base : expected_move_base { + using expected_move_base::expected_move_base; +}; + +template +struct expected_copy_assign_base : expected_move_base { + using expected_move_base::expected_move_base; + + expected_copy_assign_base() = default; + expected_copy_assign_base(const expected_copy_assign_base &rhs) = default; + + expected_copy_assign_base(expected_copy_assign_base &&rhs) = default; + expected_copy_assign_base &operator=(const expected_copy_assign_base &rhs) { + this->assign(rhs); + return *this; + } + expected_copy_assign_base & + operator=(expected_copy_assign_base &&rhs) = default; +}; + +// This class manages conditionally having a trivial move assignment operator +// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it +// doesn't implement an analogue to std::is_trivially_move_assignable. We have +// to make do with a non-trivial move assignment operator even if T is trivially +// move assignable +#ifndef TL_EXPECTED_GCC49 +template , + std::is_trivially_move_constructible, + std::is_trivially_move_assignable>>:: + value &&std::is_trivially_destructible::value + &&std::is_trivially_move_constructible::value + &&std::is_trivially_move_assignable::value> +struct expected_move_assign_base : expected_copy_assign_base { + using expected_copy_assign_base::expected_copy_assign_base; +}; +#else +template struct expected_move_assign_base; +#endif + +template +struct expected_move_assign_base + : expected_copy_assign_base { + using expected_copy_assign_base::expected_copy_assign_base; + + expected_move_assign_base() = default; + expected_move_assign_base(const expected_move_assign_base &rhs) = default; + + expected_move_assign_base(expected_move_assign_base &&rhs) = default; + + expected_move_assign_base & + operator=(const expected_move_assign_base &rhs) = default; + + expected_move_assign_base & + operator=(expected_move_assign_base &&rhs) noexcept( + std::is_nothrow_move_constructible::value + &&std::is_nothrow_move_assignable::value) { + this->assign(std::move(rhs)); + return *this; + } +}; + +// expected_delete_ctor_base will conditionally delete copy and move +// constructors depending on whether T is copy/move constructible +template ::value && + std::is_copy_constructible::value), + bool EnableMove = (is_move_constructible_or_void::value && + std::is_move_constructible::value)> +struct expected_delete_ctor_base { + expected_delete_ctor_base() = default; + expected_delete_ctor_base(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = default; + expected_delete_ctor_base & + operator=(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base & + operator=(expected_delete_ctor_base &&) noexcept = default; +}; + +template +struct expected_delete_ctor_base { + expected_delete_ctor_base() = default; + expected_delete_ctor_base(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = delete; + expected_delete_ctor_base & + operator=(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base & + operator=(expected_delete_ctor_base &&) noexcept = default; +}; + +template +struct expected_delete_ctor_base { + expected_delete_ctor_base() = default; + expected_delete_ctor_base(const expected_delete_ctor_base &) = delete; + expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = default; + expected_delete_ctor_base & + operator=(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base & + operator=(expected_delete_ctor_base &&) noexcept = default; +}; + +template +struct expected_delete_ctor_base { + expected_delete_ctor_base() = default; + expected_delete_ctor_base(const expected_delete_ctor_base &) = delete; + expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = delete; + expected_delete_ctor_base & + operator=(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base & + operator=(expected_delete_ctor_base &&) noexcept = default; +}; + +// expected_delete_assign_base will conditionally delete copy and move +// constructors depending on whether T and E are copy/move constructible + +// assignable +template ::value && + std::is_copy_constructible::value && + is_copy_assignable_or_void::value && + std::is_copy_assignable::value), + bool EnableMove = (is_move_constructible_or_void::value && + std::is_move_constructible::value && + is_move_assignable_or_void::value && + std::is_move_assignable::value)> +struct expected_delete_assign_base { + expected_delete_assign_base() = default; + expected_delete_assign_base(const expected_delete_assign_base &) = default; + expected_delete_assign_base(expected_delete_assign_base &&) noexcept = + default; + expected_delete_assign_base & + operator=(const expected_delete_assign_base &) = default; + expected_delete_assign_base & + operator=(expected_delete_assign_base &&) noexcept = default; +}; + +template +struct expected_delete_assign_base { + expected_delete_assign_base() = default; + expected_delete_assign_base(const expected_delete_assign_base &) = default; + expected_delete_assign_base(expected_delete_assign_base &&) noexcept = + default; + expected_delete_assign_base & + operator=(const expected_delete_assign_base &) = default; + expected_delete_assign_base & + operator=(expected_delete_assign_base &&) noexcept = delete; +}; + +template +struct expected_delete_assign_base { + expected_delete_assign_base() = default; + expected_delete_assign_base(const expected_delete_assign_base &) = default; + expected_delete_assign_base(expected_delete_assign_base &&) noexcept = + default; + expected_delete_assign_base & + operator=(const expected_delete_assign_base &) = delete; + expected_delete_assign_base & + operator=(expected_delete_assign_base &&) noexcept = default; +}; + +template +struct expected_delete_assign_base { + expected_delete_assign_base() = default; + expected_delete_assign_base(const expected_delete_assign_base &) = default; + expected_delete_assign_base(expected_delete_assign_base &&) noexcept = + default; + expected_delete_assign_base & + operator=(const expected_delete_assign_base &) = delete; + expected_delete_assign_base & + operator=(expected_delete_assign_base &&) noexcept = delete; +}; + +// This is needed to be able to construct the expected_default_ctor_base which +// follows, while still conditionally deleting the default constructor. +struct default_constructor_tag { + explicit constexpr default_constructor_tag() = default; +}; + +// expected_default_ctor_base will ensure that expected has a deleted default +// consturctor if T is not default constructible. +// This specialization is for when T is default constructible +template ::value || std::is_void::value> +struct expected_default_ctor_base { + constexpr expected_default_ctor_base() noexcept = default; + constexpr expected_default_ctor_base( + expected_default_ctor_base const &) noexcept = default; + constexpr expected_default_ctor_base(expected_default_ctor_base &&) noexcept = + default; + expected_default_ctor_base & + operator=(expected_default_ctor_base const &) noexcept = default; + expected_default_ctor_base & + operator=(expected_default_ctor_base &&) noexcept = default; + + constexpr explicit expected_default_ctor_base(default_constructor_tag) {} +}; + +// This specialization is for when T is not default constructible +template struct expected_default_ctor_base { + constexpr expected_default_ctor_base() noexcept = delete; + constexpr expected_default_ctor_base( + expected_default_ctor_base const &) noexcept = default; + constexpr expected_default_ctor_base(expected_default_ctor_base &&) noexcept = + default; + expected_default_ctor_base & + operator=(expected_default_ctor_base const &) noexcept = default; + expected_default_ctor_base & + operator=(expected_default_ctor_base &&) noexcept = default; + + constexpr explicit expected_default_ctor_base(default_constructor_tag) {} +}; +} // namespace detail + +template class bad_expected_access : public std::exception { +public: + explicit bad_expected_access(E e) : m_val(std::move(e)) {} + + virtual const char *what() const noexcept override { + return "Bad expected access"; + } + + const E &error() const & { return m_val; } + E &error() & { return m_val; } + const E &&error() const && { return std::move(m_val); } + E &&error() && { return std::move(m_val); } + +private: + E m_val; +}; + +/// An `expected` object is an object that contains the storage for +/// another object and manages the lifetime of this contained object `T`. +/// Alternatively it could contain the storage for another unexpected object +/// `E`. The contained object may not be initialized after the expected object +/// has been initialized, and may not be destroyed before the expected object +/// has been destroyed. The initialization state of the contained object is +/// tracked by the expected object. +template +class expected : private detail::expected_move_assign_base, + private detail::expected_delete_ctor_base, + private detail::expected_delete_assign_base, + private detail::expected_default_ctor_base { + static_assert(!std::is_reference::value, "T must not be a reference"); + static_assert(!std::is_same::type>::value, + "T must not be in_place_t"); + static_assert(!std::is_same::type>::value, + "T must not be unexpect_t"); + static_assert( + !std::is_same>::type>::value, + "T must not be unexpected"); + static_assert(!std::is_reference::value, "E must not be a reference"); + + T *valptr() { return std::addressof(this->m_val); } + const T *valptr() const { return std::addressof(this->m_val); } + unexpected *errptr() { return std::addressof(this->m_unexpect); } + const unexpected *errptr() const { + return std::addressof(this->m_unexpect); + } + + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &val() { + return this->m_val; + } + TL_EXPECTED_11_CONSTEXPR unexpected &err() { return this->m_unexpect; } + + template ::value> * = nullptr> + constexpr const U &val() const { + return this->m_val; + } + constexpr const unexpected &err() const { return this->m_unexpect; } + + using impl_base = detail::expected_move_assign_base; + using ctor_base = detail::expected_default_ctor_base; + +public: + typedef T value_type; + typedef E error_type; + typedef unexpected unexpected_type; + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) & { + return and_then_impl(*this, std::forward(f)); + } + template TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) && { + return and_then_impl(std::move(*this), std::forward(f)); + } + template constexpr auto and_then(F &&f) const & { + return and_then_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template constexpr auto and_then(F &&f) const && { + return and_then_impl(std::move(*this), std::forward(f)); + } +#endif + +#else + template + TL_EXPECTED_11_CONSTEXPR auto + and_then(F &&f) & -> decltype(and_then_impl(std::declval(), + std::forward(f))) { + return and_then_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR auto + and_then(F &&f) && -> decltype(and_then_impl(std::declval(), + std::forward(f))) { + return and_then_impl(std::move(*this), std::forward(f)); + } + template + constexpr auto and_then(F &&f) const & -> decltype(and_then_impl( + std::declval(), std::forward(f))) { + return and_then_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr auto and_then(F &&f) const && -> decltype(and_then_impl( + std::declval(), std::forward(f))) { + return and_then_impl(std::move(*this), std::forward(f)); + } +#endif +#endif + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template TL_EXPECTED_11_CONSTEXPR auto map(F &&f) & { + return expected_map_impl(*this, std::forward(f)); + } + template TL_EXPECTED_11_CONSTEXPR auto map(F &&f) && { + return expected_map_impl(std::move(*this), std::forward(f)); + } + template constexpr auto map(F &&f) const & { + return expected_map_impl(*this, std::forward(f)); + } + template constexpr auto map(F &&f) const && { + return expected_map_impl(std::move(*this), std::forward(f)); + } +#else + template + TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl( + std::declval(), std::declval())) + map(F &&f) & { + return expected_map_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval(), + std::declval())) + map(F &&f) && { + return expected_map_impl(std::move(*this), std::forward(f)); + } + template + constexpr decltype(expected_map_impl(std::declval(), + std::declval())) + map(F &&f) const & { + return expected_map_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr decltype(expected_map_impl(std::declval(), + std::declval())) + map(F &&f) const && { + return expected_map_impl(std::move(*this), std::forward(f)); + } +#endif +#endif + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template TL_EXPECTED_11_CONSTEXPR auto transform(F &&f) & { + return expected_map_impl(*this, std::forward(f)); + } + template TL_EXPECTED_11_CONSTEXPR auto transform(F &&f) && { + return expected_map_impl(std::move(*this), std::forward(f)); + } + template constexpr auto transform(F &&f) const & { + return expected_map_impl(*this, std::forward(f)); + } + template constexpr auto transform(F &&f) const && { + return expected_map_impl(std::move(*this), std::forward(f)); + } +#else + template + TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl( + std::declval(), std::declval())) + transform(F &&f) & { + return expected_map_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR decltype(expected_map_impl(std::declval(), + std::declval())) + transform(F &&f) && { + return expected_map_impl(std::move(*this), std::forward(f)); + } + template + constexpr decltype(expected_map_impl(std::declval(), + std::declval())) + transform(F &&f) const & { + return expected_map_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr decltype(expected_map_impl(std::declval(), + std::declval())) + transform(F &&f) const && { + return expected_map_impl(std::move(*this), std::forward(f)); + } +#endif +#endif + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template TL_EXPECTED_11_CONSTEXPR auto map_error(F &&f) & { + return map_error_impl(*this, std::forward(f)); + } + template TL_EXPECTED_11_CONSTEXPR auto map_error(F &&f) && { + return map_error_impl(std::move(*this), std::forward(f)); + } + template constexpr auto map_error(F &&f) const & { + return map_error_impl(*this, std::forward(f)); + } + template constexpr auto map_error(F &&f) const && { + return map_error_impl(std::move(*this), std::forward(f)); + } +#else + template + TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), + std::declval())) + map_error(F &&f) & { + return map_error_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), + std::declval())) + map_error(F &&f) && { + return map_error_impl(std::move(*this), std::forward(f)); + } + template + constexpr decltype(map_error_impl(std::declval(), + std::declval())) + map_error(F &&f) const & { + return map_error_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr decltype(map_error_impl(std::declval(), + std::declval())) + map_error(F &&f) const && { + return map_error_impl(std::move(*this), std::forward(f)); + } +#endif +#endif +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template TL_EXPECTED_11_CONSTEXPR auto transform_error(F &&f) & { + return map_error_impl(*this, std::forward(f)); + } + template TL_EXPECTED_11_CONSTEXPR auto transform_error(F &&f) && { + return map_error_impl(std::move(*this), std::forward(f)); + } + template constexpr auto transform_error(F &&f) const & { + return map_error_impl(*this, std::forward(f)); + } + template constexpr auto transform_error(F &&f) const && { + return map_error_impl(std::move(*this), std::forward(f)); + } +#else + template + TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), + std::declval())) + transform_error(F &&f) & { + return map_error_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR decltype(map_error_impl(std::declval(), + std::declval())) + transform_error(F &&f) && { + return map_error_impl(std::move(*this), std::forward(f)); + } + template + constexpr decltype(map_error_impl(std::declval(), + std::declval())) + transform_error(F &&f) const & { + return map_error_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr decltype(map_error_impl(std::declval(), + std::declval())) + transform_error(F &&f) const && { + return map_error_impl(std::move(*this), std::forward(f)); + } +#endif +#endif + template expected TL_EXPECTED_11_CONSTEXPR or_else(F &&f) & { + return or_else_impl(*this, std::forward(f)); + } + + template expected TL_EXPECTED_11_CONSTEXPR or_else(F &&f) && { + return or_else_impl(std::move(*this), std::forward(f)); + } + + template expected constexpr or_else(F &&f) const & { + return or_else_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template expected constexpr or_else(F &&f) const && { + return or_else_impl(std::move(*this), std::forward(f)); + } +#endif + constexpr expected() = default; + constexpr expected(const expected &rhs) = default; + constexpr expected(expected &&rhs) = default; + expected &operator=(const expected &rhs) = default; + expected &operator=(expected &&rhs) = default; + + template ::value> * = + nullptr> + constexpr expected(in_place_t, Args &&...args) + : impl_base(in_place, std::forward(args)...), + ctor_base(detail::default_constructor_tag{}) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected(in_place_t, std::initializer_list il, Args &&...args) + : impl_base(in_place, il, std::forward(args)...), + ctor_base(detail::default_constructor_tag{}) {} + + template ::value> * = + nullptr, + detail::enable_if_t::value> * = + nullptr> + explicit constexpr expected(const unexpected &e) + : impl_base(unexpect, e.value()), + ctor_base(detail::default_constructor_tag{}) {} + + template < + class G = E, + detail::enable_if_t::value> * = + nullptr, + detail::enable_if_t::value> * = nullptr> + constexpr expected(unexpected const &e) + : impl_base(unexpect, e.value()), + ctor_base(detail::default_constructor_tag{}) {} + + template < + class G = E, + detail::enable_if_t::value> * = nullptr, + detail::enable_if_t::value> * = nullptr> + explicit constexpr expected(unexpected &&e) noexcept( + std::is_nothrow_constructible::value) + : impl_base(unexpect, std::move(e.value())), + ctor_base(detail::default_constructor_tag{}) {} + + template < + class G = E, + detail::enable_if_t::value> * = nullptr, + detail::enable_if_t::value> * = nullptr> + constexpr expected(unexpected &&e) noexcept( + std::is_nothrow_constructible::value) + : impl_base(unexpect, std::move(e.value())), + ctor_base(detail::default_constructor_tag{}) {} + + template ::value> * = + nullptr> + constexpr explicit expected(unexpect_t, Args &&...args) + : impl_base(unexpect, std::forward(args)...), + ctor_base(detail::default_constructor_tag{}) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected(unexpect_t, std::initializer_list il, + Args &&...args) + : impl_base(unexpect, il, std::forward(args)...), + ctor_base(detail::default_constructor_tag{}) {} + + template ::value && + std::is_convertible::value)> * = + nullptr, + detail::expected_enable_from_other + * = nullptr> + explicit TL_EXPECTED_11_CONSTEXPR expected(const expected &rhs) + : ctor_base(detail::default_constructor_tag{}) { + if (rhs.has_value()) { + this->construct(*rhs); + } else { + this->construct_error(rhs.error()); + } + } + + template ::value && + std::is_convertible::value)> * = + nullptr, + detail::expected_enable_from_other + * = nullptr> + TL_EXPECTED_11_CONSTEXPR expected(const expected &rhs) + : ctor_base(detail::default_constructor_tag{}) { + if (rhs.has_value()) { + this->construct(*rhs); + } else { + this->construct_error(rhs.error()); + } + } + + template < + class U, class G, + detail::enable_if_t::value && + std::is_convertible::value)> * = nullptr, + detail::expected_enable_from_other * = nullptr> + explicit TL_EXPECTED_11_CONSTEXPR expected(expected &&rhs) + : ctor_base(detail::default_constructor_tag{}) { + if (rhs.has_value()) { + this->construct(std::move(*rhs)); + } else { + this->construct_error(std::move(rhs.error())); + } + } + + template < + class U, class G, + detail::enable_if_t<(std::is_convertible::value && + std::is_convertible::value)> * = nullptr, + detail::expected_enable_from_other * = nullptr> + TL_EXPECTED_11_CONSTEXPR expected(expected &&rhs) + : ctor_base(detail::default_constructor_tag{}) { + if (rhs.has_value()) { + this->construct(std::move(*rhs)); + } else { + this->construct_error(std::move(rhs.error())); + } + } + + template < + class U = T, + detail::enable_if_t::value> * = nullptr, + detail::expected_enable_forward_value * = nullptr> + explicit TL_EXPECTED_MSVC2015_CONSTEXPR expected(U &&v) + : expected(in_place, std::forward(v)) {} + + template < + class U = T, + detail::enable_if_t::value> * = nullptr, + detail::expected_enable_forward_value * = nullptr> + TL_EXPECTED_MSVC2015_CONSTEXPR expected(U &&v) + : expected(in_place, std::forward(v)) {} + + template < + class U = T, class G = T, + detail::enable_if_t::value> * = + nullptr, + detail::enable_if_t::value> * = nullptr, + detail::enable_if_t< + (!std::is_same, detail::decay_t>::value && + !detail::conjunction, + std::is_same>>::value && + std::is_constructible::value && + std::is_assignable::value && + std::is_nothrow_move_constructible::value)> * = nullptr> + expected &operator=(U &&v) { + if (has_value()) { + val() = std::forward(v); + } else { + err().~unexpected(); + ::new (valptr()) T(std::forward(v)); + this->m_has_val = true; + } + + return *this; + } + + template < + class U = T, class G = T, + detail::enable_if_t::value> * = + nullptr, + detail::enable_if_t::value> * = nullptr, + detail::enable_if_t< + (!std::is_same, detail::decay_t>::value && + !detail::conjunction, + std::is_same>>::value && + std::is_constructible::value && + std::is_assignable::value && + std::is_nothrow_move_constructible::value)> * = nullptr> + expected &operator=(U &&v) { + if (has_value()) { + val() = std::forward(v); + } else { + auto tmp = std::move(err()); + err().~unexpected(); + +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (valptr()) T(std::forward(v)); + this->m_has_val = true; + } catch (...) { + err() = std::move(tmp); + throw; + } +#else + ::new (valptr()) T(std::forward(v)); + this->m_has_val = true; +#endif + } + + return *this; + } + + template ::value && + std::is_assignable::value> * = nullptr> + expected &operator=(const unexpected &rhs) { + if (!has_value()) { + err() = rhs; + } else { + this->destroy_val(); + ::new (errptr()) unexpected(rhs); + this->m_has_val = false; + } + + return *this; + } + + template ::value && + std::is_move_assignable::value> * = nullptr> + expected &operator=(unexpected &&rhs) noexcept { + if (!has_value()) { + err() = std::move(rhs); + } else { + this->destroy_val(); + ::new (errptr()) unexpected(std::move(rhs)); + this->m_has_val = false; + } + + return *this; + } + + template ::value> * = nullptr> + void emplace(Args &&...args) { + if (has_value()) { + val().~T(); + } else { + err().~unexpected(); + this->m_has_val = true; + } + ::new (valptr()) T(std::forward(args)...); + } + + template ::value> * = nullptr> + void emplace(Args &&...args) { + if (has_value()) { + val().~T(); + ::new (valptr()) T(std::forward(args)...); + } else { + auto tmp = std::move(err()); + err().~unexpected(); + +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (valptr()) T(std::forward(args)...); + this->m_has_val = true; + } catch (...) { + err() = std::move(tmp); + throw; + } +#else + ::new (valptr()) T(std::forward(args)...); + this->m_has_val = true; +#endif + } + } + + template &, Args &&...>::value> * = nullptr> + void emplace(std::initializer_list il, Args &&...args) { + if (has_value()) { + T t(il, std::forward(args)...); + val() = std::move(t); + } else { + err().~unexpected(); + ::new (valptr()) T(il, std::forward(args)...); + this->m_has_val = true; + } + } + + template &, Args &&...>::value> * = nullptr> + void emplace(std::initializer_list il, Args &&...args) { + if (has_value()) { + T t(il, std::forward(args)...); + val() = std::move(t); + } else { + auto tmp = std::move(err()); + err().~unexpected(); + +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (valptr()) T(il, std::forward(args)...); + this->m_has_val = true; + } catch (...) { + err() = std::move(tmp); + throw; + } +#else + ::new (valptr()) T(il, std::forward(args)...); + this->m_has_val = true; +#endif + } + } + +private: + using t_is_void = std::true_type; + using t_is_not_void = std::false_type; + using t_is_nothrow_move_constructible = std::true_type; + using move_constructing_t_can_throw = std::false_type; + using e_is_nothrow_move_constructible = std::true_type; + using move_constructing_e_can_throw = std::false_type; + + void swap_where_both_have_value(expected & /*rhs*/, t_is_void) noexcept { + // swapping void is a no-op + } + + void swap_where_both_have_value(expected &rhs, t_is_not_void) { + using std::swap; + swap(val(), rhs.val()); + } + + void swap_where_only_one_has_value(expected &rhs, t_is_void) noexcept( + std::is_nothrow_move_constructible::value) { + ::new (errptr()) unexpected_type(std::move(rhs.err())); + rhs.err().~unexpected_type(); + std::swap(this->m_has_val, rhs.m_has_val); + } + + void swap_where_only_one_has_value(expected &rhs, t_is_not_void) { + swap_where_only_one_has_value_and_t_is_not_void( + rhs, typename std::is_nothrow_move_constructible::type{}, + typename std::is_nothrow_move_constructible::type{}); + } + + void swap_where_only_one_has_value_and_t_is_not_void( + expected &rhs, t_is_nothrow_move_constructible, + e_is_nothrow_move_constructible) noexcept { + auto temp = std::move(val()); + val().~T(); + ::new (errptr()) unexpected_type(std::move(rhs.err())); + rhs.err().~unexpected_type(); + ::new (rhs.valptr()) T(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); + } + + void swap_where_only_one_has_value_and_t_is_not_void( + expected &rhs, t_is_nothrow_move_constructible, + move_constructing_e_can_throw) { + auto temp = std::move(val()); + val().~T(); +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (errptr()) unexpected_type(std::move(rhs.err())); + rhs.err().~unexpected_type(); + ::new (rhs.valptr()) T(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); + } catch (...) { + val() = std::move(temp); + throw; + } +#else + ::new (errptr()) unexpected_type(std::move(rhs.err())); + rhs.err().~unexpected_type(); + ::new (rhs.valptr()) T(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); +#endif + } + + void swap_where_only_one_has_value_and_t_is_not_void( + expected &rhs, move_constructing_t_can_throw, + e_is_nothrow_move_constructible) { + auto temp = std::move(rhs.err()); + rhs.err().~unexpected_type(); +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (rhs.valptr()) T(std::move(val())); + val().~T(); + ::new (errptr()) unexpected_type(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); + } catch (...) { + rhs.err() = std::move(temp); + throw; + } +#else + ::new (rhs.valptr()) T(std::move(val())); + val().~T(); + ::new (errptr()) unexpected_type(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); +#endif + } + +public: + template + detail::enable_if_t::value && + detail::is_swappable::value && + (std::is_nothrow_move_constructible::value || + std::is_nothrow_move_constructible::value)> + swap(expected &rhs) noexcept( + std::is_nothrow_move_constructible::value + &&detail::is_nothrow_swappable::value + &&std::is_nothrow_move_constructible::value + &&detail::is_nothrow_swappable::value) { + if (has_value() && rhs.has_value()) { + swap_where_both_have_value(rhs, typename std::is_void::type{}); + } else if (!has_value() && rhs.has_value()) { + rhs.swap(*this); + } else if (has_value()) { + swap_where_only_one_has_value(rhs, typename std::is_void::type{}); + } else { + using std::swap; + swap(err(), rhs.err()); + } + } + + constexpr const T *operator->() const { + TL_ASSERT(has_value()); + return valptr(); + } + TL_EXPECTED_11_CONSTEXPR T *operator->() { + TL_ASSERT(has_value()); + return valptr(); + } + + template ::value> * = nullptr> + constexpr const U &operator*() const & { + TL_ASSERT(has_value()); + return val(); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &operator*() & { + TL_ASSERT(has_value()); + return val(); + } + template ::value> * = nullptr> + constexpr const U &&operator*() const && { + TL_ASSERT(has_value()); + return std::move(val()); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &&operator*() && { + TL_ASSERT(has_value()); + return std::move(val()); + } + + constexpr bool has_value() const noexcept { return this->m_has_val; } + constexpr explicit operator bool() const noexcept { return this->m_has_val; } + + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR const U &value() const & { + if (!has_value()) + detail::throw_exception(bad_expected_access(err().value())); + return val(); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &value() & { + if (!has_value()) + detail::throw_exception(bad_expected_access(err().value())); + return val(); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR const U &&value() const && { + if (!has_value()) + detail::throw_exception(bad_expected_access(std::move(err()).value())); + return std::move(val()); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &&value() && { + if (!has_value()) + detail::throw_exception(bad_expected_access(std::move(err()).value())); + return std::move(val()); + } + + constexpr const E &error() const & { + TL_ASSERT(!has_value()); + return err().value(); + } + TL_EXPECTED_11_CONSTEXPR E &error() & { + TL_ASSERT(!has_value()); + return err().value(); + } + constexpr const E &&error() const && { + TL_ASSERT(!has_value()); + return std::move(err().value()); + } + TL_EXPECTED_11_CONSTEXPR E &&error() && { + TL_ASSERT(!has_value()); + return std::move(err().value()); + } + + template constexpr T value_or(U &&v) const & { + static_assert(std::is_copy_constructible::value && + std::is_convertible::value, + "T must be copy-constructible and convertible to from U&&"); + return bool(*this) ? **this : static_cast(std::forward(v)); + } + template TL_EXPECTED_11_CONSTEXPR T value_or(U &&v) && { + static_assert(std::is_move_constructible::value && + std::is_convertible::value, + "T must be move-constructible and convertible to from U&&"); + return bool(*this) ? std::move(**this) : static_cast(std::forward(v)); + } +}; + +namespace detail { +template using exp_t = typename detail::decay_t::value_type; +template using err_t = typename detail::decay_t::error_type; +template using ret_t = expected>; + +#ifdef TL_EXPECTED_CXX14 +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval()))> +constexpr auto and_then_impl(Exp &&exp, F &&f) { + static_assert(detail::is_expected::value, "F must return an expected"); + + return exp.has_value() + ? detail::invoke(std::forward(f), *std::forward(exp)) + : Ret(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval()))> +constexpr auto and_then_impl(Exp &&exp, F &&f) { + static_assert(detail::is_expected::value, "F must return an expected"); + + return exp.has_value() ? detail::invoke(std::forward(f)) + : Ret(unexpect, std::forward(exp).error()); +} +#else +template struct TC; +template (), + *std::declval())), + detail::enable_if_t>::value> * = nullptr> +auto and_then_impl(Exp &&exp, F &&f) -> Ret { + static_assert(detail::is_expected::value, "F must return an expected"); + + return exp.has_value() + ? detail::invoke(std::forward(f), *std::forward(exp)) + : Ret(unexpect, std::forward(exp).error()); +} + +template ())), + detail::enable_if_t>::value> * = nullptr> +constexpr auto and_then_impl(Exp &&exp, F &&f) -> Ret { + static_assert(detail::is_expected::value, "F must return an expected"); + + return exp.has_value() ? detail::invoke(std::forward(f)) + : Ret(unexpect, std::forward(exp).error()); +} +#endif + +#ifdef TL_EXPECTED_CXX14 +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval())), + detail::enable_if_t::value> * = nullptr> +constexpr auto expected_map_impl(Exp &&exp, F &&f) { + using result = ret_t>; + return exp.has_value() ? result(detail::invoke(std::forward(f), + *std::forward(exp))) + : result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval())), + detail::enable_if_t::value> * = nullptr> +auto expected_map_impl(Exp &&exp, F &&f) { + using result = expected>; + if (exp.has_value()) { + detail::invoke(std::forward(f), *std::forward(exp)); + return result(); + } + + return result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval())), + detail::enable_if_t::value> * = nullptr> +constexpr auto expected_map_impl(Exp &&exp, F &&f) { + using result = ret_t>; + return exp.has_value() ? result(detail::invoke(std::forward(f))) + : result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval())), + detail::enable_if_t::value> * = nullptr> +auto expected_map_impl(Exp &&exp, F &&f) { + using result = expected>; + if (exp.has_value()) { + detail::invoke(std::forward(f)); + return result(); + } + + return result(unexpect, std::forward(exp).error()); +} +#else +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval())), + detail::enable_if_t::value> * = nullptr> + +constexpr auto expected_map_impl(Exp &&exp, F &&f) + -> ret_t> { + using result = ret_t>; + + return exp.has_value() ? result(detail::invoke(std::forward(f), + *std::forward(exp))) + : result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval())), + detail::enable_if_t::value> * = nullptr> + +auto expected_map_impl(Exp &&exp, F &&f) -> expected> { + if (exp.has_value()) { + detail::invoke(std::forward(f), *std::forward(exp)); + return {}; + } + + return unexpected>(std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval())), + detail::enable_if_t::value> * = nullptr> + +constexpr auto expected_map_impl(Exp &&exp, F &&f) + -> ret_t> { + using result = ret_t>; + + return exp.has_value() ? result(detail::invoke(std::forward(f))) + : result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval())), + detail::enable_if_t::value> * = nullptr> + +auto expected_map_impl(Exp &&exp, F &&f) -> expected> { + if (exp.has_value()) { + detail::invoke(std::forward(f)); + return {}; + } + + return unexpected>(std::forward(exp).error()); +} +#endif + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto map_error_impl(Exp &&exp, F &&f) { + using result = expected, detail::decay_t>; + return exp.has_value() + ? result(*std::forward(exp)) + : result(unexpect, detail::invoke(std::forward(f), + std::forward(exp).error())); +} +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto map_error_impl(Exp &&exp, F &&f) { + using result = expected, monostate>; + if (exp.has_value()) { + return result(*std::forward(exp)); + } + + detail::invoke(std::forward(f), std::forward(exp).error()); + return result(unexpect, monostate{}); +} +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto map_error_impl(Exp &&exp, F &&f) { + using result = expected, detail::decay_t>; + return exp.has_value() + ? result() + : result(unexpect, detail::invoke(std::forward(f), + std::forward(exp).error())); +} +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto map_error_impl(Exp &&exp, F &&f) { + using result = expected, monostate>; + if (exp.has_value()) { + return result(); + } + + detail::invoke(std::forward(f), std::forward(exp).error()); + return result(unexpect, monostate{}); +} +#else +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto map_error_impl(Exp &&exp, F &&f) + -> expected, detail::decay_t> { + using result = expected, detail::decay_t>; + + return exp.has_value() + ? result(*std::forward(exp)) + : result(unexpect, detail::invoke(std::forward(f), + std::forward(exp).error())); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto map_error_impl(Exp &&exp, F &&f) -> expected, monostate> { + using result = expected, monostate>; + if (exp.has_value()) { + return result(*std::forward(exp)); + } + + detail::invoke(std::forward(f), std::forward(exp).error()); + return result(unexpect, monostate{}); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto map_error_impl(Exp &&exp, F &&f) + -> expected, detail::decay_t> { + using result = expected, detail::decay_t>; + + return exp.has_value() + ? result() + : result(unexpect, detail::invoke(std::forward(f), + std::forward(exp).error())); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto map_error_impl(Exp &&exp, F &&f) -> expected, monostate> { + using result = expected, monostate>; + if (exp.has_value()) { + return result(); + } + + detail::invoke(std::forward(f), std::forward(exp).error()); + return result(unexpect, monostate{}); +} +#endif + +#ifdef TL_EXPECTED_CXX14 +template (), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto or_else_impl(Exp &&exp, F &&f) { + static_assert(detail::is_expected::value, "F must return an expected"); + return exp.has_value() ? std::forward(exp) + : detail::invoke(std::forward(f), + std::forward(exp).error()); +} + +template (), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +detail::decay_t or_else_impl(Exp &&exp, F &&f) { + return exp.has_value() ? std::forward(exp) + : (detail::invoke(std::forward(f), + std::forward(exp).error()), + std::forward(exp)); +} +#else +template (), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto or_else_impl(Exp &&exp, F &&f) -> Ret { + static_assert(detail::is_expected::value, "F must return an expected"); + return exp.has_value() ? std::forward(exp) + : detail::invoke(std::forward(f), + std::forward(exp).error()); +} + +template (), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +detail::decay_t or_else_impl(Exp &&exp, F &&f) { + return exp.has_value() ? std::forward(exp) + : (detail::invoke(std::forward(f), + std::forward(exp).error()), + std::forward(exp)); +} +#endif +} // namespace detail + +template +constexpr bool operator==(const expected &lhs, + const expected &rhs) { + return (lhs.has_value() != rhs.has_value()) + ? false + : (!lhs.has_value() ? lhs.error() == rhs.error() : *lhs == *rhs); +} +template +constexpr bool operator!=(const expected &lhs, + const expected &rhs) { + return (lhs.has_value() != rhs.has_value()) + ? true + : (!lhs.has_value() ? lhs.error() != rhs.error() : *lhs != *rhs); +} +template +constexpr bool operator==(const expected &lhs, + const expected &rhs) { + return (lhs.has_value() != rhs.has_value()) + ? false + : (!lhs.has_value() ? lhs.error() == rhs.error() : true); +} +template +constexpr bool operator!=(const expected &lhs, + const expected &rhs) { + return (lhs.has_value() != rhs.has_value()) + ? true + : (!lhs.has_value() ? lhs.error() == rhs.error() : false); +} + +template +constexpr bool operator==(const expected &x, const U &v) { + return x.has_value() ? *x == v : false; +} +template +constexpr bool operator==(const U &v, const expected &x) { + return x.has_value() ? *x == v : false; +} +template +constexpr bool operator!=(const expected &x, const U &v) { + return x.has_value() ? *x != v : true; +} +template +constexpr bool operator!=(const U &v, const expected &x) { + return x.has_value() ? *x != v : true; +} + +template +constexpr bool operator==(const expected &x, const unexpected &e) { + return x.has_value() ? false : x.error() == e.value(); +} +template +constexpr bool operator==(const unexpected &e, const expected &x) { + return x.has_value() ? false : x.error() == e.value(); +} +template +constexpr bool operator!=(const expected &x, const unexpected &e) { + return x.has_value() ? true : x.error() != e.value(); +} +template +constexpr bool operator!=(const unexpected &e, const expected &x) { + return x.has_value() ? true : x.error() != e.value(); +} + +template ::value || + std::is_move_constructible::value) && + detail::is_swappable::value && + std::is_move_constructible::value && + detail::is_swappable::value> * = nullptr> +void swap(expected &lhs, + expected &rhs) noexcept(noexcept(lhs.swap(rhs))) { + lhs.swap(rhs); +} +} // namespace tl + +#endif diff --git a/src/util/expected.hpp b/src/util/expected.hpp index 03bebd5a4..f1e8469e9 100644 --- a/src/util/expected.hpp +++ b/src/util/expected.hpp @@ -27,7 +27,7 @@ namespace util { // --- Interface --- -// Return value of `value` (where `T` typically is `nonstd::expected`) or throw +// Return value of `value` (where `T` typically is `tl::expected`) or throw // an exception of type `E` with a `T::error_type` as the argument. template typename T::value_type value_or_throw(const T& value); @@ -52,7 +52,7 @@ void throw_on_error(const T& value, std::string_view prefix); do { \ const auto result = x_; \ if (!result) { \ - return nonstd::make_unexpected(result.error()); \ + return tl::unexpected(result.error()); \ } \ } while (false) diff --git a/src/util/file.cpp b/src/util/file.cpp index 888b5616d..1647da49f 100644 --- a/src/util/file.cpp +++ b/src/util/file.cpp @@ -64,14 +64,14 @@ namespace fs = util::filesystem; namespace util { -nonstd::expected +tl::expected copy_file(const std::string& src, const std::string& dest, ViaTmpFile via_tmp_file) { Fd src_fd(open(src.c_str(), O_RDONLY | O_BINARY)); if (!src_fd) { - return nonstd::make_unexpected( + return tl::unexpected( FMT("Failed to open {} for reading: {}", src, strerror(errno))); } @@ -87,7 +87,7 @@ copy_file(const std::string& src, dest_fd = Fd(open(dest.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666)); if (!dest_fd) { - return nonstd::make_unexpected( + return tl::unexpected( FMT("Failed to open {} for writing: {}", dest, strerror(errno))); } } @@ -101,10 +101,10 @@ copy_file(const std::string& src, if (via_tmp_file == ViaTmpFile::yes) { const auto result = fs::rename(tmp_file, dest); if (!result) { - return nonstd::make_unexpected(FMT("Failed to rename {} to {}: {}", - tmp_file, - dest, - result.error().message())); + return tl::unexpected(FMT("Failed to rename {} to {}: {}", + tmp_file, + dest, + result.error().message())); } } @@ -131,7 +131,7 @@ create_cachedir_tag(const std::string& dir) } } -nonstd::expected +tl::expected fallocate(int fd, size_t new_size) { #ifdef HAVE_POSIX_FALLOCATE @@ -140,7 +140,7 @@ fallocate(int fd, size_t new_size) return {}; } if (posix_fallocate_err != EINVAL) { - return nonstd::make_unexpected(strerror(posix_fallocate_err)); + return tl::unexpected(strerror(posix_fallocate_err)); } // The underlying filesystem does not support the operation so fall back to // lseek. @@ -150,7 +150,7 @@ fallocate(int fd, size_t new_size) if (old_size == -1) { int err = errno; lseek(fd, saved_pos, SEEK_SET); - return nonstd::make_unexpected(strerror(err)); + return tl::unexpected(strerror(err)); } if (static_cast(old_size) >= new_size) { lseek(fd, saved_pos, SEEK_SET); @@ -161,7 +161,7 @@ fallocate(int fd, size_t new_size) void* buf = calloc(bytes_to_write, 1); if (!buf) { lseek(fd, saved_pos, SEEK_SET); - return nonstd::make_unexpected(strerror(ENOMEM)); + return tl::unexpected(strerror(ENOMEM)); } Finalizer buf_freer([&] { free(buf); }); @@ -185,7 +185,7 @@ set_cloexec_flag(int fd) #endif } -nonstd::expected +tl::expected read_fd(int fd, DataReceiver data_receiver) { int64_t n; @@ -199,7 +199,7 @@ read_fd(int fd, DataReceiver data_receiver) } } if (n == -1) { - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } return {}; } @@ -215,13 +215,13 @@ has_utf16_le_bom(std::string_view text) #endif template -nonstd::expected +tl::expected read_file(const std::string& path, size_t size_hint) { if (size_hint == 0) { const auto stat = Stat::stat(path); if (!stat) { - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } size_hint = stat.size(); } @@ -238,7 +238,7 @@ read_file(const std::string& path, size_t size_hint) }(); Fd fd(open(path.c_str(), open_flags)); if (!fd) { - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } int64_t ret = 0; @@ -264,7 +264,7 @@ read_file(const std::string& path, size_t size_hint) } if (ret == -1) { - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } result.resize(pos); @@ -289,7 +289,7 @@ read_file(const std::string& path, size_t size_hint) nullptr, nullptr); if (size <= 0) { - return nonstd::make_unexpected( + return tl::unexpected( FMT("Failed to convert {} from UTF-16LE to UTF-8: {}", path, Win32Util::error_message(GetLastError()))); @@ -311,17 +311,17 @@ read_file(const std::string& path, size_t size_hint) return result; } -template nonstd::expected -read_file(const std::string& path, size_t size_hint); +template tl::expected read_file(const std::string& path, + size_t size_hint); -template nonstd::expected +template tl::expected read_file(const std::string& path, size_t size_hint); -template nonstd::expected, std::string> +template tl::expected, std::string> read_file(const std::string& path, size_t size_hint); template -nonstd::expected +tl::expected read_file_part(const std::string& path, size_t pos, size_t count) { T result; @@ -332,11 +332,11 @@ read_file_part(const std::string& path, size_t pos, size_t count) Fd fd(open(path.c_str(), O_RDONLY | O_BINARY)); if (!fd) { LOG("Failed to open {}: {}", path, strerror(errno)); - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } if (pos != 0 && lseek(*fd, pos, SEEK_SET) != static_cast(pos)) { - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } int64_t ret = 0; @@ -359,23 +359,23 @@ read_file_part(const std::string& path, size_t pos, size_t count) if (ret == -1) { LOG("Failed to read {}: {}", path, strerror(errno)); - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } result.resize(bytes_read); return result; } -template nonstd::expected +template tl::expected read_file_part(const std::string& path, size_t pos, size_t count); -template nonstd::expected +template tl::expected read_file_part(const std::string& path, size_t pos, size_t count); -template nonstd::expected, std::string> +template tl::expected, std::string> read_file_part(const std::string& path, size_t pos, size_t count); -nonstd::expected +tl::expected remove(const std::string& path, LogFailure log_failure) { auto result = fs::remove(path); @@ -388,7 +388,7 @@ remove(const std::string& path, LogFailure log_failure) return result; } -nonstd::expected +tl::expected remove_nfs_safe(const std::string& path, LogFailure log_failure) { // fs::remove isn't atomic if path is on an NFS share, so we rename to a @@ -409,7 +409,7 @@ remove_nfs_safe(const std::string& path, LogFailure log_failure) tmp_name, rename_result.error().message()); } - return nonstd::make_unexpected(rename_result.error()); + return tl::unexpected(rename_result.error()); } auto remove_result = fs::remove(tmp_name); @@ -456,7 +456,7 @@ set_timestamps(const std::string& path, #endif } -nonstd::expected +tl::expected write_fd(int fd, const void* data, size_t size) { int64_t written = 0; @@ -465,7 +465,7 @@ write_fd(int fd, const void* data, size_t size) write(fd, static_cast(data) + written, size - written); if (count == -1) { if (errno != EAGAIN && errno != EINTR) { - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } } else { written += count; @@ -474,7 +474,7 @@ write_fd(int fd, const void* data, size_t size) return {}; } -nonstd::expected +tl::expected write_file(const std::string& path, std::string_view data, InPlace in_place) { if (in_place == InPlace::no) { @@ -482,12 +482,12 @@ write_file(const std::string& path, std::string_view data, InPlace in_place) } Fd fd(open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_TEXT, 0666)); if (!fd) { - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } return write_fd(*fd, data.data(), data.size()); } -nonstd::expected +tl::expected write_file(const std::string& path, nonstd::span data, InPlace in_place) @@ -497,7 +497,7 @@ write_file(const std::string& path, } Fd fd(open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666)); if (!fd) { - return nonstd::make_unexpected(strerror(errno)); + return tl::unexpected(strerror(errno)); } return write_fd(*fd, data.data(), data.size()); } diff --git a/src/util/file.hpp b/src/util/file.hpp index 905e3c39a..c65514b04 100644 --- a/src/util/file.hpp +++ b/src/util/file.hpp @@ -21,8 +21,8 @@ #include #include -#include #include +#include #include #include @@ -30,6 +30,7 @@ #include #include #include +#include namespace util { @@ -41,7 +42,7 @@ enum class ViaTmpFile { yes, no }; // Copy a file from `src` to `dest`. If `via_tmp_file` is yes, `src` is copied // to a temporary file and then renamed to dest. -nonstd::expected +tl::expected copy_file(const std::string& src, const std::string& dest, ViaTmpFile via_tmp_file = ViaTmpFile::no); @@ -53,14 +54,14 @@ void create_cachedir_tag(const std::string& dir); // // Note that existing holes are not filled in case posix_fallocate() is not // supported. -nonstd::expected fallocate(int fd, size_t new_size); +tl::expected fallocate(int fd, size_t new_size); // Return how much a file of `size` bytes likely would take on disk. uint64_t likely_size_on_disk(uint64_t size); // Read data from `fd` until end of file and call `data_receiver` with the read // data. Returns an error if the underlying read(2) call returned -1. -nonstd::expected read_fd(int fd, DataReceiver data_receiver); +tl::expected read_fd(int fd, DataReceiver data_receiver); // Return contents of file at `path`. // @@ -72,8 +73,8 @@ nonstd::expected read_fd(int fd, DataReceiver data_receiver); // If `size_hint` is not 0 then it is assumed that `path` has this size (this // saves system calls). template -nonstd::expected read_file(const std::string& path, - size_t size_hint = 0); +tl::expected read_file(const std::string& path, + size_t size_hint = 0); // Return (at most) `count` bytes from `path` starting at position `pos`. // @@ -82,7 +83,7 @@ nonstd::expected read_file(const std::string& path, // with a UTF-16 little-endian BOM on Windows then it will be converted to // UTF-8. template -nonstd::expected +tl::expected read_file_part(const std::string& path, size_t pos, size_t count); // Remove `path` (non-directory), NFS hazardous. Use only for files that will @@ -90,14 +91,14 @@ read_file_part(const std::string& path, size_t pos, size_t count); // // Returns whether the file was removed. A nonexistent `path` is considered // successful. -nonstd::expected +tl::expected remove(const std::string& path, LogFailure log_failure = LogFailure::yes); // Remove `path` (non-directory), NFS safe. // // Returns whether the file was removed. A nonexistent `path` is considered a // successful. -nonstd::expected +tl::expected remove_nfs_safe(const std::string& path, LogFailure log_failure = LogFailure::yes); @@ -111,20 +112,19 @@ void set_timestamps(const std::string& path, std::optional atime = std::nullopt); // Write `size` bytes from binary `data` to `fd`. -nonstd::expected -write_fd(int fd, const void* data, size_t size); +tl::expected write_fd(int fd, const void* data, size_t size); // Write text `data` to `path`. If `in_place` is no, unlink any existing file // first (i.e., break hard links). -nonstd::expected write_file(const std::string& path, - std::string_view data, - InPlace in_place = InPlace::no); +tl::expected write_file(const std::string& path, + std::string_view data, + InPlace in_place = InPlace::no); // Write binary `data` to `path`. If `in_place` is no, unlink any existing // file first (i.e., break hard links). -nonstd::expected write_file(const std::string& path, - nonstd::span data, - InPlace in_place = InPlace::no); +tl::expected write_file(const std::string& path, + nonstd::span data, + InPlace in_place = InPlace::no); // --- Inline implementations --- diff --git a/src/util/filesystem.cpp b/src/util/filesystem.cpp index 3b20ead36..b7e744057 100644 --- a/src/util/filesystem.cpp +++ b/src/util/filesystem.cpp @@ -22,14 +22,14 @@ namespace util::filesystem { -nonstd::expected +tl::expected rename(const std::filesystem::path& old_p, const std::filesystem::path& new_p) { #ifndef _WIN32 std::error_code ec; std::filesystem::rename(old_p, new_p, ec); if (ec) { - return nonstd::make_unexpected(ec); + return tl::unexpected(ec); } #else // Windows' rename() won't overwrite an existing file, so need to use @@ -39,8 +39,7 @@ rename(const std::filesystem::path& old_p, const std::filesystem::path& new_p) MOVEFILE_REPLACE_EXISTING)) { DWORD error = GetLastError(); // TODO: How should the Win32 error be mapped to std::error_code? - return nonstd::make_unexpected( - std::error_code(error, std::system_category())); + return tl::unexpected(std::error_code(error, std::system_category())); } #endif return {}; diff --git a/src/util/filesystem.hpp b/src/util/filesystem.hpp index c992d132d..49b333622 100644 --- a/src/util/filesystem.hpp +++ b/src/util/filesystem.hpp @@ -18,9 +18,10 @@ #pragma once -#include +#include #include +#include namespace util::filesystem { @@ -29,24 +30,24 @@ using path = std::filesystem::path; // Define wrapper with no parameters returning non-void result. #define DEF_WRAP_0_R(name_, r_) \ - inline nonstd::expected name_() \ + inline tl::expected name_() \ { \ std::error_code ec_; \ auto result_ = std::filesystem::name_(ec_); \ if (ec_) { \ - return nonstd::make_unexpected(ec_); \ + return tl::unexpected(ec_); \ } \ return result_; \ } // Define wrapper with one parameter returning non-void result. #define DEF_WRAP_1_R(name_, r_, t1_, p1_) \ - inline nonstd::expected name_(t1_ p1_) \ + inline tl::expected name_(t1_ p1_) \ { \ std::error_code ec_; \ auto result_ = std::filesystem::name_(p1_, ec_); \ if (ec_) { \ - return nonstd::make_unexpected(ec_); \ + return tl::unexpected(ec_); \ } \ return result_; \ } @@ -63,36 +64,36 @@ using path = std::filesystem::path; // Define wrapper with one parameter returning void. #define DEF_WRAP_1_V(name_, r_, t1_, p1_) \ - inline nonstd::expected name_(t1_ p1_) \ + inline tl::expected name_(t1_ p1_) \ { \ std::error_code ec_; \ std::filesystem::name_(p1_, ec_); \ if (ec_) { \ - return nonstd::make_unexpected(ec_); \ + return tl::unexpected(ec_); \ } \ return {}; \ } // Define wrapper with one parameter returning non-void result. #define DEF_WRAP_1_R(name_, r_, t1_, p1_) \ - inline nonstd::expected name_(t1_ p1_) \ + inline tl::expected name_(t1_ p1_) \ { \ std::error_code ec_; \ auto result_ = std::filesystem::name_(p1_, ec_); \ if (ec_) { \ - return nonstd::make_unexpected(ec_); \ + return tl::unexpected(ec_); \ } \ return result_; \ } // Define wrapper with two parameters returning void. #define DEF_WRAP_2_V(name_, r_, t1_, p1_, t2_, p2_) \ - inline nonstd::expected name_(t1_ p1_, t2_ p2_) \ + inline tl::expected name_(t1_ p1_, t2_ p2_) \ { \ std::error_code ec_; \ std::filesystem::name_(p1_, p2_, ec_); \ if (ec_) { \ - return nonstd::make_unexpected(ec_); \ + return tl::unexpected(ec_); \ } \ return {}; \ } @@ -124,7 +125,7 @@ DEF_WRAP_0_R(temp_directory_path, path) // Note: Mingw-w64's std::filesystem::rename is buggy and doesn't properly // overwrite an existing file, at least in version 9.1.0, hence this custom // wrapper. -nonstd::expected rename(const path& old_p, - const path& new_p); +tl::expected rename(const path& old_p, + const path& new_p); } // namespace util::filesystem diff --git a/src/util/string.cpp b/src/util/string.cpp index 38e2f2603..06320f3d4 100644 --- a/src/util/string.cpp +++ b/src/util/string.cpp @@ -139,7 +139,7 @@ format_human_readable_size(uint64_t size, SizeUnitPrefixType prefix_type) } } -nonstd::expected +tl::expected parse_double(const std::string& value) { size_t end; @@ -152,14 +152,13 @@ parse_double(const std::string& value) } if (failed || end != value.size()) { - return nonstd::make_unexpected( - FMT("invalid floating point: \"{}\"", value)); + return tl::unexpected(FMT("invalid floating point: \"{}\"", value)); } else { return result; } } -nonstd::expected +tl::expected parse_duration(std::string_view duration) { uint64_t factor = 0; @@ -173,7 +172,7 @@ parse_duration(std::string_view duration) factor = 1; break; default: - return nonstd::make_unexpected(FMT( + return tl::unexpected(FMT( "invalid suffix (supported: d (day) and s (second)): \"{}\"", duration)); } @@ -184,7 +183,7 @@ parse_duration(std::string_view duration) return factor * *value; } -nonstd::expected +tl::expected parse_signed(std::string_view value, const std::optional min_value, const std::optional max_value, @@ -202,21 +201,20 @@ parse_signed(std::string_view value, failed = true; } if (failed || end != stripped_value.size()) { - return nonstd::make_unexpected( - FMT("invalid integer: \"{}\"", stripped_value)); + return tl::unexpected(FMT("invalid integer: \"{}\"", stripped_value)); } const int64_t min = min_value ? *min_value : INT64_MIN; const int64_t max = max_value ? *max_value : INT64_MAX; if (result < min || result > max) { - return nonstd::make_unexpected( + return tl::unexpected( FMT("{} must be between {} and {}", description, min, max)); } else { return result; } } -nonstd::expected, std::string> +tl::expected, std::string> parse_size(const std::string& value) { errno = 0; @@ -224,7 +222,7 @@ parse_size(const std::string& value) char* p; double result = strtod(value.c_str(), &p); if (errno != 0 || result < 0 || p == value.c_str() || value.empty()) { - return nonstd::make_unexpected(FMT("invalid size: \"{}\"", value)); + return tl::unexpected(FMT("invalid size: \"{}\"", value)); } while (isspace(*p)) { @@ -252,7 +250,7 @@ parse_size(const std::string& value) result *= multiplier; break; default: - return nonstd::make_unexpected(FMT("invalid size: \"{}\"", value)); + return tl::unexpected(FMT("invalid size: \"{}\"", value)); } } else { result *= 1024 * 1024 * 1024; @@ -262,13 +260,13 @@ parse_size(const std::string& value) return std::make_pair(static_cast(result), prefix_type); } -nonstd::expected +tl::expected parse_umask(std::string_view value) { return util::parse_unsigned(value, 0, 0777, "umask", 8); } -nonstd::expected +tl::expected parse_unsigned(std::string_view value, const std::optional min_value, const std::optional max_value, @@ -293,21 +291,21 @@ parse_unsigned(std::string_view value, } if (failed || end != stripped_value.size()) { const auto base_info = base == 8 ? "octal " : ""; - return nonstd::make_unexpected( + return tl::unexpected( FMT("invalid unsigned {}integer: \"{}\"", base_info, stripped_value)); } const uint64_t min = min_value ? *min_value : 0; const uint64_t max = max_value ? *max_value : UINT64_MAX; if (result < min || result > max) { - return nonstd::make_unexpected( + return tl::unexpected( FMT("{} must be between {} and {}", description, min, max)); } else { return result; } } -nonstd::expected +tl::expected percent_decode(std::string_view string) { const auto from_hex = [](const char digit) { @@ -323,7 +321,7 @@ percent_decode(std::string_view string) result += string[i]; } else if (i + 2 >= string.size() || !std::isxdigit(string[i + 1]) || !std::isxdigit(string[i + 2])) { - return nonstd::make_unexpected( + return tl::unexpected( FMT("invalid percent-encoded string at position {}: {}", i, string)); } else { const char ch = static_cast(from_hex(string[i + 1]) << 4 diff --git a/src/util/string.hpp b/src/util/string.hpp index dfa54c33e..2c99e34a6 100644 --- a/src/util/string.hpp +++ b/src/util/string.hpp @@ -22,8 +22,8 @@ #include #include -#include #include +#include #include // for mode_t @@ -88,12 +88,11 @@ join(const T& begin, const T& end, const std::string_view delimiter); // Parse a string into a double. // // Returns an error string if `value` cannot be parsed as a double. -nonstd::expected parse_double(const std::string& value); +tl::expected parse_double(const std::string& value); // Parse `duration`, an unsigned integer with d (days) or s (seconds) suffix, // into seconds. -nonstd::expected -parse_duration(std::string_view duration); +tl::expected parse_duration(std::string_view duration); // Parse a string into a signed integer. // @@ -101,7 +100,7 @@ parse_duration(std::string_view duration); // value falls out of the range [`min_value`, `max_value`]. `min_value` and // `max_value` default to min and max values of int64_t. `description` is // included in the error message for range violations. -nonstd::expected +tl::expected parse_signed(std::string_view value, std::optional min_value = std::nullopt, std::optional max_value = std::nullopt, @@ -110,11 +109,11 @@ parse_signed(std::string_view value, // Parse a "size value", i.e. a string that can end in k, M, G, T (10-based // suffixes) or Ki, Mi, Gi, Ti (2-based suffixes). For backward compatibility, K // is also recognized as a synonym of k. -nonstd::expected, std::string> +tl::expected, std::string> parse_size(const std::string& value); // Parse `value` (an octal integer). -nonstd::expected parse_umask(std::string_view value); +tl::expected parse_umask(std::string_view value); // Parse a string into an unsigned integer. // @@ -122,7 +121,7 @@ nonstd::expected parse_umask(std::string_view value); // `base`, or if the value falls out of the range [`min_value`, `max_value`]. // `min_value` and `max_value` default to min and max values of uint64_t. // `description` is included in the error message for range violations. -nonstd::expected +tl::expected parse_unsigned(std::string_view value, std::optional min_value = std::nullopt, std::optional max_value = std::nullopt, @@ -132,8 +131,7 @@ parse_unsigned(std::string_view value, // Percent-decode[1] `string`. // // [1]: https://en.wikipedia.org/wiki/Percent-encoding -nonstd::expected -percent_decode(std::string_view string); +tl::expected percent_decode(std::string_view string); // Replace the all occurrences of `from` to `to` in `string`. std::string replace_all(std::string_view string, diff --git a/src/util/zstd.cpp b/src/util/zstd.cpp index 10264cc27..4f6f5788b 100644 --- a/src/util/zstd.cpp +++ b/src/util/zstd.cpp @@ -22,7 +22,7 @@ namespace util { -nonstd::expected +tl::expected zstd_compress(nonstd::span input, util::Bytes& output, int8_t compression_level) @@ -37,14 +37,14 @@ zstd_compress(nonstd::span input, input.size(), compression_level); if (ZSTD_isError(ret)) { - return nonstd::make_unexpected(ZSTD_getErrorName(ret)); + return tl::unexpected(ZSTD_getErrorName(ret)); } output.resize(original_output_size + ret); return {}; } -nonstd::expected +tl::expected zstd_decompress(nonstd::span input, util::Bytes& output, size_t original_size) @@ -55,7 +55,7 @@ zstd_decompress(nonstd::span input, const size_t ret = ZSTD_decompress( &output[original_output_size], original_size, input.data(), input.size()); if (ZSTD_isError(ret)) { - return nonstd::make_unexpected(ZSTD_getErrorName(ret)); + return tl::unexpected(ZSTD_getErrorName(ret)); } output.resize(original_output_size + ret); diff --git a/src/util/zstd.hpp b/src/util/zstd.hpp index 82f4be01b..9640b33b8 100644 --- a/src/util/zstd.hpp +++ b/src/util/zstd.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2022 Joel Rosdahl and other contributors +// Copyright (C) 2022-2023 Joel Rosdahl and other contributors // // See doc/AUTHORS.adoc for a complete list of contributors. // @@ -20,8 +20,8 @@ #include -#include #include +#include #include #include @@ -29,13 +29,11 @@ namespace util { -[[nodiscard]] nonstd::expected -zstd_compress(nonstd::span input, - util::Bytes& output, - int8_t compression_level); +[[nodiscard]] tl::expected zstd_compress( + nonstd::span input, Bytes& output, int8_t compression_level); -[[nodiscard]] nonstd::expected zstd_decompress( - nonstd::span input, util::Bytes& output, size_t original_size); +[[nodiscard]] tl::expected zstd_decompress( + nonstd::span input, Bytes& output, size_t original_size); size_t zstd_compress_bound(size_t input_size); diff --git a/unittest/test_util_expected.cpp b/unittest/test_util_expected.cpp index 585b1ab6a..26eac63bb 100644 --- a/unittest/test_util_expected.cpp +++ b/unittest/test_util_expected.cpp @@ -19,7 +19,7 @@ #include #include -#include +#include #include // macOS bug: https://github.com/onqtam/doctest/issues/126 #include @@ -38,9 +38,9 @@ TEST_CASE("util::value_or_throw") SUBCASE("const ref") { - const nonstd::expected with_value = 42; - const nonstd::expected with_error = - nonstd::make_unexpected("no value"); + const tl::expected with_value = 42; + const tl::expected with_error = + tl::unexpected("no value"); CHECK(value_or_throw(with_value) == 42); CHECK_THROWS_WITH(value_or_throw(with_error), "no value"); @@ -49,10 +49,10 @@ TEST_CASE("util::value_or_throw") SUBCASE("move") { const std::string value = "value"; - nonstd::expected, const char*> with_value = + tl::expected, const char*> with_value = std::make_unique(value); - const nonstd::expected with_error = - nonstd::make_unexpected("no value"); + const tl::expected with_error = + tl::unexpected("no value"); CHECK(*value_or_throw(std::move(with_value)) == value); CHECK_THROWS_WITH(value_or_throw(std::move(with_error)), @@ -61,9 +61,9 @@ TEST_CASE("util::value_or_throw") SUBCASE("const ref with prefix") { - const nonstd::expected with_value = 42; - const nonstd::expected with_error = - nonstd::make_unexpected("no value"); + const tl::expected with_value = 42; + const tl::expected with_error = + tl::unexpected("no value"); CHECK(value_or_throw(with_value, "prefix: ") == 42); CHECK_THROWS_WITH(value_or_throw(with_error, "prefix: "), @@ -73,10 +73,10 @@ TEST_CASE("util::value_or_throw") SUBCASE("move with prefix") { const std::string value = "value"; - nonstd::expected, const char*> with_value = + tl::expected, const char*> with_value = std::make_unique(value); - const nonstd::expected with_error = - nonstd::make_unexpected("no value"); + const tl::expected with_error = + tl::unexpected("no value"); CHECK(*value_or_throw(std::move(with_value), "prefix: ") == value); @@ -87,9 +87,9 @@ TEST_CASE("util::value_or_throw") SUBCASE("void T::value_type") { - const nonstd::expected without_error; - const nonstd::expected with_error = - nonstd::make_unexpected("no value"); + const tl::expected without_error; + const tl::expected with_error = + tl::unexpected("no value"); CHECK_NOTHROW(throw_on_error(without_error)); CHECK_THROWS_WITH(throw_on_error(with_error), "no value"); @@ -97,9 +97,9 @@ TEST_CASE("util::value_or_throw") SUBCASE("void T::value_type with prefix") { - const nonstd::expected without_error; - const nonstd::expected with_error = - nonstd::make_unexpected("no value"); + const tl::expected without_error; + const tl::expected with_error = + tl::unexpected("no value"); CHECK_NOTHROW(throw_on_error(without_error, "prefix: ")); CHECK_THROWS_WITH(throw_on_error(with_error, "prefix: "),