Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/outcome/test
repos/outcome/test/tests/serialisation.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (7 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/iostream_support.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(works / outcome / serialisation, "Tests that the outcome serialises and deserialises as intended") { #if !defined(__APPLE__) || defined(__cpp_exceptions) using namespace OUTCOME_V2_NAMESPACE; outcome<std::string> a("niall"), b(std::error_code(5, std::generic_category())), c(std::make_exception_ptr(std::ios_base::failure("A test failure message"))); std::cout << "a contains " << print(a) << " and b contains " << print(b) << " and c contains " << print(c) << std::endl; std::stringstream ss; outcome<int, std::string, long> d(success(5)); ss << d; ss.seekg(0); outcome<int, std::string, long> e(failure("")); ss >> e; BOOST_CHECK(d == e); #endif }
0
repos/outcome/test
repos/outcome/test/tests/issue0244.cpp
/* Unit testing for outcomes (C) 2013-2021 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/result.hpp" #include "../../include/outcome/try.hpp" #include "quickcpplib/boost/test/unit_test.hpp" namespace issues244 { namespace outcome = OUTCOME_V2_NAMESPACE; static int counter = 0; static std::vector<int> default_constructor, copy_constructor, move_constructor, destructor; struct Foo { int x{2}; explicit Foo(int v) : x(v) { std::cout << " Default constructor " << ++counter << std::endl; default_constructor.push_back(counter); } Foo(const Foo &o) noexcept : x(o.x) { std::cout << " Copy constructor " << ++counter << std::endl; copy_constructor.push_back(counter); } Foo(Foo &&o) noexcept : x(o.x) { std::cout << " Move constructor " << ++counter << std::endl; move_constructor.push_back(counter); } ~Foo() { std::cout << " Destructor " << ++counter << std::endl; destructor.push_back(counter); } }; struct Immovable { int x{2}; explicit Immovable(int v) : x(v) { } Immovable(const Immovable &) = delete; Immovable(Immovable &&) = delete; }; outcome::result<Foo> get_foo() noexcept { return outcome::result<Foo>(outcome::in_place_type<Foo>, 5); } template <typename T> T &&filterR(T &&v) { return static_cast<T &&>(v); } template <typename T> const T &filterL(T &&v) { return v; } } // namespace issues244 BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0244 / test, "TRY/TRYX has dangling reference if xvalues are emitted from tried expression") { using namespace issues244; auto check = [](const char *desc, auto &&f) { counter = 0; default_constructor.clear(); copy_constructor.clear(); move_constructor.clear(); destructor.clear(); std::cout << "\n" << desc << std::endl; auto r = f(); std::cout << " Check integer " << ++counter << std::endl; BOOST_REQUIRE(r); BOOST_CHECK(r.value() == 5); if(!copy_constructor.empty()) { BOOST_CHECK(copy_constructor.front() < destructor.front()); } else if(!move_constructor.empty()) { BOOST_CHECK(move_constructor.front() < destructor.front()); } }; /* Default constructor 1 (bind expression prvalue to unique rvalue) Move constructor 2 (move from unique rvalue to v value) After TRY 3 Destructor 4 (destruct v value) Destructor 5 (destruct lifetime extended unique rvalue) Check integer 6 */ check("prvalue from expression with lifetime extension is moved into value", []() -> outcome::result<int> { OUTCOME_TRY(auto v, get_foo()); std::cout << " After TRY " << ++counter << std::endl; return v.x; }); /* Default constructor 1 (bind expression prvalue to unique rvalue) (bind unique rvalue to v rvalue) After TRY 2 Destructor 3 (destruct lifetime extended unique rvalue) Check integer 4 */ check("prvalue from expression with lifetime extension is bound into rvalue", []() -> outcome::result<int> { OUTCOME_TRY(auto &&v, get_foo()); std::cout << " After TRY " << ++counter << std::endl; return v.x; }); /* Default constructor 1 Move constructor 2 (move expression xvalue into unique value) Destructor 3 (destruct expression xvalue) Move constructor 4 (move from unique value to v value) After TRY 5 Destructor 6 (destruct v value) Destructor 7 (destruct unique value) Check integer 8 */ check("xvalue from expression without lifetime extension is moved into temporary and then moved into value", []() -> outcome::result<int> { OUTCOME_TRY(auto v, filterR(get_foo())); std::cout << " After TRY " << ++counter << std::endl; return v.x; }); /* Default constructor 1 Move constructor 2 (move expression xvalue into unique value) Destructor 3 (destruct expression xvalue) After TRY 4 Destructor 5 (destruct unique value) Check integer 6 */ check("xvalue from expression without lifetime extension is moved into temporary and then bound into rvalue", []() -> outcome::result<int> { OUTCOME_TRY(auto &&v, filterR(get_foo())); std::cout << " After TRY " << ++counter << std::endl; return v.x; }); /* Default constructor 1 Copy constructor 2 (copy expression lvalue into unique value) Destructor 3 (destruct expression lvalue) Copy constructor 4 (copy from unique value to v value) After TRY 5 Destructor 6 (destruct v value) Destructor 7 (destruct unique value) Check integer 8 */ check("lvalue from expression without lifetime extension is moved into temporary and then moved into value", []() -> outcome::result<int> { OUTCOME_TRY(auto v, filterL(get_foo())); std::cout << " After TRY " << ++counter << std::endl; return v.x; }); /* Default constructor 1 Copy constructor 2 (copy expression lvalue into unique value) Destructor 3 (destruct expression lvalue) After TRY 4 Destructor 5 (destruct unique value) Check integer 6 */ check("lvalue from expression without lifetime extension is moved into temporary and then bound into rvalue", []() -> outcome::result<int> { OUTCOME_TRY(auto &&v, filterL(get_foo())); std::cout << " After TRY " << ++counter << std::endl; return v.x; }); check("TRY lvalue passthrough", []() -> outcome::result<int> { const auto &x = outcome::result<Immovable>(outcome::in_place_type<Immovable>, 5); // Normally a lvalue input triggers value unique, which would fail to compile here OUTCOME_TRY((auto &, v), x); return v.x; }); // Force use of rvalue refs for unique and bound value check("TRY rvalue passthrough", []() -> outcome::result<int> { auto &&x = outcome::result<Immovable>(outcome::in_place_type<Immovable>, 5); // Normally an xvalue input triggers value unique, which would fail to compile here OUTCOME_TRY((auto &&, v), x); return v.x; }); // Force use of lvalue refs for unique and bound value check("TRY prvalue as lvalue passthrough", []() -> outcome::result<int> { outcome::result<Immovable> i(outcome::in_place_type<Immovable>, 5); OUTCOME_TRY((auto &, v), i); return v.x; }); // Force use of rvalue refs for unique and bound value check("TRY prvalue as rvalue passthrough", []() -> outcome::result<int> { outcome::result<Immovable> i(outcome::in_place_type<Immovable>, 5); OUTCOME_TRY((auto &&, v), i); return v.x; }); check("TRYV lvalue passthrough", []() -> outcome::result<int> { const auto &x = outcome::result<Immovable>(outcome::in_place_type<Immovable>, 5); // Normally a lvalue input triggers value unique, which would fail to compile here OUTCOME_TRYV2(auto &, x); return 5; }); // Force use of rvalue refs for unique and bound value check("TRYV rvalue passthrough", []() -> outcome::result<int> { auto &&x = outcome::result<Immovable>(outcome::in_place_type<Immovable>, 5); // Normally an xvalue input triggers value unique, which would fail to compile here OUTCOME_TRYV2(auto &&, x); return 5; }); // Force use of lvalue refs for unique and bound value check("TRYV prvalue as lvalue passthrough", []() -> outcome::result<int> { outcome::result<Immovable> i(outcome::in_place_type<Immovable>, 5); OUTCOME_TRYV2(auto &, i); return 5; }); // Force use of rvalue refs for unique and bound value check("TRYV prvalue as rvalue passthrough", []() -> outcome::result<int> { outcome::result<Immovable> i(outcome::in_place_type<Immovable>, 5); OUTCOME_TRYV2(auto &, i); return 5; }); }
0
repos/outcome/test
repos/outcome/test/tests/issue0010.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (9 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0010 / test, "Expected's operator->(), operator*() and .error() throw exceptions when they should not") { using namespace OUTCOME_V2_NAMESPACE; const char *a = "hi", *b = "bye"; struct udt1 // NOLINT { const char *_v{nullptr}; udt1() = default; constexpr explicit udt1(const char *v) noexcept : _v(v) {} constexpr udt1(udt1 &&o) noexcept : _v(o._v) { o._v = nullptr; } udt1(const udt1 &) = default; constexpr udt1 &operator=(udt1 &&o) noexcept { _v = o._v; o._v = nullptr; return *this; } udt1 &operator=(const udt1 &) = delete; constexpr const char *operator*() const noexcept { return _v; } }; struct udt2 // NOLINT { const char *_v{nullptr}; udt2() = default; constexpr explicit udt2(const char *v) noexcept : _v(v) {} constexpr udt2(udt2 &&o) noexcept : _v(o._v) { o._v = nullptr; } udt2(const udt2 &) = default; constexpr udt2 &operator=(udt2 &&o) noexcept { _v = o._v; o._v = nullptr; return *this; } udt1 &operator=(const udt1 &) = delete; constexpr const char *operator*() const noexcept { return _v; } }; result<udt1, udt2> p(udt1{a}); result<udt1, udt2> n(udt2{b}); // State check BOOST_CHECK(p.has_value()); BOOST_CHECK(!n.has_value()); // These should behave as expected (!) // BOOST_CHECK_NO_THROW(p.value()); // BOOST_CHECK_NO_THROW(n.value()); // And state is not destroyed BOOST_CHECK(p.has_value() && *p.assume_value() == a); BOOST_CHECK(!n.has_value() && *n.assume_error() == b); // LEWG Expected provides rvalue ref semantics for operator*(), error() and error_or() udt1 a1(std::move(p.assume_value())); BOOST_CHECK(*a1 == a); BOOST_CHECK(*p.assume_value() == nullptr); udt2 e2(std::move(n).assume_error()); BOOST_CHECK(*e2 == b); BOOST_CHECK(*n.assume_error() == nullptr); // NOLINT }
0
repos/outcome/test
repos/outcome/test/tests/experimental-core-result-status.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (8 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/experimental/status_result.hpp" template <class T, class S = SYSTEM_ERROR2_NAMESPACE::system_code, class NoValuePolicy = OUTCOME_V2_NAMESPACE::experimental::policy::default_status_result_policy<T, S>> using result = OUTCOME_V2_NAMESPACE::experimental::status_result<T, S, NoValuePolicy>; using OUTCOME_V2_NAMESPACE::in_place_type; #include "quickcpplib/boost/test/unit_test.hpp" #include <exception> #include <iostream> #ifdef __cpp_exceptions // Custom error type with payload struct payload { SYSTEM_ERROR2_NAMESPACE::errc ec{SYSTEM_ERROR2_NAMESPACE::errc::success}; const char *str{nullptr}; payload() = default; payload(SYSTEM_ERROR2_NAMESPACE::errc _ec, const char *_str) : ec(_ec) , str(_str) { } }; struct payload_exception : std::exception { const char *_what{nullptr}; explicit payload_exception(const char *what) : _what(what) { } virtual const char *what() const noexcept override final { return _what; } // NOLINT }; class _payload_domain; using status_code_payload = SYSTEM_ERROR2_NAMESPACE::status_code<_payload_domain>; class _payload_domain : public SYSTEM_ERROR2_NAMESPACE::status_code_domain { template <class> friend class status_code; using _base = SYSTEM_ERROR2_NAMESPACE::status_code_domain; public: using value_type = payload; using string_ref = _base::string_ref; public: constexpr _payload_domain() noexcept : _base(0x7b782c8f935e34ba) {} static inline constexpr const _payload_domain &get(); virtual _base::string_ref name() const noexcept override final { return string_ref("payload domain"); } // NOLINT virtual payload_info_t payload_info() const noexcept override { return {sizeof(value_type), sizeof(status_code_domain *) + sizeof(value_type), (alignof(value_type) > alignof(status_code_domain *)) ? alignof(value_type) : alignof(status_code_domain *)}; } protected: virtual bool _do_failure(const SYSTEM_ERROR2_NAMESPACE::status_code<void> &code) const noexcept override final // NOLINT { assert(code.domain() == *this); // NOLINT return static_cast<const status_code_payload &>(code).value().ec != SYSTEM_ERROR2_NAMESPACE::errc::success; // NOLINT } virtual bool _do_equivalent(const SYSTEM_ERROR2_NAMESPACE::status_code<void> &code1, const SYSTEM_ERROR2_NAMESPACE::status_code<void> &code2) const noexcept override final // NOLINT { assert(code1.domain() == *this); // NOLINT const auto &c1 = static_cast<const status_code_payload &>(code1); // NOLINT if(code2.domain() == *this) { const auto &c2 = static_cast<const status_code_payload &>(code2); // NOLINT return c1.value().ec == c2.value().ec; } return false; } virtual SYSTEM_ERROR2_NAMESPACE::generic_code _generic_code(const SYSTEM_ERROR2_NAMESPACE::status_code<void> &code) const noexcept override final // NOLINT { assert(code.domain() == *this); // NOLINT return static_cast<const status_code_payload &>(code).value().ec; // NOLINT } virtual _base::string_ref _do_message(const SYSTEM_ERROR2_NAMESPACE::status_code<void> &code) const noexcept override final // NOLINT { assert(code.domain() == *this); // NOLINT const auto &c = static_cast<const status_code_payload &>(code); // NOLINT return string_ref(SYSTEM_ERROR2_NAMESPACE::detail::generic_code_message(c.value().ec)); } virtual void _do_throw_exception(const SYSTEM_ERROR2_NAMESPACE::status_code<void> &code) const override final // NOLINT { assert(code.domain() == *this); // NOLINT const auto &c = static_cast<const status_code_payload &>(code); // NOLINT throw payload_exception(c.value().str); } }; constexpr _payload_domain payload_domain; inline constexpr const _payload_domain &_payload_domain::get() { return payload_domain; } inline status_code_payload make_status_code(payload c) noexcept { return status_code_payload(SYSTEM_ERROR2_NAMESPACE::in_place, c); } #endif BOOST_OUTCOME_AUTO_TEST_CASE(works / status_code / result, "Tests that the result with status_code works as intended") { using namespace SYSTEM_ERROR2_NAMESPACE; { // errored int result<int> m(generic_code{errc::bad_address}); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); // BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(m.value(), generic_error); BOOST_CHECK_NO_THROW(m.error()); } { // errored void result<void> m(generic_code{errc::bad_address}); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); // BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(([&m]() -> void { return m.value(); }()), generic_error); BOOST_CHECK_NO_THROW(m.error()); } { // valued int result<int> m(5); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); // BOOST_CHECK(!m.has_exception()); BOOST_CHECK(m.value() == 5); m.value() = 6; BOOST_CHECK(m.value() == 6); } { // valued bool result<bool> m(false); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); // BOOST_CHECK(!m.has_exception()); BOOST_CHECK(m.value() == false); m.value() = true; BOOST_CHECK(m.value() == true); } { // moves do not clear state result<std::string> m("niall"); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); // BOOST_CHECK(!m.has_exception()); BOOST_CHECK(m.value() == "niall"); m.value() = "NIALL"; BOOST_CHECK(m.value() == "NIALL"); auto temp(std::move(m).value()); BOOST_CHECK(temp == "NIALL"); BOOST_CHECK(m.value().empty()); // NOLINT } { // valued void result<void> m(in_place_type<void>); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); // BOOST_CHECK(!m.has_exception()); BOOST_CHECK_NO_THROW(m.value()); // works, but type returned is unusable } { // errored error ec(errc::no_link); result<int> m(ec.clone()); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); // BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(m.value(), generic_error); BOOST_CHECK(m.error() == ec); } if(false) // NOLINT { // void, void is permitted, but is not constructible result<void, void> *m = nullptr; m->value(); m->error(); } { // Deliberately define non-trivial operations struct udt { int _v{0}; udt() = default; udt(udt &&o) noexcept : _v(o._v) {} udt(const udt &o) // NOLINT : _v(o._v) { } udt &operator=(udt &&o) noexcept { _v = o._v; return *this; } udt &operator=(const udt &o) // NOLINT { _v = o._v; return *this; } ~udt() { _v = 0; } }; // No default construction, no copy nor move struct udt2 { udt2() = delete; udt2(udt2 &&) = delete; udt2(const udt2 &) = delete; udt2 &operator=(udt2 &&) = delete; udt2 &operator=(const udt2 &) = delete; explicit udt2(int /*unused*/) {} ~udt2() = default; }; // Can only be constructed via multiple args struct udt3 { udt3() = delete; udt3(udt3 &&) = delete; udt3(const udt3 &) = delete; udt3 &operator=(udt3 &&) = delete; udt3 &operator=(const udt3 &) = delete; explicit udt3(int /*unused*/, const char * /*unused*/, std::nullptr_t /*unused*/) {} ~udt3() = default; }; result<int> a(5); result<int> b(generic_code{errc::invalid_argument}); std::cout << sizeof(a) << std::endl; // 32 bytes if(false) // NOLINT { b.assume_value(); a.assume_error(); } #ifdef __cpp_exceptions try { b.value(); std::cerr << "fail" << std::endl; std::terminate(); } catch(const generic_error &e) { BOOST_CHECK(!strcmp(e.what(), b.error().message().c_str())); } #endif static_assert(!std::is_default_constructible<decltype(a)>::value, ""); static_assert(!std::is_nothrow_default_constructible<decltype(a)>::value, ""); static_assert(!std::is_copy_constructible<decltype(a)>::value, ""); // Quality of implementation of std::optional is poor :( #ifndef TESTING_WG21_EXPERIMENTAL_RESULT static_assert(!std::is_trivially_copy_constructible<decltype(a)>::value, ""); static_assert(!std::is_nothrow_copy_constructible<decltype(a)>::value, ""); static_assert(!std::is_copy_assignable<decltype(a)>::value, ""); static_assert(!std::is_trivially_copy_assignable<decltype(a)>::value, ""); static_assert(!std::is_nothrow_copy_assignable<decltype(a)>::value, ""); #endif static_assert(!std::is_trivially_destructible<decltype(a)>::value, ""); static_assert(std::is_nothrow_destructible<decltype(a)>::value, ""); // Test void compiles result<void> c(in_place_type<void>); // Test a standard udt compiles result<udt> d(in_place_type<udt>); static_assert(!std::is_default_constructible<decltype(d)>::value, ""); static_assert(!std::is_nothrow_default_constructible<decltype(d)>::value, ""); static_assert(!std::is_copy_constructible<decltype(d)>::value, ""); static_assert(!std::is_trivially_copy_constructible<decltype(d)>::value, ""); static_assert(!std::is_nothrow_copy_constructible<decltype(d)>::value, ""); static_assert(!std::is_copy_assignable<decltype(d)>::value, ""); static_assert(!std::is_trivially_copy_assignable<decltype(d)>::value, ""); static_assert(!std::is_nothrow_copy_assignable<decltype(d)>::value, ""); static_assert(std::is_move_assignable<decltype(d)>::value, ""); static_assert(!std::is_trivially_move_assignable<decltype(d)>::value, ""); static_assert(std::is_nothrow_move_assignable<decltype(d)>::value, ""); static_assert(!std::is_trivially_destructible<decltype(d)>::value, ""); static_assert(std::is_nothrow_destructible<decltype(d)>::value, ""); // Test a highly pathological udt compiles result<udt2> e(in_place_type<udt2>, 5); // result<udt2> e2(e); static_assert(!std::is_default_constructible<decltype(e)>::value, ""); static_assert(!std::is_nothrow_default_constructible<decltype(e)>::value, ""); static_assert(!std::is_copy_constructible<decltype(e)>::value, ""); static_assert(!std::is_trivially_copy_constructible<decltype(e)>::value, ""); static_assert(!std::is_nothrow_copy_constructible<decltype(e)>::value, ""); static_assert(!std::is_copy_assignable<decltype(e)>::value, ""); static_assert(!std::is_trivially_copy_assignable<decltype(e)>::value, ""); static_assert(!std::is_nothrow_copy_assignable<decltype(e)>::value, ""); static_assert(!std::is_move_assignable<decltype(e)>::value, ""); static_assert(!std::is_trivially_move_assignable<decltype(e)>::value, ""); static_assert(!std::is_nothrow_move_assignable<decltype(e)>::value, ""); // Test a udt which can only be constructed in place compiles result<udt3> g(in_place_type<udt3>, 5, static_cast<const char *>("niall"), nullptr); // Does converting inplace construction also work? result<udt3> h(5, static_cast<const char *>("niall"), nullptr); result<udt3> i(generic_code{errc::not_enough_memory}); BOOST_CHECK(h.has_value()); BOOST_CHECK(i.has_error()); } // Test direct use of error code enum works { constexpr result<int, errc, OUTCOME_V2_NAMESPACE::policy::all_narrow> a(5), b(errc::invalid_argument); static_assert(a.value() == 5, "a is not 5"); static_assert(b.error() == errc::invalid_argument, "b is not errored"); } #ifdef __cpp_exceptions // Test payload facility { const char *niall = "niall"; result<int, status_code_payload> b{payload{errc::invalid_argument, niall}}; try { b.value(); BOOST_CHECK(false); } catch(const payload_exception &e) { BOOST_CHECK(!strcmp(e.what(), niall)); } catch(...) { BOOST_CHECK(false); } } #endif }
0
repos/outcome/test
repos/outcome/test/tests/issue0115.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0115 / outcome, "Initialization from `failure_type` drops default-constructed values") { namespace out = OUTCOME_V2_NAMESPACE; out::outcome<int> o1 = std::error_code{}; BOOST_CHECK(o1.has_error()); BOOST_CHECK(!o1.has_exception()); out::outcome<int> o2 = out::failure(std::error_code{}); BOOST_CHECK(o2.has_error()); BOOST_CHECK(!o2.has_exception()); out::outcome<int> o3(std::error_code{}, std::exception_ptr{}); BOOST_CHECK(o3.has_error()); BOOST_CHECK(o3.has_exception()); out::outcome<int> o4 = out::failure(std::error_code{}, std::exception_ptr{}); BOOST_CHECK(o4.has_error()); BOOST_CHECK(o4.has_exception()); out::outcome<int> o5 = out::failure(std::exception_ptr{}); BOOST_CHECK(!o5.has_error()); BOOST_CHECK(o5.has_exception()); }
0
repos/outcome/test
repos/outcome/test/tests/issue0182.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0182 / test, "result<void, int>.value() compiles without tripping fail_to_compile_observers") { namespace outcome = OUTCOME_V2_NAMESPACE; static_assert(!outcome::trait::is_error_code_available<int>::value, "int is clearly not a source for make_error_code()"); static_assert(!outcome::trait::is_exception_ptr_available<int>::value, "int is clearly not a source for make_exception_ptr()"); //outcome::result<void, int> r(5); //r.value(); BOOST_CHECK(true); }
0
repos/outcome/test
repos/outcome/test/tests/issue0203.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/std_result.hpp" #include "../../include/outcome/try.hpp" #include "quickcpplib/boost/test/unit_test.hpp" namespace outcome = OUTCOME_V2_NAMESPACE; namespace stdalias = std; enum class error { test, abcde }; class error_category_impl : public std::error_category { public: const char *name() const noexcept override { return "test"; } std::string message(int code) const noexcept override { switch(static_cast<error>(code)) { case error::test: return "test"; case error::abcde: return "abcde"; } return "unknown"; } }; const std::error_category &error_category() noexcept { static error_category_impl instance; return instance; } stdalias::error_code make_error_code(error error) noexcept { return {static_cast<int>(error), error_category()}; } namespace std { template <> struct is_error_code_enum<error> : true_type { }; } // namespace std template <typename T> using enum_result = outcome::basic_result<T, error, outcome::policy::default_policy<T, error, void>>; enum_result<int> test() { return 5; } outcome::std_result<int> abc() { static_assert(std::is_error_code_enum<error>::value, "custom enum is not marked convertible to error code"); static_assert(std::is_constructible<stdalias::error_code, error>::value, "error code is not explicitly constructible from custom enum"); static_assert(std::is_convertible<error, stdalias::error_code>::value, "error code is not implicitly constructible from custom enum"); stdalias::error_code ec = error::test; // custom enum is definitely convertible to error code OUTCOME_TRY(test()); // hence this should compile, as implicit conversions work here (void) ec; // But explicit conversions are required between dissimilar basic_result, implicit conversions are disabled static_assert(std::is_constructible<outcome::std_result<int>, enum_result<int>>::value, "basic_result with error code is not explicitly constructible from basic_result with custom enum"); static_assert(!std::is_convertible<enum_result<int>, outcome::std_result<int>>::value, "basic_result with error code is implicitly constructible from basic_result with custom enum"); return 5; } BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0203 / test, "enum convertible to error code works as designed") { BOOST_CHECK(abc().value() == 5); }
0
repos/outcome/test
repos/outcome/test/tests/issue0007.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (5 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "../../include/outcome/try.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0007 / test, "OUTCOME_TRYV(expr) in a function whose return outcome's type has no default constructor fails to compile") { using namespace OUTCOME_V2_NAMESPACE; struct udt // NOLINT { explicit udt(int /*unused*/) {} // udt() = delete; udt(const udt &) = default; udt(udt &&) = default; }; { auto f = []() -> result<udt> { auto g = [] { return result<int>(5); }; /* This fails because BOOST_OUTCOME_TRYV() returns a result<void> which if it were valued void, would implicitly convert into a default constructed udt which is not possible, hence the compile error. */ OUTCOME_TRYV(g()); return udt(5); }; (void) f(); } { auto f = []() -> outcome<udt> { auto g = [] { return outcome<int>(5); }; /* This fails because BOOST_OUTCOME_TRYV() returns a result<void> which if it were valued void, would implicitly convert into a default constructed udt which is not possible, hence the compile error. */ OUTCOME_TRYV(g()); return udt(5); }; (void) f(); } { auto f = []() -> outcome<udt> { auto g = [] { return result<int>(5); }; /* This fails because BOOST_OUTCOME_TRYV() returns a result<void> which if it were valued void, would implicitly convert into a default constructed udt which is not possible, hence the compile error. */ OUTCOME_TRYV(g()); return udt(5); }; (void) f(); } }
0
repos/outcome/test
repos/outcome/test/tests/issue0255.cpp
/* Unit testing for outcomes (C) 2013-2021 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/experimental/status_result.hpp" #include "quickcpplib/boost/test/unit_test.hpp" #if __cplusplus >= 202000L || _HAS_CXX20 namespace issues255 { namespace outcome_e = OUTCOME_V2_NAMESPACE::experimental; static_assert(outcome_e::traits::is_move_bitcopying<outcome_e::error>::value, "outcome_e::error is not move bitcopying!"); constexpr outcome_e::status_result<int> test() { return outcome_e::success(42); } } BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0255 / test, "status_result<int> not usable from constexpr in C++ 20") { BOOST_CHECK(issues255::test().value() == 42); } #else BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0255 / test, "status_result<int> not usable from constexpr in C++ 20") { BOOST_CHECK(true); } #endif
0
repos/outcome/test
repos/outcome/test/tests/comparison.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (6 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifdef _MSC_VER #pragma warning(disable : 4127) // conditional expression is constant #pragma warning(disable : 4244) // conversion from int to short #endif #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(works / outcome / comparison, "Tests that the outcome can compare to compatible outcomes") { #if !defined(__APPLE__) || defined(__cpp_exceptions) using namespace OUTCOME_V2_NAMESPACE; auto p = std::make_exception_ptr(std::runtime_error("hi")); // value comparison { outcome<int> a(1), b(2), c(2); BOOST_CHECK(a == a); BOOST_CHECK(b == b); BOOST_CHECK(c == c); BOOST_CHECK(a != b); BOOST_CHECK(b == c); } // homogeneous outcome comparison { outcome<int> a(1), b(2), c(std::errc::invalid_argument), d(p); BOOST_CHECK(a == a); BOOST_CHECK(a != b); BOOST_CHECK(a != c); BOOST_CHECK(a != d); BOOST_CHECK(b == b); BOOST_CHECK(b != c); BOOST_CHECK(b != d); BOOST_CHECK(c == c); BOOST_CHECK(c != d); BOOST_CHECK(d == d); outcome<int> e(std::errc::invalid_argument), f(p); BOOST_CHECK(c == e); BOOST_CHECK(d == f); } // heterogeneous outcome comparison, so outcome<int> to outcome<double> etc { outcome<int> a(1); outcome<double> b(1); outcome<unsigned short> c(1); BOOST_CHECK(a == b); BOOST_CHECK(a == c); BOOST_CHECK(b == a); BOOST_CHECK(b == c); BOOST_CHECK(c == a); BOOST_CHECK(c == b); // outcome<void> e(in_place_type<void>); outcome<unsigned short> f(std::errc::invalid_argument); outcome<double> g(p); // BOOST_CHECK(a != e); BOOST_CHECK(a != f); BOOST_CHECK(a != g); // BOOST_CHECK(e != f); BOOST_CHECK(f != g); } // upconverting outcome comparison, so outcome<int>==result<int> etc { outcome<int> a(1); result<int> b(1); BOOST_CHECK(a == b); BOOST_CHECK(b == a); // result<void> e(in_place_type<void>), f(std::errc::invalid_argument); // BOOST_CHECK(a != e); // BOOST_CHECK(a != f); } // Should I do outcome<int>(5) == 5? Unsure if it's wise #endif }
0
repos/outcome/test
repos/outcome/test/tests/issue0061.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (6 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0061 / result, "result<T1, E1> does not compare to incompatible result<T2, E2>") { using namespace OUTCOME_V2_NAMESPACE; struct udt1 { const char *_v{nullptr}; udt1() = default; constexpr udt1(const char *v) noexcept : _v(v) {} // NOLINT udt1(udt1 &&o) = delete; udt1(const udt1 &) = delete; udt1 &operator=(udt1 &&o) = delete; udt1 &operator=(const udt1 &) = delete; ~udt1() = default; constexpr const char *operator*() const noexcept { return _v; } }; struct udt2 { const char *_v{nullptr}; udt2() = default; constexpr explicit udt2(const char *v) noexcept : _v(v) {} udt2(udt2 &&o) = delete; udt2(const udt2 &) = delete; udt2 &operator=(udt2 &&o) = delete; udt2 &operator=(const udt2 &) = delete; ~udt2() = default; constexpr const char *operator*() const noexcept { return _v; } bool operator==(const udt1 &o) const noexcept { return _v == *o; } bool operator!=(const udt1 &o) const noexcept { return _v != *o; } }; using result1 = result<int, udt1>; using result2 = result<int, udt2>; result1 a(5); result2 b(5); BOOST_CHECK(b == a); // udt2 will compare to udt1 BOOST_CHECK(!(b != a)); // udt2 will compare to udt1 result<void> c = success(); result<void> d = success(); BOOST_CHECK(c == d); BOOST_CHECK(!(c != d)); BOOST_CHECK(a == success()); BOOST_CHECK(success() == a); BOOST_CHECK(b != failure("foo")); BOOST_CHECK(failure("foo") != b); } BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0061 / outcome, "outcome<T1, E1, P1> does not compare to incompatible outcome<T2, E2, P2>") { using namespace OUTCOME_V2_NAMESPACE; struct udt1 { const char *_v{nullptr}; udt1() = default; constexpr udt1(const char *v) noexcept : _v(v) {} // NOLINT udt1(udt1 &&o) = delete; udt1(const udt1 &) = delete; udt1 &operator=(udt1 &&o) = delete; udt1 &operator=(const udt1 &) = delete; ~udt1() = default; constexpr const char *operator*() const noexcept { return _v; } }; struct udt2 { const char *_v{nullptr}; udt2() = default; constexpr explicit udt2(const char *v) noexcept : _v(v) {} udt2(udt2 &&o) = delete; udt2(const udt2 &) = delete; udt2 &operator=(udt2 &&o) = delete; udt2 &operator=(const udt2 &) = delete; ~udt2() = default; constexpr const char *operator*() const noexcept { return _v; } bool operator==(const udt1 &o) const noexcept { return _v == *o; } bool operator!=(const udt1 &o) const noexcept { return _v != *o; } }; using outcome1 = outcome<int, udt1>; using outcome2 = outcome<int, udt2>; outcome1 a(5), _a(6); outcome2 b(5); BOOST_CHECK(b == a); // udt2 will compare to udt1 BOOST_CHECK(!(b != a)); // udt2 will compare to udt1 outcome<void> c = success(); outcome<void> d = success(); BOOST_CHECK(c == d); BOOST_CHECK(!(c != d)); BOOST_CHECK(a == success()); BOOST_CHECK(success() == a); BOOST_CHECK(b != failure("foo")); BOOST_CHECK(failure("foo") != b); }
0
repos/outcome/test
repos/outcome/test/tests/issue0140.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (2 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0140 / result, "Construction of non copy constructible value_type fails to not compile") { namespace out = OUTCOME_V2_NAMESPACE; enum op { constructed, moved, copied }; struct NotCopyMoveConstructible { op v{op::constructed}; NotCopyMoveConstructible() = default; NotCopyMoveConstructible(const NotCopyMoveConstructible &o) = delete; NotCopyMoveConstructible(NotCopyMoveConstructible &&) = delete; NotCopyMoveConstructible &operator=(const NotCopyMoveConstructible &) = delete; NotCopyMoveConstructible &operator=(NotCopyMoveConstructible &&) = delete; ~NotCopyMoveConstructible() = default; }; struct NotMoveConstructible { op v{op::constructed}; NotMoveConstructible() = default; NotMoveConstructible(const NotMoveConstructible & /*unused*/) : v(op::copied) { } NotMoveConstructible(NotMoveConstructible &&) = delete; NotMoveConstructible &operator=(const NotMoveConstructible &) = delete; NotMoveConstructible &operator=(NotMoveConstructible &&) = delete; ~NotMoveConstructible() = default; }; struct NotCopyConstructible { op v{op::constructed}; NotCopyConstructible() = default; NotCopyConstructible(NotCopyConstructible && /*unused*/) noexcept : v(op::moved) {} NotCopyConstructible(const NotCopyConstructible & /*unused*/) = delete; NotCopyConstructible &operator=(const NotCopyConstructible &) = delete; NotCopyConstructible &operator=(NotCopyConstructible &&) = delete; ~NotCopyConstructible() = default; }; // Uncopyable and immovable items should be neither copyable nor moveable static_assert(!std::is_copy_constructible<out::result<NotCopyMoveConstructible>>::value, "result<NotCopyMoveConstructible> is copy constructible!"); static_assert(!std::is_move_constructible<out::result<NotCopyMoveConstructible>>::value, "result<NotCopyMoveConstructible> is move constructible!"); static_assert(!std::is_convertible<const NotCopyMoveConstructible &, NotCopyMoveConstructible>::value, ""); static_assert(!std::is_convertible<NotCopyMoveConstructible &&, NotCopyMoveConstructible>::value, ""); static_assert(!std::is_constructible<out::result<NotCopyMoveConstructible>, const NotCopyMoveConstructible &>::value, "result<NotCopyMoveConstructible> is constructible from const NotCopyMoveConstructible&!"); static_assert(!std::is_constructible<out::result<NotCopyMoveConstructible>, NotCopyMoveConstructible &&>::value, "result<NotCopyMoveConstructible> is constructible from NotCopyMoveConstructible&&!"); // Immovable items should fall back to copy static_assert(!std::is_move_constructible<NotMoveConstructible>::value, "NotMoveConstructible is move constructible!"); static_assert(std::is_move_constructible<out::result<NotMoveConstructible>>::value, "result<NotMoveConstructible> is not move constructible!"); static_assert(std::is_constructible<out::result<NotMoveConstructible>, const NotMoveConstructible &>::value, "result<NotMoveConstructible> is not constructible from NotMoveConstructible&&!"); // Uncopyable items should never move (this was the bug report) static_assert(!std::is_copy_constructible<out::result<NotCopyConstructible>>::value, "result<NotCopyConstructible> is copy constructible!"); static_assert(!std::is_constructible<out::result<NotCopyConstructible>, const NotCopyConstructible &>::value, "result<NotCopyConstructible> is constructible from const NotCopyConstructible&!"); BOOST_CHECK(true); }
0
repos/outcome/test
repos/outcome/test/tests/noexcept-propagation.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (6 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" #ifdef _MSC_VER #pragma warning(disable : 4127) // conditional expression is constant #endif #ifdef __cpp_exceptions // std nothrow traits seem to return random values if exceptions are disabled on MSVC BOOST_OUTCOME_AUTO_TEST_CASE(works / outcome / noexcept, "Tests that the outcome correctly inherits noexcept from its type R") { using namespace OUTCOME_V2_NAMESPACE; { using type = outcome<int>; BOOST_CHECK(std::is_nothrow_copy_constructible<type>::value); BOOST_CHECK(std::is_nothrow_move_constructible<type>::value); BOOST_CHECK(std::is_nothrow_copy_assignable<type>::value); BOOST_CHECK(std::is_nothrow_move_assignable<type>::value); BOOST_CHECK(std::is_nothrow_destructible<type>::value); } { using type = outcome<std::string>; BOOST_CHECK(std::is_nothrow_copy_constructible<type>::value == std::is_nothrow_copy_constructible<std::string>::value); BOOST_CHECK(std::is_nothrow_move_constructible<type>::value == std::is_nothrow_move_constructible<std::string>::value); BOOST_CHECK(std::is_nothrow_copy_assignable<type>::value == std::is_nothrow_copy_assignable<std::string>::value); BOOST_CHECK(std::is_nothrow_move_assignable<type>::value == std::is_nothrow_move_assignable<std::string>::value); BOOST_CHECK(std::is_nothrow_destructible<type>::value == std::is_nothrow_destructible<std::string>::value); } { struct Except { int n; Except() = delete; Except(const Except & /*unused*/) noexcept(false) : n(0) { } Except(Except && /*unused*/) noexcept(false) : n(0) { } Except &operator=(const Except & /*unused*/) noexcept(false) { return *this; } Except &operator=(Except && /*unused*/) noexcept(false) { return *this; } ~Except() noexcept(false) { n = 0; } }; using type = outcome<Except>; BOOST_CHECK(!std::is_nothrow_copy_constructible<type>::value); BOOST_CHECK(!std::is_nothrow_move_constructible<type>::value); BOOST_CHECK(!std::is_nothrow_copy_assignable<type>::value); BOOST_CHECK(!std::is_nothrow_move_assignable<type>::value); BOOST_CHECK(!std::is_nothrow_destructible<type>::value); } } #endif
0
repos/outcome/test
repos/outcome/test/tests/issue0220.cpp
/* Unit testing for outcomes (C) 2013-2020 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/experimental/status_result.hpp" #include "../../include/outcome/try.hpp" #include "quickcpplib/boost/test/unit_test.hpp" #ifndef SYSTEM_ERROR2_NOT_POSIX namespace issues220 { namespace outcome_e = OUTCOME_V2_NAMESPACE::experimental; template <class T, class E = outcome_e::error> using Result = outcome_e::status_result<T, E>; template <class T> using PosixResult = outcome_e::status_result<T, outcome_e::posix_code>; Result<int> convert(const PosixResult<int> &posix_result) { return Result<int>(posix_result); } } // namespace issues220 #endif BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0220 / test, "ubsan reports reference binding to null pointer") { #ifndef SYSTEM_ERROR2_NOT_POSIX using namespace issues220; BOOST_CHECK(convert(PosixResult<int>(0)).value() == 0); #endif }
0
repos/outcome/test
repos/outcome/test/tests/issue0009.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (5 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "../../include/outcome/try.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0009 / test, "Alternative TRY macros?") { #ifdef OUTCOME_TRYX #pragma GCC diagnostic ignored "-Wpedantic" using namespace OUTCOME_V2_NAMESPACE; struct udt // NOLINT { explicit udt(int /*unused*/) {} // udt() = delete; udt(const udt &) = default; udt(udt &&) = default; }; auto f = []() -> result<udt> { auto g = [] { return result<int>(5); }; return udt(OUTCOME_TRYX(g())); }; (void) f(); #endif }
0
repos/outcome/test
repos/outcome/test/tests/issue0116.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (2 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0116 / outcome, "Bad implementation of outcome::operator==") { namespace out = OUTCOME_V2_NAMESPACE; out::outcome<int> o1 = 1; BOOST_CHECK(!o1.has_error()); out::outcome<int> o2 = out::failure(std::error_code{EINVAL, std::generic_category()}); BOOST_CHECK(o2.has_error()); BOOST_CHECK(o1 != o2); }
0
repos/outcome/test
repos/outcome/test/tests/issue0016.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (5 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0016 / test, "Default constructor of T is sometimes compiled when T has no default constructor") { using namespace OUTCOME_V2_NAMESPACE; struct udt { const char *_v{nullptr}; udt() = delete; constexpr explicit udt(const char *v) noexcept : _v(v) {} constexpr udt(udt &&o) noexcept : _v(o._v) { o._v = nullptr; } udt(const udt &) = delete; constexpr udt &operator=(udt &&o) noexcept { _v = o._v; o._v = nullptr; return *this; } udt &operator=(const udt &) = delete; ~udt() = default; constexpr const char *operator*() const noexcept { return _v; } }; result<udt> n(std::error_code(ENOMEM, std::generic_category())); (void) n; }
0
repos/outcome/test
repos/outcome/test/tests/issue0259.cpp
/* Unit testing for outcomes (C) 2013-2022 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0259 / test, "move assignable is not calculated correctly") { struct DefaultConstructibleMoveAssignable { int a; DefaultConstructibleMoveAssignable() = default; DefaultConstructibleMoveAssignable(int) {} DefaultConstructibleMoveAssignable(const DefaultConstructibleMoveAssignable &) = delete; DefaultConstructibleMoveAssignable(DefaultConstructibleMoveAssignable &&) = delete; DefaultConstructibleMoveAssignable &operator=(const DefaultConstructibleMoveAssignable &) = delete; DefaultConstructibleMoveAssignable &operator=(DefaultConstructibleMoveAssignable &&) noexcept { return *this; } ~DefaultConstructibleMoveAssignable() = default; }; struct DefaultConstructibleCopyAssignable { int a; DefaultConstructibleCopyAssignable() = default; DefaultConstructibleCopyAssignable(int) {} DefaultConstructibleCopyAssignable(const DefaultConstructibleCopyAssignable &) = delete; DefaultConstructibleCopyAssignable(DefaultConstructibleCopyAssignable &&) = delete; DefaultConstructibleCopyAssignable &operator=(const DefaultConstructibleCopyAssignable &) { return *this; } DefaultConstructibleCopyAssignable &operator=(DefaultConstructibleCopyAssignable &&) = delete; ~DefaultConstructibleCopyAssignable() = default; }; struct NonDefaultConstructibleMoveAssignable { int a; NonDefaultConstructibleMoveAssignable() = delete; NonDefaultConstructibleMoveAssignable(int) {} NonDefaultConstructibleMoveAssignable(const NonDefaultConstructibleMoveAssignable &) = delete; NonDefaultConstructibleMoveAssignable(NonDefaultConstructibleMoveAssignable &&) = delete; NonDefaultConstructibleMoveAssignable &operator=(const NonDefaultConstructibleMoveAssignable &) = delete; NonDefaultConstructibleMoveAssignable &operator=(NonDefaultConstructibleMoveAssignable &&) noexcept { return *this; } ~NonDefaultConstructibleMoveAssignable() = default; }; struct NonDefaultConstructibleCopyAssignable { int a; NonDefaultConstructibleCopyAssignable() = delete; NonDefaultConstructibleCopyAssignable(int) {} NonDefaultConstructibleCopyAssignable(const NonDefaultConstructibleCopyAssignable &) = delete; NonDefaultConstructibleCopyAssignable(NonDefaultConstructibleCopyAssignable &&) = delete; NonDefaultConstructibleCopyAssignable &operator=(const NonDefaultConstructibleCopyAssignable &) { return *this; } NonDefaultConstructibleCopyAssignable &operator=(NonDefaultConstructibleCopyAssignable &&) = delete; ~NonDefaultConstructibleCopyAssignable() = default; }; { using type = OUTCOME_V2_NAMESPACE::result<DefaultConstructibleMoveAssignable>; type test1(OUTCOME_V2_NAMESPACE::success(5)), test1a(OUTCOME_V2_NAMESPACE::success(6)); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(!std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::result<DefaultConstructibleCopyAssignable>; type test1(OUTCOME_V2_NAMESPACE::success(5)), test1a(OUTCOME_V2_NAMESPACE::success(6)); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::result<NonDefaultConstructibleMoveAssignable>; type test1(OUTCOME_V2_NAMESPACE::success(5)), test1a(OUTCOME_V2_NAMESPACE::success(6)); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(!std::is_copy_assignable<type>::value, ""); static_assert(!std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::result<NonDefaultConstructibleCopyAssignable>; type test1(OUTCOME_V2_NAMESPACE::success(5)), test1a(OUTCOME_V2_NAMESPACE::success(6)); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(!std::is_copy_assignable<type>::value, ""); static_assert(!std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::result<void, DefaultConstructibleMoveAssignable>; type test1(OUTCOME_V2_NAMESPACE::failure(5)), test1a(OUTCOME_V2_NAMESPACE::failure(6)); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(!std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::result<void, DefaultConstructibleCopyAssignable>; type test1(OUTCOME_V2_NAMESPACE::failure(5)), test1a(OUTCOME_V2_NAMESPACE::failure(6)); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::result<DefaultConstructibleMoveAssignable, void>; type test1(OUTCOME_V2_NAMESPACE::success(5)), test1a(OUTCOME_V2_NAMESPACE::success(6)); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(!std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::result<DefaultConstructibleCopyAssignable, void>; type test1(OUTCOME_V2_NAMESPACE::success(5)), test1a(OUTCOME_V2_NAMESPACE::success(6)); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::outcome<int, double, DefaultConstructibleMoveAssignable>; type test1(OUTCOME_V2_NAMESPACE::success(5)), test1a(OUTCOME_V2_NAMESPACE::success(6)); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(!std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::outcome<int, double, DefaultConstructibleCopyAssignable>; type test1(OUTCOME_V2_NAMESPACE::success(5)), test1a(OUTCOME_V2_NAMESPACE::success(6)); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::outcome<void, void, DefaultConstructibleMoveAssignable>; type test1(OUTCOME_V2_NAMESPACE::success()), test1a(OUTCOME_V2_NAMESPACE::success()); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(!std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } { using type = OUTCOME_V2_NAMESPACE::outcome<void, void, DefaultConstructibleCopyAssignable>; type test1(OUTCOME_V2_NAMESPACE::success()), test1a(OUTCOME_V2_NAMESPACE::success()); test1 = std::move(test1a); static_assert(!std::is_copy_constructible<type>::value, ""); static_assert(!std::is_move_constructible<type>::value, ""); static_assert(std::is_copy_assignable<type>::value, ""); static_assert(std::is_move_assignable<type>::value, ""); static_assert(std::is_destructible<type>::value, ""); } }
0
repos/outcome/test
repos/outcome/test/tests/core-outcome.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (18 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" #include <iostream> #ifdef _MSC_VER #pragma warning(disable : 4702) // unreachable code #endif BOOST_OUTCOME_AUTO_TEST_CASE(works / outcome, "Tests that the outcome works as intended") { using namespace OUTCOME_V2_NAMESPACE; static_assert(std::is_constructible<outcome<long>, int>::value, "Sanity check that monad can be constructed from a value_type"); static_assert(!std::is_constructible<outcome<outcome<long>>, int>::value, "Sanity check that outer monad can be constructed from an inner monad's value_type"); #if defined(__clang__) || !defined(__GNUC__) || __GNUC__ >= 9 // GCCs before 9 barf on this static_assert(!std::is_constructible<outcome<outcome<outcome<long>>>, int>::value, "Sanity check that outer monad can be constructed from an inner inner monad's value_type"); static_assert(!std::is_constructible<outcome<outcome<outcome<outcome<long>>>>, int>::value, "Sanity check that outer monad can be constructed from an inner inner monad's value_type"); #endif static_assert(std::is_constructible<outcome<int>, outcome<long>>::value, "Sanity check that compatible monads can be constructed from one another"); static_assert(std::is_constructible<outcome<outcome<int>>, outcome<long>>::value, "Sanity check that outer monad can be constructed from a compatible monad"); #if defined(__clang__) || !defined(__GNUC__) || __GNUC__ >= 9 // GCCs before 9 barf on this static_assert(!std::is_constructible<outcome<outcome<outcome<int>>>, outcome<long>>::value, "Sanity check that outer monad can be constructed from a compatible monad up to two nestings deep"); static_assert(!std::is_constructible<outcome<outcome<outcome<outcome<int>>>>, outcome<long>>::value, "Sanity check that outer monad can be constructed from a compatible monad three or more nestings deep"); #endif static_assert(!std::is_constructible<outcome<std::string>, outcome<int>>::value, "Sanity check that incompatible monads cannot be constructed from one another"); static_assert(std::is_constructible<outcome<int>, outcome<void>>::value, "Sanity check that all monads can be constructed from a void monad"); static_assert(std::is_constructible<outcome<outcome<int>>, outcome<void>>::value, "Sanity check that outer monad can be constructed from a compatible monad"); #if defined(__clang__) || !defined(__GNUC__) || __GNUC__ >= 9 // GCCs before 9 barf on this static_assert(std::is_constructible<outcome<outcome<outcome<int>>>, outcome<void>>::value, "Sanity check that outer monad can be constructed from a compatible monad up to two nestings deep"); #endif static_assert(!std::is_constructible<outcome<void>, outcome<int>>::value, "Sanity check that incompatible monads cannot be constructed from one another"); static_assert(std::is_void<result<void>::value_type>::value, "Sanity check that result<void> has a void value_type"); static_assert(std::is_void<result<void, void>::error_type>::value, "Sanity check that result<void, void> has a void error_type"); // static_assert(std::is_void<outcome<void, void, void>::exception_type>::value, "Sanity check that outcome<void, void, void> has a void exception_type"); static_assert(std::is_same<outcome<int>::value_type, int>::value, "Sanity check that outcome<int> has a int value_type"); static_assert(std::is_same<outcome<int>::error_type, std::error_code>::value, "Sanity check that outcome<int> has a error_code error_type"); static_assert(std::is_same<outcome<int>::exception_type, std::exception_ptr>::value, "Sanity check that outcome<int> has a exception_ptr exception_type"); { // errored int outcome<int> m(std::errc::bad_address); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(m.value(), std::system_error); BOOST_CHECK_NO_THROW(m.error()); BOOST_CHECK_THROW(m.exception(), bad_outcome_access); BOOST_CHECK_THROW(std::rethrow_exception(m.failure()), std::system_error); } { // errored void outcome<void> m(std::errc::bad_address); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(([&m]() -> void { return m.value(); }()), std::system_error); BOOST_CHECK_NO_THROW(m.error()); BOOST_CHECK_THROW(m.exception(), bad_outcome_access); BOOST_CHECK_THROW(std::rethrow_exception(m.failure()), std::system_error); } { // valued int outcome<int> m(5); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK(m.value() == 5); m.value() = 6; BOOST_CHECK(m.value() == 6); BOOST_CHECK_THROW(m.error(), bad_outcome_access); BOOST_CHECK_THROW(m.exception(), bad_outcome_access); BOOST_CHECK(!m.failure()); } { // moves do not clear state outcome<std::string> m("niall"); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK(m.value() == "niall"); m.value() = "NIALL"; BOOST_CHECK(m.value() == "NIALL"); auto temp(std::move(m).value()); BOOST_CHECK(temp == "NIALL"); BOOST_CHECK(m.value().empty()); // NOLINT } { // valued void outcome<void> m(in_place_type<void>); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK_NO_THROW(m.value()); // works, but type returned is unusable BOOST_CHECK_THROW(m.error(), bad_outcome_access); BOOST_CHECK_THROW(m.exception(), bad_outcome_access); BOOST_CHECK(!m.failure()); } { // errored std::error_code ec(5, std::system_category()); outcome<int> m(ec); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(m.value(), std::system_error); BOOST_CHECK(m.error() == ec); BOOST_CHECK_THROW(m.exception(), bad_outcome_access); #ifdef __cpp_exceptions BOOST_CHECK(m.failure()); try { std::rethrow_exception(m.failure()); } catch(const std::system_error &ex) { BOOST_CHECK(ex.code() == ec); BOOST_CHECK(ex.code().value() == 5); } #endif } #if !defined(__APPLE__) || defined(__cpp_exceptions) { // excepted std::error_code ec(5, std::system_category()); auto e = std::make_exception_ptr(std::system_error(ec)); // NOLINT outcome<int> m(e); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(m.has_exception()); BOOST_CHECK_THROW(m.value(), std::system_error); BOOST_CHECK_THROW(m.error(), bad_outcome_access); BOOST_CHECK(m.exception() == e); #ifdef __cpp_exceptions BOOST_CHECK(m.failure()); try { std::rethrow_exception(m.failure()); } catch(const std::system_error &ex) { BOOST_CHECK(ex.code() == ec); BOOST_CHECK(ex.code().value() == 5); } #endif } { // custom error type struct Foo { }; auto e = std::make_exception_ptr(Foo()); outcome<int> m(e); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(m.has_exception()); BOOST_CHECK_THROW(m.value(), Foo); BOOST_CHECK_THROW(m.error(), bad_outcome_access); BOOST_CHECK(m.exception() == e); } { // outcome<void, void> should work std::error_code ec(5, std::system_category()); auto e = std::make_exception_ptr(std::system_error(ec)); outcome<void, void> m(e); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(m.has_exception()); } #endif { outcome<int> a(5); outcome<int> b(std::make_error_code(std::errc::invalid_argument)); std::cout << sizeof(a) << std::endl; // 40 bytes a.assume_value(); b.assume_error(); #ifdef __cpp_exceptions try { b.value(); std::cerr << "fail" << std::endl; std::terminate(); } catch(const std::system_error & /*unused*/) { } #endif static_assert(!std::is_default_constructible<decltype(a)>::value, ""); static_assert(!std::is_nothrow_default_constructible<decltype(a)>::value, ""); static_assert(std::is_copy_constructible<decltype(a)>::value, ""); static_assert(!std::is_trivially_copy_constructible<decltype(a)>::value, ""); static_assert(std::is_nothrow_copy_constructible<decltype(a)>::value, ""); static_assert(std::is_copy_assignable<decltype(a)>::value, ""); static_assert(!std::is_trivially_copy_assignable<decltype(a)>::value, ""); static_assert(std::is_nothrow_copy_assignable<decltype(a)>::value, ""); static_assert(!std::is_trivially_destructible<decltype(a)>::value, ""); static_assert(std::is_nothrow_destructible<decltype(a)>::value, ""); // Test void compiles outcome<void> c(in_place_type<void>); outcome<void> c2(c); (void) c2; // Test int, void compiles outcome<int, void> d(in_place_type<std::exception_ptr>); } { // Can only be constructed via multiple args struct udt3 { udt3() = delete; udt3(udt3 &&) = delete; udt3(const udt3 &) = delete; udt3 &operator=(udt3 &&) = delete; udt3 &operator=(const udt3 &) = delete; explicit udt3(int /*unused*/, const char * /*unused*/, std::nullptr_t /*unused*/) {} ~udt3() = default; }; // Test a udt which can only be constructed in place compiles outcome<udt3> g(in_place_type<udt3>, 5, static_cast<const char *>("niall"), nullptr); // Does converting inplace construction also work? outcome<udt3> h(5, static_cast<const char *>("niall"), nullptr); outcome<udt3> i(ENOMEM, std::generic_category()); BOOST_CHECK(h.has_value()); BOOST_CHECK(i.has_error()); } }
0
repos/outcome/test
repos/outcome/test/tests/coroutine-support.cpp
/* Unit testing for outcomes (C) 2013-2022 Niall Douglas <http://www.nedproductions.biz/> (6 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "../../include/outcome/coroutine_support.hpp" #include "../../include/outcome/try.hpp" #if OUTCOME_FOUND_COROUTINE_HEADER #include "quickcpplib/boost/test/unit_test.hpp" namespace coroutines { template <class T> using eager = OUTCOME_V2_NAMESPACE::awaitables::eager<T>; template <class T> using lazy = OUTCOME_V2_NAMESPACE::awaitables::lazy<T>; template <class T> using generator = OUTCOME_V2_NAMESPACE::awaitables::generator<T>; template <class T, class E = std::error_code> using result = OUTCOME_V2_NAMESPACE::result<T, E>; inline eager<result<int>> eager_int(int x) { co_return x + 1; } inline lazy<result<int>> lazy_int(int x) { co_return x + 1; } inline eager<result<int>> eager_error() { co_return std::errc::not_enough_memory; } inline lazy<result<int>> lazy_error() { co_return std::errc::not_enough_memory; } inline eager<result<void>> eager_void() { co_return std::errc::not_enough_memory; } inline lazy<result<void>> lazy_void() { co_return std::errc::not_enough_memory; } inline generator<result<int>> generator_int(int x) { co_yield x; co_yield x + 1; co_yield x + 2; } inline generator<result<int>> generator_error(int x) { co_yield x; co_yield x + 1; co_yield std::errc::not_enough_memory; } template <class U, class... Args> inline eager<result<std::string>> eager_coawait(U &&f, Args... args) { OUTCOME_CO_TRYV2(auto &&, co_await f(args...)); co_return "hi"; } template <class U, class... Args> inline lazy<result<std::string>> lazy_coawait(U &&f, Args... args) { OUTCOME_CO_TRYV2(auto &&, co_await f(args...)); co_return "hi"; } #ifdef __cpp_exceptions struct custom_exception_type { }; inline lazy<result<int, std::exception_ptr>> result_exception(std::exception_ptr e) { std::rethrow_exception(e); co_return 5; } inline lazy<OUTCOME_V2_NAMESPACE::outcome<int>> outcome_exception(std::exception_ptr e) { std::rethrow_exception(e); co_return 5; } inline generator<OUTCOME_V2_NAMESPACE::outcome<int>> generator_exception(std::exception_ptr e) { co_yield 5; co_yield 6; std::rethrow_exception(e); } #endif inline eager<int> eager_int2(int x) { co_return x + 1; } inline lazy<int> lazy_int2(int x) { co_return x + 1; } inline eager<void> eager_void2() { co_return; } inline lazy<void> lazy_void2() { co_return; } } // namespace coroutines BOOST_OUTCOME_AUTO_TEST_CASE(works / coroutine / eager_lazy, "Tests that results are eager and lazy awaitable") { using namespace coroutines; auto ensure_coroutine_completed_immediately = [](auto t) { BOOST_CHECK(t.await_ready()); // must have eagerly evaluated return t.await_resume(); // fetch the value returned into the promise by the coroutine }; auto ensure_coroutine_needs_resuming_once = [](auto t) { BOOST_CHECK(!t.await_ready()); // must not have eagerly evaluated #if OUTCOME_HAVE_NOOP_COROUTINE t.await_suspend({}).resume(); // resume execution, which sets the promise #else t.await_suspend({}); // resume execution, which sets the promise #endif BOOST_CHECK(t.await_ready()); // must now be ready return t.await_resume(); // fetch the value returned into the promise by the coroutine }; // eager_int never suspends, sets promise immediately, must be able to retrieve immediately BOOST_CHECK(ensure_coroutine_completed_immediately(eager_int(5)).value() == 6); // lazy_int suspends before execution, needs resuming to set the promise BOOST_CHECK(ensure_coroutine_needs_resuming_once(lazy_int(5)).value() == 6); BOOST_CHECK(ensure_coroutine_completed_immediately(eager_error()).error() == std::errc::not_enough_memory); BOOST_CHECK(ensure_coroutine_needs_resuming_once(lazy_error()).error() == std::errc::not_enough_memory); BOOST_CHECK(ensure_coroutine_completed_immediately(eager_void()).error() == std::errc::not_enough_memory); BOOST_CHECK(ensure_coroutine_needs_resuming_once(lazy_void()).error() == std::errc::not_enough_memory); // co_await eager_int realises it has already completed, does not suspend. BOOST_CHECK(ensure_coroutine_completed_immediately(eager_coawait(eager_int, 5)).value() == "hi"); // co_await lazy_int resumes the suspended coroutine. BOOST_CHECK(ensure_coroutine_needs_resuming_once(lazy_coawait(lazy_int, 5)).value() == "hi"); #ifdef __cpp_exceptions auto e = std::make_exception_ptr(custom_exception_type()); BOOST_CHECK_THROW(ensure_coroutine_needs_resuming_once(result_exception(e)).value(), custom_exception_type); BOOST_CHECK_THROW(ensure_coroutine_needs_resuming_once(outcome_exception(e)).value(), custom_exception_type); #endif BOOST_CHECK(ensure_coroutine_completed_immediately(eager_int2(5)) == 6); BOOST_CHECK(ensure_coroutine_needs_resuming_once(lazy_int2(5)) == 6); ensure_coroutine_completed_immediately(eager_void2()); ensure_coroutine_needs_resuming_once(lazy_void2()); } BOOST_OUTCOME_AUTO_TEST_CASE(works / coroutine / generator, "Tests that results can be generated") { using namespace coroutines; auto check_generator = [](auto t) -> OUTCOME_V2_NAMESPACE::outcome<int> { #ifdef __cpp_exceptions try #endif { int count = 0, ret = 0; while(t) { auto r = t(); count++; if(r) { ret = r.value(); BOOST_CHECK(ret == 4 + count); } else { BOOST_CHECK(count == 3); OUTCOME_TRY(std::move(r)); } } return ret; } #ifdef __cpp_exceptions catch(...) { BOOST_CHECK(false); // exception must be put into outcome, nothing must throw here throw; } #endif }; BOOST_CHECK(check_generator(generator_int(5)).value() == 7); BOOST_CHECK(check_generator(generator_error(5)).error() == std::errc::not_enough_memory); #ifdef __cpp_exceptions auto e = std::make_exception_ptr(custom_exception_type()); BOOST_CHECK_THROW(check_generator(generator_exception(e)).value(), custom_exception_type); #endif } #else int main(void) { return 0; } #endif
0
repos/outcome/test
repos/outcome/test/tests/swap.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (5 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" /* Should be this: 78 move constructor count = 2 65 move assignment count = 3 78 move assignment count = 1 65 move constructor count = 2 78 move assignment count = 0 65 move assignment count = 1 78 move constructor count = 1 65 move assignment count = 2 78 move assignment count = 0 65 move assignment count = 1 78 move assignment count = 0 78 move constructor count = 2 65 move assignment count = 3 78 move assignment count = 1 65 move constructor count = 2 78 move assignment count = 0 65 move assignment count = 1 78 move constructor count = 1 65 move assignment count = 2 78 move assignment count = 0 65 move assignment count = 1 78 move assignment count = 0 78 move constructor count = 2 65 move assignment count = 3 78 move assignment count = 1 65 move constructor count = 2 78 move assignment count = 0 65 move assignment count = 1 78 move constructor count = 1 65 move assignment count = 2 78 move assignment count = 0 65 move assignment count = 1 78 move assignment count = 0 78 move constructor count = 2 65 move assignment count = 3 78 move assignment count = 1 65 move constructor count = 2 78 move assignment count = 0 65 move assignment count = 1 78 move constructor count = 1 65 move assignment count = 2 78 move assignment count = 0 65 move assignment count = 1 78 move assignment count = 0 */ #ifdef __cpp_exceptions #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4297) // function assumed not to throw an exception but does #endif #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wterminate" #endif template <bool mc, bool ma> struct Throwy { int count{0}, inc{0}, id{0}; Throwy() = default; Throwy(int c, int d, int i = 1) noexcept : count(c) , inc(i) , id(d) { } Throwy(const Throwy &) = delete; Throwy &operator=(const Throwy &) = delete; Throwy(Throwy &&o) noexcept(!mc) : count(o.count - o.inc) , inc(o.inc) , id(o.id) // NOLINT { if(mc) { std::cout << " " << id << " move constructor count = " << count << std::endl; if(!count) { std::cout << " " << id << " move constructor throws!" << std::endl; throw std::bad_alloc(); } } o.count = 0; o.inc = 0; o.id = 0; } Throwy &operator=(Throwy &&o) noexcept(!ma) { count = o.count - o.inc; if(ma) { std::cout << " " << o.id << " move assignment count = " << count << std::endl; if(!count) { std::cout << " " << o.id << " move assignment throws!" << std::endl; throw std::bad_alloc(); } } inc = o.inc; id = o.id; o.count = 0; o.inc = 0; o.id = 0; return *this; } ~Throwy() = default; }; #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #endif #ifdef _MSC_VER #pragma warning(pop) #endif enum class ErrorCode { dummy }; enum class ErrorCode2 { dummy }; template <bool mc, bool ma> using resulty1 = OUTCOME_V2_NAMESPACE::result<Throwy<mc, ma>, ErrorCode, OUTCOME_V2_NAMESPACE::policy::all_narrow>; template <bool mc, bool ma> using resulty2 = OUTCOME_V2_NAMESPACE::result<ErrorCode, Throwy<mc, ma>, OUTCOME_V2_NAMESPACE::policy::all_narrow>; template <bool mc, bool ma> using outcomey1 = OUTCOME_V2_NAMESPACE::outcome<ErrorCode, Throwy<mc, ma>, ErrorCode2, OUTCOME_V2_NAMESPACE::policy::all_narrow>; template <bool mc, bool ma> using outcomey2 = OUTCOME_V2_NAMESPACE::outcome<ErrorCode, ErrorCode2, Throwy<mc, ma>, OUTCOME_V2_NAMESPACE::policy::all_narrow>; #endif BOOST_OUTCOME_AUTO_TEST_CASE(works / outcome / swap, "Tests that the outcome swaps as intended") { using namespace OUTCOME_V2_NAMESPACE; { // Does swap actually swap? outcome<std::string> a("niall"), b("douglas"); BOOST_CHECK(a.value() == "niall"); BOOST_CHECK(b.value() == "douglas"); swap(a, b); BOOST_CHECK(a.value() == "douglas"); BOOST_CHECK(b.value() == "niall"); a = std::errc::not_enough_memory; swap(a, b); BOOST_CHECK(a.value() == "niall"); BOOST_CHECK(b.error() == std::errc::not_enough_memory); BOOST_CHECK(!a.has_lost_consistency()); BOOST_CHECK(!b.has_lost_consistency()); } #ifdef __cpp_exceptions { // Is noexcept propagated? using nothrow_t = Throwy<false, false>; using nothrow = resulty1<false, false>; static_assert(std::is_nothrow_move_constructible<nothrow_t>::value, "throwy not correct!"); static_assert(std::is_nothrow_move_assignable<nothrow_t>::value, "throwy not correct!"); static_assert(std::is_nothrow_move_constructible<nothrow>::value, "type not correct!"); static_assert(std::is_nothrow_move_assignable<nothrow>::value, "type not correct!"); static_assert(detail::is_nothrow_swappable<nothrow_t>::value, "is_nothrow_swappable is not correct!"); static_assert(noexcept(nothrow(0, 0)), "type has a throwing value constructor!"); nothrow a(1, 78), b(1, 65); a.swap(b); static_assert(noexcept(a.swap(b)), "type has a throwing swap!"); } { // Is noexcept propagated? using nothrow_t = Throwy<false, false>; using nothrow = resulty2<false, false>; static_assert(std::is_nothrow_move_constructible<nothrow_t>::value, "throwy not correct!"); static_assert(std::is_nothrow_move_assignable<nothrow_t>::value, "throwy not correct!"); static_assert(std::is_nothrow_move_constructible<nothrow>::value, "type not correct!"); static_assert(std::is_nothrow_move_assignable<nothrow>::value, "type not correct!"); static_assert(detail::is_nothrow_swappable<nothrow_t>::value, "is_nothrow_swappable is not correct!"); static_assert(noexcept(nothrow(0, 0)), "type has a throwing value constructor!"); nothrow a(1, 78), b(1, 65); a.swap(b); static_assert(noexcept(a.swap(b)), "type has a throwing swap!"); } { // Does swap implement the strong guarantee? using throwy_t = Throwy<true, true>; using throwy = resulty1<true, true>; static_assert(!std::is_nothrow_move_constructible<throwy_t>::value, "throwy not correct!"); static_assert(!std::is_nothrow_move_assignable<throwy_t>::value, "throwy not correct!"); static_assert(!std::is_nothrow_move_constructible<throwy>::value, "type not correct!"); static_assert(!std::is_nothrow_move_assignable<throwy>::value, "type not correct!"); static_assert(!detail::is_nothrow_swappable<throwy_t>::value, "is_nothrow_swappable is not correct!"); std::cout << "Result value first swap succeeds, second swap second move assignment throws:" << std::endl; { throwy a(3, 78), b(4, 65); a.swap(b); static_assert(!noexcept(a.swap(b)), "type has a non-throwing swap!"); BOOST_CHECK(a.value().id == 65); BOOST_CHECK(b.value().id == 78); try { a.swap(b); // fails on first assignment BOOST_REQUIRE(false); } catch(const std::bad_alloc & /*unused*/) { BOOST_CHECK(a.value().id == 65); // ensure it is perfectly restored BOOST_CHECK(b.value().id == 78); } BOOST_CHECK(!a.has_lost_consistency()); BOOST_CHECK(!b.has_lost_consistency()); } std::cout << "\nResult value second move assignment throws, on recover second move assignment throws:" << std::endl; { throwy a(2, 78), b(3, 65); // fails on second assignment, cannot restore try { a.swap(b); BOOST_REQUIRE(false); } catch(const std::bad_alloc & /*unused*/) { BOOST_CHECK(a.has_lost_consistency()); // both must be marked tainted BOOST_CHECK(b.has_lost_consistency()); } } } std::cout << "\nResult error first swap succeeds, second swap first move assignment throws:" << std::endl; { // Does swap implement the strong guarantee? using throwy_t = Throwy<true, true>; using throwy = resulty2<true, true>; static_assert(!std::is_nothrow_move_constructible<throwy_t>::value, "throwy not correct!"); static_assert(!std::is_nothrow_move_assignable<throwy_t>::value, "throwy not correct!"); static_assert(!std::is_nothrow_move_constructible<throwy>::value, "type not correct!"); static_assert(!std::is_nothrow_move_assignable<throwy>::value, "type not correct!"); static_assert(!detail::is_nothrow_swappable<throwy_t>::value, "is_nothrow_swappable is not correct!"); { throwy a(3, 78), b(4, 65); a.swap(b); static_assert(!noexcept(a.swap(b)), "type has a non-throwing swap!"); BOOST_CHECK(a.error().id == 65); BOOST_CHECK(b.error().id == 78); try { a.swap(b); // fails on first assignment BOOST_REQUIRE(false); } catch(const std::bad_alloc & /*unused*/) { BOOST_CHECK(a.error().id == 65); // ensure it is perfectly restored BOOST_CHECK(b.error().id == 78); } BOOST_CHECK(!a.has_lost_consistency()); BOOST_CHECK(!b.has_lost_consistency()); } std::cout << "\nResult error second move assignment throws, on recover second move assignment throws:" << std::endl; { throwy a(2, 78), b(3, 65); // fails on second assignment, cannot restore try { a.swap(b); BOOST_REQUIRE(false); } catch(const std::bad_alloc & /*unused*/) { BOOST_CHECK(a.has_lost_consistency()); // both must be marked tainted BOOST_CHECK(b.has_lost_consistency()); } } } { // Is noexcept propagated? using nothrow_t = Throwy<false, false>; using nothrow = outcomey1<false, false>; static_assert(std::is_nothrow_move_constructible<nothrow_t>::value, "throwy not correct!"); static_assert(std::is_nothrow_move_assignable<nothrow_t>::value, "throwy not correct!"); static_assert(std::is_nothrow_move_constructible<nothrow>::value, "type not correct!"); static_assert(std::is_nothrow_move_assignable<nothrow>::value, "type not correct!"); static_assert(detail::is_nothrow_swappable<nothrow_t>::value, "is_nothrow_swappable is not correct!"); static_assert(noexcept(nothrow(0, 0)), "type has a throwing value constructor!"); nothrow a(1, 78), b(1, 65); a.swap(b); static_assert(noexcept(a.swap(b)), "type has a throwing swap!"); } { // Is noexcept propagated? using nothrow_t = Throwy<false, false>; using nothrow = outcomey1<false, false>; static_assert(std::is_nothrow_move_constructible<nothrow_t>::value, "throwy not correct!"); static_assert(std::is_nothrow_move_assignable<nothrow_t>::value, "throwy not correct!"); static_assert(std::is_nothrow_move_constructible<nothrow>::value, "type not correct!"); static_assert(std::is_nothrow_move_assignable<nothrow>::value, "type not correct!"); static_assert(detail::is_nothrow_swappable<nothrow_t>::value, "is_nothrow_swappable is not correct!"); static_assert(noexcept(nothrow(0, 0)), "type has a throwing value constructor!"); nothrow a(1, 78), b(1, 65); a.swap(b); static_assert(noexcept(a.swap(b)), "type has a throwing swap!"); } std::cout << "\n\nOutcome value first swap succeeds, second swap first move assignment throws:" << std::endl; { // Does swap implement the strong guarantee? using throwy_t = Throwy<true, true>; using throwy = outcomey1<true, true>; static_assert(!std::is_nothrow_move_constructible<throwy_t>::value, "throwy not correct!"); static_assert(!std::is_nothrow_move_assignable<throwy_t>::value, "throwy not correct!"); static_assert(!std::is_nothrow_move_constructible<throwy>::value, "type not correct!"); static_assert(!std::is_nothrow_move_assignable<throwy>::value, "type not correct!"); static_assert(!detail::is_nothrow_swappable<throwy_t>::value, "is_nothrow_swappable is not correct!"); { throwy a(3, 78), b(4, 65); a.swap(b); static_assert(!noexcept(a.swap(b)), "type has a non-throwing swap!"); BOOST_CHECK(a.error().id == 65); BOOST_CHECK(b.error().id == 78); try { a.swap(b); // fails on first assignment BOOST_REQUIRE(false); } catch(const std::bad_alloc & /*unused*/) { BOOST_CHECK(a.error().id == 65); // ensure it is perfectly restored BOOST_CHECK(b.error().id == 78); } BOOST_CHECK(!a.has_lost_consistency()); BOOST_CHECK(!b.has_lost_consistency()); } std::cout << "\nOutcome value second move assignment throws, on recover second move assignment throws:" << std::endl; { throwy a(2, 78), b(3, 65); // fails on second assignment, cannot restore try { a.swap(b); BOOST_REQUIRE(false); } catch(const std::bad_alloc & /*unused*/) { BOOST_CHECK(a.has_lost_consistency()); // both must be marked tainted BOOST_CHECK(b.has_lost_consistency()); } } } std::cout << "\nOutcome error first swap succeeds, second swap first move assignment throws:" << std::endl; { // Does swap implement the strong guarantee? using throwy_t = Throwy<true, true>; using throwy = outcomey2<true, true>; static_assert(!std::is_nothrow_move_constructible<throwy_t>::value, "throwy not correct!"); static_assert(!std::is_nothrow_move_assignable<throwy_t>::value, "throwy not correct!"); static_assert(!std::is_nothrow_move_constructible<throwy>::value, "type not correct!"); static_assert(!std::is_nothrow_move_assignable<throwy>::value, "type not correct!"); static_assert(!detail::is_nothrow_swappable<throwy_t>::value, "is_nothrow_swappable is not correct!"); { throwy a(3, 78), b(4, 65); a.swap(b); static_assert(!noexcept(a.swap(b)), "type has a non-throwing swap!"); BOOST_CHECK(a.exception().id == 65); BOOST_CHECK(b.exception().id == 78); try { a.swap(b); // fails on first assignment BOOST_REQUIRE(false); } catch(const std::bad_alloc & /*unused*/) { BOOST_CHECK(a.exception().id == 65); // ensure it is perfectly restored BOOST_CHECK(b.exception().id == 78); } BOOST_CHECK(!a.has_lost_consistency()); BOOST_CHECK(!b.has_lost_consistency()); } std::cout << "\nOutcome error second move assignment throws, on recover second move assignment throws:" << std::endl; { throwy a(2, 78), b(3, 65); // fails on second assignment, cannot restore try { a.swap(b); BOOST_REQUIRE(false); } catch(const std::bad_alloc & /*unused*/) { BOOST_CHECK(a.has_lost_consistency()); // both must be marked tainted BOOST_CHECK(b.has_lost_consistency()); } } std::cout << std::endl; } #endif }
0
repos/outcome/test
repos/outcome/test/tests/experimental-core-outcome-status.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (4 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/experimental/status_outcome.hpp" #define OUTCOME_PREVENT_CONVERSION_WORKAROUND std template <class T, class S = SYSTEM_ERROR2_NAMESPACE::system_code, class P = OUTCOME_PREVENT_CONVERSION_WORKAROUND::exception_ptr> using outcome = OUTCOME_V2_NAMESPACE::experimental::status_outcome<T, S, P>; using OUTCOME_V2_NAMESPACE::in_place_type; #include "quickcpplib/boost/test/unit_test.hpp" #include <iostream> #ifdef _MSC_VER #pragma warning(disable : 4702) // unreachable code #endif BOOST_OUTCOME_AUTO_TEST_CASE(works / status_code / outcome, "Tests that the outcome with status_code works as intended") { using namespace SYSTEM_ERROR2_NAMESPACE; { // errored int outcome<int> m(generic_code{errc::bad_address}); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(m.value(), status_error<void>); BOOST_CHECK_NO_THROW(m.error()); BOOST_CHECK_THROW(OUTCOME_PREVENT_CONVERSION_WORKAROUND::rethrow_exception(m.failure()), generic_error); } { // errored void outcome<void> m(generic_code{errc::bad_address}); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(([&m]() -> void { return m.value(); }()), generic_error); BOOST_CHECK_NO_THROW(m.error()); BOOST_CHECK_THROW(OUTCOME_PREVENT_CONVERSION_WORKAROUND::rethrow_exception(m.failure()), generic_error); } { // valued int outcome<int> m(5); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK(m.value() == 5); m.value() = 6; BOOST_CHECK(m.value() == 6); BOOST_CHECK(!m.failure()); } { // moves do not clear state outcome<std::string> m("niall"); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK(m.value() == "niall"); m.value() = "NIALL"; BOOST_CHECK(m.value() == "NIALL"); auto temp(std::move(m).value()); BOOST_CHECK(temp == "NIALL"); BOOST_CHECK(m.value().empty()); // NOLINT } { // valued void outcome<void> m(in_place_type<void>); BOOST_CHECK(m); BOOST_CHECK(m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK_NO_THROW(m.value()); // works, but type returned is unusable BOOST_CHECK(!m.failure()); } { // errored error ec(errc::no_link); outcome<int> m(ec.clone()); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(m.has_error()); BOOST_CHECK(!m.has_exception()); BOOST_CHECK_THROW(m.value(), generic_error); BOOST_CHECK(m.error() == ec); #ifdef __cpp_exceptions BOOST_CHECK(m.failure()); try { OUTCOME_PREVENT_CONVERSION_WORKAROUND::rethrow_exception(m.failure()); } catch(const generic_error &ex) { BOOST_CHECK(ex.code() == ec); BOOST_CHECK(ex.code().value() == errc::no_link); } #endif } #if !defined(__APPLE__) || defined(__cpp_exceptions) { // excepted OUTCOME_PREVENT_CONVERSION_WORKAROUND::error_code ec(5, OUTCOME_PREVENT_CONVERSION_WORKAROUND::system_category()); auto e = OUTCOME_PREVENT_CONVERSION_WORKAROUND::make_exception_ptr(OUTCOME_PREVENT_CONVERSION_WORKAROUND::system_error(ec)); // NOLINT outcome<int> m(e); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(m.has_exception()); BOOST_CHECK_THROW(m.value(), OUTCOME_PREVENT_CONVERSION_WORKAROUND::system_error); BOOST_CHECK(m.exception() == e); #ifdef __cpp_exceptions BOOST_CHECK(m.failure()); try { OUTCOME_PREVENT_CONVERSION_WORKAROUND::rethrow_exception(m.failure()); } catch(const OUTCOME_PREVENT_CONVERSION_WORKAROUND::system_error &ex) { BOOST_CHECK(ex.code() == ec); BOOST_CHECK(ex.code().value() == 5); } #endif } { // custom error type struct Foo { }; auto e = OUTCOME_PREVENT_CONVERSION_WORKAROUND::make_exception_ptr(Foo()); outcome<int> m(e); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(m.has_exception()); BOOST_CHECK_THROW(m.value(), Foo); BOOST_CHECK(m.exception() == e); } { // outcome<void, void> should work OUTCOME_PREVENT_CONVERSION_WORKAROUND::error_code ec(5, OUTCOME_PREVENT_CONVERSION_WORKAROUND::system_category()); auto e = OUTCOME_PREVENT_CONVERSION_WORKAROUND::make_exception_ptr(OUTCOME_PREVENT_CONVERSION_WORKAROUND::system_error(ec)); outcome<void, void> m(e); BOOST_CHECK(!m); BOOST_CHECK(!m.has_value()); BOOST_CHECK(!m.has_error()); BOOST_CHECK(m.has_exception()); } #endif { outcome<int> a(5); outcome<int> b(generic_code{errc::invalid_argument}); std::cout << sizeof(a) << std::endl; // 40 bytes a.assume_value(); b.assume_error(); #ifdef __cpp_exceptions try { b.value(); std::cerr << "fail" << std::endl; std::terminate(); } catch(const generic_error & /*unused*/) { } #endif static_assert(!std::is_default_constructible<decltype(a)>::value, ""); static_assert(!std::is_nothrow_default_constructible<decltype(a)>::value, ""); static_assert(!std::is_copy_constructible<decltype(a)>::value, ""); static_assert(!std::is_trivially_copy_constructible<decltype(a)>::value, ""); static_assert(!std::is_nothrow_copy_constructible<decltype(a)>::value, ""); static_assert(!std::is_copy_assignable<decltype(a)>::value, ""); static_assert(!std::is_trivially_copy_assignable<decltype(a)>::value, ""); static_assert(!std::is_nothrow_copy_assignable<decltype(a)>::value, ""); static_assert(!std::is_trivially_destructible<decltype(a)>::value, ""); static_assert(std::is_nothrow_destructible<decltype(a)>::value, ""); // Test void compiles outcome<void> c(in_place_type<void>); // Test int, void compiles outcome<int, void> d(in_place_type<OUTCOME_PREVENT_CONVERSION_WORKAROUND::exception_ptr>); } { // Can only be constructed via multiple args struct udt3 { udt3() = delete; udt3(udt3 &&) = delete; udt3(const udt3 &) = delete; udt3 &operator=(udt3 &&) = delete; udt3 &operator=(const udt3 &) = delete; explicit udt3(int /*unused*/, const char * /*unused*/, std::nullptr_t /*unused*/) {} ~udt3() = default; }; // Test a udt which can only be constructed in place compiles outcome<udt3> g(in_place_type<udt3>, 5, static_cast<const char *>("niall"), nullptr); // Does converting inplace construction also work? outcome<udt3> h(5, static_cast<const char *>("niall"), nullptr); BOOST_CHECK(h.has_value()); } }
0
repos/outcome/test
repos/outcome/test/tests/containers.cpp
/* Unit testing for outcomes (C) 2013-2019 Niall Douglas <http://www.nedproductions.biz/> (7 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" BOOST_OUTCOME_AUTO_TEST_CASE(works / outcome / containers, "Tests that outcome works as intended inside containers") { using namespace OUTCOME_V2_NAMESPACE; outcome<std::vector<int>> a(std::vector<int>{5, 6, 7, 8}); BOOST_CHECK(a.has_value()); BOOST_CHECK(a.value().size() == 4U); auto b(a); BOOST_CHECK(a.has_value()); BOOST_CHECK(a.value().size() == 4U); BOOST_CHECK(b.has_value()); BOOST_CHECK(b.value().size() == 4U); std::vector<outcome<std::vector<int>>> vect; vect.push_back(std::vector<int>{5, 6, 7, 8}); vect.push_back(std::vector<int>{1, 2, 3, 4}); BOOST_REQUIRE(vect.size() == 2U); // NOLINT BOOST_CHECK(vect[0].has_value()); BOOST_CHECK(vect[1].has_value()); BOOST_CHECK(vect[0].value().size() == 4U); BOOST_CHECK(vect[1].value().size() == 4U); BOOST_CHECK(vect[0].value().front() == 5); BOOST_CHECK(vect[0].value().back() == 8); BOOST_CHECK(vect[1].value().front() == 1); BOOST_CHECK(vect[1].value().back() == 4); }
0
repos/outcome/test
repos/outcome/test/tests/issue0291.cpp
/* Unit testing for outcomes (C) 2013-2023 Niall Douglas <http://www.nedproductions.biz/> (1 commit) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../../include/outcome/outcome.hpp" #include "quickcpplib/boost/test/unit_test.hpp" #ifdef __clang__ #pragma clang diagnostic ignored "-Wunneeded-internal-declaration" #endif namespace { namespace outcome = OUTCOME_V2_NAMESPACE; struct MovableError { MovableError() = default; MovableError(MovableError &&) = default; MovableError &operator=(MovableError &&) = default; }; std::error_code make_error_code(MovableError const &) { return {}; } void outcome_throw_as_system_error_with_payload(MovableError) {} template <typename T> using MyResult = outcome::result<T, MovableError>; } // namespace BOOST_OUTCOME_AUTO_TEST_CASE(issues / 0291 / test, "move of a non-const available void Result fails to compile") { MyResult<int> f(outcome::success()); MyResult<void> g(outcome::success()); std::move(f).value(); std::move(g).value(); }
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/span.hpp
/* span support (C) 2016-2023 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Sept 2016 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_SPAN_HPP #define QUICKCPPLIB_SPAN_HPP // `_HAS_CXX20` is defined in `<vcruntime.h>`, i.e. we need to drag it in (indirectly). // `<cstddef>` is inexpensive to include and would be included for `std::size_t` anyways. // It is also guaranteed to include the MS STL versioning machinery for `std::byte`. #include <cstddef> #include "config.hpp" #if defined(QUICKCPPLIB_USE_STD_SPAN) || ((_HAS_CXX20 || __cplusplus >= 202002) && __has_include(<span>)) #include "declval.hpp" #include <span> #include <type_traits> QUICKCPPLIB_NAMESPACE_BEGIN namespace span { #if QUICKCPPLIB_USE_UNPATCHED_STD_SPAN template <class T, size_t Extent = std::dynamic_extent> using span = std::span<T, Extent>; #else template <class T, size_t Extent = std::dynamic_extent> class span : public std::span<T, Extent> { using _base = std::span<T, Extent>; using _const_base = std::span<const T, Extent>; public: using _base::_base; constexpr span(_base v) noexcept : _base(v) { } // libc++ incorrectly makes the range consuming constructor explicit which breaks all implicit // construction of spans from vectors. Let's add a constructor to fix that, even though it'll // break double implicit conversions :( template <class U> requires( !std::is_same_v<std::decay_t<U>, span> && !std::is_same_v<std::decay_t<U>, _base> && !std::is_same_v<std::decay_t<U>, _const_base> && std::is_convertible<typename std::decay_t<U>::pointer, typename _base::pointer>::value && requires { declval<U>().data(); } && requires { declval<U>().size(); }) constexpr span(U &&v) noexcept : _base(v.data(), v.size()) { } }; #endif } // namespace span #undef QUICKCPPLIB_USE_STD_SPAN #define QUICKCPPLIB_USE_STD_SPAN 1 QUICKCPPLIB_NAMESPACE_END #else #include "span-lite/include/nonstd/span.hpp" QUICKCPPLIB_NAMESPACE_BEGIN namespace span { template <class T> using span = nonstd::span<T>; } QUICKCPPLIB_NAMESPACE_END #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/config.hpp
/* Configure QuickCppLib (C) 2016-2021 Niall Douglas <http://www.nedproductions.biz/> (8 commits) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_CONFIG_HPP #define QUICKCPPLIB_CONFIG_HPP #include "cpp_feature.h" #ifndef QUICKCPPLIB_DISABLE_ABI_PERMUTATION #include "revision.hpp" #endif #define QUICKCPPLIB_VERSION_GLUE2(a, b) a##b #define QUICKCPPLIB_VERSION_GLUE(a, b) QUICKCPPLIB_VERSION_GLUE2(a, b) // clang-format off #ifdef DOXYGEN_IS_IN_THE_HOUSE //! \brief The QuickCppLib namespace namespace quickcpplib { //! \brief Per commit unique namespace to prevent different git submodule versions clashing namespace _xxx { } } #define QUICKCPPLIB_NAMESPACE quickcpplib::_xxx #define QUICKCPPLIB_NAMESPACE_BEGIN namespace quickcpplib { namespace _xxx { #define QUICKCPPLIB_NAMESPACE_END } } #elif defined(QUICKCPPLIB_DISABLE_ABI_PERMUTATION) #define QUICKCPPLIB_NAMESPACE quickcpplib #define QUICKCPPLIB_NAMESPACE_BEGIN namespace quickcpplib { #define QUICKCPPLIB_NAMESPACE_END } #else #define QUICKCPPLIB_NAMESPACE quickcpplib::QUICKCPPLIB_VERSION_GLUE(_, QUICKCPPLIB_PREVIOUS_COMMIT_UNIQUE) #define QUICKCPPLIB_NAMESPACE_BEGIN namespace quickcpplib { namespace QUICKCPPLIB_VERSION_GLUE(_, QUICKCPPLIB_PREVIOUS_COMMIT_UNIQUE) { #define QUICKCPPLIB_NAMESPACE_END } } #endif // clang-format on #ifdef _MSC_VER #define QUICKCPPLIB_BIND_MESSAGE_PRAGMA2(x) __pragma(message(x)) #define QUICKCPPLIB_BIND_MESSAGE_PRAGMA(x) QUICKCPPLIB_BIND_MESSAGE_PRAGMA2(x) #define QUICKCPPLIB_BIND_MESSAGE_PREFIX(type) __FILE__ "(" QUICKCPPLIB_BIND_STRINGIZE2(__LINE__) "): " type ": " #define QUICKCPPLIB_BIND_MESSAGE_(type, prefix, msg) QUICKCPPLIB_BIND_MESSAGE_PRAGMA(prefix msg) #else #define QUICKCPPLIB_BIND_MESSAGE_PRAGMA2(x) _Pragma(#x) #define QUICKCPPLIB_BIND_MESSAGE_PRAGMA(type, x) QUICKCPPLIB_BIND_MESSAGE_PRAGMA2(type x) #define QUICKCPPLIB_BIND_MESSAGE_(type, prefix, msg) QUICKCPPLIB_BIND_MESSAGE_PRAGMA(type, msg) #endif //! Have the compiler output a message #define QUICKCPPLIB_MESSAGE(msg) QUICKCPPLIB_BIND_MESSAGE_(message, QUICKCPPLIB_BIND_MESSAGE_PREFIX("message"), msg) //! Have the compiler output a note #define QUICKCPPLIB_NOTE(msg) QUICKCPPLIB_BIND_MESSAGE_(message, QUICKCPPLIB_BIND_MESSAGE_PREFIX("note"), msg) //! Have the compiler output a warning #define QUICKCPPLIB_WARNING(msg) QUICKCPPLIB_BIND_MESSAGE_(GCC warning, QUICKCPPLIB_BIND_MESSAGE_PREFIX("warning"), msg) //! Have the compiler output an error #define QUICKCPPLIB_ERROR(msg) QUICKCPPLIB_BIND_MESSAGE_(GCC error, QUICKCPPLIB_BIND_MESSAGE_PREFIX("error"), msg) #ifdef QUICKCPPLIB_ENABLE_VALGRIND #include "./valgrind/drd.h" #define QUICKCPPLIB_ANNOTATE_RWLOCK_CREATE(p) ANNOTATE_RWLOCK_CREATE(p) #define QUICKCPPLIB_ANNOTATE_RWLOCK_DESTROY(p) ANNOTATE_RWLOCK_DESTROY(p) #define QUICKCPPLIB_ANNOTATE_RWLOCK_ACQUIRED(p, s) ANNOTATE_RWLOCK_ACQUIRED(p, s) #define QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(p, s) ANNOTATE_RWLOCK_RELEASED(p, s) #define QUICKCPPLIB_ANNOTATE_IGNORE_READS_BEGIN() ANNOTATE_IGNORE_READS_BEGIN() #define QUICKCPPLIB_ANNOTATE_IGNORE_READS_END() ANNOTATE_IGNORE_READS_END() #define QUICKCPPLIB_ANNOTATE_IGNORE_WRITES_BEGIN() ANNOTATE_IGNORE_WRITES_BEGIN() #define QUICKCPPLIB_ANNOTATE_IGNORE_WRITES_END() ANNOTATE_IGNORE_WRITES_END() #define QUICKCPPLIB_DRD_IGNORE_VAR(x) DRD_IGNORE_VAR(x) #define QUICKCPPLIB_DRD_STOP_IGNORING_VAR(x) DRD_STOP_IGNORING_VAR(x) #define QUICKCPPLIB_RUNNING_ON_VALGRIND RUNNING_ON_VALGRIND #else #define QUICKCPPLIB_ANNOTATE_RWLOCK_CREATE(p) #define QUICKCPPLIB_ANNOTATE_RWLOCK_DESTROY(p) #define QUICKCPPLIB_ANNOTATE_RWLOCK_ACQUIRED(p, s) #define QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(p, s) #define QUICKCPPLIB_ANNOTATE_IGNORE_READS_BEGIN() #define QUICKCPPLIB_ANNOTATE_IGNORE_READS_END() #define QUICKCPPLIB_ANNOTATE_IGNORE_WRITES_BEGIN() #define QUICKCPPLIB_ANNOTATE_IGNORE_WRITES_END() #define QUICKCPPLIB_DRD_IGNORE_VAR(x) #define QUICKCPPLIB_DRD_STOP_IGNORING_VAR(x) #define QUICKCPPLIB_RUNNING_ON_VALGRIND (0) #endif #ifndef QUICKCPPLIB_IN_ADDRESS_SANITIZER #if defined(__has_feature) #if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__) #define QUICKCPPLIB_IN_ADDRESS_SANITIZER 1 #endif #elif defined(__SANITIZE_ADDRESS__) #define QUICKCPPLIB_IN_ADDRESS_SANITIZER 1 #endif #endif #ifndef QUICKCPPLIB_IN_ADDRESS_SANITIZER #define QUICKCPPLIB_IN_ADDRESS_SANITIZER 0 #endif #ifndef QUICKCPPLIB_IN_THREAD_SANITIZER #if defined(__has_feature) #if __has_feature(thread_sanitizer) || defined(__SANITIZE_THREAD__) #define QUICKCPPLIB_IN_THREAD_SANITIZER 1 #endif #elif defined(__SANITIZE_THREAD__) #define QUICKCPPLIB_IN_THREAD_SANITIZER 1 #endif #endif #ifndef QUICKCPPLIB_IN_THREAD_SANITIZER #define QUICKCPPLIB_IN_THREAD_SANITIZER 0 #endif #ifndef QUICKCPPLIB_IN_UNDEFINED_SANITIZER #if defined(__has_feature) #if __has_feature(undefined_behavior_sanitizer) || defined(__SANITIZE_UNDEFINED__) || (__GNUC__ <= 9 && defined(__SANITIZE_ADDRESS__)) #define QUICKCPPLIB_IN_UNDEFINED_SANITIZER 1 #endif #elif defined(__SANITIZE_UNDEFINED__) || (__GNUC__ <= 9 && defined(__SANITIZE_ADDRESS__)) #define QUICKCPPLIB_IN_UNDEFINED_SANITIZER 1 #endif #endif #ifndef QUICKCPPLIB_IN_UNDEFINED_SANITIZER #define QUICKCPPLIB_IN_UNDEFINED_SANITIZER 0 #endif #if QUICKCPPLIB_IN_THREAD_SANITIZER #define QUICKCPPLIB_DISABLE_THREAD_SANITIZE __attribute__((no_sanitize_thread)) #else #define QUICKCPPLIB_DISABLE_THREAD_SANITIZE #endif #if QUICKCPPLIB_IN_THREAD_SANITIZER #define QUICKCPPLIB_DISABLE_THREAD_SANITIZE __attribute__((no_sanitize_thread)) #else #define QUICKCPPLIB_DISABLE_THREAD_SANITIZE #endif #if QUICKCPPLIB_IN_UNDEFINED_SANITIZER #define QUICKCPPLIB_DISABLE_UNDEFINED_SANITIZE __attribute__((no_sanitize_undefined)) #else #define QUICKCPPLIB_DISABLE_UNDEFINED_SANITIZE #endif #ifndef QUICKCPPLIB_SMT_PAUSE #if !defined(__clang__) && defined(_MSC_VER) && _MSC_VER >= 1310 && (defined(_M_IX86) || defined(_M_X64)) extern "C" void _mm_pause(); #if !defined(_M_ARM64EC) #pragma intrinsic(_mm_pause) #endif #define QUICKCPPLIB_SMT_PAUSE _mm_pause(); #elif !defined(__c2__) && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) #define QUICKCPPLIB_SMT_PAUSE __asm__ __volatile__("rep; nop" : : : "memory"); #endif #endif #ifndef QUICKCPPLIB_FORCEINLINE #if defined(_MSC_VER) #define QUICKCPPLIB_FORCEINLINE __forceinline #elif defined(__GNUC__) #define QUICKCPPLIB_FORCEINLINE __attribute__((always_inline)) #else #define QUICKCPPLIB_FORCEINLINE #endif #endif #ifndef QUICKCPPLIB_NOINLINE #if defined(_MSC_VER) #define QUICKCPPLIB_NOINLINE __declspec(noinline) #elif defined(__GNUC__) #define QUICKCPPLIB_NOINLINE __attribute__((noinline)) #else #define QUICKCPPLIB_NOINLINE #endif #endif #ifdef __has_cpp_attribute #define QUICKCPPLIB_HAS_CPP_ATTRIBUTE(attr, edition) (__has_cpp_attribute(attr) >= (edition) && __cplusplus >= (edition)) #else #define QUICKCPPLIB_HAS_CPP_ATTRIBUTE(attr, edition) (0) #endif #if !defined(QUICKCPPLIB_NORETURN) #if QUICKCPPLIB_HAS_CPP_ATTRIBUTE(noreturn, 201100) #define QUICKCPPLIB_NORETURN [[noreturn]] #elif defined(_MSC_VER) #define QUICKCPPLIB_NORETURN __declspec(noreturn) #elif defined(__GNUC__) #define QUICKCPPLIB_NORETURN __attribute__((__noreturn__)) #else #define QUICKCPPLIB_NORETURN #endif #endif #ifndef QUICKCPPLIB_NODISCARD #if defined(STANDARDESE_IS_IN_THE_HOUSE) || (_HAS_CXX17 && _MSC_VER >= 1911 /* VS2017.3 */) #define QUICKCPPLIB_NODISCARD [[nodiscard]] #endif #endif #ifndef QUICKCPPLIB_NODISCARD #if QUICKCPPLIB_HAS_CPP_ATTRIBUTE(nodiscard, 201700) && (!defined(__GNUC__) || __cpp_concepts >= 202000L /* -fconcepts-ts and [[nodiscard]] don't mix on GCC \ */) #define QUICKCPPLIB_NODISCARD [[nodiscard]] #elif defined(__clang__) // deliberately not GCC #define QUICKCPPLIB_NODISCARD __attribute__((warn_unused_result)) #elif defined(_MSC_VER) // _Must_inspect_result_ expands into this #define QUICKCPPLIB_NODISCARD \ __declspec( \ "SAL_name" \ "(" \ "\"_Must_inspect_result_\"" \ "," \ "\"\"" \ "," \ "\"2\"" \ ")") __declspec("SAL_begin") __declspec("SAL_post") __declspec("SAL_mustInspect") __declspec("SAL_post") __declspec("SAL_checkReturn") __declspec("SAL_end") #endif #endif #ifndef QUICKCPPLIB_NODISCARD #define QUICKCPPLIB_NODISCARD #endif #ifndef QUICKCPPLIB_SYMBOL_VISIBLE #if defined(_MSC_VER) #define QUICKCPPLIB_SYMBOL_VISIBLE #elif defined(__GNUC__) #define QUICKCPPLIB_SYMBOL_VISIBLE __attribute__((visibility("default"))) #else #define QUICKCPPLIB_SYMBOL_VISIBLE #endif #endif #ifndef QUICKCPPLIB_SYMBOL_EXPORT #if defined(_MSC_VER) #define QUICKCPPLIB_SYMBOL_EXPORT __declspec(dllexport) #elif defined(__GNUC__) #define QUICKCPPLIB_SYMBOL_EXPORT __attribute__((visibility("default"))) #else #define QUICKCPPLIB_SYMBOL_EXPORT #endif #endif #ifndef QUICKCPPLIB_SYMBOL_IMPORT #if defined(_MSC_VER) #define QUICKCPPLIB_SYMBOL_IMPORT __declspec(dllimport) #elif defined(__GNUC__) #define QUICKCPPLIB_SYMBOL_IMPORT #else #define QUICKCPPLIB_SYMBOL_IMPORT #endif #endif #ifndef QUICKCPPLIB_THREAD_LOCAL #if _MSC_VER >= 1800 #define QUICKCPPLIB_THREAD_LOCAL_IS_CXX11 1 #elif __cplusplus >= 201103L #if __GNUC__ >= 5 && !defined(__clang__) #define QUICKCPPLIB_THREAD_LOCAL_IS_CXX11 1 #elif defined(__has_feature) #if __has_feature(cxx_thread_local) #define QUICKCPPLIB_THREAD_LOCAL_IS_CXX11 1 #endif #endif #endif #ifdef QUICKCPPLIB_THREAD_LOCAL_IS_CXX11 #define QUICKCPPLIB_THREAD_LOCAL thread_local #endif #ifndef QUICKCPPLIB_THREAD_LOCAL #if defined(_MSC_VER) #define QUICKCPPLIB_THREAD_LOCAL __declspec(thread) #elif defined(__GNUC__) #define QUICKCPPLIB_THREAD_LOCAL __thread #else #error Unknown compiler, cannot set QUICKCPPLIB_THREAD_LOCAL #endif #endif #endif #ifndef QUICKCPPLIB_DISABLE_EXECINFO #if defined(__EMSCRIPTEN__) #define QUICKCPPLIB_DISABLE_EXECINFO 1 #endif #endif #ifndef QUICKCPPLIB_PLATFORM_NATIVE_BITLENGTH #if defined(__SIZEOF_POINTER__) #define QUICKCPPLIB_PLATFORM_NATIVE_BITLENGTH (__SIZEOF_POINTER__ * __CHAR_BIT__) #elif defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__ia64__) || defined(_M_IA64) || \ defined(__ppc64__) #define QUICKCPPLIB_PLATFORM_NATIVE_BITLENGTH (64) #else #define QUICKCPPLIB_PLATFORM_NATIVE_BITLENGTH (32) #endif #endif #include "detail/preprocessor_macro_overload.h" #if defined(__cpp_concepts) && !defined(QUICKCPPLIB_DISABLE_CONCEPTS_SUPPORT) #define QUICKCPPLIB_TREQUIRES_EXPAND8(a, b, c, d, e, f, g, h) a &&QUICKCPPLIB_TREQUIRES_EXPAND7(b, c, d, e, f, g, h) #define QUICKCPPLIB_TREQUIRES_EXPAND7(a, b, c, d, e, f, g) a &&QUICKCPPLIB_TREQUIRES_EXPAND6(b, c, d, e, f, g) #define QUICKCPPLIB_TREQUIRES_EXPAND6(a, b, c, d, e, f) a &&QUICKCPPLIB_TREQUIRES_EXPAND5(b, c, d, e, f) #define QUICKCPPLIB_TREQUIRES_EXPAND5(a, b, c, d, e) a &&QUICKCPPLIB_TREQUIRES_EXPAND4(b, c, d, e) #define QUICKCPPLIB_TREQUIRES_EXPAND4(a, b, c, d) a &&QUICKCPPLIB_TREQUIRES_EXPAND3(b, c, d) #define QUICKCPPLIB_TREQUIRES_EXPAND3(a, b, c) a &&QUICKCPPLIB_TREQUIRES_EXPAND2(b, c) #define QUICKCPPLIB_TREQUIRES_EXPAND2(a, b) a &&QUICKCPPLIB_TREQUIRES_EXPAND1(b) #define QUICKCPPLIB_TREQUIRES_EXPAND1(a) a //! Expands into a && b && c && ... #define QUICKCPPLIB_TREQUIRES(...) requires QUICKCPPLIB_CALL_OVERLOAD(QUICKCPPLIB_TREQUIRES_EXPAND, __VA_ARGS__) #define QUICKCPPLIB_TEMPLATE(...) template <__VA_ARGS__> #define QUICKCPPLIB_TEXPR(...) \ requires \ { \ (__VA_ARGS__); \ } #define QUICKCPPLIB_TPRED(...) (__VA_ARGS__) #if !defined(_MSC_VER) || _MSC_FULL_VER >= 192400000 // VS 2019 16.3 is broken here #define QUICKCPPLIB_REQUIRES(...) requires(__VA_ARGS__) #else #define QUICKCPPLIB_REQUIRES(...) #endif #else #define QUICKCPPLIB_TEMPLATE(...) template <__VA_ARGS__ #define QUICKCPPLIB_TREQUIRES(...) , __VA_ARGS__ > #define QUICKCPPLIB_TEXPR(...) typename = decltype(__VA_ARGS__) #ifdef _MSC_VER // MSVC gives an error if every specialisation of a template is always ill-formed, so // the more powerful SFINAE form below causes pukeage :( #define QUICKCPPLIB_TPRED(...) typename = typename std::enable_if<(__VA_ARGS__)>::type #else #define QUICKCPPLIB_TPRED(...) typename std::enable_if<(__VA_ARGS__), bool>::type = true #endif #define QUICKCPPLIB_REQUIRES(...) #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/optional.hpp
/* optional support (C) 2017 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Jul 2017 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_OPTIONAL_HPP #define QUICKCPPLIB_OPTIONAL_HPP #include "config.hpp" #ifdef QUICKCPPLIB_USE_STD_OPTIONAL #include <optional> QUICKCPPLIB_NAMESPACE_BEGIN namespace optional { template <class T> using optional = std::optional<T>; } QUICKCPPLIB_NAMESPACE_END #elif _HAS_CXX17 || (__cplusplus >= 201700 && (!defined(__APPLE__) || _LIBCPP_VERSION > 7000 /* approx end of 2017 */)) #include <optional> QUICKCPPLIB_NAMESPACE_BEGIN namespace optional { template <class T> using optional = std::optional<T>; } QUICKCPPLIB_NAMESPACE_END #else #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4702) // unreachable code #endif #include "optional/optional.hpp" #ifdef _MSC_VER #pragma warning(pop) #endif QUICKCPPLIB_NAMESPACE_BEGIN namespace optional { template <class T> using optional = std::experimental::optional<T>; } QUICKCPPLIB_NAMESPACE_END #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/revision.hpp
// Note the second line of this file must ALWAYS be the git SHA, third line ALWAYS the git SHA update time #define QUICKCPPLIB_PREVIOUS_COMMIT_REF d822bf7841ea5c8f79e0c046becc09ccb14c8ca7 #define QUICKCPPLIB_PREVIOUS_COMMIT_DATE "2023-03-01 16:39:36 +00:00" #define QUICKCPPLIB_PREVIOUS_COMMIT_UNIQUE d822bf78
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/erasure_cast.hpp
/* Erasure cast extending bit cast. (C) 2018 - 2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: May 2019 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_ERASURE_CAST_HPP #define QUICKCPPLIB_ERASURE_CAST_HPP #include "bit_cast.hpp" QUICKCPPLIB_NAMESPACE_BEGIN namespace erasure_cast { using bit_cast::bit_cast; namespace traits = bit_cast::traits; namespace detail { using namespace bit_cast::detail; /* A partially compliant implementation of C++20's std::bit_cast function contributed by Jesse Towner. erasure_cast performs a bit_cast with additional rules to handle types of differing sizes. For integral & enum types, it may perform a narrowing or widing conversion with static_cast if necessary, before doing the final conversion with bit_cast. When casting to or from non-integral, non-enum types it may insert the value into another object with extra padding bytes to satisfy bit_cast's preconditions that both types have the same size. */ template <class To, class From> using is_erasure_castable = std::integral_constant<bool, traits::is_move_relocating<To>::value && traits::is_move_relocating<From>::value>; template <class T, bool = std::is_enum<T>::value> struct identity_or_underlying_type { using type = T; }; template <class T> struct identity_or_underlying_type<T, true> { using type = typename std::underlying_type<T>::type; }; template <class OfSize, class OfSign> using erasure_integer_type = typename std::conditional<std::is_signed<typename identity_or_underlying_type<OfSign>::type>::value, typename std::make_signed<typename identity_or_underlying_type<OfSize>::type>::type, typename std::make_unsigned<typename identity_or_underlying_type<OfSize>::type>::type>::type; template <class ErasedType, std::size_t N> struct padded_erasure_object { static_assert(traits::is_move_relocating<ErasedType>::value, "ErasedType must be TriviallyCopyable or MoveRelocating"); static_assert(alignof(ErasedType) <= sizeof(ErasedType), "ErasedType must not be over-aligned"); ErasedType value; char padding[N]; constexpr explicit padded_erasure_object(const ErasedType &v) noexcept : value(v) , padding{} { } }; struct bit_cast_equivalence_overload { }; struct static_cast_dest_smaller_overload { }; struct static_cast_dest_larger_overload { }; struct union_cast_dest_smaller_overload { }; struct union_cast_dest_larger_overload { }; } // namespace detail /*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable, have identical size, and are bit castable. Constexpr. Forwards to `bit_cast()` directly. */ QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value // && (sizeof(To) == sizeof(From)))) constexpr inline To erasure_cast(const From &from, detail::bit_cast_equivalence_overload = {}) noexcept { return bit_cast<To>(from); } /*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable, are statically castable, and destination type is smaller than source type. Constexpr. */ QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value // &&detail::is_static_castable<To, From>::value // && (sizeof(To) < sizeof(From)))) constexpr inline To erasure_cast(const From &from, detail::static_cast_dest_smaller_overload = {}) noexcept { return static_cast<To>(bit_cast<detail::erasure_integer_type<From, To>>(from)); } /*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable, are statically castable, and destination type is larger than source type. Constexpr. */ QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value // &&detail::is_static_castable<To, From>::value // && (sizeof(To) > sizeof(From)))) constexpr inline To erasure_cast(const From &from, detail::static_cast_dest_larger_overload = {}) noexcept { return bit_cast<To>(static_cast<detail::erasure_integer_type<To, From>>(from)); } /*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable, are union castable, and destination type is smaller than source type. May be constexpr if underlying bit cast is constexpr. */ QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value // && !detail::is_static_castable<To, From>::value // && (sizeof(To) < sizeof(From)))) constexpr inline To erasure_cast(const From &from, detail::union_cast_dest_smaller_overload = {}) noexcept { return bit_cast<detail::padded_erasure_object<To, sizeof(From) - sizeof(To)>>(from).value; } /*! \brief Erasure cast implementation chosen if types are move relocating or trivally copyable, are union castable, and destination type is larger than source type. May be constexpr if underlying bit cast is constexpr. */ QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_erasure_castable<To, From>::value // && !detail::is_static_castable<To, From>::value // && (sizeof(To) > sizeof(From)))) constexpr inline To erasure_cast(const From &from, detail::union_cast_dest_larger_overload = {}) noexcept { return bit_cast<To>(detail::padded_erasure_object<From, sizeof(To) - sizeof(From)>{from}); } } // namespace erasure_cast QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/execinfo_win64.h
/* Implements backtrace() et al from glibc on win64 (C) 2016-2017 Niall Douglas <http://www.nedproductions.biz/> (4 commits) File Created: Mar 2016 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BINDLIB_EXECINFO_WIN64_H #define BOOST_BINDLIB_EXECINFO_WIN64_H #ifndef _WIN32 #error Can only be included on Windows #endif #include <sal.h> #include <stddef.h> #ifdef QUICKCPPLIB_EXPORTS #define EXECINFO_DECL extern __declspec(dllexport) #else #if defined(__cplusplus) && (!defined(QUICKCPPLIB_HEADERS_ONLY) || QUICKCPPLIB_HEADERS_ONLY == 1) && !defined(DOXYGEN_SHOULD_SKIP_THIS) #define EXECINFO_DECL inline #elif defined(QUICKCPPLIB_DYN_LINK) && !defined(QUICKCPPLIB_STATIC_LINK) #define EXECINFO_DECL extern __declspec(dllimport) #else #define EXECINFO_DECL extern #endif #endif #ifdef __cplusplus extern "C" { #endif //! Fill the array of void * at bt with up to len entries, returning entries filled. EXECINFO_DECL _Check_return_ size_t backtrace(_Out_writes_(len) void **bt, _In_ size_t len); //! Returns a malloced block of string representations of the input backtrace. EXECINFO_DECL _Check_return_ _Ret_writes_maybenull_(len) char **backtrace_symbols(_In_reads_(len) void *const *bt, _In_ size_t len); // extern void backtrace_symbols_fd(void *const *bt, size_t len, int fd); #ifdef __cplusplus } #if(!defined(QUICKCPPLIB_HEADERS_ONLY) || QUICKCPPLIB_HEADERS_ONLY == 1) && !defined(DOXYGEN_SHOULD_SKIP_THIS) #define QUICKCPPLIB_INCLUDED_BY_HEADER 1 #include "detail/impl/execinfo_win64.ipp" #undef QUICKCPPLIB_INCLUDED_BY_HEADER #endif #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/console_colours.hpp
/* Portable colourful console printing (C) 2016-2017 Niall Douglas <http://www.nedproductions.biz/> (5 commits) File Created: Apr 2016 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_CONSOLE_COLOURS_HPP #define QUICKCPPLIB_CONSOLE_COLOURS_HPP #include "config.hpp" #ifdef _WIN32 #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> #else #include <unistd.h> #endif QUICKCPPLIB_NAMESPACE_BEGIN namespace console_colours { #ifdef _WIN32 namespace detail { inline bool &am_in_bold() { static bool v; return v; } inline void set(WORD v) { if(am_in_bold()) v |= FOREGROUND_INTENSITY; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), v); } } //! Makes the text on the console red inline std::ostream &red(std::ostream &s) { s.flush(); detail::set(FOREGROUND_RED); return s; } //! Makes the text on the console green inline std::ostream &green(std::ostream &s) { s.flush(); detail::set(FOREGROUND_GREEN); return s; } //! Makes the text on the console blue inline std::ostream &blue(std::ostream &s) { s.flush(); detail::set(FOREGROUND_BLUE); return s; } //! Makes the text on the console yellow inline std::ostream &yellow(std::ostream &s) { s.flush(); detail::set(FOREGROUND_RED | FOREGROUND_GREEN); return s; } //! Makes the text on the console magenta inline std::ostream &magenta(std::ostream &s) { s.flush(); detail::set(FOREGROUND_RED | FOREGROUND_BLUE); return s; } //! Makes the text on the console cyan inline std::ostream &cyan(std::ostream &s) { s.flush(); detail::set(FOREGROUND_GREEN | FOREGROUND_BLUE); return s; } //! Makes the text on the console white inline std::ostream &white(std::ostream &s) { s.flush(); detail::set(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); return s; } //! Makes the text on the console bold inline std::ostream &bold(std::ostream &s) { detail::am_in_bold() = true; return s; } //! Makes the text on the console non-bold and white inline std::ostream &normal(std::ostream &s) { detail::am_in_bold() = false; return white(s); } #else namespace detail { inline std::ostream &color_if_term(std::ostream &s, const char seq[]) { if((&s == &std::cout && isatty(1 /*STDOUT_FILENO*/)) || (&s == &std::cerr && isatty(2 /*STDERR_FILENO*/))) s << seq; return s; } constexpr const char red[] = {0x1b, '[', '3', '1', 'm', 0}; constexpr const char green[] = {0x1b, '[', '3', '2', 'm', 0}; constexpr const char blue[] = {0x1b, '[', '3', '4', 'm', 0}; constexpr const char yellow[] = {0x1b, '[', '3', '3', 'm', 0}; constexpr const char magenta[] = {0x1b, '[', '3', '5', 'm', 0}; constexpr const char cyan[] = {0x1b, '[', '3', '6', 'm', 0}; constexpr const char white[] = {0x1b, '[', '3', '7', 'm', 0}; constexpr const char bold[] = {0x1b, '[', '1', 'm', 0}; constexpr const char normal[] = {0x1b, '[', '0', 'm', 0}; } //! Makes the text on the console red inline std::ostream &red(std::ostream &s) { return detail::color_if_term(s, detail::red); } //! Makes the text on the console green inline std::ostream &green(std::ostream &s) { return detail::color_if_term(s, detail::green); } //! Makes the text on the console blue inline std::ostream &blue(std::ostream &s) { return detail::color_if_term(s, detail::blue); } //! Makes the text on the console yellow inline std::ostream &yellow(std::ostream &s) { return detail::color_if_term(s, detail::yellow); } //! Makes the text on the console magenta inline std::ostream &magenta(std::ostream &s) { return detail::color_if_term(s, detail::magenta); } //! Makes the text on the console cyan inline std::ostream &cyan(std::ostream &s) { return detail::color_if_term(s, detail::cyan); } //! Makes the text on the console white inline std::ostream &white(std::ostream &s) { return detail::color_if_term(s, detail::white); } //! Makes the text on the console bold inline std::ostream &bold(std::ostream &s) { return detail::color_if_term(s, detail::bold); } //! Makes the text on the console non-bold and white inline std::ostream &normal(std::ostream &s) { return detail::color_if_term(s, detail::normal); } #endif } QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/type_traits.hpp
/* Extended type traits (C) 2012-2017 Niall Douglas <http://www.nedproductions.biz/> (7 commits) Created: May 2016 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_TYPE_TRAITS_HPP #define QUICKCPPLIB_TYPE_TRAITS_HPP #include "config.hpp" #include <type_traits> #include <functional> QUICKCPPLIB_NAMESPACE_BEGIN //! Gets the compiler to error out printing a type template <class T> struct print_type { private: print_type() {} }; namespace type_traits { namespace detail { template <class T> struct decay_preserving_cv { typedef typename std::remove_reference<T>::type U; typedef typename std::conditional<std::is_array<U>::value, typename std::remove_extent<U>::type *, typename std::conditional<std::is_function<U>::value, typename std::add_pointer<U>::type, U>::type>::type type; }; // Support for SFINAE detection of iterator/pointer ranges (Can it dereference? Can it increment?) // template<class T, typename = void> struct is_rangeable : std::false_type { }; // template<class T> struct is_rangeable<T, decltype(*std::declval<T&>(), ++std::declval<T&>(), void())> : std::true_type { }; // Support for SFINAE detection of containers (does it have begin() and end()?), made considerably more complex by needing MSVC to work. template <class T> inline auto is_sequence_impl(T &&) -> decltype(*std::begin(std::declval<T>()), *std::end(std::declval<T>()), bool()) { return true; } inline int is_sequence_impl(...) { return 0; } template <class T> struct make_sequence_type { auto operator()() const -> decltype(std::declval<T>()); }; template <> struct make_sequence_type<void> { int operator()() const; }; } // namespace detail //! True if type T is a STL compliant sequence (does it have begin() and end()?) template <class T, typename = decltype(detail::is_sequence_impl(detail::make_sequence_type<T>()()))> struct is_sequence : std::false_type { }; template <> struct is_sequence<void> : std::false_type { }; template <class T> struct is_sequence<T, bool> : std::true_type { typedef decltype(*std::begin(*((typename std::remove_reference<T>::type *) nullptr))) raw_type; //!< The raw type (probably a (const) lvalue ref) returned by *it typedef typename detail::decay_preserving_cv<raw_type>::type type; //!< The type held by the container, still potentially const if container does not permit write access }; #if __cplusplus >= 201700 template <class Fn, class... Args> using is_invocable = std::is_invocable<Fn, Args...>; #else template <typename F, typename... Args> struct is_invocable : std::is_constructible<std::function<void(Args...)>, std::reference_wrapper<typename std::remove_reference<F>::type>> { }; template <> struct is_invocable<void> : std::false_type { }; #endif #if 0 // Disabled until I find the time to get it working namespace detail { template <size_t N> struct Char { char foo[N]; }; // Overload only available if a default constructed T has a constexpr-available size() template <class T, size_t N = static_cast<T *>(nullptr)->size() + 1> constexpr inline Char<N> constexpr_size(const T &) { return Char<N>(); } template <class T> constexpr inline Char<1> constexpr_size(...) { return Char<1>(); } } /*! Returns true if the instance of v has a constexpr size() /note This is too overly conservative, it does not correctly return true for constexpr input. */ template <class T> constexpr inline bool has_constexpr_size(const T &v) { return sizeof(detail::constexpr_size<typename std::decay<T>::type>(std::move(v))) > 1; } //! \overload template <class T> constexpr inline bool has_constexpr_size() { return sizeof(detail::constexpr_size<typename std::decay<T>::type>(std::declval<T>())) > 1; } static_assert(has_constexpr_size<std::array<std::string, 2>>(), "failed"); #if 0 // Non-constexpr array (always has a constexpr size()) auto ca = std::array<int, 2>(); // Constexpr initializer_list (has constexpr size()). Note fails to compile on // VS2015 as its initializer_list isn't constexpr constructible yet #ifndef _MSC_VER constexpr std::initializer_list<int> cil{ 1, 2 }; #endif // Non-constexpr initializer_list (does not have constexpr size()) std::initializer_list<int> il{ 1, 2 }; // Non-constexpr vector (never has constexpr size()) std::vector<int> vec{ 1, 2 }; // Correct on GCC 4.9 and clang 3.8 and VS2015 static_assert(ca.size(), "non-constexpr array size constexpr"); // Correct on GCC 4.9 and clang 3.8. #ifndef _MSC_VER static_assert(cil.size(), "constexpr il size constexpr"); #endif // Fails as you'd expect everywhere with non-constexpr il error // static_assert(il.size(), "non-constexpr il size constexpr"); // Correct on GCC 4.9 and clang 3.8 and VS2015 static_assert(has_constexpr_size(ca), "ca"); // Incorrect on GCC 4.9 and clang 3.8 and VS2015 #ifndef _MSC_VER static_assert(!has_constexpr_size(cil), "cil"); // INCORRECT! #endif // Correct on GCC 4.9 and clang 3.8 and VS2015 static_assert(!has_constexpr_size(il), "il"); // Correct on GCC 4.9 and clang 3.8 and VS2015 static_assert(!has_constexpr_size(vec), "vec"); constexpr bool test_ca() { return has_constexpr_size(std::array<int, 2>{1, 2}); } constexpr bool testca = test_ca(); // Correct on GCC 4.9 and clang 3.8 and VS2015 static_assert(testca, "testca()"); constexpr bool test_cil() { return has_constexpr_size(std::initializer_list<int>{1, 2}); } constexpr bool testcil = test_cil(); // Incorrect on GCC 4.9 and clang 3.8 and VS2015 static_assert(!testcil, "testcil()"); // INCORRECT! #endif #endif } // namespace type_traits QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/allocator_testing.hpp
/* Provides an allocator useful for unit testing exception safety (C) 2014-2017 Niall Douglas <http://www.nedproductions.biz/> (2 commits) File Created: Aug 2014 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_ALLOCATOR_TESTING_HPP #define QUICKCPPLIB_ALLOCATOR_TESTING_HPP #include "config.hpp" #include <atomic> QUICKCPPLIB_NAMESPACE_BEGIN namespace allocator_testing { struct config { std::atomic<size_t> count, fail_from, fail_at; config() : count(0) , fail_from((size_t) -1) , fail_at((size_t) -1) { } }; static inline config &get_config(bool reset = false) { static config c; if(reset) { c.count = 0; c.fail_from = (size_t) -1; c.fail_at = (size_t) -1; } return c; } template <class T, class A = std::allocator<T>> struct allocator : public A { template <class U> struct rebind { typedef allocator<U> other; }; allocator() {} allocator(const allocator &o) : A(o) { } template <class U> allocator(const allocator<U> &o) : A(o) { } typename A::pointer allocate(typename A::size_type n, typename std::allocator<void>::const_pointer hint = 0) { config &c = get_config(); size_t count = ++c.count; if(count >= c.fail_from || count == c.fail_at) throw std::bad_alloc(); return A::allocate(n, hint); } }; } QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/mem_flush_loads_stores.hpp
/* Ensuring no load nor dead store elimination (C) 2018 - 2021 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: April 2018 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_MEM_FLUSH_LOADS_STORES_HPP #define QUICKCPPLIB_MEM_FLUSH_LOADS_STORES_HPP #include "byte.hpp" #include <atomic> #include <cstddef> // for size_t #ifdef _MSC_VER #include <intrin.h> #endif QUICKCPPLIB_NAMESPACE_BEGIN namespace mem_flush_loads_stores { using byte::byte; /*! \brief The kinds of cache line flushing which can be performed. */ enum class memory_flush { memory_flush_none, //!< No memory flushing. memory_flush_retain, //!< Flush modified cache line to memory, but retain as unmodified in cache. memory_flush_evict //!< Flush modified cache line to memory, and evict completely from all caches. }; //! No memory flushing. constexpr memory_flush memory_flush_none = memory_flush::memory_flush_none; //! Flush modified cache line to memory, but retain as unmodified in cache. constexpr memory_flush memory_flush_retain = memory_flush::memory_flush_retain; //! Flush modified cache line to memory, and evict completely from all caches. constexpr memory_flush memory_flush_evict = memory_flush::memory_flush_evict; namespace detail { using flush_impl_type = memory_flush (*)(const void *addr, size_t bytes, memory_flush kind); inline QUICKCPPLIB_NOINLINE flush_impl_type make_flush_impl() noexcept { #if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) #if !defined(_MSC_VER) || (defined(_MSC_VER) && defined(__clang__) && !defined(__c2__)) static const auto __cpuidex = [](int *cpuInfo, int func1, int func2) { __asm__ __volatile__("cpuid\n\t" : "=a"(cpuInfo[0]), "=b"(cpuInfo[1]), "=c"(cpuInfo[2]), "=d"(cpuInfo[3]) : "a"(func1), "c"(func2)); }; // NOLINT // static constexpr auto _mm_clwb = [](const void *addr) { __asm__ __volatile__("clwb (%0)\n\t" : : "r"(addr)); }; // NOLINT static const auto _mm_clwb = [](const void *addr) { __asm__ __volatile__(".byte 0x66, 0x0f, 0xae, 0x30\n\t" : : "a"(addr)); }; // NOLINT static const auto _mm_clflushopt = [](const void *addr) { __asm__ __volatile__("clflushopt (%0)\n\t" : : "r"(addr)); }; // NOLINT static const auto _mm_clflush = [](const void *addr) { __asm__ __volatile__("clflush (%0)\n\t" : : "r"(addr)); }; // NOLINT static const auto _mm_sfence = []() { __asm__ __volatile__("sfence\n\t"); }; // NOLINT #endif int nBuff[4]; __cpuidex(nBuff, 0x7, 0x0); if(nBuff[1] & (1 << 24)) // has CLWB instruction { return [](const void *addr, size_t bytes, memory_flush kind) -> memory_flush { if(kind == memory_flush_retain) { while(bytes > 0) { _mm_clwb(addr); addr = (void *) ((uintptr_t) addr + 64); bytes -= 64; } _mm_sfence(); return memory_flush_retain; } while(bytes > 0) { _mm_clflushopt(addr); addr = (void *) ((uintptr_t) addr + 64); bytes -= 64; } _mm_sfence(); return memory_flush_evict; }; } if(nBuff[1] & (1 << 23)) // has CLFLUSHOPT instruction { return [](const void *addr, size_t bytes, memory_flush /*unused*/) -> memory_flush { while(bytes > 0) { _mm_clflushopt(addr); addr = (void *) ((uintptr_t) addr + 64); bytes -= 64; } _mm_sfence(); return memory_flush_evict; }; } else { // Use CLFLUSH instruction return [](const void *addr, size_t bytes, memory_flush /*unused*/) -> memory_flush { while(bytes > 0) { _mm_clflush(addr); addr = (void *) ((uintptr_t) addr + 64); bytes -= 64; } return memory_flush_evict; }; } #elif defined(__aarch64__) || defined(_M_ARM64) #if !defined(_MSC_VER) || (defined(_MSC_VER) && defined(__clang__) && !defined(__c2__)) static const auto _dmb_ish = []() { __asm__ __volatile__("dmb ish" : : : "memory"); }; static const auto _dc_cvac = [](const void *addr) { __asm__ __volatile__("dc cvac, %0" : : "r"(addr) : "memory"); }; static const auto _dc_civac = [](const void *addr) { __asm__ __volatile__("dc civac, %0" : : "r"(addr) : "memory"); }; #else static const auto _dmb_ish = []() { __dmb(_ARM64_BARRIER_ISH); }; static const auto _dc_cvac = [](const void *addr) { (void) addr; abort(); // currently MSVC doesn't have an intrinsic for this, could use __emit()? }; static const auto _dc_civac = [](const void *addr) { (void) addr; abort(); // currently MSVC doesn't have an intrinsic for this, could use __emit()? }; #endif return [](const void *addr, size_t bytes, memory_flush kind) -> memory_flush { if(kind == memory_flush_retain) { while(bytes > 0) { _dc_cvac(addr); addr = (void *) ((uintptr_t) addr + 64); bytes -= 64; } _dmb_ish(); return memory_flush_retain; } while(bytes > 0) { _dc_civac(addr); addr = (void *) ((uintptr_t) addr + 64); bytes -= 64; } _dmb_ish(); return memory_flush_evict; }; #elif defined(__arm__) || defined(_M_ARM) #if !defined(_MSC_VER) || (defined(_MSC_VER) && defined(__clang__) && !defined(__c2__)) #undef _MoveToCoprocessor #define _MoveToCoprocessor(value, coproc, opcode1, crn, crm, opcode2) \ __asm__ __volatile__("MCR p" #coproc ", " #opcode1 ", %0, c" #crn ", c" #crm ", " #opcode2 : : "r"(value) : "memory"); // NOLINT #endif return [](const void *addr, size_t bytes, memory_flush kind) -> memory_flush { if(kind == memory_flush_retain) { while(bytes > 0) { // __asm__ __volatile__("MCR p15, 0, %0, c7, c10, 1" : : "r"(addr) : "memory"); _MoveToCoprocessor(addr, 15, 0, 7, 10, 1); addr = (void *) ((uintptr_t) addr + 64); bytes -= 64; } // __asm__ __volatile__("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory"); _MoveToCoprocessor(0, 15, 0, 7, 10, 5); return memory_flush_retain; } while(bytes > 0) { // __asm__ __volatile__("MCR p15, 0, %0, c7, c14, 1" : : "r"(addr) : "memory"); _MoveToCoprocessor(addr, 15, 0, 7, 14, 1); addr = (void *) ((uintptr_t) addr + 64); bytes -= 64; } // __asm__ __volatile__("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory"); _MoveToCoprocessor(0, 15, 0, 7, 10, 5); return memory_flush_evict; }; #else #error Unsupported platform #endif } inline flush_impl_type flush_impl() noexcept { static flush_impl_type f; if(f != nullptr) return f; f = make_flush_impl(); return f; } using potentially_unknown_jump_ptr = void (*)(const byte *data, size_t bytes); extern inline potentially_unknown_jump_ptr potentially_unknown_jump(potentially_unknown_jump_ptr set = nullptr) { static potentially_unknown_jump_ptr f = +[](const byte * /*unused*/, size_t /*unused*/) -> void {}; if(set != nullptr) { f = set; } return f; } } // namespace detail /*! \brief Ensures that reload elimination does not happen for a region of memory, optionally synchronising the region with main memory. \addtogroup P1631 \return The kind of memory flush actually used \param data The beginning of the byte array to ensure loads from. \param bytes The number of bytes to ensure loads from. \param kind Whether to ensure loads from the region are from main memory. Defaults to not doing so. \param order The atomic reordering constraints to apply to this operation. Defaults to atomic acquire constraints, which prevents reads and writes to this region subsequent to this operation being reordered to before this operation. \note `memory_flush_retain` has no effect for loads, it is the same as doing nothing. Only `memory_flush_evict` evicts all the cache lines for the region of memory, thus ensuring that subsequent loads are from main memory. */ inline memory_flush mem_force_reload(const byte *data, size_t bytes, memory_flush kind = memory_flush_none, std::memory_order order = std::memory_order_acquire) noexcept { memory_flush ret = kind; // Ensure reload elimination does not occur on our region by calling a // potentially unknown external function which forces the compiler to // reload state after this call returns detail::potentially_unknown_jump()(data, bytes); if(memory_flush_evict == kind) { // TODO FIXME We assume a 64 byte cache line, which is bold. void *_data = (void *) (((uintptr_t) data) & ~63); size_t _bytes = ((uintptr_t) data + bytes + 63) - ((uintptr_t) _data); _bytes &= ~63; ret = detail::flush_impl()(_data, _bytes, kind); } // I really wish this would work on a region, not globally atomic_thread_fence(order); return ret; } /*! \brief Sized C byte array overload for `mem_force_reload()`. \addtogroup P1631 */ template <size_t N> inline memory_flush mem_force_reload(const byte (&region)[N], memory_flush kind = memory_flush_none, std::memory_order order = std::memory_order_acquire) noexcept { return mem_force_reload(region, N, kind, order); } /*! \brief Ensures that dead store elimination does not happen for a region of memory, optionally synchronising the region with main memory. \addtogroup P1631 \return The kind of memory flush actually used \param data The beginning of the byte array to ensure stores to. \param bytes The number of bytes to ensure stores to. \param kind Whether to wait until all stores to the region reach main memory. Defaults to not waiting. \param order The atomic reordering constraints to apply to this operation. Defaults to atomic release constraints, which prevents reads and writes to this region preceding this operation being reordered to after this operation. \warning On older Intel CPUs, due to lack of hardware support, we always execute `memory_flush_evict` even if asked for `memory_flush_retain`. This can produce some very poor performance. Check the value returned to see what kind of flush was actually performed. */ inline memory_flush mem_flush_stores(const byte *data, size_t bytes, memory_flush kind = memory_flush_none, std::memory_order order = std::memory_order_release) noexcept { // I really wish this would work on a region, not globally atomic_thread_fence(order); // Ensure dead store elimination does not occur on our region by calling a // potentially unknown external function which forces the compiler to dump // out all pending writes before this call detail::potentially_unknown_jump()(data, bytes); if(memory_flush_none != kind) { // TODO FIXME We assume a 64 byte cache line, which is bold. void *_data = (void *) (((uintptr_t) data) & ~63); size_t _bytes = ((uintptr_t) data + bytes + 63) - ((uintptr_t) _data); _bytes &= ~63; memory_flush ret = detail::flush_impl()(_data, _bytes, kind); return ret; } return kind; } /*! \brief Sized C byte array overload for `mem_flush_stores()`. \addtogroup P1631 */ template <size_t N> inline memory_flush mem_flush_stores(const byte (&region)[N], memory_flush kind = memory_flush_none, std::memory_order order = std::memory_order_release) noexcept { return mem_flush_stores(region, N, kind, order); } } // namespace mem_flush_loads_stores QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/cpp_feature.h
/* Provides SG-10 feature checking for all C++ compilers (C) 2014-2017 Niall Douglas <http://www.nedproductions.biz/> (13 commits) File Created: Nov 2014 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_HAS_FEATURE_H #define QUICKCPPLIB_HAS_FEATURE_H #if __cplusplus >= 201103L // Some of these macros ended up getting removed by ISO standards, // they are prefixed with //// ////#if !defined(__cpp_alignas) ////#define __cpp_alignas 190000 ////#endif ////#if !defined(__cpp_default_function_template_args) ////#define __cpp_default_function_template_args 190000 ////#endif ////#if !defined(__cpp_defaulted_functions) ////#define __cpp_defaulted_functions 190000 ////#endif ////#if !defined(__cpp_deleted_functions) ////#define __cpp_deleted_functions 190000 ////#endif ////#if !defined(__cpp_generalized_initializers) ////#define __cpp_generalized_initializers 190000 ////#endif ////#if !defined(__cpp_implicit_moves) ////#define __cpp_implicit_moves 190000 ////#endif ////#if !defined(__cpp_inline_namespaces) ////#define __cpp_inline_namespaces 190000 ////#endif ////#if !defined(__cpp_local_type_template_args) ////#define __cpp_local_type_template_args 190000 ////#endif ////#if !defined(__cpp_noexcept) ////#define __cpp_noexcept 190000 ////#endif ////#if !defined(__cpp_nonstatic_member_init) ////#define __cpp_nonstatic_member_init 190000 ////#endif ////#if !defined(__cpp_nullptr) ////#define __cpp_nullptr 190000 ////#endif ////#if !defined(__cpp_override_control) ////#define __cpp_override_control 190000 ////#endif ////#if !defined(__cpp_thread_local) ////#define __cpp_thread_local 190000 ////#endif ////#if !defined(__cpp_auto_type) ////#define __cpp_auto_type 190000 ////#endif ////#if !defined(__cpp_strong_enums) ////#define __cpp_strong_enums 190000 ////#endif ////#if !defined(__cpp_trailing_return) ////#define __cpp_trailing_return 190000 ////#endif ////#if !defined(__cpp_unrestricted_unions) ////#define __cpp_unrestricted_unions 190000 ////#endif #if !defined(__cpp_alias_templates) #define __cpp_alias_templates 190000 #endif #if !defined(__cpp_attributes) #define __cpp_attributes 190000 #endif #if !defined(__cpp_constexpr) #if __cplusplus >= 201402L #define __cpp_constexpr 201304 // relaxed constexpr #else #define __cpp_constexpr 190000 #endif #endif #if !defined(__cpp_decltype) #define __cpp_decltype 190000 #endif #if !defined(__cpp_delegating_constructors) #define __cpp_delegating_constructors 190000 #endif #if !defined(__cpp_explicit_conversion) //// renamed from __cpp_explicit_conversions #define __cpp_explicit_conversion 190000 #endif #if !defined(__cpp_inheriting_constructors) #define __cpp_inheriting_constructors 190000 #endif #if !defined(__cpp_initializer_lists) //// NEW #define __cpp_initializer_lists 190000 #endif #if !defined(__cpp_lambdas) #define __cpp_lambdas 190000 #endif #if !defined(__cpp_nsdmi) #define __cpp_nsdmi 190000 //// NEW #endif #if !defined(__cpp_range_based_for) //// renamed from __cpp_range_for #define __cpp_range_based_for 190000 #endif #if !defined(__cpp_raw_strings) #define __cpp_raw_strings 190000 #endif #if !defined(__cpp_ref_qualifiers) //// renamed from __cpp_reference_qualified_functions #define __cpp_ref_qualifiers 190000 #endif #if !defined(__cpp_rvalue_references) #define __cpp_rvalue_references 190000 #endif #if !defined(__cpp_static_assert) #define __cpp_static_assert 190000 #endif #if !defined(__cpp_unicode_characters) //// NEW #define __cpp_unicode_characters 190000 #endif #if !defined(__cpp_unicode_literals) #define __cpp_unicode_literals 190000 #endif #if !defined(__cpp_user_defined_literals) #define __cpp_user_defined_literals 190000 #endif #if !defined(__cpp_variadic_templates) #define __cpp_variadic_templates 190000 #endif #endif #if __cplusplus >= 201402L // Some of these macros ended up getting removed by ISO standards, // they are prefixed with //// ////#if !defined(__cpp_contextual_conversions) ////#define __cpp_contextual_conversions 190000 ////#endif ////#if !defined(__cpp_digit_separators) ////#define __cpp_digit_separators 190000 ////#endif ////#if !defined(__cpp_relaxed_constexpr) ////#define __cpp_relaxed_constexpr 190000 ////#endif ////#if !defined(__cpp_runtime_arrays) ////# define __cpp_runtime_arrays 190000 ////#endif #if !defined(__cpp_aggregate_nsdmi) #define __cpp_aggregate_nsdmi 190000 #endif #if !defined(__cpp_binary_literals) #define __cpp_binary_literals 190000 #endif #if !defined(__cpp_decltype_auto) #define __cpp_decltype_auto 190000 #endif #if !defined(__cpp_generic_lambdas) #define __cpp_generic_lambdas 190000 #endif #if !defined(__cpp_init_captures) #define __cpp_init_captures 190000 #endif #if !defined(__cpp_return_type_deduction) #define __cpp_return_type_deduction 190000 #endif #if !defined(__cpp_sized_deallocation) #define __cpp_sized_deallocation 190000 #endif #if !defined(__cpp_variable_templates) #define __cpp_variable_templates 190000 #endif #endif // VS2010: _MSC_VER=1600 // VS2012: _MSC_VER=1700 // VS2013: _MSC_VER=1800 // VS2015: _MSC_VER=1900 // VS2017: _MSC_VER=1910 #if defined(_MSC_VER) && !defined(__clang__) #if !defined(__cpp_exceptions) && defined(_CPPUNWIND) #define __cpp_exceptions 190000 #endif #if !defined(__cpp_rtti) && defined(_CPPRTTI) #define __cpp_rtti 190000 #endif // C++ 11 #if !defined(__cpp_alias_templates) && _MSC_VER >= 1800 #define __cpp_alias_templates 190000 #endif #if !defined(__cpp_attributes) #define __cpp_attributes 190000 #endif #if !defined(__cpp_constexpr) && _MSC_FULL_VER >= 190023506 /* VS2015 */ #define __cpp_constexpr 190000 #endif #if !defined(__cpp_decltype) && _MSC_VER >= 1600 #define __cpp_decltype 190000 #endif #if !defined(__cpp_delegating_constructors) && _MSC_VER >= 1800 #define __cpp_delegating_constructors 190000 #endif #if !defined(__cpp_explicit_conversion) && _MSC_VER >= 1800 #define __cpp_explicit_conversion 190000 #endif #if !defined(__cpp_inheriting_constructors) && _MSC_VER >= 1900 #define __cpp_inheriting_constructors 190000 #endif #if !defined(__cpp_initializer_lists) && _MSC_VER >= 1900 #define __cpp_initializer_lists 190000 #endif #if !defined(__cpp_lambdas) && _MSC_VER >= 1600 #define __cpp_lambdas 190000 #endif #if !defined(__cpp_nsdmi) && _MSC_VER >= 1900 #define __cpp_nsdmi 190000 #endif #if !defined(__cpp_range_based_for) && _MSC_VER >= 1700 #define __cpp_range_based_for 190000 #endif #if !defined(__cpp_raw_strings) && _MSC_VER >= 1800 #define __cpp_raw_strings 190000 #endif #if !defined(__cpp_ref_qualifiers) && _MSC_VER >= 1900 #define __cpp_ref_qualifiers 190000 #endif #if !defined(__cpp_rvalue_references) && _MSC_VER >= 1600 #define __cpp_rvalue_references 190000 #endif #if !defined(__cpp_static_assert) && _MSC_VER >= 1600 #define __cpp_static_assert 190000 #endif //#if !defined(__cpp_unicode_literals) //# define __cpp_unicode_literals 190000 //#endif #if !defined(__cpp_user_defined_literals) && _MSC_VER >= 1900 #define __cpp_user_defined_literals 190000 #endif #if !defined(__cpp_variadic_templates) && _MSC_VER >= 1800 #define __cpp_variadic_templates 190000 #endif // C++ 14 //#if !defined(__cpp_aggregate_nsdmi) //#define __cpp_aggregate_nsdmi 190000 //#endif #if !defined(__cpp_binary_literals) && _MSC_VER >= 1900 #define __cpp_binary_literals 190000 #endif #if !defined(__cpp_decltype_auto) && _MSC_VER >= 1900 #define __cpp_decltype_auto 190000 #endif #if !defined(__cpp_generic_lambdas) && _MSC_VER >= 1900 #define __cpp_generic_lambdas 190000 #endif #if !defined(__cpp_init_captures) && _MSC_VER >= 1900 #define __cpp_init_captures 190000 #endif #if !defined(__cpp_return_type_deduction) && _MSC_VER >= 1900 #define __cpp_return_type_deduction 190000 #endif #if !defined(__cpp_sized_deallocation) && _MSC_VER >= 1900 #define __cpp_sized_deallocation 190000 #endif #if !defined(__cpp_variable_templates) && _MSC_FULL_VER >= 190023506 #define __cpp_variable_templates 190000 #endif #endif // _MSC_VER // Much to my surprise, GCC's support of these is actually incomplete, so fill in the gaps #if(defined(__GNUC__) && !defined(__clang__)) #define QUICKCPPLIB_GCC (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #if !defined(__cpp_exceptions) && defined(__EXCEPTIONS) #define __cpp_exceptions 190000 #endif #if !defined(__cpp_rtti) && defined(__GXX_RTTI) #define __cpp_rtti 190000 #endif // C++ 11 #if defined(__GXX_EXPERIMENTAL_CXX0X__) #if !defined(__cpp_alias_templates) && (QUICKCPPLIB_GCC >= 40700) #define __cpp_alias_templates 190000 #endif #if !defined(__cpp_attributes) && (QUICKCPPLIB_GCC >= 40800) #define __cpp_attributes 190000 #endif #if !defined(__cpp_constexpr) && (QUICKCPPLIB_GCC >= 40600) #define __cpp_constexpr 190000 #endif #if !defined(__cpp_decltype) && (QUICKCPPLIB_GCC >= 40300) #define __cpp_decltype 190000 #endif #if !defined(__cpp_delegating_constructors) && (QUICKCPPLIB_GCC >= 40700) #define __cpp_delegating_constructors 190000 #endif #if !defined(__cpp_explicit_conversion) && (QUICKCPPLIB_GCC >= 40500) #define __cpp_explicit_conversion 190000 #endif #if !defined(__cpp_inheriting_constructors) && (QUICKCPPLIB_GCC >= 40800) #define __cpp_inheriting_constructors 190000 #endif #if !defined(__cpp_initializer_lists) && (QUICKCPPLIB_GCC >= 40800) #define __cpp_initializer_lists 190000 #endif #if !defined(__cpp_lambdas) && (QUICKCPPLIB_GCC >= 40500) #define __cpp_lambdas 190000 #endif #if !defined(__cpp_nsdmi) && (QUICKCPPLIB_GCC >= 40700) #define __cpp_nsdmi 190000 #endif #if !defined(__cpp_range_based_for) && (QUICKCPPLIB_GCC >= 40600) #define __cpp_range_based_for 190000 #endif #if !defined(__cpp_raw_strings) && (QUICKCPPLIB_GCC >= 40500) #define __cpp_raw_strings 190000 #endif #if !defined(__cpp_ref_qualifiers) && (QUICKCPPLIB_GCC >= 40801) #define __cpp_ref_qualifiers 190000 #endif // __cpp_rvalue_reference deviation #if !defined(__cpp_rvalue_references) && defined(__cpp_rvalue_reference) #define __cpp_rvalue_references __cpp_rvalue_reference #endif #if !defined(__cpp_static_assert) && (QUICKCPPLIB_GCC >= 40300) #define __cpp_static_assert 190000 #endif #if !defined(__cpp_unicode_characters) && (QUICKCPPLIB_GCC >= 40500) #define __cpp_unicode_characters 190000 #endif #if !defined(__cpp_unicode_literals) && (QUICKCPPLIB_GCC >= 40500) #define __cpp_unicode_literals 190000 #endif #if !defined(__cpp_user_defined_literals) && (QUICKCPPLIB_GCC >= 40700) #define __cpp_user_defined_literals 190000 #endif #if !defined(__cpp_variadic_templates) && (QUICKCPPLIB_GCC >= 40400) #define __cpp_variadic_templates 190000 #endif // C++ 14 // Every C++ 14 supporting GCC does the right thing here #endif // __GXX_EXPERIMENTAL_CXX0X__ #endif // GCC // clang deviates in some places from the present SG-10 draft, plus older // clangs are quite incomplete #if defined(__clang__) #define QUICKCPPLIB_CLANG (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) #if !defined(__cpp_exceptions) && (defined(__EXCEPTIONS) || defined(_CPPUNWIND)) #define __cpp_exceptions 190000 #endif #if !defined(__cpp_rtti) && (defined(__GXX_RTTI) || defined(_CPPRTTI)) #define __cpp_rtti 190000 #endif // C++ 11 #if defined(__GXX_EXPERIMENTAL_CXX0X__) #if !defined(__cpp_alias_templates) && (QUICKCPPLIB_CLANG >= 30000) #define __cpp_alias_templates 190000 #endif #if !defined(__cpp_attributes) && (QUICKCPPLIB_CLANG >= 30300) #define __cpp_attributes 190000 #endif #if !defined(__cpp_constexpr) && (QUICKCPPLIB_CLANG >= 30100) #define __cpp_constexpr 190000 #endif #if !defined(__cpp_decltype) && (QUICKCPPLIB_CLANG >= 20900) #define __cpp_decltype 190000 #endif #if !defined(__cpp_delegating_constructors) && (QUICKCPPLIB_CLANG >= 30000) #define __cpp_delegating_constructors 190000 #endif #if !defined(__cpp_explicit_conversion) && (QUICKCPPLIB_CLANG >= 30000) #define __cpp_explicit_conversion 190000 #endif #if !defined(__cpp_inheriting_constructors) && (QUICKCPPLIB_CLANG >= 30300) #define __cpp_inheriting_constructors 190000 #endif #if !defined(__cpp_initializer_lists) && (QUICKCPPLIB_CLANG >= 30100) #define __cpp_initializer_lists 190000 #endif #if !defined(__cpp_lambdas) && (QUICKCPPLIB_CLANG >= 30100) #define __cpp_lambdas 190000 #endif #if !defined(__cpp_nsdmi) && (QUICKCPPLIB_CLANG >= 30000) #define __cpp_nsdmi 190000 #endif #if !defined(__cpp_range_based_for) && (QUICKCPPLIB_CLANG >= 30000) #define __cpp_range_based_for 190000 #endif // __cpp_raw_string_literals deviation #if !defined(__cpp_raw_strings) && defined(__cpp_raw_string_literals) #define __cpp_raw_strings __cpp_raw_string_literals #endif #if !defined(__cpp_raw_strings) && (QUICKCPPLIB_CLANG >= 30000) #define __cpp_raw_strings 190000 #endif #if !defined(__cpp_ref_qualifiers) && (QUICKCPPLIB_CLANG >= 20900) #define __cpp_ref_qualifiers 190000 #endif // __cpp_rvalue_reference deviation #if !defined(__cpp_rvalue_references) && defined(__cpp_rvalue_reference) #define __cpp_rvalue_references __cpp_rvalue_reference #endif #if !defined(__cpp_rvalue_references) && (QUICKCPPLIB_CLANG >= 20900) #define __cpp_rvalue_references 190000 #endif #if !defined(__cpp_static_assert) && (QUICKCPPLIB_CLANG >= 20900) #define __cpp_static_assert 190000 #endif #if !defined(__cpp_unicode_characters) && (QUICKCPPLIB_CLANG >= 30000) #define __cpp_unicode_characters 190000 #endif #if !defined(__cpp_unicode_literals) && (QUICKCPPLIB_CLANG >= 30000) #define __cpp_unicode_literals 190000 #endif // __cpp_user_literals deviation #if !defined(__cpp_user_defined_literals) && defined(__cpp_user_literals) #define __cpp_user_defined_literals __cpp_user_literals #endif #if !defined(__cpp_user_defined_literals) && (QUICKCPPLIB_CLANG >= 30100) #define __cpp_user_defined_literals 190000 #endif #if !defined(__cpp_variadic_templates) && (QUICKCPPLIB_CLANG >= 20900) #define __cpp_variadic_templates 190000 #endif // C++ 14 // Every C++ 14 supporting clang does the right thing here #endif // __GXX_EXPERIMENTAL_CXX0X__ #endif // clang #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/ringbuffer_log.hpp
/* Very fast threadsafe ring buffer log (C) 2016-2021 Niall Douglas <http://www.nedproductions.biz/> (21 commits) File Created: Mar 2016 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_RINGBUFFER_LOG_HPP #define QUICKCPPLIB_RINGBUFFER_LOG_HPP #ifndef QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES_DEBUG #define QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES_DEBUG 4096 #endif #ifndef QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES_NDEBUG #define QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES_NDEBUG 256 #endif #ifdef NDEBUG #define QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES_NDEBUG #else #define QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES_DEBUG #endif // If I'm on winclang, I can't stop the deprecation warnings from MSVCRT unless I do this #if defined(_MSC_VER) && defined(__clang__) #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif #include "packed_backtrace.hpp" #include "scope.hpp" #include <array> #include <atomic> #include <chrono> #include <cstddef> // for ptrdiff_t #include <cstdint> // for uint32_t etc #include <cstring> // for memcmp #include <iomanip> #include <ostream> #include <sstream> #include <system_error> #include <type_traits> #include <vector> #ifdef _WIN32 #include "execinfo_win64.h" #else #include <dlfcn.h> #if !QUICKCPPLIB_DISABLE_EXECINFO #include <execinfo.h> #endif #include <fcntl.h> #include <limits.h> #include <signal.h> // for siginfo_t #include <spawn.h> #include <sys/wait.h> #include <unistd.h> #if defined(__FreeBSD__) || defined(__APPLE__) extern "C" char **environ; #endif #endif QUICKCPPLIB_NAMESPACE_BEGIN namespace ringbuffer_log { //! Level of logged item enum class level : unsigned char { none = 0, fatal, error, warn, info, debug, all }; //! A default ringbuffer log_level checker which returns whatever the log instance's level is struct default_ringbuffer_log_level_checker { level operator()(level v) const noexcept { return v; } }; template <class Policy, class LogLevelChecker = default_ringbuffer_log_level_checker> class ringbuffer_log; //! Returns a const char * no more than 190 chars from its end template <class T> inline const char *last190(const T &v) { size_t size = v.size(); return size <= 190 ? v.data() : v.data() + (size - 190); } namespace simple_ringbuffer_log_policy_detail { using level_ = level; struct value_type { uint64_t counter{0}; uint64_t timestamp{0}; union { uint32_t code32[2]; uint64_t code64; }; union { char backtrace[40]; // packed_backtrace char function[40]; }; uint8_t level : 4; uint8_t using_code64 : 1; uint8_t using_backtrace : 1; char message[191]; private: static std::chrono::high_resolution_clock::time_point _first_item() { static std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now(); return now; } public: value_type() noexcept : code64{0} , backtrace{0} , level{0} , using_code64{0} , using_backtrace{0} , message{0} { } value_type(level_ _level, const char *_message, uint32_t _code1, uint32_t _code2, const char *_function = nullptr, unsigned lineno = 0) : counter((size_t) -1) , timestamp(std::chrono::duration_cast<std::chrono::nanoseconds>((_first_item(), std::chrono::high_resolution_clock::now() - _first_item())).count()) , code32{_code1, _code2} , level(static_cast<uint8_t>(_level)) , using_code64(false) #if !QUICKCPPLIB_DISABLE_EXECINFO , using_backtrace(!_function) #else , using_backtrace{0} #endif { size_t _messagelen = strlen(_message) + 1; if(_messagelen > sizeof(message)) { _messagelen = sizeof(message); } memcpy(message, _message, _messagelen); if(_function) { if(_function[0]) { size_t _functionlen = strlen(_function) + 1; if(_functionlen > sizeof(function)) { _functionlen = sizeof(function); } memcpy(function, _function, _functionlen); char temp[32], *e = function; for(size_t n = 0; n < sizeof(function) && *e != 0; n++, e++) ; #ifdef _MSC_VER _ultoa_s(lineno, temp, 10); #else snprintf(temp, sizeof(temp), "%u", lineno); #endif temp[31] = 0; ptrdiff_t len = strlen(temp) + 1; if(function + sizeof(function) - e >= len + 1) { *e++ = ':'; memcpy(e, temp, len); } } else { function[0] = 0; } } else { function[0] = 0; #if !QUICKCPPLIB_DISABLE_EXECINFO const void *temp[16]; memset(temp, 0, sizeof(temp)); (void) ::backtrace((void **) temp, 16); packed_backtrace::make_packed_backtrace(backtrace, temp); #endif } } bool operator==(const value_type &o) const noexcept { return memcmp(this, &o, sizeof(*this)) == 0; } bool operator!=(const value_type &o) const noexcept { return memcmp(this, &o, sizeof(*this)) != 0; } bool operator<(const value_type &o) const noexcept { return memcmp(this, &o, sizeof(*this)) < 0; } bool operator>(const value_type &o) const noexcept { return memcmp(this, &o, sizeof(*this)) > 0; } bool operator<=(const value_type &o) const noexcept { return memcmp(this, &o, sizeof(*this)) <= 0; } bool operator>=(const value_type &o) const noexcept { return memcmp(this, &o, sizeof(*this)) >= 0; } }; static_assert(sizeof(value_type) == 256, "value_type is not 256 bytes long!"); //! Location generator for simple_ringbuffer_log_policy's value_type inline std::string location(const value_type &v) { std::string ret; if(v.using_backtrace) { void *backtrace[16]; memset(backtrace, 0, sizeof(backtrace)); size_t len = 0; { packed_backtrace::packed_backtrace<> pb(v.backtrace); for(auto *i : pb) { backtrace[len] = i; len++; if(len == sizeof(backtrace) / sizeof(backtrace[0])) break; } } #ifndef _WIN32 bool done = false; // Try llvm-symbolizer for nicer backtraces int temp[2]; struct _h { int fd; } childreadh, childwriteh, readh, writeh; if(-1 != ::pipe(temp)) { using namespace scope; childreadh.fd = temp[0]; readh.fd = temp[1]; if(-1 != ::pipe(temp)) { writeh.fd = temp[0]; childwriteh.fd = temp[1]; auto unmypipes = make_scope_exit([&]() noexcept { (void) ::close(readh.fd); (void) ::close(writeh.fd); }); auto unhispipes = make_scope_exit([&]() noexcept { (void) ::close(childreadh.fd); (void) ::close(childwriteh.fd); }); (void) ::fcntl(readh.fd, F_SETFD, FD_CLOEXEC); (void) ::fcntl(writeh.fd, F_SETFD, FD_CLOEXEC); posix_spawn_file_actions_t child_fd_actions; if(!::posix_spawn_file_actions_init(&child_fd_actions)) { auto unactions = make_scope_exit([&]() noexcept { ::posix_spawn_file_actions_destroy(&child_fd_actions); }); if(!::posix_spawn_file_actions_adddup2(&child_fd_actions, childreadh.fd, STDIN_FILENO)) { if(!::posix_spawn_file_actions_addclose(&child_fd_actions, childreadh.fd)) { if(!::posix_spawn_file_actions_adddup2(&child_fd_actions, childwriteh.fd, STDOUT_FILENO)) { if(!::posix_spawn_file_actions_addclose(&child_fd_actions, childwriteh.fd)) { pid_t pid; std::vector<const char *> argptrs(2); argptrs[0] = "llvm-symbolizer"; if(!::posix_spawnp(&pid, "llvm-symbolizer", &child_fd_actions, nullptr, (char **) argptrs.data(), environ)) { (void) ::close(childreadh.fd); (void) ::close(childwriteh.fd); std::string addrs; addrs.reserve(1024); for(size_t n = 0; n < len; n++) { Dl_info info; memset(&info, 0, sizeof(info)); ::dladdr(backtrace[n], &info); if(info.dli_fname == nullptr) { break; } // std::cerr << bt[n] << " dli_fname = " << info.dli_fname << " dli_fbase = " << info.dli_fbase // << std::endl; addrs.append(info.dli_fname); addrs.append(" 0x"); const bool has_slash = (strrchr(info.dli_fname, '/') != nullptr); const bool is_dll = (strstr(info.dli_fname, ".so") != nullptr); if(has_slash) { ssize_t diff; if(is_dll) { diff = (char *) backtrace[n] - (char *) info.dli_fbase; } else { diff = (ssize_t) backtrace[n]; } char buffer[32]; snprintf(buffer, 32, "%zx", diff); buffer[31] = 0; addrs.append(buffer); } else { char buffer[32]; snprintf(buffer, 32, "%zx", (uintptr_t) backtrace[n]); buffer[31] = 0; addrs.append(buffer); } addrs.push_back('\n'); } // std::cerr << "\n\n---\n" << addrs << "---\n\n" << std::endl; // Suppress SIGPIPE sigset_t toblock, oldset; sigemptyset(&toblock); sigaddset(&toblock, SIGPIPE); pthread_sigmask(SIG_BLOCK, &toblock, &oldset); auto unsigmask = make_scope_exit([&toblock, &oldset]() noexcept { #ifdef __APPLE__ pthread_kill(pthread_self(), SIGPIPE); int cleared = 0; sigwait(&toblock, &cleared); #else struct timespec ts = {0, 0}; sigtimedwait(&toblock, 0, &ts); #endif pthread_sigmask(SIG_SETMASK, &oldset, nullptr); }); (void) unsigmask; ssize_t written = ::write(readh.fd, addrs.data(), addrs.size()); (void) ::close(readh.fd); addrs.clear(); if(written != -1) { char buffer[1024]; for(;;) { auto bytes = ::read(writeh.fd, buffer, sizeof(buffer)); if(bytes < 1) break; addrs.append(buffer, bytes); } (void) ::close(writeh.fd); unmypipes.release(); unhispipes.release(); } // std::cerr << "\n\n---\n" << addrs << "---\n\n" << std::endl; // reap child siginfo_t info; memset(&info, 0, sizeof(info)); int options = WEXITED | WSTOPPED; if(-1 == ::waitid(P_PID, pid, &info, options)) abort(); if(!addrs.empty()) { // We want the second line from every section separated by a double newline size_t n = 0; auto printitem = [&](size_t idx) { if(n) ret.append(", "); auto idx2 = addrs.find(10, idx), idx3 = addrs.find(10, idx2 + 1); ret.append(addrs.data() + idx2 + 1, idx3 - idx2 - 1); n++; }; size_t oldidx = 0; for(size_t idx = addrs.find("\n\n"); idx != std::string::npos; oldidx = idx + 2, idx = addrs.find("\n\n", idx + 1)) { printitem(oldidx); } done = true; } } } } } } } } } if(!done) #endif { #if !QUICKCPPLIB_DISABLE_EXECINFO char **symbols = backtrace_symbols(backtrace, len); if(!symbols) ret.append("BACKTRACE FAILED!"); else { for(size_t n = 0; n < len; n++) { if(symbols[n]) { if(n) ret.append(", "); ret.append(symbols[n]); } } free(symbols); } #endif } } else { char temp[256]; memcpy(temp, v.function, sizeof(v.function)); temp[sizeof(v.function)] = 0; ret.append(temp); } return ret; } //! std::ostream writer for simple_ringbuffer_log_policy's value_type inline std::ostream &operator<<(std::ostream &s, const value_type &v) { s << "+" << std::setfill('0') << std::setw(16) << v.timestamp << " " << std::setfill(' ') << std::setw(1); switch(v.level) { case 0: s << "none: "; break; case 1: s << "fatal: "; break; case 2: s << "error: "; break; case 3: s << "warn: "; break; case 4: s << "info: "; break; case 5: s << "debug: "; break; case 6: s << "all: "; break; default: s << "unknown: "; break; } if(v.using_code64) s << "{ " << v.code64 << " } "; else s << "{ " << v.code32[0] << ", " << v.code32[1] << " } "; char temp[256]; memcpy(temp, v.message, sizeof(v.message)); temp[sizeof(v.message)] = 0; s << temp << " @ "; s << location(v); return s << "\n"; } //! CSV std::ostream writer for simple_ringbuffer_log_policy's value_type inline std::ostream &csv(std::ostream &s, const value_type &v) { // timestamp,level,using_code64,using_backtrace,code0,code1,message,backtrace s << v.timestamp << "," << (unsigned) v.level << "," << (unsigned) v.using_code64 << "," << (unsigned) v.using_backtrace << ","; if(v.using_code64) s << v.code64 << ",0,\""; else s << v.code32[0] << "," << v.code32[1] << ",\""; char temp[256]; memcpy(temp, v.message, sizeof(v.message)); temp[sizeof(v.message)] = 0; s << temp << "\",\""; if(v.using_backtrace) { #if !QUICKCPPLIB_DISABLE_EXECINFO char **symbols = backtrace_symbols((void **) v.backtrace, sizeof(v.backtrace) / sizeof(v.backtrace[0])); if(!symbols) s << "BACKTRACE FAILED!"; else { for(size_t n = 0; n < sizeof(v.backtrace) / sizeof(v.backtrace[0]); n++) { if(symbols[n]) { if(n) s << ";"; s << symbols[n]; } } free(symbols); } #endif } else { memcpy(temp, v.function, sizeof(v.function)); temp[sizeof(v.function)] = 0; s << temp; } return s << "\"\n"; } } // namespace simple_ringbuffer_log_policy_detail /*! \tparam Bytes The size of the ring buffer \brief A ring buffer log stored in a fixed QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES_NDEBUG/QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES_DEBUG std::array recording monotonic counter (8 bytes), high resolution clock time stamp (8 bytes), stack backtrace or __func__ (40 bytes), level (1 byte), 191 bytes of char message. Each record is 256 bytes, therefore the ring buffer wraps after 256/4096 entries by default. */ template <size_t Bytes = QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES * 256> struct simple_ringbuffer_log_policy { //! Item logged in this log using value_type = simple_ringbuffer_log_policy_detail::value_type; //! Maximum items of this value_type in this log static constexpr size_t max_items = Bytes / sizeof(value_type); //! Container for storing log using container_type = std::array<value_type, max_items>; }; /*! \class ringbuffer_log \brief Very fast threadsafe ring buffer log Works on the basis of an always incrementing atomic<size_t> which writes into the ring buffer at modulus of the ring buffer size. Items stored per log entry are defined by the Policy class' value_type. To log an item, call the QUICKCPPLIB_RINGBUFFERLOG_ITEM_* family of macros. Be aware iteration, indexing etc. is most recent first, so log[0] is the most recently logged item. Use the reversed iterators if you don't want this. For simple_ringbuffer_log_policy, typical item logging times are: - without backtrace: 1.2 microseconds. - with backtrace (windows): up to 33 microseconds. \todo Implement STL allocator for a memory mapped file on disc so log survives sudden process exit. */ template <class Policy, class LogLevelChecker> class ringbuffer_log { friend Policy; public: /*! The container used to store the logged records set by Policy::container_type. Must be a ContiguousContainer. */ using container_type = typename Policy::container_type; //! The maximum items to store according to Policy::max_items. If zero, use container's size(). static constexpr size_t max_items = Policy::max_items; //! The log record type using value_type = typename container_type::value_type; //! The size type using size_type = typename container_type::size_type; //! The difference type using difference_type = typename container_type::difference_type; //! The reference type using reference = typename container_type::reference; //! The const reference type using const_reference = typename container_type::const_reference; //! The pointer type using pointer = typename container_type::pointer; //! The const pointer type using const_pointer = typename container_type::const_pointer; protected: template <class Parent, class Pointer, class Reference> class iterator_; template <class Parent, class Pointer, class Reference> class iterator_ { friend class ringbuffer_log; template <class Parent_, class Pointer_, class Reference_> friend class iterator_; Parent *_parent; size_type _counter, _togo; constexpr iterator_(Parent *parent, size_type counter, size_type items) : _parent(parent) , _counter(counter) , _togo(items) { } public: using iterator_category = std::random_access_iterator_tag; using value_type = typename container_type::value_type; using difference_type = typename container_type::difference_type; using pointer = typename container_type::pointer; using reference = typename container_type::reference; constexpr iterator_() : _parent(nullptr) , _counter(0) , _togo(0) { } constexpr iterator_(const iterator_ &) noexcept = default; constexpr iterator_(iterator_ &&) noexcept = default; iterator_ &operator=(const iterator_ &) noexcept = default; iterator_ &operator=(iterator_ &&) noexcept = default; // Non-const to const iterator template <class Parent_, class Pointer_, class Reference_, typename = typename std::enable_if<!std::is_const<Pointer_>::value && !std::is_const<Reference_>::value>::type> constexpr iterator_(const iterator_<Parent_, Pointer_, Reference_> &o) noexcept : _parent(o._parent) , _counter(o._counter) , _togo(o._togo) { } iterator_ &operator++() noexcept { if(_parent && _togo) { --_counter; --_togo; } return *this; } void swap(iterator_ &o) noexcept { std::swap(_parent, o._parent); std::swap(_counter, o._counter); std::swap(_togo, o._togo); } Pointer operator->() const noexcept { if(!_parent || !_togo) return nullptr; return &_parent->_store[_parent->counter_to_idx(_counter)]; } bool operator==(const iterator_ &o) const noexcept { return _parent == o._parent && _counter == o._counter && _togo == o._togo; } bool operator!=(const iterator_ &o) const noexcept { return _parent != o._parent || _counter != o._counter || _togo != o._togo; } Reference operator*() const noexcept { if(!_parent || !_togo) { static value_type v; return v; } return _parent->_store[_parent->counter_to_idx(_counter)]; } iterator_ operator++(int) noexcept { iterator_ ret(*this); if(_parent && _togo) { --_counter; --_togo; } return ret; } iterator_ &operator--() noexcept { if(_parent && _togo < _parent->size()) { ++_counter; ++_togo; } return *this; } iterator_ operator--(int) noexcept { iterator_ ret(*this); if(_parent && _togo < _parent->size()) { ++_counter; ++_togo; } return ret; } bool operator<(const iterator_ &o) const noexcept { return _parent == o._parent && _parent->counter_to_idx(_counter) < o._parent->counter_to_idx(o._counter); } bool operator>(const iterator_ &o) const noexcept { return _parent == o._parent && _parent->counter_to_idx(_counter) > o._parent->counter_to_idx(o._counter); } bool operator<=(const iterator_ &o) const noexcept { return _parent == o._parent && _parent->counter_to_idx(_counter) <= o._parent->counter_to_idx(o._counter); } bool operator>=(const iterator_ &o) const noexcept { return _parent == o._parent && _parent->counter_to_idx(_counter) >= o._parent->counter_to_idx(o._counter); } iterator_ &operator+=(size_type v) const noexcept { if(_parent && _togo) { if(v > _togo) v = _togo; _counter -= v; _togo -= v; } return *this; } iterator_ operator+(size_type v) const noexcept { iterator_ ret(*this); if(_parent && _togo) { if(v > _togo) v = _togo; ret._counter -= v; ret._togo -= v; } return ret; } iterator_ &operator-=(size_type v) const noexcept { if(_parent && _togo < _parent->size()) { if(v > _parent->size() - _togo) v = _parent->size() - _togo; _counter += v; _togo += v; } return *this; } iterator_ operator-(size_type v) const noexcept { iterator_ ret(*this); if(_parent && _togo < _parent->size()) { if(v > _parent->size() - _togo) v = _parent->size() - _togo; ret._counter += v; ret._togo += v; } return ret; } difference_type operator-(const iterator_ &o) const noexcept { return (difference_type)(o._counter - _counter); } Reference operator[](size_type v) const noexcept { return _parent->_store[_parent->counter_to_idx(_counter + v)]; } }; template <class Parent, class Pointer, class Reference> friend class iterator_; public: //! The iterator type using iterator = iterator_<ringbuffer_log, pointer, reference>; //! The const iterator type using const_iterator = iterator_<const ringbuffer_log, const_pointer, const_reference>; //! The reverse iterator type using reverse_iterator = std::reverse_iterator<iterator>; //! The const reverse iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; protected: container_type _store; std::atomic<level> _instance_level; std::atomic<size_type> _counter; std::ostream *_immediate; size_type counter_to_idx(size_type counter) const noexcept { return max_items ? (counter % max_items) : (counter % _store.size()); } public: //! Default construction, passes through args to container_type template <class... Args> explicit ringbuffer_log(level starting_level, Args &&... args) noexcept(noexcept(container_type(std::forward<Args>(args)...))) : _store(std::forward<Args>(args)...) , _instance_level(starting_level) , _counter(0) , _immediate(nullptr) { } //! No copying ringbuffer_log(const ringbuffer_log &) = delete; //! No moving ringbuffer_log(ringbuffer_log &&) = delete; //! No copying ringbuffer_log &operator=(const ringbuffer_log &) = delete; //! No moving ringbuffer_log &operator=(ringbuffer_log &&) = delete; //! Swaps with another instance void swap(ringbuffer_log &o) noexcept { std::swap(_store, o._store); auto t = o._instance_level.load(std::memory_order_relaxed); o._instance_level.store(_instance_level.load(std::memory_order_relaxed), std::memory_order_relaxed); _instance_level.store(t, std::memory_order_relaxed); std::swap(_counter, o._counter); std::swap(_immediate, o._immediate); } //! THREADSAFE Returns the log level from the instance filtered by any `LogLevelChecker`. level log_level() const noexcept { return LogLevelChecker()(instance_log_level()); } //! THREADSAFE Returns the current per-instance log level level instance_log_level() const noexcept { return _instance_level.load(std::memory_order_relaxed); } //! THREADSAFE Sets the current per-instance log level void instance_log_level(level new_level) noexcept { _instance_level.store(new_level, std::memory_order_relaxed); } //! Returns true if the log is empty bool empty() const noexcept { return _counter.load(std::memory_order_relaxed) == 0; } //! Returns the number of items in the log size_type size() const noexcept { size_type ret = _counter.load(std::memory_order_relaxed); if(_store.size() < ret) ret = _store.size(); return ret; } //! Returns the maximum number of items in the log size_type max_size() const noexcept { return max_items ? max_items : _store.size(); } //! Returns any `std::ostream` immediately printed to when a new log entry is added std::ostream *immediate() const noexcept { return _immediate; } //! Set any `std::ostream` immediately printed to when a new log entry is added void immediate(std::ostream *s) noexcept { _immediate = s; } //! Used to tag an index as being an absolute lookup of a unique counter value returned by push_back/emplace_back. struct unique_id { size_type value; constexpr unique_id(size_type _value) : value(_value) { } }; //! True if a unique id is still valid bool valid(unique_id id) const noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return id.value < counter && id.value >= counter - size; } //! Returns the front of the ringbuffer. Be careful of races with concurrent modifies. reference front() noexcept { return _store[counter_to_idx(_counter.load(std::memory_order_relaxed) - 1)]; } //! Returns the front of the ringbuffer. Be careful of races with concurrent modifies. const_reference front() const noexcept { return _store[counter_to_idx(_counter.load(std::memory_order_relaxed) - 1)]; } #ifdef __cpp_exceptions //! Returns a reference to the specified element. Be careful of races with concurrent modifies. reference at(size_type pos) { if(pos >= size()) throw std::out_of_range("index exceeds size"); return _store[counter_to_idx(_counter.load(std::memory_order_relaxed) - 1 - pos)]; } //! Returns a reference to the specified element. reference at(unique_id id) { if(!valid(id)) throw std::out_of_range("index exceeds size"); return _store[counter_to_idx(id.value)]; } //! Returns a reference to the specified element. Be careful of races with concurrent modifies. const_reference at(size_type pos) const { if(pos >= size()) throw std::out_of_range("index exceeds size"); return _store[counter_to_idx(_counter.load(std::memory_order_relaxed) - 1 - pos)]; } //! Returns a reference to the specified element. const_reference at(unique_id id) const { if(!valid(id)) throw std::out_of_range("index exceeds size"); return _store[counter_to_idx(id.value)]; } #endif //! Returns a reference to the specified element. Be careful of races with concurrent modifies. reference operator[](size_type pos) noexcept { return _store[counter_to_idx(_counter.load(std::memory_order_relaxed) - 1 - pos)]; } //! Returns a reference to the specified element. reference operator[](unique_id id) noexcept { return _store[counter_to_idx(id.value)]; } //! Returns a reference to the specified element. Be careful of races with concurrent modifies. const_reference operator[](size_type pos) const noexcept { return _store[counter_to_idx(_counter.load(std::memory_order_relaxed) - 1 - pos)]; } //! Returns a reference to the specified element. const_reference operator[](unique_id id) const noexcept { return _store[counter_to_idx(id.value)]; } //! Returns the back of the ringbuffer. Be careful of races with concurrent modifies. reference back() noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return _store[counter_to_idx(counter - size)]; } //! Returns the back of the ringbuffer. Be careful of races with concurrent modifies. const_reference back() const noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return _store[counter_to_idx(counter - size)]; } //! Returns an iterator to the first item in the log. Be careful of races with concurrent modifies. iterator begin() noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return iterator(this, counter - 1, size); } //! Returns an iterator to the first item in the log. Be careful of races with concurrent modifies. const_iterator begin() const noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return const_iterator(this, counter - 1, size); } //! Returns an iterator to the first item in the log. Be careful of races with concurrent modifies. const_iterator cbegin() const noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return const_iterator(this, counter - 1, size); } //! Returns an iterator to the item after the last in the log. Be careful of races with concurrent modifies. iterator end() noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return iterator(this, counter - 1 - size, 0); } //! Returns an iterator to the item after the last in the log. Be careful of races with concurrent modifies. const_iterator end() const noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return const_iterator(this, counter - 1 - size, 0); } //! Returns an iterator to the item after the last in the log. Be careful of races with concurrent modifies. const_iterator cend() const noexcept { size_type counter = _counter.load(std::memory_order_relaxed); size_type size = counter; if(_store.size() < size) size = _store.size(); return const_iterator(this, counter - 1 - size, 0); } //! Clears the log void clear() noexcept { _counter.store(0, std::memory_order_relaxed); std::fill(_store.begin(), _store.end(), value_type()); } //! THREADSAFE Logs a new item, returning its unique counter id size_type push_back(value_type &&v) noexcept { if(static_cast<level>(v.level) <= log_level()) { if(_immediate) *_immediate << v << std::endl; size_type thisitem = _counter++; v.counter = thisitem; _store[counter_to_idx(thisitem)] = std::move(v); return thisitem; } return (size_type) -1; } //! THREADSAFE Logs a new item, returning its unique counter id template <class... Args> size_type emplace_back(level __level, Args &&... args) noexcept { if(__level <= log_level()) { value_type v(__level, std::forward<Args>(args)...); if(_immediate) *_immediate << v << std::endl; size_type thisitem = _counter++; v.counter = thisitem; _store[counter_to_idx(thisitem)] = std::move(v); return thisitem; } return (size_type) -1; } }; //! std::ostream writer for a log template <class Policy, class LogLevelChecker> inline std::ostream &operator<<(std::ostream &s, const ringbuffer_log<Policy, LogLevelChecker> &l) { for(const auto &i : l) { s << i; } return s; } //! CSV string writer for a log template <class Policy, class LogLevelChecker> inline std::string csv(const ringbuffer_log<Policy, LogLevelChecker> &l) { std::stringstream s; // timestamp,level,using_code64,using_backtrace,code0,code1,message,backtrace s << "timestamp,level,using_code64,using_backtrace,code0,code1,message,backtrace\n"; for(const auto &i : l) { csv(s, i); } return s.str(); } //! Alias for a simple ringbuffer log template <size_t Bytes = QUICKCPPLIB_RINGBUFFER_LOG_DEFAULT_ENTRIES * 256, class LogLevelChecker = default_ringbuffer_log_level_checker> using simple_ringbuffer_log = ringbuffer_log<simple_ringbuffer_log_policy<Bytes>, LogLevelChecker>; } // namespace ringbuffer_log QUICKCPPLIB_NAMESPACE_END //! Logs an item to the log with calling function name #define QUICKCPPLIB_RINGBUFFERLOG_ITEM_FUNCTION(log, level, message, code1, code2) (log).emplace_back((level), (message), (code1), (code2), __func__, __LINE__) //! Logs an item to the log with stack backtrace #define QUICKCPPLIB_RINGBUFFERLOG_ITEM_BACKTRACE(log, level, message, code1, code2) (log).emplace_back((level), (message), (code1), (code2), nullptr) #ifndef QUICKCPPLIB_RINGBUFFERLOG_LEVEL #if defined(_DEBUG) || defined(DEBUG) #define QUICKCPPLIB_RINGBUFFERLOG_LEVEL 5 // debug #else #define QUICKCPPLIB_RINGBUFFERLOG_LEVEL 2 // error #endif #endif #if QUICKCPPLIB_RINGBUFFERLOG_LEVEL >= 1 //! Logs an item to the log at fatal level with calling function name #define QUICKCPPLIB_RINGBUFFERLOG_FATAL_FUNCTION(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_FUNCTION((log), ringbuffer_log::level::fatal, (message), (code1), (code2)) //! Logs an item to the log at fatal level with stack backtrace #define QUICKCPPLIB_RINGBUFFERLOG_FATAL_BACKTRACE(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_BACKTRACE((log), ringbuffer_log::level::fatal, (message), (code1), (code2)) #else #define QUICKCPPLIB_RINGBUFFERLOG_FATAL_FUNCTION(log, message, code1, code2) #define QUICKCPPLIB_RINGBUFFERLOG_FATAL_BACKTRACE(log, message, code1, code2) #endif #if QUICKCPPLIB_RINGBUFFERLOG_LEVEL >= 2 //! Logs an item to the log at error level with calling function name #define QUICKCPPLIB_RINGBUFFERLOG_ERROR_FUNCTION(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_FUNCTION((log), ringbuffer_log::level::error, (message), (code1), (code2)) //! Logs an item to the log at error level with stack backtrace #define QUICKCPPLIB_RINGBUFFERLOG_ERROR_BACKTRACE(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_BACKTRACE((log), ringbuffer_log::level::error, (message), (code1), (code2)) #else #define QUICKCPPLIB_RINGBUFFERLOG_ERROR_FUNCTION(log, message, code1, code2) #define QUICKCPPLIB_RINGBUFFERLOG_ERROR_BACKTRACE(log, message, code1, code2) #endif #if QUICKCPPLIB_RINGBUFFERLOG_LEVEL >= 3 //! Logs an item to the log at warn level with calling function name #define QUICKCPPLIB_RINGBUFFERLOG_WARN_FUNCTION(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_FUNCTION((log), ringbuffer_log::level::warn, (message), (code1), (code2)) //! Logs an item to the log at warn level with stack backtrace #define QUICKCPPLIB_RINGBUFFERLOG_WARN_BACKTRACE(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_BACKTRACE((log), ringbuffer_log::level::warn, (message), (code1), (code2)) #else #define QUICKCPPLIB_RINGBUFFERLOG_WARN_FUNCTION(log, message, code1, code2) #define QUICKCPPLIB_RINGBUFFERLOG_WARN_BACKTRACE(log, message, code1, code2) #endif #if QUICKCPPLIB_RINGBUFFERLOG_LEVEL >= 4 //! Logs an item to the log at info level with calling function name #define QUICKCPPLIB_RINGBUFFERLOG_INFO_FUNCTION(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_FUNCTION((log), ringbuffer_log::level::info, (message), (code1), (code2)) //! Logs an item to the log at info level with stack backtrace #define QUICKCPPLIB_RINGBUFFERLOG_INFO_BACKTRACE(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_BACKTRACE((log), ringbuffer_log::level::info, (message), (code1), (code2)) #else #define QUICKCPPLIB_RINGBUFFERLOG_INFO_FUNCTION(log, message, code1, code2) #define QUICKCPPLIB_RINGBUFFERLOG_INFO_BACKTRACE(log, message, code1, code2) #endif #if QUICKCPPLIB_RINGBUFFERLOG_LEVEL >= 5 //! Logs an item to the log at debug level with calling function name #define QUICKCPPLIB_RINGBUFFERLOG_DEBUG_FUNCTION(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_FUNCTION((log), ringbuffer_log::level::debug, (message), (code1), (code2)) //! Logs an item to the log at debug level with stack backtrace #define QUICKCPPLIB_RINGBUFFERLOG_DEBUG_BACKTRACE(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_BACKTRACE((log), ringbuffer_log::level::debug, (message), (code1), (code2)) #else #define QUICKCPPLIB_RINGBUFFERLOG_DEBUG_FUNCTION(log, message, code1, code2) #define QUICKCPPLIB_RINGBUFFERLOG_DEBUG_BACKTRACE(log, message, code1, code2) #endif #if QUICKCPPLIB_RINGBUFFERLOG_LEVEL >= 6 //! Logs an item to the log at all level with calling function name #define QUICKCPPLIB_RINGBUFFERLOG_ALL_FUNCTION(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_FUNCTION((log), ringbuffer_log::level::all, (message), (code1), (code2)) //! Logs an item to the log at all level with stack backtrace #define QUICKCPPLIB_RINGBUFFERLOG_ALL_BACKTRACE(log, message, code1, code2) \ QUICKCPPLIB_RINGBUFFERLOG_ITEM_BACKTRACE((log), ringbuffer_log::level::all, (message), (code1), (code2)) #else #define QUICKCPPLIB_RINGBUFFERLOG_ALL_FUNCTION(log, message, code1, code2) #define QUICKCPPLIB_RINGBUFFERLOG_ALL_BACKTRACE(log, message, code1, code2) #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/aligned_allocator.hpp
/* * File: Aligned_Allocator.hpp * Author: atlas * * Created on July 5, 2013, 6:52 PM Boost Software License - Version 1.0 - August 17th, 2003 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: 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. 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. */ #ifndef QUICKCPPLIB_ALIGNED_ALLOCATOR_HPP #define QUICKCPPLIB_ALIGNED_ALLOCATOR_HPP #include "config.hpp" #include <cstddef> #include <memory> #include <type_traits> #include <typeinfo> #include <vector> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) // conditional expression is constant #endif QUICKCPPLIB_NAMESPACE_BEGIN namespace aligned_allocator { namespace detail { enum class allocator_alignment : size_t { Default = sizeof(void*), //!< The default alignment on this machine. SSE = 16, //!< The alignment for SSE. Better to use M128 for NEON et al support. M128 = 16, //!< The alignment for a 128 bit vector. AVX = 32, //!< The alignment for AVX. Better to use M256 for NEON et al support. M256 = 32 //!< The alignment for a 256 bit vector. }; #ifdef _WIN32 extern "C" __declspec(allocator) __declspec(restrict) void *_aligned_malloc(size_t size, size_t alignment); extern "C" void _aligned_free(void *blk); #else extern "C" int posix_memalign(void **memptr, size_t alignment, size_t size); #endif inline void* allocate_aligned_memory(size_t align, size_t size) { #ifdef _WIN32 return _aligned_malloc(size, align); #else void *ret = nullptr; if (posix_memalign(&ret, align, size)) return nullptr; return ret; #endif } inline void deallocate_aligned_memory(void* ptr) noexcept { #ifdef _WIN32 _aligned_free(ptr); #else free(ptr); #endif } } /*! \class aligned_allocator \brief An STL allocator which allocates aligned memory Stolen from http://stackoverflow.com/questions/12942548/making-stdvector-allocate-aligned-memory */ template <typename T, size_t Align = std::alignment_of<T>::value, bool initialize = true> class aligned_allocator { public: typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; enum { alignment = Align }; typedef std::true_type propagate_on_container_move_assignment; template <class U> struct rebind { typedef aligned_allocator<U, Align, initialize> other; }; public: aligned_allocator() noexcept {} template <class U> aligned_allocator(const aligned_allocator<U, Align, initialize>&) noexcept {} size_type max_size() const noexcept { return (size_type(~0) - size_type(Align)) / sizeof(T); } pointer address(reference x) const noexcept { return std::addressof(x); } const_pointer address(const_reference x) const noexcept { return std::addressof(x); } pointer allocate(size_type n, typename aligned_allocator<void, Align, initialize>::const_pointer = 0) { const size_type alignment = static_cast<size_type>(Align); void* ptr = detail::allocate_aligned_memory(alignment, n * sizeof(T)); if (ptr == nullptr) { throw std::bad_alloc(); } return reinterpret_cast<pointer>(ptr); } void deallocate(pointer p, size_type) noexcept { return detail::deallocate_aligned_memory(p); } template <class U, class ...Args> void construct(U* p, Args&&... args) { if (initialize || !std::is_same<char, U>::value) ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); } void destroy(pointer p) { (void)p; p->~T(); } }; template <size_t Align, bool initialize> class aligned_allocator<void, Align, initialize> { public: typedef void value_type; typedef void * pointer; typedef const void * const_pointer; typedef void reference; typedef const void const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; enum { alignment = Align }; }; template <size_t Align, bool initialize> class aligned_allocator<const void, Align, initialize> { public: typedef const void value_type; typedef const void* pointer; typedef const void* const_pointer; typedef void reference; typedef const void const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; enum { alignment = Align }; }; template <typename T, size_t Align, bool initialize> class aligned_allocator<const T, Align, initialize> { public: typedef T value_type; typedef const T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; enum { alignment = Align }; typedef std::true_type propagate_on_container_move_assignment; template <class U> struct rebind { typedef aligned_allocator<U, Align, initialize> other; }; public: aligned_allocator() noexcept {} template <class U> aligned_allocator(const aligned_allocator<U, Align, initialize>&) noexcept {} size_type max_size() const noexcept { return (size_type(~0) - size_type(Align)) / sizeof(T); } const_pointer address(const_reference x) const noexcept { return std::addressof(x); } pointer allocate(size_type n, typename aligned_allocator<void, Align, initialize>::const_pointer = 0) { const size_type alignment = static_cast<size_type>(Align); void* ptr = detail::allocate_aligned_memory(alignment, n * sizeof(T)); if (ptr == nullptr) { throw std::bad_alloc(); } return reinterpret_cast<pointer>(ptr); } void deallocate(pointer p, size_type) noexcept { return detail::deallocate_aligned_memory(p); } template <class U, class ...Args> void construct(U* p, Args&&... args) { if (initialize || !std::is_same<char, U>::value) ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); } void destroy(pointer p) { p->~T(); } }; template <typename T, size_t TAlign, bool Tinit, typename U, size_t UAlign, bool Uinit> inline bool operator== (const aligned_allocator<T, TAlign, Tinit>&, const aligned_allocator<U, UAlign, Uinit>&) noexcept { return TAlign == UAlign; } template <typename T, size_t TAlign, bool Tinit, typename U, size_t UAlign, bool Uinit> inline bool operator!= (const aligned_allocator<T, TAlign, Tinit>&, const aligned_allocator<U, UAlign, Uinit>&) noexcept { return TAlign != UAlign; } } QUICKCPPLIB_NAMESPACE_END #ifdef _MSC_VER #pragma warning(pop) #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/import.h
/* Convenience macros for importing local namespace binds (C) 2014-2017 Niall Douglas <http://www.nedproductions.biz/> (9 commits) File Created: Aug 2014 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_BIND_IMPORT_HPP #define QUICKCPPLIB_BIND_IMPORT_HPP /* 2014-10-9 ned: I lost today figuring out the below. I really hate the C preprocessor now. * * Anyway, infinity = 8. It's easy to expand below if needed. */ #include "detail/preprocessor_macro_overload.h" #define QUICKCPPLIB_BIND_STRINGIZE(a) #a #define QUICKCPPLIB_BIND_STRINGIZE2(a) QUICKCPPLIB_BIND_STRINGIZE(a) #define QUICKCPPLIB_BIND_NAMESPACE_VERSION8(a, b, c, d, e, f, g, h) a##_##b##_##c##_##d##_##e##_##f##_##g##_##h #define QUICKCPPLIB_BIND_NAMESPACE_VERSION7(a, b, c, d, e, f, g) a##_##b##_##c##_##d##_##e##_##f##_##g #define QUICKCPPLIB_BIND_NAMESPACE_VERSION6(a, b, c, d, e, f) a##_##b##_##c##_##d##_##e##_##f #define QUICKCPPLIB_BIND_NAMESPACE_VERSION5(a, b, c, d, e) a##_##b##_##c##_##d##_##e #define QUICKCPPLIB_BIND_NAMESPACE_VERSION4(a, b, c, d) a##_##b##_##c##_##d #define QUICKCPPLIB_BIND_NAMESPACE_VERSION3(a, b, c) a##_##b##_##c #define QUICKCPPLIB_BIND_NAMESPACE_VERSION2(a, b) a##_##b #define QUICKCPPLIB_BIND_NAMESPACE_VERSION1(a) a //! Concatenates each parameter with _ #define QUICKCPPLIB_BIND_NAMESPACE_VERSION(...) QUICKCPPLIB_CALL_OVERLOAD(QUICKCPPLIB_BIND_NAMESPACE_VERSION, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_SELECT_2(name, modifier) name #define QUICKCPPLIB_BIND_NAMESPACE_SELECT2(name, modifier) ::name #define QUICKCPPLIB_BIND_NAMESPACE_SELECT_1(name) name #define QUICKCPPLIB_BIND_NAMESPACE_SELECT1(name) ::name #define QUICKCPPLIB_BIND_NAMESPACE_SELECT_(...) QUICKCPPLIB_CALL_OVERLOAD_(QUICKCPPLIB_BIND_NAMESPACE_SELECT_, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_SELECT(...) QUICKCPPLIB_CALL_OVERLOAD_(QUICKCPPLIB_BIND_NAMESPACE_SELECT, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_EXPAND8(a, b, c, d, e, f, g, h) \ QUICKCPPLIB_BIND_NAMESPACE_SELECT_ a QUICKCPPLIB_BIND_NAMESPACE_SELECT b QUICKCPPLIB_BIND_NAMESPACE_SELECT c QUICKCPPLIB_BIND_NAMESPACE_SELECT d QUICKCPPLIB_BIND_NAMESPACE_SELECT e QUICKCPPLIB_BIND_NAMESPACE_SELECT f QUICKCPPLIB_BIND_NAMESPACE_SELECT g QUICKCPPLIB_BIND_NAMESPACE_SELECT h #define QUICKCPPLIB_BIND_NAMESPACE_EXPAND7(a, b, c, d, e, f, g) QUICKCPPLIB_BIND_NAMESPACE_SELECT_ a QUICKCPPLIB_BIND_NAMESPACE_SELECT b QUICKCPPLIB_BIND_NAMESPACE_SELECT c QUICKCPPLIB_BIND_NAMESPACE_SELECT d QUICKCPPLIB_BIND_NAMESPACE_SELECT e QUICKCPPLIB_BIND_NAMESPACE_SELECT f QUICKCPPLIB_BIND_NAMESPACE_SELECT g #define QUICKCPPLIB_BIND_NAMESPACE_EXPAND6(a, b, c, d, e, f) QUICKCPPLIB_BIND_NAMESPACE_SELECT_ a QUICKCPPLIB_BIND_NAMESPACE_SELECT b QUICKCPPLIB_BIND_NAMESPACE_SELECT c QUICKCPPLIB_BIND_NAMESPACE_SELECT d QUICKCPPLIB_BIND_NAMESPACE_SELECT e QUICKCPPLIB_BIND_NAMESPACE_SELECT f #define QUICKCPPLIB_BIND_NAMESPACE_EXPAND5(a, b, c, d, e) QUICKCPPLIB_BIND_NAMESPACE_SELECT_ a QUICKCPPLIB_BIND_NAMESPACE_SELECT b QUICKCPPLIB_BIND_NAMESPACE_SELECT c QUICKCPPLIB_BIND_NAMESPACE_SELECT d QUICKCPPLIB_BIND_NAMESPACE_SELECT e #define QUICKCPPLIB_BIND_NAMESPACE_EXPAND4(a, b, c, d) QUICKCPPLIB_BIND_NAMESPACE_SELECT_ a QUICKCPPLIB_BIND_NAMESPACE_SELECT b QUICKCPPLIB_BIND_NAMESPACE_SELECT c QUICKCPPLIB_BIND_NAMESPACE_SELECT d #define QUICKCPPLIB_BIND_NAMESPACE_EXPAND3(a, b, c) QUICKCPPLIB_BIND_NAMESPACE_SELECT_ a QUICKCPPLIB_BIND_NAMESPACE_SELECT b QUICKCPPLIB_BIND_NAMESPACE_SELECT c #define QUICKCPPLIB_BIND_NAMESPACE_EXPAND2(a, b) QUICKCPPLIB_BIND_NAMESPACE_SELECT_ a QUICKCPPLIB_BIND_NAMESPACE_SELECT b #define QUICKCPPLIB_BIND_NAMESPACE_EXPAND1(a) QUICKCPPLIB_BIND_NAMESPACE_SELECT_ a //! Expands into a::b::c:: ... #define QUICKCPPLIB_BIND_NAMESPACE(...) QUICKCPPLIB_CALL_OVERLOAD(QUICKCPPLIB_BIND_NAMESPACE_EXPAND, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT2(name, modifier) \ modifier namespace name \ { #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT1(name) \ namespace name \ { #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT(...) QUICKCPPLIB_CALL_OVERLOAD_(QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND8(a, b, c, d, e, f, g, h) QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND7(b, c, d, e, f, g, h) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND7(a, b, c, d, e, f, g) QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND6(b, c, d, e, f, g) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND6(a, b, c, d, e, f) QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND5(b, c, d, e, f) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND5(a, b, c, d, e) QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND4(b, c, d, e) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND4(a, b, c, d) QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND3(b, c, d) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND3(a, b, c) QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND2(b, c) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND2(a, b) QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND1(b) #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND1(a) QUICKCPPLIB_BIND_NAMESPACE_BEGIN_NAMESPACE_SELECT a //! Expands into namespace a { namespace b { namespace c ... #define QUICKCPPLIB_BIND_NAMESPACE_BEGIN(...) QUICKCPPLIB_CALL_OVERLOAD(QUICKCPPLIB_BIND_NAMESPACE_BEGIN_EXPAND, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT2(name, modifier) \ modifier namespace name \ { #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT1(name) \ export namespace name \ { #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT(...) QUICKCPPLIB_CALL_OVERLOAD_(QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND8(a, b, c, d, e, f, g, h) QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND7(b, c, d, e, f, g, h) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND7(a, b, c, d, e, f, g) QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND6(b, c, d, e, f, g) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND6(a, b, c, d, e, f) QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND5(b, c, d, e, f) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND5(a, b, c, d, e) QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND4(b, c, d, e) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND4(a, b, c, d) QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND3(b, c, d) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND3(a, b, c) QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND2(b, c) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND2(a, b) QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND1(b) #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND1(a) QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_NAMESPACE_SELECT a //! Expands into export namespace a { namespace b { namespace c ... #define QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN(...) QUICKCPPLIB_CALL_OVERLOAD(QUICKCPPLIB_BIND_NAMESPACE_EXPORT_BEGIN_EXPAND, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT2(name, modifier) } #define QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT1(name) } #define QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT(...) QUICKCPPLIB_CALL_OVERLOAD_(QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT, __VA_ARGS__) #define QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND8(a, b, c, d, e, f, g, h) QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND7(b, c, d, e, f, g, h) #define QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND7(a, b, c, d, e, f, g) QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND6(b, c, d, e, f, g) #define QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND6(a, b, c, d, e, f) QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND5(b, c, d, e, f) #define QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND5(a, b, c, d, e) QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND4(b, c, d, e) #define QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND4(a, b, c, d) QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND3(b, c, d) #define QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND3(a, b, c) QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND2(b, c) #define QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND2(a, b) QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT a QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND1(b) #define QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND1(a) QUICKCPPLIB_BIND_NAMESPACE_END_NAMESPACE_SELECT a //! Expands into } } ... #define QUICKCPPLIB_BIND_NAMESPACE_END(...) QUICKCPPLIB_CALL_OVERLOAD(QUICKCPPLIB_BIND_NAMESPACE_END_EXPAND, __VA_ARGS__) //! Expands into a static const char string array used to mark BindLib compatible namespaces #define QUICKCPPLIB_BIND_DECLARE(decl, desc) static const char *quickcpplib_out[] = {#decl, desc}; #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/bit_cast.hpp
/* C++ 20 bit cast emulation. (C) 2018 - 2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: May 2019 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_BIT_CAST_HPP #define QUICKCPPLIB_BIT_CAST_HPP #include "config.hpp" #ifndef QUICKCPPLIB_USE_STD_BIT_CAST #if __cplusplus >= 202000 && __has_include(<bit>) #include <bit> #if __cpp_lib_bit_cast #define QUICKCPPLIB_USE_STD_BIT_CAST 1 #else #define QUICKCPPLIB_USE_STD_BIT_CAST 0 #endif #else #define QUICKCPPLIB_USE_STD_BIT_CAST 0 #endif #endif #include <type_traits> QUICKCPPLIB_NAMESPACE_BEGIN namespace bit_cast { //! Namespace for user specialised traits namespace traits { /*! Specialise to true if you guarantee that a type is move relocating (i.e. its move constructor equals copying bits from old to new, old is left in a default constructed state, and calling the destructor on a default constructed instance is trivial). All trivially copyable types are move relocating by definition, and that is the unspecialised implementation. */ template <class T> struct is_move_relocating { static constexpr bool value = std::is_trivially_copyable<T>::value; }; } // namespace traits namespace detail { template <class T> using is_integral_or_enum = std::integral_constant<bool, std::is_integral<T>::value || std::is_enum<T>::value>; template <class To, class From> using is_static_castable = std::integral_constant<bool, is_integral_or_enum<To>::value && is_integral_or_enum<From>::value>; } // namespace detail #if QUICKCPPLIB_USE_STD_BIT_CAST using std::bit_cast; #else namespace detail { /* A partially compliant implementation of C++20's std::bit_cast function contributed by Jesse Towner. Our bit_cast is only guaranteed to be constexpr when both the input and output arguments are either integrals or enums. We still attempt a constexpr union-based type pun for non-array input types, which some compilers accept. For array inputs, we fall back to non-constexpr memmove. */ template <class To, class From> using is_union_castable = std::integral_constant<bool, !is_static_castable<To, From>::value && !std::is_array<To>::value && !std::is_array<From>::value>; template <class To, class From> using is_bit_castable = std::integral_constant<bool, sizeof(To) == sizeof(From) && traits::is_move_relocating<To>::value && traits::is_move_relocating<From>::value>; template <class To, class From> union bit_cast_union { From source; To target; }; struct static_cast_overload { }; struct union_cast_overload { }; struct memmove_overload { }; } // namespace detail /*! \brief Bit cast emulation chosen if types are move relocating or trivally copyable, have identical size, and are statically castable. Constexpr. */ QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_bit_castable<To, From>::value // &&detail::is_static_castable<To, From>::value // && !detail::is_union_castable<To, From>::value)) constexpr inline To bit_cast(const From &from, detail::static_cast_overload = {}) noexcept { return static_cast<To>(from); } /*! \brief Bit cast emulation chosen if types are move relocating or trivally copyable, have identical size, and are union castable. Constexpr. */ QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_bit_castable<To, From>::value // && !detail::is_static_castable<To, From>::value // && detail::is_union_castable<To, From>::value)) constexpr inline To bit_cast(const From &from, detail::union_cast_overload = {}) noexcept { return detail::bit_cast_union<To, From>{from}.target; } /*! \brief Bit cast emulation chosen if an array of types which are move relocating or trivally copyable, and have identical size. NOT constexpr. */ QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_bit_castable<To, From>::value // && !detail::is_static_castable<To, From>::value // && !detail::is_union_castable<To, From>::value)) inline To bit_cast(const From &from, detail::memmove_overload = {}) noexcept { detail::bit_cast_union<To, From> ret; memmove(&ret.source, &from, sizeof(ret.source)); return ret.target; } #endif } // namespace bit_cast QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/declval.hpp
/* std::declval without #include <utility> (C) 2021 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Nov 2021 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_DECLVAL_HPP #define QUICKCPPLIB_DECLVAL_HPP #include "config.hpp" #include <cstdlib> QUICKCPPLIB_NAMESPACE_BEGIN namespace detail { template<class T, class U = T&&> U declval_selector(int); template<class T> T declval_selector(long); template<class T, class U> struct declval_issame { static constexpr bool value = false; }; template<class T> struct declval_issame<T, T> { static constexpr bool value = true; }; } //! \brief `std::declval` without `<utility>` template<class T> auto declval() noexcept -> decltype(detail::declval_selector<T>(0)) { static_assert(!detail::declval_issame<T, T>::value, "declval() must not be instanced!"); abort(); } QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/detach_cast.hpp
/* C++ 23? detach and attach cast emulation. (C) 2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: May 2019 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_DETACH_CAST_HPP #define QUICKCPPLIB_DETACH_CAST_HPP #include "bit_cast.hpp" #include "byte.hpp" #include "span.hpp" #include "type_traits.hpp" #include <cstring> // for memcpy #include <type_traits> QUICKCPPLIB_NAMESPACE_BEGIN namespace detach_cast { using QUICKCPPLIB_NAMESPACE::byte::to_byte; using QUICKCPPLIB_NAMESPACE::bit_cast::bit_cast; using QUICKCPPLIB_NAMESPACE::byte::byte; //! Namespace for user specialised traits namespace traits { /*! \brief Specialise to true if you want to enable the reinterpret cast based implementation of `detach_cast()` for some type `T`. This introduces undefined behaviour in C++ 20. */ template <class T> struct enable_reinterpret_detach_cast : public std::false_type { }; /*! \brief Specialise to true if you want to enable the reinterpret cast based implementation of `attach_cast()` for some type `T`. This introduces undefined behaviour in C++ 20. */ template <class T> struct enable_reinterpret_attach_cast : public std::false_type { }; } // namespace traits namespace detail { QUICKCPPLIB_TEMPLATE(class To, class From) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TEXPR(QUICKCPPLIB_NAMESPACE::bit_cast::bit_cast<To, From>(std::declval<From>()))) inline constexpr bool _is_bit_cast_valid(int) { return true; }; template <class To, class From> // inline constexpr bool _is_bit_cast_valid(...) { return false; }; template <class To, class From> // inline constexpr bool is_bit_cast_valid() { return _is_bit_cast_valid<To, From>(5); }; template <class T> struct byte_array_wrapper { byte value[sizeof(T)]; }; struct bit_castable_overload { }; struct reinterpret_cast_overload { }; } // namespace detail //! \brief A reference to a byte array sized the same as `T` template <class T> using byte_array_reference = byte (&)[sizeof(T)]; //! \brief A const reference to a byte array sized the same as `const T` template <class T> using const_byte_array_reference = const byte (&)[sizeof(T)]; /*! \brief Detaches a live object into its detached byte representation, ending the lifetime of the input object, and beginning the lifetime of an array of byte sized exactly the size of the input object at the same memory location, which is returned. All references to the input object become INVALID. Any use of the input object after detachment has occurred is illegal! Implementation notes: If the input type is bit castable, bit casting is used to implement detachment using defined behaviour in C++ 20. Otherwise `traits::enable_reinterpret_detach_cast<T>` is used to determine whether to implement detachment using undefined behaviour by reinterpret casting. */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(!detail::is_bit_cast_valid<detail::byte_array_wrapper<T>, T>() // && !traits::enable_reinterpret_detach_cast<typename std::decay<T>::type>::value)) QUICKCPPLIB_NODISCARD constexpr inline byte_array_reference<T> detach_cast(const T &, ...) noexcept { // static_assert(!std::is_same<T, T>::value, "In C++ 20, detach_cast(T) is defined behaviour only for types which are bit castable. " // "Set traits::enable_reinterpret_detach_cast<T> for specific types if you don't mind undefined behaviour."); } /*! \brief Reattaches a previously detached object, beginning the lifetime of the output object, and ending the lifetime of the input array of byte. All references to the input byte array become INVALID. Any use of the input array after attachment has occurred is illegal! Implementation notes: If the output type is bit castable, bit casting is used to implement attachment using defined behaviour in C++ 20. Otherwise `traits::enable_reinterpret_attach_cast<T>` is used to determine whether to implement attachment using undefined behaviour by reinterpret casting. */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(!detail::is_bit_cast_valid<T, detail::byte_array_wrapper<T>>() // && !traits::enable_reinterpret_attach_cast<typename std::decay<T>::type>::value)) QUICKCPPLIB_NODISCARD constexpr inline T &attach_cast(const_byte_array_reference<T> &, ...) noexcept { // static_assert(!std::is_same<T, T>::value, "In C++ 20, attach_cast(T) is defined behaviour only for types which are bit castable. " // "Set traits::enable_reinterpret_attach_cast<T> for specific types if you don't mind undefined behaviour."); } /*! \brief Detaches a non-const bit-castable object into its detached non-const byte representation, ending the lifetime of the input object. Defined behaviour in C++ 20 (though only the clang compiler currently reliably does not copy the byte array twice. GCC avoids the memory copy for small objects, MSVC always copies the byte array twice). */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_bit_cast_valid<detail::byte_array_wrapper<T>, T>() // && !traits::enable_reinterpret_detach_cast<typename std::decay<T>::type>::value)) QUICKCPPLIB_NODISCARD constexpr inline byte_array_reference<T> detach_cast(T &v, detail::bit_castable_overload = {}) noexcept { // Bit cast and copy the input object into a stack allocated byte array. This // is defined behaviour for trivially copyable types. auto buffer(bit_cast<detail::byte_array_wrapper<T>>(v)); // Cast input reference to output reference. Using the cast reference is defined // behaviour for a few special functions e.g. memcpy() auto &ret = reinterpret_cast<byte_array_reference<T>>(v); // Copy the detached byte representation back over the input storage. This ends // the lifetime of the input object, which is defined behaviour due to it being // trivially copyable. The compiler now knows that the output reference does not // alias the same object given by the input reference. memcpy(&ret, buffer.value, sizeof(T)); // Return a reference to the byte array representing the detached object. return ret; } /*! \brief Detaches a const bit-castable object into its detached const byte representation, ending the lifetime of the input object. Defined behaviour in C++ 20 (though only the clang compiler currently reliably does not copy the byte array twice. GCC avoids the memory copy for small objects, MSVC always copies the byte array twice). */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_bit_cast_valid<const detail::byte_array_wrapper<T>, const T>() // && !traits::enable_reinterpret_detach_cast<typename std::decay<T>::type>::value)) QUICKCPPLIB_NODISCARD constexpr inline const_byte_array_reference<T> detach_cast(const T &v, detail::bit_castable_overload = {}) noexcept { const auto buffer(bit_cast<const detail::byte_array_wrapper<T>>(v)); auto &ret = const_cast<byte_array_reference<T>>(reinterpret_cast<const_byte_array_reference<T>>(v)); memcpy(&ret, buffer.value, sizeof(T)); return ret; } /*! \brief Attaches a non-const bit-castable object from its detached non-const byte representation, ending the lifetime of the input array. Defined behaviour in C++ 20 (though only the clang compiler currently reliably does not copy the byte array twice. GCC avoids the memory copy for small objects, MSVC always copies the byte array twice). */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_bit_cast_valid<T, detail::byte_array_wrapper<T>>() // && !traits::enable_reinterpret_attach_cast<typename std::decay<T>::type>::value // && !std::is_const<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline T &attach_cast(byte_array_reference<T> v, detail::bit_castable_overload = {}) noexcept { // Bit cast and copy the input byte array into a stack allocated object. This // is defined behaviour for trivially copyable types. T temp(bit_cast<T>(v)); // Cast input reference to output reference. Using the cast reference is defined // behaviour for a few special functions e.g. memcpy() T &ret = reinterpret_cast<T &>(v); // Trivially copyable types can be memcpy()ied, this begins lifetime in the destination memcpy(&ret, &temp, sizeof(T)); // Return a reference to the new object. return ret; } /*! \brief Attaches a const bit-castable object from its detached const byte representation, ending the lifetime of the input array. Defined behaviour in C++ 20 (though only the clang compiler currently reliably does not copy the byte array twice. GCC avoids the memory copy for small objects, MSVC always copies the byte array twice). */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_bit_cast_valid<T, const detail::byte_array_wrapper<T>>() // && !traits::enable_reinterpret_attach_cast<typename std::decay<T>::type>::value // && std::is_const<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline const T &attach_cast(const_byte_array_reference<T> v, detail::bit_castable_overload = {}) noexcept { using nonconst = typename std::remove_const<T>::type; T temp(bit_cast<nonconst>(v)); nonconst &ret = const_cast<nonconst &>(reinterpret_cast<T &>(v)); memcpy(&ret, &temp, sizeof(T)); return ret; } /*! \brief Reinterpret casts a non-const object reference into a non-const byte representation. Pure undefined behaviour. Available only if `traits::enable_reinterpret_detach_cast<T>` is true for the type. */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(!detail::is_bit_cast_valid<detail::byte_array_wrapper<T>, T>() // && traits::enable_reinterpret_detach_cast<typename std::decay<T>::type>::value)) QUICKCPPLIB_NODISCARD constexpr inline byte_array_reference<T> detach_cast(T &v, detail::reinterpret_cast_overload = {}) noexcept { return reinterpret_cast<byte_array_reference<T>>(v); } /*! \brief Reinterpret casts a const object reference into a const byte representation. Pure undefined behaviour. Available only if `traits::enable_reinterpret_detach_cast<T>` is true for the type. */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(!detail::is_bit_cast_valid<const detail::byte_array_wrapper<T>, const T>() // && traits::enable_reinterpret_detach_cast<typename std::decay<T>::type>::value)) QUICKCPPLIB_NODISCARD constexpr inline const_byte_array_reference<T> detach_cast(const T &v, detail::reinterpret_cast_overload = {}) noexcept { return reinterpret_cast<const_byte_array_reference<T>>(v); } /*! \brief Reinterpret casts a const byte representation into a const object. Pure undefined behaviour. Available only if `traits::enable_reinterpret_attach_cast<T>` is true for the type. */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(!detail::is_bit_cast_valid<T, detail::byte_array_wrapper<T>>() // && traits::enable_reinterpret_attach_cast<typename std::decay<T>::type>::value // && !std::is_const<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline T &attach_cast(byte_array_reference<T> v, detail::reinterpret_cast_overload = {}) noexcept { return reinterpret_cast<T &>(v); } /*! \brief Reinterpret casts a non-const byte representation into a non-const object. Pure undefined behaviour. Available only if `traits::enable_reinterpret_attach_cast<T>` is true for the type. */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(!detail::is_bit_cast_valid<const T, const detail::byte_array_wrapper<T>>() // && traits::enable_reinterpret_attach_cast<typename std::decay<T>::type>::value // && std::is_const<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline T &attach_cast(const_byte_array_reference<T> v, detail::reinterpret_cast_overload = {}) noexcept { return reinterpret_cast<T &>(v); } } // namespace detach_cast QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/byte.hpp
/* byte support (C) 2018 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Apr 2018 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_BYTE_HPP #define QUICKCPPLIB_BYTE_HPP #include "config.hpp" #ifndef QUICKCPPLIB_USE_STD_BYTE #if _HAS_CXX17 || __cplusplus >= 201700 #define QUICKCPPLIB_USE_STD_BYTE 1 #else #define QUICKCPPLIB_USE_STD_BYTE 0 #endif #endif #if QUICKCPPLIB_USE_STD_BYTE #include <cstddef> QUICKCPPLIB_NAMESPACE_BEGIN namespace byte { using std::byte; template <class IntegerType> inline constexpr byte to_byte(IntegerType v) noexcept { return static_cast<byte>(v); } } QUICKCPPLIB_NAMESPACE_END #else #include "byte/include/nonstd/byte.hpp" QUICKCPPLIB_NAMESPACE_BEGIN namespace byte { using nonstd::byte; using nonstd::to_byte; } QUICKCPPLIB_NAMESPACE_END #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/function_ptr.hpp
/* Function pointer support (C) 2019 Niall Douglas <http://www.nedproductions.biz/> (4 commits) File Created: June 2019 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_FUNCTION_PTR_HPP #define QUICKCPPLIB_FUNCTION_PTR_HPP #include "config.hpp" #include <cassert> #include <cstdint> #include <cstdlib> #include <type_traits> QUICKCPPLIB_NAMESPACE_BEGIN //! \brief The namespace for the function pointer type namespace function_ptr { static constexpr size_t default_callable_storage_bytes = 32 - sizeof(uintptr_t); /*! \brief A move only lightweight `std::function` alternative, with configurable small object optimisation. Requirements for small object optimisation: 1. `U` must be nothrow move constructible. 2. Default of `sizeof(U) + sizeof(vptr) + sizeof(void *) <= 32`, but is configurable by the make functions. */ template <class F, size_t callable_storage_bytes = default_callable_storage_bytes> class function_ptr; template <class R, class... Args, size_t callable_storage_bytes> class function_ptr<R(Args...), callable_storage_bytes> { #if !defined(__clang__) || __clang_major__ >= 5 template <class ErasedPrototype_, class Callable_, size_t callable_storage_bytes_, class... CallableConstructionArgs_> friend constexpr inline function_ptr<ErasedPrototype_, callable_storage_bytes_> emplace_function_ptr(CallableConstructionArgs_ &&... args); #endif template <class ErasedPrototype_, class Callable_, class... CallableConstructionArgs_> friend constexpr inline function_ptr<ErasedPrototype_, (sizeof(Callable_) + sizeof(void *) + sizeof(void *) - 1) & ~(sizeof(void *) - 1)> emplace_function_ptr_nothrow(CallableConstructionArgs_ &&... args) noexcept; struct _function_ptr_storage { _function_ptr_storage() = default; _function_ptr_storage(const _function_ptr_storage &) = delete; _function_ptr_storage(_function_ptr_storage &&) = delete; _function_ptr_storage &operator=(const _function_ptr_storage &) = delete; _function_ptr_storage &operator=(_function_ptr_storage &&) = delete; virtual ~_function_ptr_storage() = default; virtual R operator()(Args... args) = 0; virtual _function_ptr_storage *move(char *v) noexcept = 0; }; // Dynamically allocated callables template <class U> struct _function_ptr_storage_nonmoveable final : public _function_ptr_storage { U c; template <class... Args2> constexpr explicit _function_ptr_storage_nonmoveable(Args2 &&... args) : c(static_cast<Args2 &&>(args)...) { } _function_ptr_storage_nonmoveable(const _function_ptr_storage_nonmoveable &) = delete; _function_ptr_storage_nonmoveable(_function_ptr_storage_nonmoveable &&) = delete; _function_ptr_storage_nonmoveable &operator=(const _function_ptr_storage_nonmoveable &) = delete; _function_ptr_storage_nonmoveable &operator=(_function_ptr_storage_nonmoveable &&) = delete; R operator()(Args... args) override { return c(static_cast<Args &&>(args)...); } _function_ptr_storage *move(char * /*unused*/) noexcept final { abort(); } }; // In-class stored callables template <class U> struct _function_ptr_storage_moveable final : public _function_ptr_storage { struct standin_t { template <class... Args2> standin_t(Args2 &&... /*unused*/) {} R operator()(Args... /*unused*/) { return {}; } }; using type = std::conditional_t<std::is_move_constructible<U>::value, U, standin_t>; type c; template <class... Args2> constexpr explicit _function_ptr_storage_moveable(Args2 &&... args) : c(static_cast<Args2 &&>(args)...) { } _function_ptr_storage_moveable(const _function_ptr_storage_moveable &) = delete; _function_ptr_storage_moveable(_function_ptr_storage_moveable &&o) noexcept // NOLINT : c(static_cast<type &&>(o.c)) { } _function_ptr_storage_moveable &operator=(const _function_ptr_storage_moveable &) = delete; _function_ptr_storage_moveable &operator=(_function_ptr_storage_moveable &&) = delete; R operator()(Args... args) override { return c(static_cast<Args &&>(args)...); } _function_ptr_storage *move(char *v) noexcept final { return new(v) _function_ptr_storage_moveable(static_cast<_function_ptr_storage_moveable &&>(*this)); } }; // Used for sizing, and nothing else struct _empty_callable { size_t foo; R operator()(Args... /*unused*/); }; uintptr_t _ptr_{0}; char _sso[callable_storage_bytes]; public: //! \brief The type returned by the callable and our call operator using result_type = R; //! \brief The largest size of callable for which SSO will be used static constexpr size_t max_callable_size = sizeof(_sso) - sizeof(_function_ptr_storage_nonmoveable<_empty_callable>) + sizeof(_empty_callable); //! \brief True if this callable would be SSOable in this type template <class U> static constexpr bool is_ssoable = std::is_nothrow_move_constructible<typename std::decay<U>::type>::value // && (sizeof(_function_ptr_storage_nonmoveable<typename std::decay<U>::type>) <= sizeof(_sso)); //! \brief The types of pointer we can store enum _ptrtype_t { none = 0, //!< We are empty owned = 1, //!< We own our dynamically allocated callable and we will free it upon destruction ssoed = 2, //!< We store our callable internally to ourselves external = 3 //!< We use an externally supplied allocation for the callable which we do NOT free upon destruction }; #if !defined(__clang__) || __clang_major__ >= 5 private: #endif // Get the pointer, minus ptrtype_t _function_ptr_storage *_ptr() const { auto *ret = reinterpret_cast<_function_ptr_storage *>(_ptr_ & ~3); #ifdef __cpp_rtti assert(nullptr != dynamic_cast<_function_ptr_storage *>(ret)); #endif return ret; } // Used by the constructors to statically munge in the ptrtype_t bits static uintptr_t _ptr(_function_ptr_storage *p, _ptrtype_t type) { return reinterpret_cast<uintptr_t>(p) | static_cast<uintptr_t>(type); } template <class U> struct _emplace_t { void *mem{nullptr}; }; template <class U> struct _noallocate_t { }; // Non in-class constructor, emplaces callble either into supplied memory or dynamically allocated memory template <class U, class... Args2> function_ptr(_emplace_t<U> *_, Args2 &&... args) : _ptr_((_->mem != nullptr) // ? _ptr(new(_->mem) _function_ptr_storage_nonmoveable<typename std::decay<U>::type>(static_cast<Args2 &&>(args)...), external) // : _ptr(new _function_ptr_storage_nonmoveable<typename std::decay<U>::type>(static_cast<Args2 &&>(args)...), owned)) { } // In-class constructor template <class U, class... Args2> function_ptr(_noallocate_t<U> /*unused*/, Args2 &&... args) : _ptr_(_ptr(new((void *) (is_ssoable<U> ? _sso : nullptr)) _function_ptr_storage_moveable<typename std::decay<U>::type>(static_cast<Args2 &&>(args)...), ssoed)) { } // Delegate to in-class or out-of-class constructor template <class U, class... Args2> explicit function_ptr(_emplace_t<U> _, Args2 &&... args) : function_ptr(is_ssoable<U> // ? function_ptr(_noallocate_t<U>{}, static_cast<Args2 &&>(args)...) // : function_ptr(&_, static_cast<Args2 &&>(args)...)) { } public: //! \brief Default constructs to empty constexpr function_ptr() {} // NOLINT //! \brief Move constructor constexpr function_ptr(function_ptr &&o) noexcept { if(ssoed == o.ptr_type()) { _ptr_ = _ptr(o._ptr()->move(_sso), ssoed); } else { _ptr_ = o._ptr_; } o._ptr_ = 0; } //! \brief Move assigment function_ptr &operator=(function_ptr &&o) noexcept { this->~function_ptr(); new(this) function_ptr(static_cast<function_ptr &&>(o)); return *this; } //! \brief Copying prevented function_ptr(const function_ptr &) = delete; //! \brief Copying prevented function_ptr &operator=(const function_ptr &) = delete; ~function_ptr() { reset(); } //! \brief True if the ptr is not empty explicit constexpr operator bool() const noexcept { return _ptr_ != 0; } //! \brief Returns whether this ptr's callable is empty, owned, ssoed or externally managed _ptrtype_t ptr_type() const { return static_cast<_ptrtype_t>(_ptr_ & 3); } //! \brief Calls the callable, returning what the callable returns template <class... Args2> constexpr R operator()(Args2 &&... args) const { auto *r = _ptr(); return (*r)(static_cast<Args2 &&>(args)...); } //! \brief Disposes of the callable, resetting ptr to empty constexpr void reset() noexcept { if(_ptr_ != 0) { switch(ptr_type()) { case none: case external: break; case owned: delete _ptr(); break; case ssoed: _ptr()->~_function_ptr_storage(); break; } _ptr_ = 0; } } }; /*! \brief Return a `function_ptr<ErasedPrototype>` by emplacing `Callable(CallableConstructionArgs...)`. If `Callable` is nothrow move constructible and sufficiently small, avoids dynamic memory allocation. */ template <class ErasedPrototype, class Callable, size_t callable_storage_bytes = default_callable_storage_bytes, class... CallableConstructionArgs> // constexpr inline function_ptr<ErasedPrototype, callable_storage_bytes> emplace_function_ptr(CallableConstructionArgs &&... args) { return function_ptr<ErasedPrototype, callable_storage_bytes>(typename function_ptr<ErasedPrototype, callable_storage_bytes>::template _emplace_t<Callable>(), static_cast<CallableConstructionArgs &&>(args)...); } /*! \brief Return a `function_ptr<ErasedPrototype>` by emplacing `Callable(CallableConstructionArgs...)`, without dynamically allocating memory. Note that the size of function ptr returned will be exactly the amount to store the callable, which may not be the default size of `function_ptr<ErasedPrototype>`. */ template <class ErasedPrototype, class Callable, class... CallableConstructionArgs> // constexpr inline function_ptr<ErasedPrototype, (sizeof(Callable) + sizeof(void *) + sizeof(void *) - 1) & ~(sizeof(void *) - 1)> emplace_function_ptr_nothrow(CallableConstructionArgs &&... args) noexcept { using type = function_ptr<ErasedPrototype, (sizeof(Callable) + sizeof(void *) + sizeof(void *) - 1) & ~(sizeof(void *) - 1)>; static_assert(type::template is_ssoable<Callable>, "The specified callable is not SSOable (probably lacks nothrow move construction)"); return type(typename type::template _emplace_t<Callable>(), static_cast<CallableConstructionArgs &&>(args)...); } /*! \brief Return a `function_ptr<ErasedPrototype>` by from an input `Callable`. If `Callable` is nothrow move constructible and sufficiently small, avoids dynamic memory allocation. */ template <class ErasedPrototype, class Callable, size_t callable_storage_bytes = default_callable_storage_bytes> // constexpr inline function_ptr<ErasedPrototype, callable_storage_bytes> make_function_ptr(Callable &&f) { return emplace_function_ptr<ErasedPrototype, std::decay_t<Callable>, callable_storage_bytes>(static_cast<Callable &&>(f)); } /*! \brief Return a `function_ptr<ErasedPrototype>` by from an input `Callable`, without dynamically allocating memory. Note that the size of function ptr returned will be exactly the amount to store the callable, which may not be the default size of `function_ptr<ErasedPrototype>`. */ template <class ErasedPrototype, class Callable> // constexpr inline auto make_function_ptr_nothrow(Callable &&f) noexcept { return emplace_function_ptr_nothrow<ErasedPrototype, std::decay_t<Callable>>(static_cast<Callable &&>(f)); } } // namespace function_ptr QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/memory_resource.hpp
/* PMR support (C) 2018 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Nov 2018 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_MEMORY_RESOURCE_HPP #define QUICKCPPLIB_MEMORY_RESOURCE_HPP #include "config.hpp" #ifdef QUICKCPPLIB_USE_STD_MEMORY_RESOURCE #include <memory_resource> QUICKCPPLIB_NAMESPACE_BEGIN namespace pmr = std::pmr; QUICKCPPLIB_NAMESPACE_END #elif(_HAS_CXX17 || __cplusplus >= 201700) && __has_include(<memory_resource>) #include <memory_resource> QUICKCPPLIB_NAMESPACE_BEGIN namespace pmr = std::pmr; QUICKCPPLIB_NAMESPACE_END #else #include <cstddef> #include <memory> QUICKCPPLIB_NAMESPACE_BEGIN namespace pmr { //! memory_resource emulation class memory_resource { friend inline bool operator==(const memory_resource &a, const memory_resource &b) noexcept; friend inline bool operator!=(const memory_resource &a, const memory_resource &b) noexcept; virtual void *do_allocate(size_t bytes, size_t alignment) = 0; virtual void do_deallocate(void *p, size_t bytes, size_t alignment) = 0; virtual bool do_is_equal(const memory_resource &other) const noexcept = 0; public: memory_resource() = default; memory_resource(const memory_resource &) = default; memory_resource &operator=(const memory_resource &) = default; virtual ~memory_resource() {} QUICKCPPLIB_NODISCARD void *allocate(size_t bytes, size_t alignment = alignof(std::max_align_t)) { return do_allocate(bytes, alignment); } void deallocate(void *p, size_t bytes, size_t alignment = alignof(std::max_align_t)) { return do_deallocate(p, bytes, alignment); } }; inline bool operator==(const memory_resource &a, const memory_resource &b) noexcept { return a.do_is_equal(b); } inline bool operator!=(const memory_resource &a, const memory_resource &b) noexcept { return !a.do_is_equal(b); } //! A just barely good enough C++ 14 emulation of monotonic_buffer_resource class monotonic_buffer_resource : public memory_resource { char *_ptr{nullptr}, *_end{nullptr}; virtual void *do_allocate(size_t bytes, size_t alignment) override { if(_ptr >= _end) { throw std::bad_alloc(); } _ptr = (char *) (((uintptr_t) _ptr + alignment - 1) & ~(alignment - 1)); void *ret = (void *) _ptr; _ptr += bytes; if(_ptr > _end) { throw std::bad_alloc(); } return ret; } virtual void do_deallocate(void *p, size_t bytes, size_t alignment) override { (void) p; (void) bytes; (void) alignment; } virtual bool do_is_equal(const memory_resource &other) const noexcept override { return this == &other; } public: monotonic_buffer_resource() = default; monotonic_buffer_resource(const monotonic_buffer_resource &) = delete; monotonic_buffer_resource(void *buffer, size_t length) : _ptr((char *) buffer) , _end((char *) buffer + length) { } monotonic_buffer_resource &operator=(const monotonic_buffer_resource &) = delete; }; //! The world's worst C++ 14 emulation of polymorphic_allocator, which maps onto std::allocator template <class T> class polymorphic_allocator { template <class U> friend class polymorphic_allocator; memory_resource *_r{nullptr}; public: using value_type = T; polymorphic_allocator() = default; polymorphic_allocator(memory_resource *r) : _r(r) { } polymorphic_allocator(const polymorphic_allocator &o) : _r(o._r) { } template <class U> polymorphic_allocator(const polymorphic_allocator<U> &o) noexcept : _r(o._r) { } polymorphic_allocator &operator=(const polymorphic_allocator &) = delete; memory_resource *resource() const { return _r; } QUICKCPPLIB_NODISCARD T *allocate(size_t n) { return static_cast<T *>(resource()->allocate(n * sizeof(T), alignof(T))); } void deallocate(T *p, size_t n) { resource()->deallocate(p, n * sizeof(T), alignof(T)); } template <class U, class... Args> void construct(U *p, Args &&...args) { new(p) U(static_cast<Args &&>(args)...); } template <class U> void destroy(U *p) { p->~U(); } }; template <class T1, class T2> inline bool operator==(const polymorphic_allocator<T1> &a, const polymorphic_allocator<T2> &b) noexcept { return *a.resource() == *b.resource(); } template <class T1, class T2> inline bool operator!=(const polymorphic_allocator<T1> &a, const polymorphic_allocator<T2> &b) noexcept { return *a.resource() != *b.resource(); } } // namespace pmr QUICKCPPLIB_NAMESPACE_END #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/tribool.hpp
/* A C++ 11 tribool (C) 2015-2017 Niall Douglas <http://www.nedproductions.biz/> (7 commits) File Created: June 2015 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_TRIBOOL_H #define QUICKCPPLIB_TRIBOOL_H /*! \file tribool.hpp \brief Provides a constexpr C++ 11 tribool */ #include "config.hpp" #include <istream> QUICKCPPLIB_NAMESPACE_BEGIN namespace tribool { /*! \defgroup tribool Constexpr C++ 11 tribool This tries to be mostly compatible with Boost.Tribool, except it's written in C++ 11 and is 100% constexpr throughout by being a strongly typed enum. Note that `other` state is aliased to `indeterminate` for Boost.Tribool compatibility. It is also aliased to unknown. Unlike Boost.Tribool this deliberately does not provide automatic conversion to bool. It was always questionable if code coped well with `operator!` != `!operator bool` anyway. Use the free functions true_(), false_(), other(), indeterminate() and unknown() to test the contents of this tribool. For sorting, false < unknown < true. Same for max/min. STL functions operators << and >> for iostream are defined. */ //! \brief A constexpr C++ 11 tribool \ingroup tribool enum class tribool : signed char { false_ = -1, //!< False true_ = 1, //!< True other = 0, //!< Other/Indeterminate/Unknown indeterminate = 0, //!< Other/Indeterminate/Unknown unknown = 0 //!< Other/Indeterminate/Unknown }; //! \brief Explicit construction from some signed integer. <0 false, >0 true, 0 is other \ingroup tribool constexpr inline tribool make_tribool(int v) noexcept { return v > 0 ? tribool::true_ : v < 0 ? tribool::false_ : tribool::other; } //! \brief If tribool is true return false, if tribool is false return true, else return other \ingroup tribool constexpr inline tribool operator~(tribool v) noexcept { return static_cast<tribool>(-static_cast<signed char>(v)); } //! \brief If a is true and b is true, return true, if either is false return false, else return other \ingroup tribool constexpr inline tribool operator&(tribool a, tribool b) noexcept { return (a == tribool::true_ && b == tribool::true_) ? tribool::true_ : (a == tribool::false_ || b == tribool::false_) ? tribool::false_ : tribool::other; } //! \brief If a is true or b is true, return true, if either is other return other, else return false \ingroup tribool constexpr inline tribool operator|(tribool a, tribool b) noexcept { return (a == tribool::true_ || b == tribool::true_) ? tribool::true_ : (a == tribool::other || b == tribool::other) ? tribool::other : tribool::false_; } // //! \brief If tribool is false return true, else return false \ingroup tribool // constexpr inline bool operator !(tribool v) noexcept { return a==tribool::false_; } //! \brief If a is true and b is true, return true \ingroup tribool constexpr inline bool operator&&(tribool a, tribool b) noexcept { return (a == tribool::true_ && b == tribool::true_); } //! \brief If a is true or b is true, return true \ingroup tribool constexpr inline bool operator||(tribool a, tribool b) noexcept { return (a == tribool::true_ || b == tribool::true_); } //! \brief Return true if tribool is true. \ingroup tribool constexpr inline bool true_(tribool a) noexcept { return a == tribool::true_; } //! \brief Return true if tribool is true. \ingroup tribool constexpr inline bool false_(tribool a) noexcept { return a == tribool::false_; } //! \brief Return true if tribool is other/indeterminate/unknown. \ingroup tribool constexpr inline bool other(tribool a) noexcept { return a == tribool::indeterminate; } //! \brief Return true if tribool is other/indeterminate/unknown. \ingroup tribool constexpr inline bool indeterminate(tribool a) noexcept { return a == tribool::indeterminate; } //! \brief Return true if tribool is other/indeterminate/unknown. \ingroup tribool constexpr inline bool unknown(tribool a) noexcept { return a == tribool::indeterminate; } } QUICKCPPLIB_NAMESPACE_END namespace std { inline istream &operator>>(istream &s, QUICKCPPLIB_NAMESPACE::tribool::tribool &a) { char c; s >> c; a = (c == '1') ? QUICKCPPLIB_NAMESPACE::tribool::tribool::true_ : (c == '0') ? QUICKCPPLIB_NAMESPACE::tribool::tribool::false_ : QUICKCPPLIB_NAMESPACE::tribool::tribool::other; return s; } inline ostream &operator<<(ostream &s, QUICKCPPLIB_NAMESPACE::tribool::tribool a) { char c = (a == QUICKCPPLIB_NAMESPACE::tribool::tribool::true_) ? '1' : (a == QUICKCPPLIB_NAMESPACE::tribool::tribool::false_) ? '0' : '?'; return s << c; } } #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/start_lifetime_as.hpp
/* bless support (C) 2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Oct 2019 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_START_LIFETIME_AS_HPP #define QUICKCPPLIB_START_LIFETIME_AS_HPP #include "config.hpp" #include <memory> // for start_lifetime_as #include <new> // for launder #include <type_traits> QUICKCPPLIB_NAMESPACE_BEGIN namespace start_lifetime_as { namespace detail { using namespace std; template <class T> constexpr inline T *launder(T *p, ...) noexcept { return p; } template <typename T> inline T *start_lifetime_as(void *p, ...) noexcept { return reinterpret_cast<T *>(p); } template <typename T> inline const T *start_lifetime_as(const void *p, ...) noexcept { return reinterpret_cast<const T *>(p); } template <typename T> inline T *start_lifetime_as_array(void *p, size_t, ...) noexcept { return reinterpret_cast<T *>(p); } template <typename T> inline const T *start_lifetime_as_array(const void *p, size_t, ...) noexcept { return reinterpret_cast<const T *>(p); } template <class T> constexpr inline T *_launder(T *p) noexcept { return launder<T>(p); } template <class T> struct _start_lifetime_as { constexpr T *operator()(void *p) const noexcept { return start_lifetime_as<T>(p); } constexpr const T *operator()(const void *p) const noexcept { return start_lifetime_as<T>(p); } constexpr T *operator()(void *p, size_t n) const noexcept { return start_lifetime_as_array<T>(p, n); } constexpr const T *operator()(const void *p, size_t n) const noexcept { return start_lifetime_as_array<T>(p, n); } }; #if __cplusplus >= 202600L template <class T> using _is_implicit_lifetime = std::is_implicit_lifetime<T>; #else /* Note that this is broken in C++'s without the actual type trait as it's not possible to fully correctly implement this. To be specific, aggregates with user provided destructors are reported to have implicit lifetime, when they do not. Also, the trait should be true for types with trivial constructors even if they're not available to the public, which is undetectable in current C++. */ template <class T> struct _is_implicit_lifetime { using _type = typename std::remove_cv<T>::type; static constexpr bool value = std::is_scalar<_type>::value // || std::is_array<_type>::value // #if __cplusplus >= 201700LL || _HAS_CXX17 || std::is_aggregate<_type>::value // #endif || (std::is_trivially_destructible<_type>::value // && (std::is_trivially_default_constructible<_type>::value // || std::is_trivially_copy_constructible<_type>::value // || std::is_trivially_move_constructible<_type>::value)); }; #endif } // namespace detail //! `std::launder<T>` from C++ 17, or an emulation QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(!std::is_function<T>::value), QUICKCPPLIB_TPRED(!std::is_void<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline T *launder(T *p) noexcept { return detail::_launder(p); } //! `std::start_lifetime_as<T>` from C++ 23, or an emulation QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::_is_implicit_lifetime<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline auto *start_lifetime_as(void *p) noexcept { return detail::_start_lifetime_as<T>()(p); } //! `std::start_lifetime_as<T>` from C++ 23, or an emulation QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::_is_implicit_lifetime<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline auto *start_lifetime_as(const void *p) noexcept { return detail::_start_lifetime_as<T>()(p); } //! `std::start_lifetime_as_array<T>` from C++ 23, or an emulation QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::_is_implicit_lifetime<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline auto *start_lifetime_as_array(void *p, size_t n) noexcept { return detail::_start_lifetime_as<T>()(p, n); } //! `std::start_lifetime_as_array<T>` from C++ 23, or an emulation QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::_is_implicit_lifetime<T>::value)) QUICKCPPLIB_NODISCARD constexpr inline auto *start_lifetime_as_array(const void *p, size_t n) noexcept { return detail::_start_lifetime_as<T>()(p, n); } } // namespace start_lifetime_as QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/uint128.hpp
/* 128 bit integer support (C) 2016-2017 Niall Douglas <http://www.nedproductions.biz/> (4 commits) File Created: Sept 2016 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_UINT128_HPP #define QUICKCPPLIB_UINT128_HPP #include "config.hpp" #include <cstdint> #include <stdexcept> // for std::domain_error #if defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2) #include <emmintrin.h> // for __m128i on VS2017 #endif QUICKCPPLIB_NAMESPACE_BEGIN namespace integers128 { /*! \union uint128 \brief An unsigned 128 bit value */ union alignas(16) uint128 { struct empty_type { } _empty; uint8_t as_bytes[16]; uint16_t as_shorts[8]; uint32_t as_ints[4]; uint64_t as_longlongs[2]; // Strongly hint to the compiler what to do here #if defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2) __m128i as_m128i; #endif #if defined(__GNUC__) || defined(__clang__) typedef unsigned uint32_4_t __attribute__((vector_size(16))); uint32_4_t as_uint32_4; #endif //! Default constructor, no bits set constexpr uint128() noexcept : _empty() {} //! Construct from a number constexpr uint128(uint64_t v) noexcept : as_longlongs{v, 0} {} //! Construct from input constexpr uint128(uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3, uint8_t v4, uint8_t v5, uint8_t v6, uint8_t v7, uint8_t v8, uint8_t v9, uint8_t v10, uint8_t v11, uint8_t v12, uint8_t v13, uint8_t v14, uint8_t v15) noexcept : as_bytes{v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15} {} //! Construct from input constexpr uint128(uint16_t v0, uint16_t v1, uint16_t v2, uint16_t v3, uint16_t v4, uint16_t v5, uint16_t v6, uint16_t v7) noexcept : as_shorts{v0, v1, v2, v3, v4, v5, v6, v7} {} //! Construct from input constexpr uint128(uint32_t v0, uint32_t v1, uint32_t v2, uint32_t v3) noexcept : as_ints{v0, v1, v2, v3} {} //! Construct from input constexpr uint128(uint64_t v0, uint64_t v1) noexcept : as_longlongs{v0, v1} {} //! Return the bottom unsigned short bits of the number explicit operator unsigned short() const noexcept { return static_cast<unsigned short>(as_longlongs[0]); } //! Return the bottom unsigned bits of the number explicit operator unsigned() const noexcept { return static_cast<unsigned>(as_longlongs[0]); } //! Return the bottom long bits of the number explicit operator unsigned long() const noexcept { return static_cast<unsigned long>(as_longlongs[0]); } //! Return the bottom long long bits of the number explicit operator unsigned long long() const noexcept { return static_cast<unsigned long long>(as_longlongs[0]); } private: static const uint128 &_allbitszero() { static uint128 v(0); return v; } public: explicit operator bool() const noexcept { return (*this) != _allbitszero(); } bool operator!() const noexcept { return (*this) == _allbitszero(); } // uint128 operator~() const noexcept; // uint128 operator++() noexcept; // uint128 operator++(int) noexcept; // uint128 operator--() noexcept; // uint128 operator--(int) noexcept; uint128 operator+(const uint128 &v) const noexcept { uint128 t(*this); t += v; return t; } uint128 operator+=(const uint128 &v) noexcept { // Produces wrong result on GCC #if 0 // defined(__GNUC__) || defined(__clang__) as_uint32_4 += v.as_uint32_4; return *this; #endif auto o = as_longlongs[0]; as_longlongs[0] += v.as_longlongs[0]; as_longlongs[1] += v.as_longlongs[1]; as_longlongs[1] += (as_longlongs[0] < o); return *this; } uint128 operator-(const uint128 &v) const noexcept { uint128 t(*this); t -= v; return t; } uint128 operator-=(const uint128 &v) noexcept { // Produces wrong result on GCC #if 0 // defined(__GNUC__) || defined(__clang__) as_uint32_4 += v.as_uint32_4; return *this; #endif auto o = as_longlongs[0]; as_longlongs[0] -= v.as_longlongs[0]; as_longlongs[1] -= v.as_longlongs[1]; as_longlongs[1] -= (as_longlongs[0] > o); return *this; } // uint128 operator*(uint128 v) const noexcept; // uint128 operator*=(uint128 v) noexcept; // uint128 operator/(uint128 v) const noexcept; // uint128 operator/=(uint128 v) noexcept; uint128 operator%(const uint128 &v) const noexcept { uint128 t(*this); t %= v; return t; } uint128 operator%=(const uint128 &b) { if(!b) throw std::domain_error("divide by zero"); // Looks like this fails with SIGFPE on both GCC and clang no matter what #if 0 // defined(__GNUC__) || defined(__clang__) as_uint32_4 %= b.as_uint32_4; return *this; #endif uint128 x(b), y(*this >> 1); while(x <= y) { x <<= 1; } while(*this >= b) { if(*this >= x) *this -= x; x >>= 1; } return *this; } #if 0 // actually slower than the 128 bit version, believe it or not. Modern optimisers are amazing! uint32_t operator%(uint32_t b) { if(!b) throw std::domain_error("divide by zero"); // Looks like this fails with SIGFPE on both GCC and clang no matter what #if 0 // defined(__GNUC__) || defined(__clang__) as_uint32_4 %= b; return *this; #endif uint64_t result = 0; uint64_t a = (~0 % b) + 1; as_longlongs[1] %= b; while(as_longlongs[1] != 0) { if((as_longlongs[1] & 1) == 1) { result += a; if(result >= b) { result -= b; } } a <<= 1; if(a >= b) { a -= b; } as_longlongs[1] >>= 1; } if(as_longlongs[0] > b) { as_longlongs[0] -= b; } return (as_longlongs[0] + result) % b; } #endif // uint128 operator&(uint128 v) const noexcept; // uint128 operator&=(uint128 v) noexcept; // uint128 operator|(uint128 v) const noexcept; // uint128 operator|=(uint128 v) noexcept; // uint128 operator^(uint128 v) const noexcept; // uint128 operator^=(uint128 v) noexcept; uint128 operator<<(uint8_t v) const noexcept { uint128 t(*this); t <<= v; return t; } uint128 operator<<=(uint8_t v) noexcept { #if 0 // defined(__GNUC__) || defined(__clang__) as_uint32_4 <<= v; return *this; #endif as_longlongs[1] <<= v; as_longlongs[1] |= as_longlongs[0] >> (64 - v); as_longlongs[0] <<= v; return *this; } uint128 operator>>(uint8_t v) const noexcept { uint128 t(*this); t >>= v; return t; } uint128 operator>>=(uint8_t v) noexcept { #if 0 // defined(__GNUC__) || defined(__clang__) as_uint32_4 >>= v; return *this; #endif as_longlongs[0] >>= v; as_longlongs[0] |= as_longlongs[1] << (64 - v); as_longlongs[1] >>= v; return *this; } bool operator==(const uint128 &o) const noexcept { return as_longlongs[1] == o.as_longlongs[1] && as_longlongs[0] == o.as_longlongs[0]; } bool operator!=(const uint128 &o) const noexcept { return as_longlongs[1] != o.as_longlongs[1] || as_longlongs[0] != o.as_longlongs[0]; } bool operator<(const uint128 &o) const noexcept { return as_longlongs[1] < o.as_longlongs[1] || (as_longlongs[1] == o.as_longlongs[1] && as_longlongs[0] < o.as_longlongs[0]); } bool operator<=(const uint128 &o) const noexcept { return as_longlongs[1] < o.as_longlongs[1] || (as_longlongs[1] == o.as_longlongs[1] && as_longlongs[0] <= o.as_longlongs[0]); } bool operator>(const uint128 &o) const noexcept { return as_longlongs[1] > o.as_longlongs[1] || (as_longlongs[1] == o.as_longlongs[1] && as_longlongs[0] > o.as_longlongs[0]); } bool operator>=(const uint128 &o) const noexcept { return as_longlongs[1] > o.as_longlongs[1] || (as_longlongs[1] == o.as_longlongs[1] && as_longlongs[0] >= o.as_longlongs[0]); } }; static_assert(sizeof(uint128) == 16, "uint128 is not 16 bytes long!"); static_assert(alignof(uint128) == 16, "uint128 is not aligned to 16 byte multiples!"); //! \brief Hashes a uint128 struct uint128_hasher { size_t operator()(const uint128 &v) const { return (size_t)(v.as_longlongs[0] ^ v.as_longlongs[1]); } }; } QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/in_place_detach_attach.hpp
/* C++ 23? detach and attach cast emulation. (C) 2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: May 2019 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_IN_PLACE_DETACH_ATTACH_HPP #define QUICKCPPLIB_IN_PLACE_DETACH_ATTACH_HPP #include "detach_cast.hpp" QUICKCPPLIB_NAMESPACE_BEGIN namespace in_place_attach_detach { using QUICKCPPLIB_NAMESPACE::detach_cast::attach_cast; using QUICKCPPLIB_NAMESPACE::detach_cast::detach_cast; //! Namespace for user specialised traits namespace traits { /*! \brief Specialise to true if you want to `attached<>` to do nothing when constructed from some source `T`. */ template <class T> struct disable_attached_for : public std::false_type { }; } // namespace traits namespace detail { template <class T> using byte_array_wrapper = QUICKCPPLIB_NAMESPACE::detach_cast::detail::byte_array_wrapper<T>; struct default_cast_operator_overload { }; } // namespace detail /*! \brief An ADL customisation point for the in-place detachment of an array of live `T` objects into an array of bytes representing their detached object representations. This overload is available if `detach_cast()` is available for `T`. */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TEXPR(detach_cast(std::declval<T>()))) constexpr inline auto in_place_detach(QUICKCPPLIB_NAMESPACE::span::span<T> objects, detail::default_cast_operator_overload = {}) noexcept { using byte_type = typename std::conditional<std::is_const<T>::value, const QUICKCPPLIB_NAMESPACE::byte::byte, QUICKCPPLIB_NAMESPACE::byte::byte>::type; QUICKCPPLIB_NAMESPACE::span::span<byte_type> ret; if(objects.empty()) { ret = QUICKCPPLIB_NAMESPACE::span::span<byte_type>((byte_type *) objects.data(), (byte_type *) objects.data()); return ret; } for(size_t n = 0; n < objects.size(); n++) { auto &d = detach_cast(objects[n]); if(0 == n) { ret = {d, sizeof(d)}; } else { ret = {ret.data(), ret.size() + sizeof(d)}; } } return ret; } /*! \brief An ADL customisation point for the in-place attachment of previously detached object representations, back into an array of live `T` objects. This overload is available if `attach_cast()` is available for `T`. */ QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TEXPR(attach_cast<T>(std::declval<QUICKCPPLIB_NAMESPACE::detach_cast::byte_array_reference<T>>()))) constexpr inline QUICKCPPLIB_NAMESPACE::span::span<T> in_place_attach(QUICKCPPLIB_NAMESPACE::span::span<QUICKCPPLIB_NAMESPACE::byte::byte> bytearray, detail::default_cast_operator_overload = {}) noexcept { QUICKCPPLIB_NAMESPACE::span::span<detail::byte_array_wrapper<T>> input = {(detail::byte_array_wrapper<T> *) bytearray.data(), bytearray.size() / sizeof(T)}; QUICKCPPLIB_NAMESPACE::span::span<T> ret; if(bytearray.empty()) { ret = QUICKCPPLIB_NAMESPACE::span::span<T>((T *) bytearray.data(), (T *) bytearray.data()); return ret; } for(size_t n = 0; n < input.size(); n++) { T &a = attach_cast<T>(input[n].value); if(0 == n) { ret = {&a, 1}; } else { ret = {ret.data(), ret.size() + 1}; } } return ret; } struct adopt_t { }; constexpr adopt_t adopt{}; /*! \brief An RAII refinement of `span<T>` for automatically calling `in_place_attach()` and `in_place_detach()` on an input array of `T`. Move-only, detaches only on final object destruction. */ template <class T> class attached : protected QUICKCPPLIB_NAMESPACE::span::span<T> { using _base = QUICKCPPLIB_NAMESPACE::span::span<T>; bool _disabled{false}; public: //! The index type //using index_type = typename _base::index_type; //! The element type using element_type = typename _base::element_type; //! The value type using value_type = typename _base::value_type; //! The reference type using reference = typename _base::reference; //! The pointer type using pointer = typename _base::pointer; //! The const reference type using const_reference = typename _base::const_reference; //! The const pointer type using const_pointer = typename _base::const_pointer; //! The iterator type using iterator = typename _base::iterator; //! The const iterator type //using const_iterator = typename _base::const_iterator; //! The reverse iterator type using reverse_iterator = typename _base::reverse_iterator; //! The const reverse iterator type //using const_reverse_iterator = typename _base::const_reverse_iterator; //! The difference type using difference_type = typename _base::difference_type; public: //! Default constructor constexpr attached() {} // NOLINT attached(const attached &) = delete; //! Move constructs the instance, leaving the source empty. constexpr attached(attached &&o) noexcept : _base(std::move(o)), _disabled{o._disabled} { static_cast<_base &>(o) = {}; } attached &operator=(const attached &) = delete; constexpr attached &operator=(attached &&o) noexcept { this->~attached(); new(this) attached(std::move(o)); return *this; } //! Detaches the array of `T`, if not empty ~attached() { if(!this->empty() && !_disabled) { in_place_detach(as_span()); } } //! Implicitly construct from anything for which `in_place_attach<T>()` is valid. QUICKCPPLIB_TEMPLATE(class U) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TEXPR(in_place_attach<T>(std::declval<U>()))) constexpr attached(U &&v) : _base(in_place_attach<T>(static_cast<U &&>(v))), _disabled(traits::disable_attached_for<std::decay_t<U>>::value) { } //! Explicitly construct from a span of already attached objects explicit constexpr attached(adopt_t /*unused*/, _base v) : _base(v) { } //! Returns the attached region as a plain span of `T` constexpr _base as_span() const noexcept { return *this; } using _base::empty; using _base::first; using _base::last; using _base::size; using _base::size_bytes; //using _base::ssize; using _base::subspan; using _base::operator[]; //using _base::operator(); //using _base::at; using _base::begin; //using _base::cbegin; //using _base::cend; //using _base::crbegin; //using _base::crend; using _base::data; using _base::end; using _base::rbegin; using _base::rend; //using _base::swap; }; } // namespace in_place_attach_detach QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/spinlock.hpp
/* Provides yet another spinlock (C) 2013-2017 Niall Douglas <http://www.nedproductions.biz/> (14 commits) File Created: Sept 2013 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /*! \file spinlock.hpp \brief Provides a Lockable policy driven spinlock */ #ifndef QUICKCPPLIB_SPINLOCK_H #define QUICKCPPLIB_SPINLOCK_H #include "config.hpp" #include <atomic> #include <chrono> #include <thread> QUICKCPPLIB_NAMESPACE_BEGIN namespace configurable_spinlock { template <class T> using atomic = std::atomic<T>; namespace chrono = std::chrono; namespace this_thread = std::this_thread; using std::memory_order; using std::memory_order_acq_rel; using std::memory_order_acquire; using std::memory_order_consume; using std::memory_order_relaxed; using std::memory_order_release; using std::memory_order_seq_cst; template <class T> class lock_guard { T *_m; public: using mutex_type = T; explicit lock_guard(mutex_type &m) noexcept : _m(&m) { _m->lock(); } explicit lock_guard(mutex_type &&m) noexcept : _m(&m) { _m->lock(); } lock_guard(const lock_guard &) = delete; lock_guard(lock_guard &&o) noexcept : _m(std::move(o._m)) { o._m = nullptr; } ~lock_guard() { if(_m) _m->unlock(); } }; namespace detail { template <class T> struct choose_half_type { static_assert(!std::is_same<T, T>::value, "detail::choose_half_type<T> not specialised for type T"); }; template <> struct choose_half_type<uint64_t> { using type = uint32_t; }; template <> struct choose_half_type<uint32_t> { using type = uint16_t; }; template <> struct choose_half_type<uint16_t> { using type = uint8_t; }; } /*! \tparam T The type of the pointer * \brief Lets you use a pointer to memory as a spinlock :) */ template <typename T> struct lockable_ptr : atomic<T *> { constexpr lockable_ptr(T *v = nullptr) : atomic<T *>(v) { } //! Returns the memory pointer part of the atomic T *get() noexcept { union { T *v; size_t n; } value; value.v = atomic<T *>::load(memory_order_relaxed); value.n &= ~(size_t) 1; return value.v; } //! Returns the memory pointer part of the atomic const T *get() const noexcept { union { T *v; size_t n; } value; value.v = atomic<T *>::load(memory_order_relaxed); value.n &= ~(size_t) 1; return value.v; } T &operator*() noexcept { return *get(); } const T &operator*() const noexcept { return *get(); } T *operator->() noexcept { return get(); } const T *operator->() const noexcept { return get(); } }; template <typename T> struct spinlockbase { protected: atomic<T> v; public: typedef T value_type; #ifndef QUICKCPPLIB_ENABLE_VALGRIND constexpr #endif spinlockbase() noexcept : v(0) { QUICKCPPLIB_ANNOTATE_RWLOCK_CREATE(this); #if QUICKCPPLIB_IN_THREAD_SANITIZER v.store(0, memory_order_release); #endif } spinlockbase(const spinlockbase &) = delete; //! Atomically move constructs #ifndef QUICKCPPLIB_ENABLE_VALGRIND constexpr #endif spinlockbase(spinlockbase &&) noexcept : v(0) { QUICKCPPLIB_ANNOTATE_RWLOCK_CREATE(this); // v.store(o.v.exchange(0, memory_order_acq_rel)); #if QUICKCPPLIB_IN_THREAD_SANITIZER v.store(0, memory_order_release); #endif } ~spinlockbase() { #ifdef QUICKCPPLIB_ENABLE_VALGRIND if(v.load(memory_order_acquire)) { QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(this, true); } #endif QUICKCPPLIB_ANNOTATE_RWLOCK_DESTROY(this); } spinlockbase &operator=(const spinlockbase &) = delete; spinlockbase &operator=(spinlockbase &&) = delete; //! Returns the raw atomic constexpr T load(memory_order o = memory_order_seq_cst) const noexcept { return v.load(o); } //! Sets the raw atomic void store(T a, memory_order o = memory_order_seq_cst) noexcept { v.store(a, o); } //! If atomic is zero, sets to 1 and returns true, else false. bool try_lock() noexcept { #if !QUICKCPPLIB_IN_THREAD_SANITIZER // no early outs for the sanitizer #ifdef QUICKCPPLIB_USE_VOLATILE_READ_FOR_AVOIDING_CMPXCHG // MSVC's atomics always seq_cst, so use volatile read to create a true acquire volatile T *_v = (volatile T *) &v; if(*_v) // Avoid unnecessary cache line invalidation traffic return false; #else if(v.load(memory_order_relaxed)) // Avoid unnecessary cache line invalidation traffic return false; #endif #endif #if 0 /* Disabled as CMPXCHG seems to have sped up on recent Intel */ // defined(__i386__) || defined(_M_IX86) || // defined(__x86_64__) || defined(_M_X64) // Intel is a lot quicker if you use XCHG instead of CMPXCHG. ARM is definitely not! T ret = v.exchange(1, memory_order_acquire); if(!ret) #else T expected = 0; bool ret = v.compare_exchange_weak(expected, 1, memory_order_acquire, memory_order_relaxed); if(ret) #endif { QUICKCPPLIB_ANNOTATE_RWLOCK_ACQUIRED(this, true); return true; } else return false; } constexpr bool try_lock() const noexcept { return v.load(memory_order_consume) ? false : true; // Avoid unnecessary cache line invalidation traffic } //! If atomic equals expected, sets to 1 and returns true, else false with expected updated to actual value. bool try_lock(T &expected) noexcept { T t(0); #if !QUICKCPPLIB_IN_THREAD_SANITIZER // no early outs for the sanitizer #ifdef QUICKCPPLIB_USE_VOLATILE_READ_FOR_AVOIDING_CMPXCHG // MSVC's atomics always seq_cst, so use volatile read to create a true acquire volatile T *_v = (volatile T *) &v; if((t = *_v)) // Avoid unnecessary cache line invalidation traffic #else t = v.load(memory_order_relaxed); if(t) // Avoid unnecessary cache line invalidation traffic #endif { expected = t; return false; } #endif bool ret = v.compare_exchange_weak(expected, 1, memory_order_acquire, memory_order_relaxed); if(ret) { QUICKCPPLIB_ANNOTATE_RWLOCK_ACQUIRED(this, true); return true; } else return false; } //! Sets the atomic to zero void unlock() noexcept { // assert(v == 1); QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(this, true); v.store(0, memory_order_release); } constexpr bool int_yield(size_t) noexcept { return false; } }; template <typename T> struct spinlockbase<lockable_ptr<T>> { private: lockable_ptr<T> v; public: typedef T *value_type; spinlockbase() noexcept {} spinlockbase(const spinlockbase &) = delete; //! Atomically move constructs spinlockbase(spinlockbase &&o) noexcept { v.store(o.v.exchange(nullptr, memory_order_acq_rel), memory_order_release); } spinlockbase &operator=(const spinlockbase &) = delete; spinlockbase &operator=(spinlockbase &&) = delete; //! Returns the memory pointer part of the atomic T *get() noexcept { return v.get(); } T *operator->() noexcept { return get(); } //! Returns the raw atomic T *load(memory_order o = memory_order_seq_cst) noexcept { return v.load(o); } #if 0 // Forces cmpxchng on everything else, so avoid if at all possible. //! Sets the memory pointer part of the atomic preserving lockedness void set(T *a) noexcept { union { T *v; size_t n; } value; T *expected; do { value.v=v.load(memory_order_relaxed); expected=value.v; bool locked=value.n&1; value.v=a; if(locked) value.n|=1; } while(!v.compare_exchange_weak(expected, value.v, memory_order_acquire, memory_order_relaxed)); } #endif //! Sets the raw atomic void store(T *a, memory_order o = memory_order_seq_cst) noexcept { v.store(a, o); } bool try_lock() noexcept { union { T *v; size_t n; } value; value.v = v.load(memory_order_relaxed); if(value.n & 1) // Avoid unnecessary cache line invalidation traffic return false; T *expected = value.v; value.n |= 1; return v.compare_exchange_weak(expected, value.v, memory_order_acquire, memory_order_relaxed); } void unlock() noexcept { union { T *v; size_t n; } value; value.v = v.load(memory_order_relaxed); // assert(value.n & 1); value.n &= ~(size_t) 1; v.store(value.v, memory_order_release); } constexpr bool int_yield(size_t) noexcept { return false; } }; template <typename T> struct ordered_spinlockbase { #ifndef _MSC_VER // Amazingly VS2015 incorrectly fails when T is an unsigned! static_assert(((T) -1) > 0, "T must be an unsigned type for ordered_spinlockbase"); #endif typedef T value_type; protected: atomic<value_type> _v; using _halfT = typename detail::choose_half_type<value_type>::type; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4201) // nameless struct/union #endif union _internals { value_type uint; struct { _halfT exit, entry; }; }; static_assert(sizeof(_internals) == sizeof(value_type), ""); #ifdef _MSC_VER #pragma warning(pop) #endif public: #ifndef QUICKCPPLIB_ENABLE_VALGRIND constexpr #endif ordered_spinlockbase() noexcept : _v(0) { QUICKCPPLIB_ANNOTATE_RWLOCK_CREATE(this); // v.store(0, memory_order_release); } ordered_spinlockbase(const ordered_spinlockbase &) = delete; //! Atomically move constructs ordered_spinlockbase(ordered_spinlockbase &&) noexcept : _v(0) { QUICKCPPLIB_ANNOTATE_RWLOCK_CREATE(this); // v.store(o.v.exchange(0, memory_order_acq_rel)); // v.store(0, memory_order_release); } ~ordered_spinlockbase() { #ifdef QUICKCPPLIB_ENABLE_VALGRIND _internals i = {_v.load(memory_order_relaxed)}; if(i.entry != i.exit) { QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(this, true); } #endif QUICKCPPLIB_ANNOTATE_RWLOCK_DESTROY(this); } ordered_spinlockbase &operator=(const ordered_spinlockbase &) = delete; ordered_spinlockbase &operator=(ordered_spinlockbase &&) = delete; //! Returns the raw atomic constexpr T load(memory_order o = memory_order_seq_cst) const noexcept { return _v.load(o); } //! Sets the raw atomic void store(T a, memory_order o = memory_order_seq_cst) noexcept { _v.store(a, o); } //! Tries to lock the spinlock, returning true if successful. bool try_lock() noexcept { _internals i = {_v.load(memory_order_relaxed)}, o = i; // If locked, bail out immediately if(i.entry != i.exit) return false; o.entry++; if(_v.compare_exchange_weak(i.uint, o.uint, memory_order_acquire, memory_order_relaxed)) { QUICKCPPLIB_ANNOTATE_RWLOCK_ACQUIRED(this, true); return true; } return false; } protected: value_type _begin_try_lock() noexcept { return _v.load(memory_order_relaxed); } bool _try_lock(value_type &state) noexcept { _internals i = {state}, o; o = i; o.entry++; if(_v.compare_exchange_weak(i.uint, o.uint, memory_order_acquire, memory_order_relaxed)) { QUICKCPPLIB_ANNOTATE_RWLOCK_ACQUIRED(this, true); return true; } state = i.uint; return false; } public: //! Releases the lock void unlock() noexcept { QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(this, true); _internals i = {_v.load(memory_order_relaxed)}, o; for(;;) { o = i; o.exit++; if(_v.compare_exchange_weak(i.uint, o.uint, memory_order_release, memory_order_relaxed)) return; } } bool int_yield(size_t) noexcept { return false; } }; template <typename T> struct shared_spinlockbase { #ifndef _MSC_VER // Amazingly VS2015 incorrectly fails when T is an unsigned! static_assert(((T) -1) > 0, "T must be an unsigned type for shared_spinlockbase"); #endif typedef T value_type; protected: atomic<value_type> _v; public: #ifndef QUICKCPPLIB_ENABLE_VALGRIND constexpr #endif shared_spinlockbase() noexcept : _v(0) { QUICKCPPLIB_ANNOTATE_RWLOCK_CREATE(this); #if QUICKCPPLIB_IN_THREAD_SANITIZER _v.store(0, memory_order_release); #endif } shared_spinlockbase(const shared_spinlockbase &) = delete; //! Atomically move constructs shared_spinlockbase(shared_spinlockbase &&) noexcept : _v(0) { QUICKCPPLIB_ANNOTATE_RWLOCK_CREATE(this); // v.store(o.v.exchange(0, memory_order_acq_rel)); #if QUICKCPPLIB_IN_THREAD_SANITIZER _v.store(0, memory_order_release); #endif } ~shared_spinlockbase() { #ifdef QUICKCPPLIB_ENABLE_VALGRIND value_type i = _v.load(memory_order_relaxed); if(i == 1) { QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(this, true); } else if(i != 0) { QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(this, false); } #endif QUICKCPPLIB_ANNOTATE_RWLOCK_DESTROY(this); } shared_spinlockbase &operator=(const shared_spinlockbase &) = delete; shared_spinlockbase &operator=(shared_spinlockbase &&) = delete; //! Returns the raw atomic constexpr T load(memory_order o = memory_order_seq_cst) const noexcept { return _v.load(o); } //! Sets the raw atomic void store(T a, memory_order o = memory_order_seq_cst) noexcept { _v.store(a, o); } //! Tries to lock the spinlock for exclusive access, returning true if successful. bool try_lock() noexcept { value_type i = _v.load(memory_order_relaxed), o = i; // If locked by anybody, bail out immediately if(i) return false; o = 1; if(_v.compare_exchange_weak(i, o, memory_order_acquire, memory_order_relaxed)) { QUICKCPPLIB_ANNOTATE_RWLOCK_ACQUIRED(this, true); return true; } return false; } //! Releases the lock from exclusive access void unlock() noexcept { // assert(_v == 1); QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(this, true); _v.store(0, memory_order_release); } //! Tries to lock the spinlock for shared access, returning true if successful. bool try_lock_shared() noexcept { // OR in the exclusive lock bit value_type i = _v.fetch_or(1, memory_order_acquire); if(i & 1) return false; // If not locked, increment reader count and unlock i += 2; i &= ~1; _v.store(i, memory_order_release); QUICKCPPLIB_ANNOTATE_RWLOCK_ACQUIRED(this, false); return true; } //! Releases the lock from shared access void unlock_shared() noexcept { value_type i; for(size_t n = 0;; n++) { i = _v.fetch_or(1, memory_order_acquire); // assert(i > 1); if(!(i & 1)) break; // For very heavily contended locks, stop thrashing the cache line if(n > 2) { for(size_t m = 0; m < 15000; m = m + 1) { volatile int x = 1; (void) x; } } } QUICKCPPLIB_ANNOTATE_RWLOCK_RELEASED(this, false); i -= 2; i &= ~1; _v.store(i, memory_order_release); } //! Tries to convert an exclusive lock to a shared lock, returning true if successful. bool try_convert_lock_to_shared() noexcept { value_type expected = 1; return _v.compare_exchange_strong(expected, 2, memory_order_acquire, memory_order_relaxed); } //! Tries to convert a shared lock to an exclusive lock, returning true if successful. bool try_convert_lock_to_exclusive() noexcept { value_type expected = 2; return _v.compare_exchange_strong(expected, 1, memory_order_acquire, memory_order_relaxed); } bool int_yield(size_t) noexcept { return false; } }; namespace detail { template <bool use_pause> inline void smt_pause() noexcept {}; template <> inline void smt_pause<true>() noexcept { #ifdef QUICKCPPLIB_SMT_PAUSE QUICKCPPLIB_SMT_PAUSE; #endif }; } //! \brief How many spins to loop, optionally calling the SMT pause instruction on Intel template <size_t spins, bool use_pause = true> struct spins_to_loop { template <class parenttype> struct policy : parenttype { static constexpr size_t spins_to_loop = spins; constexpr policy() {} policy(const policy &) = delete; constexpr policy(policy &&o) noexcept : parenttype(std::move(o)) { } constexpr inline bool int_yield(size_t n) noexcept { if(parenttype::int_yield(n)) return true; if(n >= spins) return false; detail::smt_pause<use_pause>(); return true; } }; }; //! \brief How many spins to yield the current thread's timeslice template <size_t spins> struct spins_to_yield { template <class parenttype> struct policy : parenttype { static constexpr size_t spins_to_yield = spins; constexpr policy() {} policy(const policy &) = delete; constexpr policy(policy &&o) noexcept : parenttype(std::move(o)) { } constexpr bool int_yield(size_t n) noexcept { if(parenttype::int_yield(n)) return true; if(n >= spins) return false; this_thread::yield(); return true; } }; }; //! \brief How many spins to sleep the current thread struct spins_to_sleep { template <class parenttype> struct policy : parenttype { constexpr policy() {} policy(const policy &) = delete; constexpr policy(policy &&o) noexcept : parenttype(std::move(o)) { } constexpr bool int_yield(size_t n) noexcept { if(parenttype::int_yield(n)) return true; this_thread::sleep_for(chrono::milliseconds(1)); return true; } }; }; //! \brief A spin policy which does nothing struct null_spin_policy { template <class parenttype> struct policy : parenttype { }; }; template <class T> inline bool is_lockable_locked(T &lockable) noexcept; /*! \class spinlock \brief A non-FIFO policy configurable spin lock meeting the `Mutex` concept providing the fastest possible spin lock. \tparam T An integral type capable of atomic usage `sizeof(spinlock<T>) == sizeof(T)`. Suitable for usage in shared memory. Meets the requirements of BasicLockable and Lockable. Provides a get() and set() for the type used for the spin lock. Suitable for limited usage in constexpr. \warning `spinlock<bool>` which might seem obvious is usually slower than `spinlock<uintptr_t>` on most architectures. So why reinvent the wheel? 1. Policy configurable spin. 2. Implemented in pure C++ 11 atomics so the thread sanitiser works as expected. 3. Multistate locks are possible instead of just 0|1. 4. I don't much care for doing writes during the spin which a lot of other spinlocks do. It generates an unnecessary amount of cache line invalidation traffic. Better to spin-read and only write when the read suggests you might have a chance. 5. This spin lock can use a pointer to memory as the spin lock at the cost of some performance. It uses the bottom bit as the locked flag. See locked_ptr<T>. */ template <typename T, template <class> class spinpolicy2 = spins_to_loop<125>::policy, template <class> class spinpolicy3 = spins_to_yield<250>::policy, template <class> class spinpolicy4 = spins_to_sleep::policy> class spinlock : public spinpolicy4<spinpolicy3<spinpolicy2<spinlockbase<T>>>> { typedef spinpolicy4<spinpolicy3<spinpolicy2<spinlockbase<T>>>> parenttype; public: constexpr spinlock() {} spinlock(const spinlock &) = delete; constexpr spinlock(spinlock &&o) noexcept : parenttype(std::move(o)) { } void lock() noexcept { for(size_t n = 0;; n++) { if(parenttype::try_lock()) return; parenttype::int_yield(n); } } //! Locks if the atomic is not the supplied value, else returning false bool lock(T only_if_not_this) noexcept { for(size_t n = 0;; n++) { T expected = 0; if(parenttype::try_lock(expected)) return true; if(expected == only_if_not_this) return false; parenttype::int_yield(n); } } }; #if 0 // fails its correctness testing in the unit tests, so disabled /*! \class ordered_spinlock \brief A FIFO policy configurable spin lock meeting the `Mutex` concept. \tparam T An unsigned integral type capable of atomic usage `sizeof(ordered_spinlock<T>) == sizeof(T)`. Suitable for usage in shared memory. Has all the advantages of spinlock apart from potential constexpr usage, but also guarantees FIFO ordering such that every lock grant is guaranteed to be in order of lock entry. It is implemented as two monotonically rising counters to enforce ordering of lock grants. Maximum performance on Intel is roughly one third that of `spinlock<uintptr_t>`. \note Maximum contention is the largest integer fitting into half a `T`, so if T were an unsigned short, the maximum threads which could wait on this spinlock before experiencing undefined behaviour would be 255. */ template <typename T = uintptr_t, template <class> class spinpolicy2 = spins_to_loop<125>::policy, template <class> class spinpolicy3 = spins_to_yield<250>::policy, template <class> class spinpolicy4 = spins_to_sleep::policy> class ordered_spinlock : public spinpolicy4<spinpolicy3<spinpolicy2<ordered_spinlockbase<T>>>> { typedef spinpolicy4<spinpolicy3<spinpolicy2<ordered_spinlockbase<T>>>> parenttype; public: constexpr ordered_spinlock() {} ordered_spinlock(const ordered_spinlock &) = delete; ordered_spinlock(ordered_spinlock &&o) noexcept : parenttype(std::move(o)) {} //! Locks the spinlock void lock() noexcept { auto state = parenttype::_begin_try_lock(); for(size_t n = 0;; n++) { if(parenttype::_try_lock(state)) return; parenttype::int_yield(n); } } }; #endif /*! \class shared_spinlock \brief A non-FIFO policy configurable shared/exclusive spin lock meeting the `SharedMutex` concept. \tparam T An unsigned integral type capable of atomic usage `sizeof(shared_spinlock<T>) == sizeof(T)`. Suitable for usage in shared memory. Implementing a fair shared spin lock with acceptable performance in just four bytes of storage is challenging, so this is a reader-biased shared lock which uses bit 0 as the exclusion bit, and the remainder of the bits to track how many readers are in the shared lock. Undefined behaviour will occur if the number of concurrent readers exceeds half the maximum value of a `T`. Maximum performance on Intel for exclusive locks is the same as a `spinlock<uintptr_t>`. For shared locks it is roughly one third that of `spinlock<uintptr_t>` due to performing twice as many atomic read-modify-updates. */ template <typename T = uintptr_t, template <class> class spinpolicy2 = spins_to_loop<125>::policy, template <class> class spinpolicy3 = spins_to_yield<250>::policy, template <class> class spinpolicy4 = spins_to_sleep::policy> class shared_spinlock : public spinpolicy4<spinpolicy3<spinpolicy2<shared_spinlockbase<T>>>> { typedef spinpolicy4<spinpolicy3<spinpolicy2<shared_spinlockbase<T>>>> parenttype; public: constexpr shared_spinlock() {} shared_spinlock(const shared_spinlock &) = delete; shared_spinlock(shared_spinlock &&o) noexcept : parenttype(std::move(o)) { } //! Locks the spinlock for exclusive access void lock() noexcept { for(size_t n = 0;; n++) { if(parenttype::try_lock()) return; parenttype::int_yield(n); } } //! Locks the spinlock for shared access void lock_shared() noexcept { for(size_t n = 0;; n++) { if(parenttype::try_lock_shared()) return; parenttype::int_yield(n); } } }; //! \brief Determines if a lockable is locked. Type specialise this for performance if your lockable allows //! examination. template <class T> inline bool is_lockable_locked(T &lockable) noexcept { if(lockable.try_lock()) { lockable.unlock(); return false; } return true; } // For when used with a spinlock template <class T, template <class> class spinpolicy2, template <class> class spinpolicy3, template <class> class spinpolicy4> constexpr inline T is_lockable_locked(spinlock<T, spinpolicy2, spinpolicy3, spinpolicy4> &lockable) noexcept { #ifdef QUICKCPPLIB_HAVE_TRANSACTIONAL_MEMORY_COMPILER // Annoyingly the atomic ops are marked as unsafe for atomic transactions, so ... return *((volatile T *) &lockable); #else return lockable.load(memory_order_consume); #endif } // For when used with a spinlock template <class T, template <class> class spinpolicy2, template <class> class spinpolicy3, template <class> class spinpolicy4> constexpr inline T is_lockable_locked(const spinlock<T, spinpolicy2, spinpolicy3, spinpolicy4> &lockable) noexcept { #ifdef QUICKCPPLIB_HAVE_TRANSACTIONAL_MEMORY_COMPILER // Annoyingly the atomic ops are marked as unsafe for atomic transactions, so ... return *((volatile T *) &lockable); #else return lockable.load(memory_order_consume); #endif } // For when used with a locked_ptr template <class T, template <class> class spinpolicy2, template <class> class spinpolicy3, template <class> class spinpolicy4> constexpr inline bool is_lockable_locked(spinlock<lockable_ptr<T>, spinpolicy2, spinpolicy3, spinpolicy4> &lockable) noexcept { return ((size_t) lockable.load(memory_order_consume)) & 1; } #if 0 // For when used with an ordered spinlock template <class T, template <class> class spinpolicy2, template <class> class spinpolicy3, template <class> class spinpolicy4> constexpr inline bool is_lockable_locked(ordered_spinlock<T, spinpolicy2, spinpolicy3, spinpolicy4> &lockable) noexcept { using halfT = typename detail::choose_half_type<T>::type; union { T v; struct { halfT entry, exit; }; }; #ifdef QUICKCPPLIB_HAVE_TRANSACTIONAL_MEMORY_COMPILER // Annoyingly the atomic ops are marked as unsafe for atomic transactions, so ... v = *((volatile T *) &lockable); #else v = lockable.load(memory_order_consume); #endif return entry != exit; } #endif // For when used with a shared spinlock template <class T, template <class> class spinpolicy2, template <class> class spinpolicy3, template <class> class spinpolicy4> constexpr inline T is_lockable_locked(shared_spinlock<T, spinpolicy2, spinpolicy3, spinpolicy4> &lockable) noexcept { #ifdef QUICKCPPLIB_HAVE_TRANSACTIONAL_MEMORY_COMPILER // Annoyingly the atomic ops are marked as unsafe for atomic transactions, so ... return *((volatile T *) &lockable); #else return lockable.load(memory_order_consume); #endif } #ifndef QUICKCPPLIB_BEGIN_TRANSACT_LOCK #ifdef QUICKCPPLIB_HAVE_TRANSACTIONAL_MEMORY_COMPILER #undef QUICKCPPLIB_USING_INTEL_TSX #define QUICKCPPLIB_BEGIN_TRANSACT_LOCK(lockable) \ __transaction_relaxed \ { \ (void) QUICKCPPLIB_NAMESPACE::is_lockable_locked(lockable); \ { #define QUICKCPPLIB_BEGIN_TRANSACT_LOCK_ONLY_IF_NOT(lockable, only_if_not_this) \ __transaction_relaxed \ { \ if((only_if_not_this) != QUICKCPPLIB_NAMESPACE::is_lockable_locked(lockable)) \ { #define QUICKCPPLIB_END_TRANSACT_LOCK(lockable) \ } \ } #define QUICKCPPLIB_BEGIN_NESTED_TRANSACT_LOCK(N) __transaction_relaxed #define QUICKCPPLIB_END_NESTED_TRANSACT_LOCK(N) #endif // QUICKCPPLIB_BEGIN_TRANSACT_LOCK #endif #ifndef QUICKCPPLIB_BEGIN_TRANSACT_LOCK #define QUICKCPPLIB_BEGIN_TRANSACT_LOCK(lockable) \ { \ QUICKCPPLIB_NAMESPACE::configurable_spinlock::lock_guard<decltype(lockable)> __tsx_transaction(lockable); #define QUICKCPPLIB_BEGIN_TRANSACT_LOCK_ONLY_IF_NOT(lockable, only_if_not_this) \ if(lockable.lock(only_if_not_this)) \ { \ QUICKCPPLIB_NAMESPACE::configurable_spinlock::lock_guard<decltype(lockable)> __tsx_transaction( \ lockable, QUICKCPPLIB_NAMESPACE::adopt_lock_t()); #define QUICKCPPLIB_END_TRANSACT_LOCK(lockable) } #define QUICKCPPLIB_BEGIN_NESTED_TRANSACT_LOCK(N) #define QUICKCPPLIB_END_NESTED_TRANSACT_LOCK(N) #endif // QUICKCPPLIB_BEGIN_TRANSACT_LOCK } QUICKCPPLIB_NAMESPACE_END #endif // QUICKCPPLIB_HPP
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/offset_ptr.hpp
/* Offset pointer support (C) 2018 Niall Douglas <http://www.nedproductions.biz/> (4 commits) File Created: June 2018 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_OFFSET_PTR_HPP #define QUICKCPPLIB_OFFSET_PTR_HPP #include "config.hpp" #include <atomic> #include <cstdint> QUICKCPPLIB_NAMESPACE_BEGIN //! \brief The namespace for the offset pointer types namespace offset_ptr { namespace detail { template <class T> struct ptr_to_intptr { using type = intptr_t; }; template <class T> struct ptr_to_intptr<const T> { using type = const intptr_t; }; template <class T> struct ptr_to_intptr<volatile T> { using type = volatile intptr_t; }; template <class T> struct ptr_to_intptr<const volatile T> { using type = const volatile intptr_t; }; } /* \class offset_ptr \brief A pointer invariant to relocation if the target is equally relocated. Very useful for shared memory regions where one is pointing into the same shared memory region. On a Skylake x64 CPU, setting the offset pointer has a latency of 5 CPU cycles, throughput is 2. On a Skylake x64 CPU, getting the offset pointer has a latency of 3 CPU cycles, throughput is 2. */ template <class T> class offset_ptr { using intptr_type = typename detail::ptr_to_intptr<T>::type; intptr_type _v; constexpr void _set(T *v = nullptr) { _v = reinterpret_cast<intptr_t>(v) - reinterpret_cast<intptr_t>(this); } constexpr T *_get() const { return reinterpret_cast<T *>(_v + reinterpret_cast<intptr_t>(this)); } struct _reference_disabled_type; using _element_type = std::conditional_t<!std::is_void<T>::value, T, _reference_disabled_type>; public: //! The pointer type using pointer = T *; //! The pointed to type using element_type = T; //! Construct a null pointer constexpr offset_ptr() noexcept { _set(); } //! Implicitly construct a null pointer constexpr offset_ptr(std::nullptr_t) noexcept { _set(); } //! Copy constructor constexpr offset_ptr(const offset_ptr &o) noexcept { _set(o._get()); } //! Move constructor constexpr offset_ptr(offset_ptr &&o) noexcept { _set(o._get()); } //! Copy assignment constexpr offset_ptr &operator=(const offset_ptr &o) noexcept { _set(o._get()); return *this; } //! Move assignment constexpr offset_ptr &operator=(offset_ptr &&o) noexcept { _set(o._get()); return *this; } ~offset_ptr() = default; //! Implicitly construct constexpr offset_ptr(pointer v) { _set(v); } //! Implicitly convert constexpr operator pointer() const noexcept { return _get(); } //! Dereference constexpr pointer operator->() const noexcept { return _get(); } //! Dereference constexpr _element_type &operator*() noexcept { return *_get(); } //! Dereference constexpr const _element_type &operator*() const noexcept { return *_get(); } }; template <class T> class offset_ptr<const T> { using intptr_type = typename detail::ptr_to_intptr<T>::type; intptr_type _v; constexpr void _set(const T *v = nullptr) { _v = reinterpret_cast<intptr_t>(v) - reinterpret_cast<intptr_t>(this); } constexpr const T *_get() const { return reinterpret_cast<const T *>(_v + reinterpret_cast<intptr_t>(this)); } struct _reference_disabled_type; using _element_type = std::conditional_t<!std::is_void<T>::value, T, _reference_disabled_type>; public: using pointer = const T *; using element_type = const T; constexpr offset_ptr() noexcept { _set(); } constexpr offset_ptr(const offset_ptr &o) noexcept { _set(o._get()); } constexpr offset_ptr(offset_ptr &&o) noexcept { _set(o._get()); } constexpr offset_ptr &operator=(const offset_ptr &o) noexcept { _set(o._get()); return *this; } constexpr offset_ptr &operator=(offset_ptr &&o) noexcept { _set(o._get()); return *this; } ~offset_ptr() = default; constexpr offset_ptr(pointer v) { _set(v); } constexpr operator pointer() const noexcept { return _get(); } constexpr pointer operator->() const noexcept { return _get(); } constexpr _element_type &operator*() const noexcept { return *_get(); } }; /* \class atomic_offset_ptr \brief A pointer invariant to relocation if the target is equally relocated. Very useful for shared memory regions where one is pointing into the same shared memory region. On a Skylake x64 CPU, setting the offset pointer has a latency of 21 CPU cycles, throughput is 1 (`memory_order_seq_cst`). On a Skylake x64 CPU, getting the offset pointer has a latency of 20 CPU cycles, throughput is 1 (`memory_order_seq_cst`). */ template <class T> class atomic_offset_ptr { using intptr_type = typename detail::ptr_to_intptr<T>::type; std::atomic<intptr_type> _v; constexpr void _set(T *v, std::memory_order o) { _v.store(reinterpret_cast<intptr_t>(v) - reinterpret_cast<intptr_t>(this), o); } constexpr T *_get(std::memory_order o) const { return reinterpret_cast<T *>(_v.load(o) + reinterpret_cast<intptr_t>(this)); } struct _reference_disabled_type; using _element_type = std::conditional_t<!std::is_void<T>::value, T, _reference_disabled_type>; public: //! The pointer type using pointer = T *; //! The pointed to type using element_type = T; //! Construct a null pointer constexpr atomic_offset_ptr(std::memory_order w = std::memory_order_seq_cst) noexcept { _set(nullptr, w); } //! Implicitly construct a null pointer constexpr atomic_offset_ptr(std::nullptr_t, std::memory_order w = std::memory_order_seq_cst) noexcept { _set(nullptr, w); } //! Copy constructor constexpr atomic_offset_ptr(const atomic_offset_ptr &o, std::memory_order w = std::memory_order_seq_cst, std::memory_order r = std::memory_order_seq_cst) noexcept { _set(o._get(r), w); } //! Move constructor constexpr atomic_offset_ptr(atomic_offset_ptr &&o, std::memory_order w = std::memory_order_seq_cst, std::memory_order r = std::memory_order_seq_cst) noexcept { _set(o._get(r, w)); } //! Copy assignment constexpr atomic_offset_ptr &operator=(const atomic_offset_ptr &o) noexcept { _set(o._get(std::memory_order_seq_cst), std::memory_order_seq_cst); return *this; } //! Move assignment constexpr atomic_offset_ptr &operator=(atomic_offset_ptr &&o) noexcept { _set(o._get(std::memory_order_seq_cst), std::memory_order_seq_cst); return *this; } ~atomic_offset_ptr() = default; //! Implicitly construct constexpr atomic_offset_ptr(pointer v, std::memory_order w = std::memory_order_seq_cst) { _set(v, w); } //! Get constexpr pointer get(std::memory_order r = std::memory_order_seq_cst) const noexcept { return _get(r); } //! Set constexpr void set(pointer v, std::memory_order w = std::memory_order_seq_cst) noexcept { _set(v, w); } }; } QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/bitfield.hpp
/* Yet another C++ 11 constexpr bitfield (C) 2016-2017 Niall Douglas <http://www.nedproductions.biz/> (5 commits) File Created: Aug 2016 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_BITFIELD_HPP #define QUICKCPPLIB_BITFIELD_HPP #include "config.hpp" #include <type_traits> // for std::underlying_type QUICKCPPLIB_NAMESPACE_BEGIN //! \brief The namespace for the bitfield types namespace bitfield { /*! \brief Constexpr typesafe bitwise flags support Usage: \code QUICKCPPLIB_BITFIELD_BEGIN(flag) { flag1 = 1 << 0, flag2 = 1 << 1, ... } QUICKCPPLIB_BITFIELD_END(flag) ... flag myflags = flag::flag1|flag::flag2; if(myflags & flag::flag1) ... if(!myflags) ... // This intentionally fails to compile: // if(myflags && flag::flag2) // // That is because of operator precedence difficulties in say: // if(myflags && flag::flag1 && myflags && flag::flag2) // // This works fine though: if((myflags & flag::flag1) || (myflags & flag::flag2)) ... \endcode */ template <class Enum> struct bitfield : public Enum { //! The C style enum type which represents flags in this bitfield using enum_type = typename Enum::enum_type; //! The type which the C style enum implicitly converts to using underlying_type = std::underlying_type_t<enum_type>; private: underlying_type _value; public: //! Default construct to all bits zero constexpr bitfield() noexcept : _value(0) {} //! Implicit construction from the C style enum constexpr bitfield(enum_type v) noexcept : _value(v) {} //! Implicit construction from the underlying type of the C enum constexpr bitfield(underlying_type v) noexcept : _value(v) {} //! Permit explicit casting to the underlying type explicit constexpr operator underlying_type() const noexcept { return _value; } //! Test for non-zeroness explicit constexpr operator bool() const noexcept { return !!_value; } //! Test for zeroness constexpr bool operator!() const noexcept { return !_value; } //! Test for equality constexpr bool operator==(bitfield o) const noexcept { return _value == o._value; } //! Test for equality constexpr bool operator==(enum_type o) const noexcept { return _value == o; } //! Test for inequality constexpr bool operator!=(bitfield o) const noexcept { return _value != o._value; } //! Test for inequality constexpr bool operator!=(enum_type o) const noexcept { return _value != o; } //! Performs a bitwise NOT constexpr bitfield operator~() const noexcept { return bitfield(~_value); } //! Performs a bitwise AND constexpr bitfield operator&(bitfield o) const noexcept { return bitfield(_value & o._value); } //! Performs a bitwise AND constexpr bitfield operator&(enum_type o) const noexcept { return bitfield(_value & o); } //! Performs a bitwise AND constexpr bitfield &operator&=(bitfield o) noexcept { _value &= o._value; return *this; } //! Performs a bitwise AND constexpr bitfield &operator&=(enum_type o) noexcept { _value &= o; return *this; } //! Trap incorrect use of logical AND template <class T> bool operator&&(T) noexcept = delete; //! Trap incorrect use of logical OR // template <class T> bool operator||(T) noexcept = delete; //! Performs a bitwise OR constexpr bitfield operator|(bitfield o) const noexcept { return bitfield(_value | o._value); } //! Performs a bitwise OR constexpr bitfield operator|(enum_type o) const noexcept { return bitfield(_value | o); } //! Performs a bitwise OR constexpr bitfield &operator|=(bitfield o) noexcept { _value |= o._value; return *this; } //! Performs a bitwise OR constexpr bitfield &operator|=(enum_type o) noexcept { _value |= o; return *this; } //! Performs a bitwise XOR constexpr bitfield operator^(bitfield o) const noexcept { return bitfield(_value ^ o._value); } //! Performs a bitwise XOR constexpr bitfield operator^(enum_type o) const noexcept { return bitfield(_value ^ o); } //! Performs a bitwise XOR constexpr bitfield &operator^=(bitfield o) noexcept { _value ^= o._value; return *this; } //! Performs a bitwise XOR constexpr bitfield &operator^=(enum_type o) noexcept { _value ^= o; return *this; } }; #ifdef DOXYGEN_IS_IN_THE_HOUSE //! Begins a typesafe bitfield #define QUICKCPPLIB_BITFIELD_BEGIN(type) enum bitfield__##type : unsigned //! Begins a typesafe bitfield #define QUICKCPPLIB_BITFIELD_BEGIN_T(type, UT) enum bitfield__##type : UT //! Ends a typesafe bitfield #define QUICKCPPLIB_BITFIELD_END(type) ; #else //! Begins a typesafe bitfield with underlying representation `unsigned` #define QUICKCPPLIB_BITFIELD_BEGIN(type) \ \ struct type##_base \ \ { \ enum enum_type : unsigned //! Begins a typesafe bitfield with underlying representation `unsigned` #define QUICKCPPLIB_BITFIELD_BEGIN_T(type, UT) \ \ struct type##_base \ \ { \ enum enum_type : UT //! Ends a typesafe bitfield #define QUICKCPPLIB_BITFIELD_END(type) \ \ ; \ } \ ; \ \ using type = QUICKCPPLIB_NAMESPACE::bitfield::bitfield<type##_base>; } #endif QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/string_view.hpp
/* string_view support (C) 2017 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Jul 2017 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_STRING_VIEW_HPP #define QUICKCPPLIB_STRING_VIEW_HPP #include "config.hpp" #if(_HAS_CXX17 || __cplusplus >= 201700) && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20170519) // libstdc++'s string_view is missing constexpr #include <string_view> QUICKCPPLIB_NAMESPACE_BEGIN namespace string_view { template <typename charT, typename traits = std::char_traits<charT>> using basic_string_view = std::basic_string_view<charT, traits>; typedef basic_string_view<char, std::char_traits<char>> string_view; typedef basic_string_view<wchar_t, std::char_traits<wchar_t>> wstring_view; typedef basic_string_view<char16_t, std::char_traits<char16_t>> u16string_view; typedef basic_string_view<char32_t, std::char_traits<char32_t>> u32string_view; } QUICKCPPLIB_NAMESPACE_END #else #include <algorithm> #include <cstddef> #include <cstring> #include <iosfwd> #include <iterator> #include <stdexcept> #include <string> #include <string> QUICKCPPLIB_NAMESPACE_BEGIN namespace string_view { template <typename charT, typename traits = std::char_traits<charT>> class basic_string_view; typedef basic_string_view<char, std::char_traits<char>> string_view; typedef basic_string_view<wchar_t, std::char_traits<wchar_t>> wstring_view; typedef basic_string_view<char16_t, std::char_traits<char16_t>> u16string_view; typedef basic_string_view<char32_t, std::char_traits<char32_t>> u32string_view; // The remainder of this file is a hacked edition of Boost's string_view /* Copyright (c) Marshall Clow 2012-2015. Copyright (c) Beman Dawes 2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) For more information, see http://www.boost.org Based on the StringRef implementation in LLVM (http://llvm.org) and N3422 by Jeffrey Yasskin http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3442.html Updated July 2015 to reflect the Library Fundamentals TS http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4480.html */ namespace detail { // A helper functor because sometimes we don't have lambdas template <typename charT, typename traits> class string_view_traits_eq { public: string_view_traits_eq(charT ch) : ch_(ch) { } bool operator()(charT val) const { return traits::eq(ch_, val); } charT ch_; }; } template <typename charT, typename traits> // traits defaulted in string_view_fwd.hpp class basic_string_view { public: // types typedef traits traits_type; typedef charT value_type; typedef charT *pointer; typedef const charT *const_pointer; typedef charT &reference; typedef const charT &const_reference; typedef const_pointer const_iterator; // impl-defined typedef const_iterator iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef const_reverse_iterator reverse_iterator; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; static constexpr size_type npos = size_type(-1); // construct/copy constexpr basic_string_view() noexcept : ptr_(NULL), len_(0) {} // by defaulting these functions, basic_string_ref becomes // trivially copy/move constructible. constexpr basic_string_view(const basic_string_view &rhs) noexcept = default; basic_string_view &operator=(const basic_string_view &rhs) noexcept = default; template <typename Allocator> basic_string_view(const std::basic_string<charT, traits, Allocator> &str) noexcept : ptr_(str.data()), len_(str.length()) {} // #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS) // // Constructing a string_view from a temporary string is a bad idea // template<typename Allocator> // basic_string_view( std::basic_string<charT, traits, Allocator>&&) // = delete; // #endif QUICKCPPLIB_TEMPLATE(class T) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(std::is_pointer<T>::value && std::is_convertible<T, const_pointer>::value)) // exclude array to pointer constexpr basic_string_view(T str) : ptr_(str) , len_(traits::length(str)) { } constexpr basic_string_view(const charT *str, size_type len) : ptr_(str) , len_(len) { } template<size_t N> constexpr basic_string_view(const charT (&str)[N]) : ptr_(str) , len_(N - 1) { } // iterators constexpr const_iterator begin() const noexcept { return ptr_; } constexpr const_iterator cbegin() const noexcept { return ptr_; } constexpr const_iterator end() const noexcept { return ptr_ + len_; } constexpr const_iterator cend() const noexcept { return ptr_ + len_; } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } // capacity constexpr size_type size() const noexcept { return len_; } constexpr size_type length() const noexcept { return len_; } constexpr size_type max_size() const noexcept { return len_; } constexpr bool empty() const noexcept { return len_ == 0; } // element access constexpr const_reference operator[](size_type pos) const noexcept { return ptr_[pos]; } constexpr const_reference at(size_t pos) const { return pos >= len_ ? throw std::out_of_range("boost::string_view::at"), ptr_[0] : ptr_[pos]; } constexpr const_reference front() const { return ptr_[0]; } constexpr const_reference back() const { return ptr_[len_ - 1]; } constexpr const_pointer data() const noexcept { return ptr_; } // modifiers void clear() noexcept { len_ = 0; } // Boost extension constexpr void remove_prefix(size_type n) { if(n > len_) n = len_; ptr_ += n; len_ -= n; } constexpr void remove_suffix(size_type n) { if(n > len_) n = len_; len_ -= n; } constexpr void swap(basic_string_view &s) noexcept { std::swap(ptr_, s.ptr_); std::swap(len_, s.len_); } // basic_string_view string operations template <typename Allocator> explicit operator std::basic_string<charT, traits, Allocator>() const { return std::basic_string<charT, traits, Allocator>(begin(), end()); } template <typename Allocator = std::allocator<charT>> std::basic_string<charT, traits, Allocator> to_string(const Allocator &a = Allocator()) const { return std::basic_string<charT, traits, Allocator>(begin(), end(), a); } size_type copy(charT *s, size_type n, size_type pos = 0) const { if(pos > size()) throw std::out_of_range("string_view::copy"); size_type rlen = (std::min)(n, len_ - pos); traits_type::copy(s, data() + pos, rlen); return rlen; } constexpr basic_string_view substr(size_type pos, size_type n = npos) const { if(pos > size()) throw std::out_of_range("string_view::substr"); return basic_string_view(data() + pos, (std::min)(size() - pos, n)); } constexpr int compare(basic_string_view x) const noexcept { const int cmp = traits::compare(ptr_, x.ptr_, (std::min)(len_, x.len_)); return cmp != 0 ? cmp : (len_ == x.len_ ? 0 : len_ < x.len_ ? -1 : 1); } constexpr int compare(size_type pos1, size_type n1, basic_string_view x) const noexcept { return substr(pos1, n1).compare(x); } constexpr int compare(size_type pos1, size_type n1, basic_string_view x, size_type pos2, size_type n2) const { return substr(pos1, n1).compare(x.substr(pos2, n2)); } constexpr int compare(const charT *x) const { return compare(basic_string_view(x)); } constexpr int compare(size_type pos1, size_type n1, const charT *x) const { return substr(pos1, n1).compare(basic_string_view(x)); } constexpr int compare(size_type pos1, size_type n1, const charT *x, size_type n2) const { return substr(pos1, n1).compare(basic_string_view(x, n2)); } // Searches constexpr bool starts_with(charT c) const noexcept { // Boost extension return !empty() && traits::eq(c, front()); } constexpr bool starts_with(basic_string_view x) const noexcept { // Boost extension return len_ >= x.len_ && traits::compare(ptr_, x.ptr_, x.len_) == 0; } constexpr bool ends_with(charT c) const noexcept { // Boost extension return !empty() && traits::eq(c, back()); } constexpr bool ends_with(basic_string_view x) const noexcept { // Boost extension return len_ >= x.len_ && traits::compare(ptr_ + len_ - x.len_, x.ptr_, x.len_) == 0; } // find constexpr size_type find(basic_string_view s, size_type pos = 0) const noexcept { if(pos > size()) return npos; if(s.empty()) return pos; const_iterator iter = std::search(this->cbegin() + pos, this->cend(), s.cbegin(), s.cend(), traits::eq); return iter == this->cend() ? npos : std::distance(this->cbegin(), iter); } constexpr size_type find(charT c, size_type pos = 0) const noexcept { return find(basic_string_view(&c, 1), pos); } constexpr size_type find(const charT *s, size_type pos, size_type n) const noexcept { return find(basic_string_view(s, n), pos); } constexpr size_type find(const charT *s, size_type pos = 0) const noexcept { return find(basic_string_view(s), pos); } // rfind constexpr size_type rfind(basic_string_view s, size_type pos = npos) const noexcept { if(len_ < s.len_) return npos; if(pos > len_ - s.len_) pos = len_ - s.len_; if(s.len_ == 0u) // an empty string is always found return pos; for(const charT *cur = ptr_ + pos;; --cur) { if(traits::compare(cur, s.ptr_, s.len_) == 0) return cur - ptr_; if(cur == ptr_) return npos; }; } constexpr size_type rfind(charT c, size_type pos = npos) const noexcept { return rfind(basic_string_view(&c, 1), pos); } constexpr size_type rfind(const charT *s, size_type pos, size_type n) const noexcept { return rfind(basic_string_view(s, n), pos); } constexpr size_type rfind(const charT *s, size_type pos = npos) const noexcept { return rfind(basic_string_view(s), pos); } // find_first_of constexpr size_type find_first_of(basic_string_view s, size_type pos = 0) const noexcept { if(pos >= len_ || s.len_ == 0) return npos; const_iterator iter = std::find_first_of(this->cbegin() + pos, this->cend(), s.cbegin(), s.cend(), traits::eq); return iter == this->cend() ? npos : std::distance(this->cbegin(), iter); } constexpr size_type find_first_of(charT c, size_type pos = 0) const noexcept { return find_first_of(basic_string_view(&c, 1), pos); } constexpr size_type find_first_of(const charT *s, size_type pos, size_type n) const noexcept { return find_first_of(basic_string_view(s, n), pos); } constexpr size_type find_first_of(const charT *s, size_type pos = 0) const noexcept { return find_first_of(basic_string_view(s), pos); } // find_last_of constexpr size_type find_last_of(basic_string_view s, size_type pos = npos) const noexcept { if(s.len_ == 0u) return npos; if(pos >= len_) pos = 0; else pos = len_ - (pos + 1); const_reverse_iterator iter = std::find_first_of(this->crbegin() + pos, this->crend(), s.cbegin(), s.cend(), traits::eq); return iter == this->crend() ? npos : reverse_distance(this->crbegin(), iter); } constexpr size_type find_last_of(charT c, size_type pos = npos) const noexcept { return find_last_of(basic_string_view(&c, 1), pos); } constexpr size_type find_last_of(const charT *s, size_type pos, size_type n) const noexcept { return find_last_of(basic_string_view(s, n), pos); } constexpr size_type find_last_of(const charT *s, size_type pos = npos) const noexcept { return find_last_of(basic_string_view(s), pos); } // find_first_not_of constexpr size_type find_first_not_of(basic_string_view s, size_type pos = 0) const noexcept { if(pos >= len_) return npos; if(s.len_ == 0) return pos; const_iterator iter = find_not_of(this->cbegin() + pos, this->cend(), s); return iter == this->cend() ? npos : std::distance(this->cbegin(), iter); } constexpr size_type find_first_not_of(charT c, size_type pos = 0) const noexcept { return find_first_not_of(basic_string_view(&c, 1), pos); } constexpr size_type find_first_not_of(const charT *s, size_type pos, size_type n) const noexcept { return find_first_not_of(basic_string_view(s, n), pos); } constexpr size_type find_first_not_of(const charT *s, size_type pos = 0) const noexcept { return find_first_not_of(basic_string_view(s), pos); } // find_last_not_of constexpr size_type find_last_not_of(basic_string_view s, size_type pos = npos) const noexcept { if(pos >= len_) pos = len_ - 1; if(s.len_ == 0u) return pos; pos = len_ - (pos + 1); const_reverse_iterator iter = find_not_of(this->crbegin() + pos, this->crend(), s); return iter == this->crend() ? npos : reverse_distance(this->crbegin(), iter); } constexpr size_type find_last_not_of(charT c, size_type pos = npos) const noexcept { return find_last_not_of(basic_string_view(&c, 1), pos); } constexpr size_type find_last_not_of(const charT *s, size_type pos, size_type n) const noexcept { return find_last_not_of(basic_string_view(s, n), pos); } constexpr size_type find_last_not_of(const charT *s, size_type pos = npos) const noexcept { return find_last_not_of(basic_string_view(s), pos); } private: template <typename r_iter> size_type reverse_distance(r_iter first, r_iter last) const noexcept { // Portability note here: std::distance is not NOEXCEPT, but calling it with a string_view::reverse_iterator will not throw. return len_ - 1 - std::distance(first, last); } template <typename Iterator> Iterator find_not_of(Iterator first, Iterator last, basic_string_view s) const noexcept { for(; first != last; ++first) if(0 == traits::find(s.ptr_, s.len_, *first)) return first; return last; } const charT *ptr_; std::size_t len_; }; // Comparison operators // Equality template <typename charT, typename traits> inline constexpr bool operator==(basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept { if(x.size() != y.size()) return false; return x.compare(y) == 0; } // Inequality template <typename charT, typename traits> inline constexpr bool operator!=(basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept { if(x.size() != y.size()) return true; return x.compare(y) != 0; } // Less than template <typename charT, typename traits> inline constexpr bool operator<(basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept { return x.compare(y) < 0; } // Greater than template <typename charT, typename traits> inline constexpr bool operator>(basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept { return x.compare(y) > 0; } // Less than or equal to template <typename charT, typename traits> inline constexpr bool operator<=(basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept { return x.compare(y) <= 0; } // Greater than or equal to template <typename charT, typename traits> inline constexpr bool operator>=(basic_string_view<charT, traits> x, basic_string_view<charT, traits> y) noexcept { return x.compare(y) >= 0; } // "sufficient additional overloads of comparison functions" template <typename charT, typename traits, typename Allocator> inline constexpr bool operator==(basic_string_view<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) noexcept { return x == basic_string_view<charT, traits>(y); } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator==(const std::basic_string<charT, traits, Allocator> &x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) == y; } template <typename charT, typename traits> inline constexpr bool operator==(basic_string_view<charT, traits> x, const charT *y) noexcept { return x == basic_string_view<charT, traits>(y); } template <typename charT, typename traits> inline constexpr bool operator==(const charT *x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) == y; } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator!=(basic_string_view<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) noexcept { return x != basic_string_view<charT, traits>(y); } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator!=(const std::basic_string<charT, traits, Allocator> &x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) != y; } template <typename charT, typename traits> inline constexpr bool operator!=(basic_string_view<charT, traits> x, const charT *y) noexcept { return x != basic_string_view<charT, traits>(y); } template <typename charT, typename traits> inline constexpr bool operator!=(const charT *x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) != y; } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator<(basic_string_view<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) noexcept { return x < basic_string_view<charT, traits>(y); } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator<(const std::basic_string<charT, traits, Allocator> &x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) < y; } template <typename charT, typename traits> inline constexpr bool operator<(basic_string_view<charT, traits> x, const charT *y) noexcept { return x < basic_string_view<charT, traits>(y); } template <typename charT, typename traits> inline constexpr bool operator<(const charT *x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) < y; } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator>(basic_string_view<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) noexcept { return x > basic_string_view<charT, traits>(y); } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator>(const std::basic_string<charT, traits, Allocator> &x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) > y; } template <typename charT, typename traits> inline constexpr bool operator>(basic_string_view<charT, traits> x, const charT *y) noexcept { return x > basic_string_view<charT, traits>(y); } template <typename charT, typename traits> inline constexpr bool operator>(const charT *x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) > y; } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator<=(basic_string_view<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) noexcept { return x <= basic_string_view<charT, traits>(y); } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator<=(const std::basic_string<charT, traits, Allocator> &x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) <= y; } template <typename charT, typename traits> inline constexpr bool operator<=(basic_string_view<charT, traits> x, const charT *y) noexcept { return x <= basic_string_view<charT, traits>(y); } template <typename charT, typename traits> inline constexpr bool operator<=(const charT *x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) <= y; } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator>=(basic_string_view<charT, traits> x, const std::basic_string<charT, traits, Allocator> &y) noexcept { return x >= basic_string_view<charT, traits>(y); } template <typename charT, typename traits, typename Allocator> inline constexpr bool operator>=(const std::basic_string<charT, traits, Allocator> &x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) >= y; } template <typename charT, typename traits> inline constexpr bool operator>=(basic_string_view<charT, traits> x, const charT *y) noexcept { return x >= basic_string_view<charT, traits>(y); } template <typename charT, typename traits> inline constexpr bool operator>=(const charT *x, basic_string_view<charT, traits> y) noexcept { return basic_string_view<charT, traits>(x) >= y; } namespace detail { template <class charT, class traits> inline void sv_insert_fill_chars(std::basic_ostream<charT, traits> &os, std::size_t n) { enum { chunk_size = 8 }; charT fill_chars[chunk_size]; std::fill_n(fill_chars, static_cast<std::size_t>(chunk_size), os.fill()); for(; n >= chunk_size && os.good(); n -= chunk_size) os.write(fill_chars, static_cast<std::size_t>(chunk_size)); if(n > 0 && os.good()) os.write(fill_chars, n); } template <class charT, class traits> void sv_insert_aligned(std::basic_ostream<charT, traits> &os, const basic_string_view<charT, traits> &str) { const std::size_t size = str.size(); const std::size_t alignment_size = static_cast<std::size_t>(os.width()) - size; const bool align_left = (os.flags() & std::basic_ostream<charT, traits>::adjustfield) == std::basic_ostream<charT, traits>::left; if(!align_left) { detail::sv_insert_fill_chars(os, alignment_size); if(os.good()) os.write(str.data(), size); } else { os.write(str.data(), size); if(os.good()) detail::sv_insert_fill_chars(os, alignment_size); } } } // namespace detail // Inserter template <class charT, class traits> inline std::basic_ostream<charT, traits> &operator<<(std::basic_ostream<charT, traits> &os, const basic_string_view<charT, traits> &str) { if(os.good()) { const std::size_t size = str.size(); const std::size_t w = static_cast<std::size_t>(os.width()); if(w <= size) os.write(str.data(), size); else detail::sv_insert_aligned(os, str); os.width(0); } return os; } #if 0 // numeric conversions // // These are short-term implementations. // In a production environment, I would rather avoid the copying. // inline int stoi(string_view str, size_t* idx = 0, int base = 10) { return std::stoi(std::string(str), idx, base); } inline long stol(string_view str, size_t* idx = 0, int base = 10) { return std::stol(std::string(str), idx, base); } inline unsigned long stoul(string_view str, size_t* idx = 0, int base = 10) { return std::stoul(std::string(str), idx, base); } inline long long stoll(string_view str, size_t* idx = 0, int base = 10) { return std::stoll(std::string(str), idx, base); } inline unsigned long long stoull(string_view str, size_t* idx = 0, int base = 10) { return std::stoull(std::string(str), idx, base); } inline float stof(string_view str, size_t* idx = 0) { return std::stof(std::string(str), idx); } inline double stod(string_view str, size_t* idx = 0) { return std::stod(std::string(str), idx); } inline long double stold(string_view str, size_t* idx = 0) { return std::stold(std::string(str), idx); } inline int stoi(wstring_view str, size_t* idx = 0, int base = 10) { return std::stoi(std::wstring(str), idx, base); } inline long stol(wstring_view str, size_t* idx = 0, int base = 10) { return std::stol(std::wstring(str), idx, base); } inline unsigned long stoul(wstring_view str, size_t* idx = 0, int base = 10) { return std::stoul(std::wstring(str), idx, base); } inline long long stoll(wstring_view str, size_t* idx = 0, int base = 10) { return std::stoll(std::wstring(str), idx, base); } inline unsigned long long stoull(wstring_view str, size_t* idx = 0, int base = 10) { return std::stoull(std::wstring(str), idx, base); } inline float stof(wstring_view str, size_t* idx = 0) { return std::stof(std::wstring(str), idx); } inline double stod(wstring_view str, size_t* idx = 0) { return std::stod(std::wstring(str), idx); } inline long double stold(wstring_view str, size_t* idx = 0) { return std::stold(std::wstring(str), idx); } #endif #if 0 namespace std { // Hashing template<> struct hash<boost::string_view>; template<> struct hash<boost::u16string_view>; template<> struct hash<boost::u32string_view>; template<> struct hash<boost::wstring_view>; } #endif } QUICKCPPLIB_NAMESPACE_END #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/signal_guard.hpp
/* Signal guard support (C) 2018-2021 Niall Douglas <http://www.nedproductions.biz/> (4 commits) File Created: June 2018 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_SIGNAL_GUARD_HPP #define QUICKCPPLIB_SIGNAL_GUARD_HPP #include "config.hpp" #include <setjmp.h> #include <signal.h> #include <stdbool.h> #ifdef _WIN32 #ifndef SIGBUS #define SIGBUS (7) #endif #ifndef SIGPIPE #define SIGPIPE (13) #endif struct sigset_t { unsigned mask; }; #define sigismember(s, signo) (((s)->mask & (1ULL << signo)) != 0) #ifdef _MSC_VER extern "C" unsigned long __cdecl _exception_code(void); extern "C" void *__cdecl _exception_info(void); #endif #endif #if defined(__cplusplus) #include "bitfield.hpp" #include <atomic> #include <cassert> #include <exception> #include <new> // for placement new #endif #ifdef QUICKCPPLIB_EXPORTS #define SIGNALGUARD_CLASS_DECL QUICKCPPLIB_SYMBOL_EXPORT #define SIGNALGUARD_FUNC_DECL extern QUICKCPPLIB_SYMBOL_EXPORT #define SIGNALGUARD_MEMFUNC_DECL #else #if defined(__cplusplus) && (!defined(QUICKCPPLIB_HEADERS_ONLY) || QUICKCPPLIB_HEADERS_ONLY == 1) && !defined(DOXYGEN_SHOULD_SKIP_THIS) #define SIGNALGUARD_CLASS_DECL #define SIGNALGUARD_FUNC_DECL extern inline #define SIGNALGUARD_MEMFUNC_DECL inline #elif defined(QUICKCPPLIB_DYN_LINK) && !defined(QUICKCPPLIB_STATIC_LINK) #define SIGNALGUARD_CLASS_DECL QUICKCPPLIB_SYMBOL_IMPORT #define SIGNALGUARD_FUNC_DECL extern QUICKCPPLIB_SYMBOL_IMPORT #define SIGNALGUARD_MEMFUNC_DECL #else #define SIGNALGUARD_CLASS_DECL #define SIGNALGUARD_FUNC_DECL extern #define SIGNALGUARD_MEMFUNC_DECL #endif #endif #if defined(__cplusplus) extern "C" { #endif /*! \union raised_signal_info_value \brief User defined value. */ union raised_signal_info_value { int int_value; void *ptr_value; #if defined(__cplusplus) raised_signal_info_value() = default; raised_signal_info_value(int v) : int_value(v) { } raised_signal_info_value(void *v) : ptr_value(v) { } #endif }; #if defined(__cplusplus) static_assert(std::is_trivial<raised_signal_info_value>::value, "raised_signal_info_value is not trivial!"); static_assert(std::is_trivially_copyable<raised_signal_info_value>::value, "raised_signal_info_value is not trivially copyable!"); static_assert(std::is_standard_layout<raised_signal_info_value>::value, "raised_signal_info_value does not have standard layout!"); #endif //! Typedef to a system specific error code type #ifdef _WIN32 typedef long raised_signal_error_code_t; #else typedef int raised_signal_error_code_t; #endif /*! \struct raised_signal_info \brief A platform independent subset of `siginfo_t`. */ struct raised_signal_info { jmp_buf buf; //!< setjmp() buffer written on entry to guarded section int signo; //!< The signal raised //! The system specific error code for this signal, the `si_errno` code (POSIX) or `NTSTATUS` code (Windows) raised_signal_error_code_t error_code; void *addr; //!< Memory location which caused fault, if appropriate union raised_signal_info_value value; //!< A user-defined value //! The OS specific `siginfo_t *` (POSIX) or `PEXCEPTION_RECORD` (Windows) void *raw_info; //! The OS specific `ucontext_t` (POSIX) or `PCONTEXT` (Windows) void *raw_context; }; //! \brief The type of the guarded function. typedef union raised_signal_info_value (*thrd_signal_guard_guarded_t)(union raised_signal_info_value); //! \brief The type of the function called to recover from a signal being raised in a guarded section. typedef union raised_signal_info_value (*thrd_signal_guard_recover_t)(const struct raised_signal_info *); //! \brief The type of the function called when a signal is raised. Returns true to continue guarded code, false to recover. typedef bool (*thrd_signal_guard_decide_t)(struct raised_signal_info *); #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4190) // C-linkage with UDTs #endif /*! \brief Installs a thread-local signal guard for the calling thread, and calls the guarded function `guarded`. \return The value returned by `guarded`, or `recovery`. \param signals The set of signals to guard against. \param guarded A function whose execution is to be guarded against signal raises. \param recovery A function to be called if a signal is raised. \param decider A function to be called to decide whether to recover from the signal and continue the execution of the guarded routine, or to abort and call the recovery routine. \param value A value to supply to the guarded routine. */ SIGNALGUARD_FUNC_DECL union raised_signal_info_value thrd_signal_guard_call(const sigset_t *signals, thrd_signal_guard_guarded_t guarded, thrd_signal_guard_recover_t recovery, thrd_signal_guard_decide_t decider, union raised_signal_info_value value); #ifdef _MSC_VER #pragma warning(pop) #endif /*! \brief Call the currently installed signal handler for a signal (POSIX), or raise a Win32 structured exception (Windows), returning false if no handler was called due to the currently installed handler being `SIG_IGN` (POSIX). Note that on POSIX, we fetch the currently installed signal handler and try to call it directly. This allows us to supply custom `raw_info` and `raw_context`, and we do all the things which the signal handler flags tell us to do beforehand [1]. If the current handler has been defaulted, we enable the signal and execute `pthread_kill(pthread_self(), signo)` in order to invoke the default handling. Note that on Windows, `raw_context` is ignored as there is no way to override the context thrown with a Win32 structured exception. [1]: We currently do not implement alternative stack switching. If a handler requests that, we simply abort the process. Code donations implementing support are welcome. */ SIGNALGUARD_FUNC_DECL bool thrd_raise_signal(int signo, void *raw_info, void *raw_context); /*! \brief On platforms where it is necessary (POSIX), installs, and potentially enables, the global signal handlers for the signals specified by `guarded`. Each signal installed is threadsafe reference counted, so this is safe to call from multiple threads or instantiate multiple times. On platforms with better than POSIX global signal support, this function does nothing. ## POSIX only Any existing global signal handlers are replaced with a filtering signal handler, which checks if the current kernel thread has installed a signal guard, and if so executes the guard. If no signal guard has been installed for the current kernel thread, global signal continuation handlers are executed. If none claims the signal, the previously installed signal handler is called. After the new signal handlers have been installed, the guarded signals are globally enabled for all threads of execution. Be aware that the handlers are installed with `SA_NODEFER` to avoid the need to perform an expensive syscall when a signal is handled. However this may also produce surprise e.g. infinite loops. \warning This class is threadsafe with respect to other concurrent executions of itself, but is NOT threadsafe with respect to other code modifying the global signal handlers. */ SIGNALGUARD_FUNC_DECL void *signal_guard_create(const sigset_t *guarded); /*! \brief Uninstall a previously installed signal guard. */ SIGNALGUARD_FUNC_DECL bool signal_guard_destroy(void *i); /*! \brief Create a global signal continuation decider. Threadsafe with respect to other calls of this function, but not reentrant i.e. modifying the global signal continuation decider registry whilst inside a global signal continuation decider is racy. Called after all thread local handling is exhausted. Note that what you can safely do in the decider function is extremely limited, only async signal safe functions may be called. \return An opaque pointer to the registered decider. `NULL` if `malloc` failed. \param guarded The set of signals to be guarded against. \param callfirst True if this decider should be called before any other. Otherwise call order is in the order of addition. \param decider A decider function, which must return `true` if execution is to resume, `false` if the next decider function should be called. \param value A user supplied value to set in the `raised_signal_info` passed to the decider callback. */ SIGNALGUARD_FUNC_DECL void *signal_guard_decider_create(const sigset_t *guarded, bool callfirst, thrd_signal_guard_decide_t decider, union raised_signal_info_value value); /*! \brief Destroy a global signal continuation decider. Threadsafe with respect to other calls of this function, but not reentrant i.e. do not call whilst inside a global signal continuation decider. \return True if recognised and thus removed. */ SIGNALGUARD_FUNC_DECL bool signal_guard_decider_destroy(void *decider); #if defined(__cplusplus) } #endif /**************************************** The C++ API ***************************************/ #if defined(__cplusplus) static_assert(std::is_trivial<raised_signal_info>::value, "raised_signal_info is not trivial!"); static_assert(std::is_trivially_copyable<raised_signal_info>::value, "raised_signal_info is not trivially copyable!"); static_assert(std::is_standard_layout<raised_signal_info>::value, "raised_signal_info does not have standard layout!"); QUICKCPPLIB_NAMESPACE_BEGIN //! \brief The namespace for signal_guard namespace signal_guard { using raised_signal_info = ::raised_signal_info; //! \brief The signals which are supported enum class signalc { none = 0, abort_process = SIGABRT, //!< The process is aborting (`SIGABRT`) undefined_memory_access = SIGBUS, //!< Attempt to access a memory location which can't exist (`SIGBUS`) illegal_instruction = SIGILL, //!< Execution of illegal instruction (`SIGILL`) interrupt = SIGINT, //!< The process is interrupted (`SIGINT`). Note on Windows the continuation decider is ALWAYS called from a separate thread, and the process exits after you return (or take too long executing). broken_pipe = SIGPIPE, //!< Reader on a pipe vanished (`SIGPIPE`). Note that Windows never raises this signal. segmentation_fault = SIGSEGV, //!< Attempt to access a memory page whose permissions disallow (`SIGSEGV`) floating_point_error = SIGFPE, //!< Floating point error (`SIGFPE`) process_terminate = SIGTERM, //!< Process termination requested (`SIGTERM`). Note on Windows the handler is ALWAYS called from a separate thread, and the process exits after you return (or take too long executing). #ifndef _WIN32 timer_expire = SIGALRM, //!< Timer has expired (`SIGALRM`). POSIX only. child_exit = SIGCHLD, //!< Child has exited (`SIGCHLD`). POSIX only. process_continue = SIGCONT, //!< Process is being continued (`SIGCONT`). POSIX only. tty_hangup = SIGHUP, //!< Controlling terminal has hung up (`SIGHUP`). POSIX only. process_kill = SIGKILL, //!< Process has received kill signal (`SIGKILL`). POSIX only. #ifdef SIGPOLL pollable_event = SIGPOLL, //!< i/o is now possible (`SIGPOLL`). POSIX only. #endif profile_event = SIGPROF, //!< Profiling timer expired (`SIGPROF`). POSIX only. process_quit = SIGQUIT, //!< Process is being quit (`SIGQUIT`). POSIX only. process_stop = SIGSTOP, //!< Process is being stopped (`SIGSTOP`). POSIX only. tty_stop = SIGTSTP, //!< Terminal requests stop (`SIGTSTP`). POSIX only. bad_system_call = SIGSYS, //!< Bad system call (`SIGSYS`). POSIX only. process_trap = SIGTRAP, //!< Process has reached a breakpoint (`SIGTRAP`). POSIX only. tty_input = SIGTTIN, //!< Terminal has input (`SIGTTIN`). POSIX only. tty_output = SIGTTOU, //!< Terminal ready for output (`SIGTTOU`). POSIX only. urgent_condition = SIGURG, //!< Urgent condition (`SIGURG`). POSIX only. user_defined1 = SIGUSR1, //!< User defined 1 (`SIGUSR1`). POSIX only. user_defined2 = SIGUSR2, //!< User defined 2 (`SIGUSR2`). POSIX only. virtual_alarm_clock = SIGVTALRM, //!< Virtual alarm clock (`SIGVTALRM`). POSIX only. cpu_time_limit_exceeded = SIGXCPU, //!< CPU time limit exceeded (`SIGXCPU`). POSIX only. file_size_limit_exceeded = SIGXFSZ, //!< File size limit exceeded (`SIGXFSZ`). POSIX only. #endif /* C++ handlers On all the systems I examined, all signal numbers are <= 30 in order to fit inside a sigset_t. Note that apparently IBM uses the full 32 bit range in its signal numbers. */ cxx_out_of_memory = 32, //!< A call to operator new failed, and a throw is about to occur cxx_termination = 33, //!< A call to std::terminate() was made. NOT `SIGTERM`. _max_value }; //! \brief Bitfield for the signals which are supported QUICKCPPLIB_BITFIELD_BEGIN_T(signalc_set, uint64_t){ none = 0, abort_process = (1ULL << static_cast<int>(signalc::abort_process)), //!< The process is aborting (`SIGABRT`) undefined_memory_access = (1ULL << static_cast<int>(signalc::undefined_memory_access)), //!< Attempt to access a memory location which can't exist (`SIGBUS`) illegal_instruction = (1ULL << static_cast<int>(signalc::illegal_instruction)), //!< Execution of illegal instruction (`SIGILL`) interrupt = (1ULL << static_cast<int>( signalc:: interrupt)), //!< The process is interrupted (`SIGINT`). Note on Windows the handler is ALWAYS called from a separate thread, and the process exits after you return (or take too long executing). broken_pipe = (1ULL << static_cast<int>(signalc::broken_pipe)), //!< Reader on a pipe vanished (`SIGPIPE`). Note that Windows never raises this signal. segmentation_fault = (1ULL << static_cast<int>(signalc::segmentation_fault)), //!< Attempt to access a memory page whose permissions disallow (`SIGSEGV`) floating_point_error = (1ULL << static_cast<int>(signalc::floating_point_error)), //!< Floating point error (`SIGFPE`) process_terminate = (1ULL << static_cast<int>( signalc:: process_terminate)), //!< Process termination requested (`SIGTERM`). Note on Windows the handler is ALWAYS called from a separate thread, and the process exits after you return (or take too long executing). #ifndef _WIN32 timer_expire = (1ULL << static_cast<int>(signalc::timer_expire)), //!< Timer has expired (`SIGALRM`). POSIX only. child_exit = (1ULL << static_cast<int>(signalc::child_exit)), //!< Child has exited (`SIGCHLD`). POSIX only. process_continue = (1ULL << static_cast<int>(signalc::process_continue)), //!< Process is being continued (`SIGCONT`). POSIX only. tty_hangup = (1ULL << static_cast<int>(signalc::tty_hangup)), //!< Controlling terminal has hung up (`SIGHUP`). POSIX only. process_kill = (1ULL << static_cast<int>(signalc::process_kill)), //!< Process has received kill signal (`SIGKILL`). POSIX only. #ifdef SIGPOLL pollable_event = (1ULL << static_cast<int>(signalc::pollable_event)), //!< i/o is now possible (`SIGPOLL`). POSIX only. #endif profile_event = (1ULL << static_cast<int>(signalc::profile_event)), //!< Profiling timer expired (`SIGPROF`). POSIX only. process_quit = (1ULL << static_cast<int>(signalc::process_quit)), //!< Process is being quit (`SIGQUIT`). POSIX only. process_stop = (1ULL << static_cast<int>(signalc::process_stop)), //!< Process is being stopped (`SIGSTOP`). POSIX only. tty_stop = (1ULL << static_cast<int>(signalc::tty_stop)), //!< Terminal requests stop (`SIGTSTP`). POSIX only. bad_system_call = (1ULL << static_cast<int>(signalc::bad_system_call)), //!< Bad system call (`SIGSYS`). POSIX only. process_trap = (1ULL << static_cast<int>(signalc::process_trap)), //!< Process has reached a breakpoint (`SIGTRAP`). POSIX only. tty_input = (1ULL << static_cast<int>(signalc::tty_input)), //!< Terminal has input (`SIGTTIN`). POSIX only. tty_output = (1ULL << static_cast<int>(signalc::tty_output)), //!< Terminal ready for output (`SIGTTOU`). POSIX only. urgent_condition = (1ULL << static_cast<int>(signalc::urgent_condition)), //!< Urgent condition (`SIGURG`). POSIX only. user_defined1 = (1ULL << static_cast<int>(signalc::user_defined1)), //!< User defined 1 (`SIGUSR1`). POSIX only. user_defined2 = (1ULL << static_cast<int>(signalc::user_defined2)), //!< User defined 2 (`SIGUSR2`). POSIX only. virtual_alarm_clock = (1ULL << static_cast<int>(signalc::virtual_alarm_clock)), //!< Virtual alarm clock (`SIGVTALRM`). POSIX only. cpu_time_limit_exceeded = (1ULL << static_cast<int>(signalc::cpu_time_limit_exceeded)), //!< CPU time limit exceeded (`SIGXCPU`). POSIX only. file_size_limit_exceeded = (1ULL << static_cast<int>(signalc::file_size_limit_exceeded)), //!< File size limit exceeded (`SIGXFSZ`). POSIX only. #endif // C++ handlers cxx_out_of_memory = (1ULL << static_cast<int>(signalc::cxx_out_of_memory)), //!< A call to operator new failed, and a throw is about to occur cxx_termination = (1ULL << static_cast<int>(signalc::cxx_termination)) //!< A call to std::terminate() was made } QUICKCPPLIB_BITFIELD_END(signalc_set) namespace detail { SIGNALGUARD_FUNC_DECL const char *signalc_to_string(signalc code) noexcept; extern inline std::atomic<signalc_set> &signal_guards_installed() { static std::atomic<signalc_set> v; return v; } } /*! \brief On platforms where it is necessary (POSIX), installs, and potentially enables, the global signal handlers for the signals specified by `guarded`. Each signal installed is threadsafe reference counted, so this is safe to call from multiple threads or instantiate multiple times. It is also guaranteed safe to call from within static data init or deinit, so a very common use case is simply to place an instance into global static data. This ensures that dynamically loaded and unloaded shared objects compose signal guards appropriately. On platforms with better than POSIX global signal support, this class does nothing. ## POSIX only Any existing global signal handlers are replaced with a filtering signal handler, which checks if the current kernel thread has installed a signal guard, and if so executes the guard. If no signal guard has been installed for the current kernel thread, global signal continuation handlers are executed. If none claims the signal, the previously installed signal handler is called. After the new signal handlers have been installed, the guarded signals are globally enabled for all threads of execution. Be aware that the handlers are installed with `SA_NODEFER` to avoid the need to perform an expensive syscall when a signal is handled. However this may also produce surprise e.g. infinite loops. \warning This class is threadsafe with respect to other concurrent executions of itself, but is NOT threadsafe with respect to other code modifying the global signal handlers. It is NOT async signal safe. */ class SIGNALGUARD_CLASS_DECL signal_guard_install { signalc_set _guarded; public: SIGNALGUARD_MEMFUNC_DECL explicit signal_guard_install(signalc_set guarded); SIGNALGUARD_MEMFUNC_DECL ~signal_guard_install(); signal_guard_install(const signal_guard_install &) = delete; signal_guard_install(signal_guard_install &&o) noexcept : _guarded(o._guarded) { o._guarded = signalc_set::none; } signal_guard_install &operator=(const signal_guard_install &) = delete; signal_guard_install &operator=(signal_guard_install &&o) noexcept { this->~signal_guard_install(); new(this) signal_guard_install(static_cast<signal_guard_install &&>(o)); return *this; } }; namespace detail { static inline bool signal_guard_global_decider_impl_indirect(raised_signal_info *rsi); class SIGNALGUARD_CLASS_DECL signal_guard_global_decider_impl { friend inline bool signal_guard_global_decider_impl_indirect(raised_signal_info *rsi); signal_guard_install _install; void *_p{nullptr}; virtual bool _call(raised_signal_info *) const noexcept = 0; public: SIGNALGUARD_MEMFUNC_DECL signal_guard_global_decider_impl(signalc_set guarded, bool callfirst); virtual SIGNALGUARD_MEMFUNC_DECL ~signal_guard_global_decider_impl(); signal_guard_global_decider_impl(const signal_guard_global_decider_impl &) = delete; SIGNALGUARD_MEMFUNC_DECL signal_guard_global_decider_impl(signal_guard_global_decider_impl &&o) noexcept; signal_guard_global_decider_impl &operator=(const signal_guard_global_decider_impl &) = delete; signal_guard_global_decider_impl &operator=(signal_guard_global_decider_impl &&) = delete; }; } // namespace detail /*! \brief Install a global signal continuation decider. This is threadsafe with respect to concurrent instantiations of this type, but not reentrant i.e. modifying the global signal continuation decider registry whilst inside a global signal continuation decider is racy. Callable is called after all thread local handling is exhausted. Note that what you can safely do in the decider callable is extremely limited, only async signal safe functions may be called. A `signal_guard_install` is always instanced for every global decider, and creating and destroying these is NOT async signal safe i.e. create and destroy these ONLY outside a signal handler. On POSIX only, a global signal continuation decider is ALWAYS installed for `signalc::timer_expire` (`SIGALRM`) in order to implement `signal_guard_watchdog`. Be aware that if any `signal_guard_watchdog` exist and their expiry times indicate that they have expired, the `SIGALRM` will be consumed. You may wish to install further global signal continuation deciders using `callfirst = true` if you wish to be called before any `signal_guard_watchdog` processing. Note also that if no `signal_guard_watchdog` expiry times have expired, then the default action for `SIGALRM` is taken. */ template <class T> class signal_guard_global_decider : public detail::signal_guard_global_decider_impl { T _f; virtual bool _call(raised_signal_info *rsi) const noexcept override final { return _f(rsi); } public: /*! \brief Constructs an instance. \param guarded The signal set for which this decider ought to be called. \param f A callable with prototype `bool(raised_signal_info *)`, which must return `true` if execution is to resume, `false` if the next decider function should be called. Note that on Windows only, `signalc::interrupt` and `signalc::process_terminate` call `f` from some other kernel thread, and the return value is always treated as `false`. \param callfirst True if this decider should be called before any other. Otherwise call order is in the order of addition. */ QUICKCPPLIB_TEMPLATE(class U) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(std::is_constructible<T, U>::value), QUICKCPPLIB_TEXPR(std::declval<U>()((raised_signal_info *) 0))) signal_guard_global_decider(signalc_set guarded, U &&f, bool callfirst) : detail::signal_guard_global_decider_impl(guarded, callfirst) , _f(static_cast<U &&>(f)) { } ~signal_guard_global_decider() = default; signal_guard_global_decider(const signal_guard_global_decider &) = delete; signal_guard_global_decider(signal_guard_global_decider &&o) noexcept = default; signal_guard_global_decider &operator=(const signal_guard_global_decider &) = delete; signal_guard_global_decider &operator=(signal_guard_global_decider &&o) noexcept { this->~signal_guard_global_decider(); new(this) signal_guard_global_decider(static_cast<signal_guard_global_decider &&>(o)); return *this; } }; //! \brief Convenience instantiator of `signal_guard_global_decider`. QUICKCPPLIB_TEMPLATE(class U) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TEXPR(std::declval<U>()((raised_signal_info *) 0))) inline signal_guard_global_decider<std::decay_t<U>> make_signal_guard_global_decider(signalc_set guarded, U &&f, bool callfirst = false) { return signal_guard_global_decider<std::decay_t<U>>(guarded, static_cast<U &&>(f), callfirst); } /*! \brief Call the currently installed signal handler for a signal (POSIX), or raise a Win32 structured exception (Windows), returning false if no handler was called due to the currently installed handler being `SIG_IGN` (POSIX). Note that on POSIX, we fetch the currently installed signal handler and try to call it directly. This allows us to supply custom `raw_info` and `raw_context`, and we do all the things which the signal handler flags tell us to do beforehand [1]. If the current handler has been defaulted, we enable the signal and execute `pthread_kill(pthread_self(), signo)` in order to invoke the default handling. Note that on Windows, `raw_context` is ignored as there is no way to override the context thrown with a Win32 structured exception. [1]: We currently do not implement alternative stack switching. If a handler requests that, we simply abort the process. Code donations implementing support are welcome. */ SIGNALGUARD_FUNC_DECL bool thrd_raise_signal(signalc signo, void *raw_info = nullptr, void *raw_context = nullptr); /*! \brief This initiates a fast fail process termination which immediately exits the process without calling any handlers: on POSIX, this is `SIGKILL`, on Windows this is `TerminateProcess()`. If `msg` is specified, it async signal safely prints that message before termination. If you don't specify a message (`nullptr`), a default message is printed. A message of `""` prints nothing. */ QUICKCPPLIB_NORETURN SIGNALGUARD_FUNC_DECL void terminate_process_immediately(const char *msg = nullptr) noexcept; namespace detail { struct invoke_terminate_process_immediately { void operator()() const noexcept { terminate_process_immediately("signal_guard_watchdog expired"); } }; class SIGNALGUARD_CLASS_DECL signal_guard_watchdog_impl { struct _signal_guard_watchdog_decider; friend struct watchdog_decider_t; #ifdef _WIN32 void *_threadh{nullptr}; #else void *_timerid{nullptr}; #endif signal_guard_watchdog_impl *_prev{nullptr}, *_next{nullptr}; uint64_t _deadline_ms{0}; bool _inuse{false}, _alreadycalled{false}; virtual void _call() const noexcept = 0; SIGNALGUARD_MEMFUNC_DECL void _detach() noexcept; public: SIGNALGUARD_MEMFUNC_DECL signal_guard_watchdog_impl(unsigned ms); virtual ~signal_guard_watchdog_impl() { if(_inuse) { try { release(); } catch(...) { } } } signal_guard_watchdog_impl(const signal_guard_watchdog_impl &) = delete; SIGNALGUARD_MEMFUNC_DECL signal_guard_watchdog_impl(signal_guard_watchdog_impl &&o) noexcept; signal_guard_watchdog_impl &operator=(const signal_guard_watchdog_impl &) = delete; signal_guard_watchdog_impl &operator=(signal_guard_watchdog_impl &&) = delete; SIGNALGUARD_MEMFUNC_DECL void release(); }; } // namespace detail /*! \brief Call an optional specified routine after a period of time, possibly on another thread. Async signal safe. In your signal handler, you may have no choice but to execute async signal unsafe code e.g. you absolutely must call `malloc()` because third party code does so and there is no way to not call that third party code. This can very often lead to hangs, whether due to infinite loops or getting deadlocked by locking an already locked mutex. This facility provides the ability to set a watchdog timer which will either call your specified routine or the default routine after a period of time after construction, unless it is released or destructed first. Your routine will be called via an async signal (`SIGALRM`) if on POSIX, or from a separate thread if on Windows. Therefore, if on Windows, a kernel thread will be launched on construction, and killed on destruction. On POSIX, a global signal continuation decider is ALWAYS installed at process init for `signalc::timer_expire` (`SIGALRM`) in order to implement `signal_guard_watchdog`, this is a filtering decider which only matches `signal_guard_watchdog` whose timers have expired, otherwise it passes on the signal to other handlers. If you don't specify a routine, the default routine is `terminate_process_immediately()` which performs a fast fail process termination. */ template <class T> class signal_guard_watchdog : public detail::signal_guard_watchdog_impl { T _f; virtual void _call() const noexcept override final { _f(); } public: /*! \brief Constructs an instance. \param f A callable with prototype `bool(raised_signal_info *)`, which must return `true` if execution is to resume, `false` if the next decider function should be called. Note that on Windows only, `signalc::interrupt` and `signalc::process_terminate` call `f` from some other kernel thread, and the return value is always treated as `false`. \param callfirst True if this decider should be called before any other. Otherwise call order is in the order of addition. */ QUICKCPPLIB_TEMPLATE(class U) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(std::is_constructible<T, U>::value), QUICKCPPLIB_TEXPR(std::declval<U>()())) signal_guard_watchdog(U &&f, unsigned ms) : detail::signal_guard_watchdog_impl(ms) , _f(static_cast<U &&>(f)) { } ~signal_guard_watchdog() = default; signal_guard_watchdog(const signal_guard_watchdog &) = delete; signal_guard_watchdog(signal_guard_watchdog &&o) noexcept = default; signal_guard_watchdog &operator=(const signal_guard_watchdog &) = delete; signal_guard_watchdog &operator=(signal_guard_watchdog &&o) noexcept { this->~signal_guard_watchdog(); new(this) signal_guard_watchdog(static_cast<signal_guard_watchdog &&>(o)); return *this; } }; //! \brief Convenience instantiator of `signal_guard_watchdog`. QUICKCPPLIB_TEMPLATE(class U) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TEXPR(std::declval<U>()())) inline signal_guard_watchdog<std::decay_t<U>> make_signal_guard_watchdog(U &&f, unsigned ms = 3000) { return signal_guard_watchdog<std::decay_t<U>>(static_cast<U &&>(f), ms); } //! \brief Convenience instantiator of `signal_guard_watchdog`. inline signal_guard_watchdog<detail::invoke_terminate_process_immediately> make_signal_guard_watchdog(unsigned ms = 3000) { return signal_guard_watchdog<detail::invoke_terminate_process_immediately>(detail::invoke_terminate_process_immediately(), ms); } //! \brief Thrown by the default signal handler to abort the current operation class signal_raised : public std::exception { signalc _code; public: //! Constructor signal_raised(signalc code) : _code(code) { } virtual const char *what() const noexcept override { return detail::signalc_to_string(_code); } }; namespace detail { struct thread_local_signal_guard; #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wattributes" #endif SIGNALGUARD_FUNC_DECL void push_thread_local_signal_handler(thread_local_signal_guard *) noexcept; SIGNALGUARD_FUNC_DECL void pop_thread_local_signal_handler(thread_local_signal_guard *) noexcept; SIGNALGUARD_FUNC_DECL thread_local_signal_guard *current_thread_local_signal_handler() noexcept; #ifdef __GNUC__ #pragma GCC diagnostic pop #endif struct thread_local_signal_guard { signalc_set guarded; raised_signal_info info; thread_local_signal_guard *previous{nullptr}; thread_local_signal_guard(signalc_set _guarded) : guarded(_guarded) { push_thread_local_signal_handler(this); } virtual ~thread_local_signal_guard() { pop_thread_local_signal_handler(this); } virtual bool call_continuer() = 0; }; #ifdef _WIN32 namespace win32 { struct _EXCEPTION_POINTERS; } SIGNALGUARD_FUNC_DECL long win32_exception_filter_function(unsigned long code, win32::_EXCEPTION_POINTERS *pts) noexcept; #endif template <class R> inline R throw_signal_raised(const raised_signal_info *i) { throw signal_raised(signalc(1ULL << i->signo)); } inline bool continue_or_handle(const raised_signal_info * /*unused*/) noexcept { return false; } template <class R, class V> struct is_constructible_or_void : std::is_constructible<R, V> { }; template <> struct is_constructible_or_void<void, void> : std::true_type { }; } // namespace detail #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 6 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wclobbered" #if __GNUC__ >= 7 #pragma GCC diagnostic ignored "-Wnoexcept-type" #endif #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4611) // interaction between setjmp() and C++ object destruction is non-portable #endif /*! Call a callable `f` with signals `guarded` protected for this thread only, returning whatever `f` or `h` returns. Firstly, how to restore execution to this context is saved, and `f(Args...)` is executed, returning whatever `f(Args...)` returns if `f` completes execution successfully. This is usually inlined code, so it will be quite fast. No memory allocation is performed if a `signal_guard_install` for the guarded signal set is already instanced. Approximate best case overhead: - Linux: 28 CPU cycles (Intel CPU), 53 CPU cycles (AMD CPU) - Windows: 36 CPU cycles (Intel CPU), 68 CPU cycles (AMD CPU) If during the execution of `f`, any one of the signals `guarded` is raised: 1. `c`, which must have the prototype `bool(raised_signal_info *)`, is called with the signal which was raised. You can fix the cause of the signal and return `true` to continue execution, or else return `false` to halt execution. Note that the variety of code you can call in `c` is extremely limited, the same restrictions as for signal handlers apply. Note that on Windows only, `signalc::interrupt` and `signalc::process_terminate` call `c` from some other kernel thread, and the return value is always ignored (the process is always exited). 2. If `c` returned `false`, the execution of `f` is halted **immediately** without stack unwind, the thread is returned to the state just before the calling of `f`, and the callable `g` is called with the specific signal which occurred. `g` must have the prototype `R(const raised_signal_info *)` where `R` is the return type of `f`. `g` is called with this signal guard removed, though a signal guard higher in the call chain may instead be active. Obviously all state which `f` may have been in the process of doing will be thrown away, in particular any stack allocated variables not marked `volatile` will have unspecified values. You should therefore make sure that `f` never causes side effects, including the interruption in the middle of some operation, which cannot be fixed by the calling of `h`. The default `h` simply throws a `signal_raised` C++ exception. \note On POSIX, if a `signal_guard_install` is not already instanced for the guarded set, one is temporarily installed, which is not quick. You are therefore very strongly recommended, when on POSIX, to call this function with a `signal_guard_install` already installed for all the signals you will ever guard. `signal_guard_install` is guaranteed to be composable and be safe to use within static data init, so a common use pattern is simply to place a guard install into your static data init. \note On MSVC because `std::set_terminate()` is thread local, we ALWAYS install our termination handler for every thread on creation and we never uninstall it. \note On MSVC, you cannot pass a type with a non-trivial destructor through `__try`, so this will limit the complexity of types that can be returned directly by this function. You can usually work around this via an intermediate `std::optional`. */ QUICKCPPLIB_TEMPLATE(class F, class H, class C, class... Args, class R = decltype(std::declval<F>()(std::declval<Args>()...))) QUICKCPPLIB_TREQUIRES( QUICKCPPLIB_TPRED(detail::is_constructible_or_void<R, decltype(std::declval<H>()(std::declval<const raised_signal_info *>()))>::value), // QUICKCPPLIB_TPRED(detail::is_constructible_or_void<bool, decltype(std::declval<C>()(std::declval<raised_signal_info *>()))>::value)) inline R signal_guard(signalc_set guarded, F &&f, H &&h, C &&c, Args &&...args) { if(guarded == signalc_set::none) { return f(static_cast<Args &&>(args)...); } struct signal_guard_installer final : detail::thread_local_signal_guard { char _storage[sizeof(signal_guard_install)]; signal_guard_install *sgi{nullptr}; C &continuer; signal_guard_installer(signalc_set guarded, C &c) : detail::thread_local_signal_guard(guarded) , continuer(c) { #ifndef _WIN32 uint64_t oldinstalled(detail::signal_guards_installed().load(std::memory_order_relaxed)); uint64_t newinstalled = oldinstalled | uint64_t(guarded); if(newinstalled != oldinstalled) { // Need a temporary signal guard install sgi = new(_storage) signal_guard_install(guarded); } #endif } ~signal_guard_installer() { reset(); } void reset() { #ifndef _WIN32 if(nullptr != sgi) { sgi->~signal_guard_install(); } #endif } bool call_continuer() override { return continuer(&this->info); } } sgi(guarded, c); // Nothing in the C++ standard says that the compiler cannot reorder reads and writes // around a setjmp(), so let's prevent that. This is the weak form affecting the // compiler reordering only. std::atomic_signal_fence(std::memory_order_seq_cst); if(setjmp(sgi.info.buf)) { // returning from longjmp, so unset the TLS and call failure handler sgi.reset(); return h(&sgi.info); } std::atomic_signal_fence(std::memory_order_seq_cst); #ifdef _WIN32 // Cannot use __try in a function with non-trivial destructors return [&] { __try { static_assert(std::is_trivially_destructible<R>::value || std::is_void<R>::value, "On MSVC, the return type of F must be trivially destructible, otherwise the compiler will refuse to compile the code."); return f(static_cast<Args &&>(args)...); } __except(detail::win32_exception_filter_function(_exception_code(), (struct detail::win32::_EXCEPTION_POINTERS *) _exception_info())) { longjmp(sgi.info.buf, 1); } }(); #else return f(static_cast<Args &&>(args)...); #endif } #ifdef _MSC_VER #pragma warning(pop) #endif #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 6 #pragma GCC diagnostic pop #endif //! \overload template <class F, class R = decltype(std::declval<F>()())> inline R signal_guard(signalc_set guarded, F &&f) { return signal_guard(guarded, static_cast<F &&>(f), detail::throw_signal_raised<R>, detail::continue_or_handle); } //! \overload QUICKCPPLIB_TEMPLATE(class F, class H, class R = decltype(std::declval<F>()())) QUICKCPPLIB_TREQUIRES(QUICKCPPLIB_TPRED(detail::is_constructible_or_void<R, decltype(std::declval<H>()(std::declval<const raised_signal_info *>()))>::value)) inline auto signal_guard(signalc_set guarded, F &&f, H &&h) { return signal_guard(guarded, static_cast<F &&>(f), static_cast<H &&>(h), detail::continue_or_handle); } } // namespace signal_guard QUICKCPPLIB_NAMESPACE_END #if(!defined(QUICKCPPLIB_HEADERS_ONLY) || QUICKCPPLIB_HEADERS_ONLY == 1) && !defined(DOXYGEN_SHOULD_SKIP_THIS) #define QUICKCPPLIB_INCLUDED_BY_HEADER 1 #include "detail/impl/signal_guard.ipp" #undef QUICKCPPLIB_INCLUDED_BY_HEADER #endif #endif #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/scope.hpp
/* scope support (C) 2019 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Apr 2019 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_SCOPE_HPP #define QUICKCPPLIB_SCOPE_HPP #include "config.hpp" #ifndef QUICKCPPLIB_USE_STD_SCOPE #if(__cplusplus >= 202000 || _HAS_CXX20) && __has_include(<scope>) #define QUICKCPPLIB_USE_STD_SCOPE 1 #else #define QUICKCPPLIB_USE_STD_SCOPE 0 #endif #endif #if QUICKCPPLIB_USE_STD_SCOPE #include <scope> #else #include <type_traits> #include <utility> #endif #include <exception> QUICKCPPLIB_NAMESPACE_BEGIN namespace scope { #if QUICKCPPLIB_USE_STD_SCOPE template <class T> using scope_exit = std::scope_exit<T>; template <class T> using scope_fail = std::scope_fail<T>; template <class T> using scope_success = std::scope_success<T>; #else namespace detail { template <class T, bool v = noexcept(std::declval<T>()())> constexpr inline bool _is_nothrow_invocable(int) noexcept { return v; } template <class T> constexpr inline bool _is_nothrow_invocable(...) noexcept { return false; } template <class T> constexpr inline bool is_nothrow_invocable() noexcept { return _is_nothrow_invocable<typename std::decay<T>::type>(5); } enum class scope_impl_kind { exit, fail, success }; template <class EF, scope_impl_kind kind> class scope_impl { EF _f; bool _released{false}; #if __cplusplus >= 201700 || _HAS_CXX17 int _uncaught_exceptions; #endif public: scope_impl() = delete; scope_impl(const scope_impl &) = delete; scope_impl &operator=(const scope_impl &) = delete; scope_impl &operator=(scope_impl &&) = delete; constexpr scope_impl(scope_impl &&o) noexcept(std::is_nothrow_move_constructible<EF>::value) : _f(static_cast<EF &&>(o._f)) , _released(o._released) #if __cplusplus >= 201700 || _HAS_CXX17 , _uncaught_exceptions(o._uncaught_exceptions) #endif { o._released = true; } template <class T, typename = decltype(std::declval<T>()()), typename std::enable_if<!std::is_same<scope_impl, typename std::decay<T>::type>::value // && std::is_constructible<EF, T>::value // && (scope_impl_kind::success == kind || is_nothrow_invocable<T>()) // , bool>::type = true> explicit constexpr scope_impl(T &&f) noexcept(std::is_nothrow_constructible<EF, T>::value) : _f(static_cast<T &&>(f)) #if __cplusplus >= 201700 || _HAS_CXX17 , _uncaught_exceptions(std::uncaught_exceptions()) #endif { } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) // conditional expression is constant #endif ~scope_impl() { if(!_released) { if(scope_impl_kind::exit == kind) { _f(); return; } #if __cplusplus >= 201700 || _HAS_CXX17 bool unwind_is_due_to_throw = (std::uncaught_exceptions() > _uncaught_exceptions); #else bool unwind_is_due_to_throw = std::uncaught_exception(); #endif if(scope_impl_kind::fail == kind && unwind_is_due_to_throw) { _f(); return; } if(scope_impl_kind::success == kind && !unwind_is_due_to_throw) { _f(); return; } } } #ifdef _MSC_VER #pragma warning(pop) #endif constexpr void release() noexcept { _released = true; } }; } // namespace detail template <class T> using scope_exit = detail::scope_impl<T, detail::scope_impl_kind::exit>; template <class T> using scope_fail = detail::scope_impl<T, detail::scope_impl_kind::fail>; template <class T> using scope_success = detail::scope_impl<T, detail::scope_impl_kind::success>; template <class T // #ifndef _MSC_VER , typename = decltype(std::declval<T>()()), // MSVC chokes on these constraints here yet is typename std::enable_if<detail::is_nothrow_invocable<T>(), bool>::type // perfectly fine with them on the // constructor above :( = true #endif > constexpr inline auto make_scope_exit(T &&v) { return scope_exit<typename std::decay<T>::type>(static_cast<T &&>(v)); } template <class T // #ifndef _MSC_VER , typename = decltype(std::declval<T>()()), // typename std::enable_if<detail::is_nothrow_invocable<T>(), bool>::type // = true #endif > constexpr inline auto make_scope_fail(T &&v) { return scope_fail<typename std::decay<T>::type>(static_cast<T &&>(v)); } template <class T // #ifndef _MSC_VER , typename = decltype(std::declval<T>()()) #endif > constexpr inline auto make_scope_success(T &&v) { return scope_success<typename std::decay<T>::type>(static_cast<T &&>(v)); } #endif } // namespace scope QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include
repos/outcome/test/quickcpplib/include/quickcpplib/packed_backtrace.hpp
/* Space packed stack backtrace (C) 2017 Niall Douglas <http://www.nedproductions.biz/> (21 commits) File Created: Jun 2017 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_PACKED_BACKTRACE_HPP #define QUICKCPPLIB_PACKED_BACKTRACE_HPP #include "config.hpp" #include "span.hpp" #include <cstddef> // for ptrdiff_t etc #include <cstdint> // for uint32_t etc #include <cstdlib> // for abort() #include <cstring> // for memset QUICKCPPLIB_NAMESPACE_BEGIN namespace packed_backtrace { namespace detail { template <class T> struct constify { using type = const T; }; template <class T> struct constify<T *> { using type = const T *; }; } namespace impl { template <class FramePtrType, size_t FrameTypeSize> class packed_backtrace #ifndef DOXYGEN_IS_IN_THE_HOUSE { using storage_type = span::span<FramePtrType>; storage_type _storage; protected: explicit packed_backtrace(span::span<const char> storage) : _storage(reinterpret_cast<FramePtrType *>(const_cast<char *>(storage.data())), storage.size() / sizeof(FramePtrType)) { } explicit packed_backtrace(span::span<char> storage, std::nullptr_t) : _storage(reinterpret_cast<FramePtrType *>(storage.data()), storage.size() / sizeof(FramePtrType)) { } public: //! The type stored in the container using value_type = typename storage_type::element_type; //! The const type stored in the container using const_value_type = typename detail::constify<typename storage_type::element_type>::type; //! The size type using size_type = size_t; //! The difference type using difference_type = typename storage_type::difference_type; //! The reference type using reference = typename storage_type::reference; //! The const reference type using const_reference = typename storage_type::const_reference; //! The pointer type using pointer = typename storage_type::pointer; //! The const pointer type using const_pointer = typename storage_type::const_pointer; //! The iterator type using iterator = typename storage_type::iterator; //! The const iterator type using const_iterator = decltype(std::cbegin(std::declval<const storage_type>())); //! The reverse iterator type using reverse_iterator = typename storage_type::reverse_iterator; //! The const reverse iterator type using const_reverse_iterator = decltype(std::crbegin(std::declval<const storage_type>())); //! Returns true if the index is empty bool empty() const noexcept { return _storage.empty(); } //! Returns the number of items in the backtrace size_type size() const noexcept { return _storage.size(); } //! Returns the maximum number of items in the backtrace size_type max_size() const noexcept { return _storage.size(); } //! Returns an iterator to the first item in the backtrace. iterator begin() noexcept { return _storage.begin(); } //! Returns an iterator to the first item in the backtrace. const_iterator begin() const noexcept { return _storage.begin(); } //! Returns an iterator to the first item in the backtrace. const_iterator cbegin() const noexcept { return begin(); } //! Returns an iterator to the item after the last in the backtrace. iterator end() noexcept { return _storage.end(); } //! Returns an iterator to the item after the last in the backtrace. const_iterator end() const noexcept { return _storage.end(); } //! Returns an iterator to the item after the last in the backtrace. const_iterator cend() const noexcept { return end(); } //! Returns the specified element, unchecked. value_type operator[](size_type idx) const noexcept { return _storage[idx]; } //! Returns the specified element, checked. value_type at(size_type idx) const { return _storage.at(idx); } //! Swaps with another instance void swap(packed_backtrace &o) noexcept { _storage.swap(o._storage); } //! Assigns a raw stack backtrace to the packed storage void assign(span::span<const_value_type> input) noexcept { memcpy(_storage.data(), input.data(), _storage.size_bytes()); } }; template <class FramePtrType> class packed_backtrace<FramePtrType, 8> #endif { using storage_type = span::span<uint8_t>; using uintptr_type = std::conditional_t<sizeof(uintptr_t) >= 8, uintptr_t, uint64_t>; static constexpr uintptr_type bits63_43 = ~((1ULL << 43) - 1); static constexpr uintptr_type bit20 = (1ULL << 20); static constexpr uintptr_type bits20_0 = ((1ULL << 21) - 1); static constexpr uintptr_type bits42_21 = ~(bits63_43 | bits20_0); static constexpr uintptr_type bits42_0 = ((1ULL << 43) - 1); storage_type _storage; size_t _count; // number of decoded items template <size_t signbit> static intptr_t _sign_extend(uintptr_type x) noexcept { #if 1 const size_t m = (63 - signbit); intptr_t v = static_cast<intptr_t>(x << m); return v >> m; #else uintptr_type m = 1ULL << signbit; uintptr_type y = (x ^ m) - m; return static_cast<intptr_t>(y); #endif } bool _decode(uintptr_type &out, size_t &idx) const noexcept { bool first = true; for(;;) { if(idx >= _storage.size()) return false; uint8_t t = _storage[idx++]; switch(t >> 6) { case 3: { if(idx > _storage.size() - 3) // 22 bit payload return false; // Replace bits 63-43, keeping bits 42-0 out &= bits42_0; out |= ((uintptr_type)(t & 0x3f) << 59); out |= (uintptr_type) _storage[idx++] << 51; out |= (uintptr_type) _storage[idx++] << 43; break; } case 2: { if(idx > _storage.size() - 3) // 22 bit payload return false; // Replace bits 42-21, setting bit 20, zeroing 19-0, keeping bits 63-43 out &= bits63_43; out |= bit20; out |= ((uintptr_type)(t & 0x3f) << 37); out |= (uintptr_type) _storage[idx++] << 29; out |= (uintptr_type) _storage[idx++] << 21; break; } case 1: { if(idx > _storage.size() - 3) // 22 bit payload return false; // Offset bits 21-0 uintptr_type offset = ((uintptr_type)(t & 0x3f) << 16); offset |= (uintptr_type) _storage[idx++] << 8; offset |= (uintptr_type) _storage[idx++] << 0; out += _sign_extend<21>(offset); return true; } case 0: { if(idx > _storage.size() - 2) // 14 bit payload return false; if(first && !t) { // If he's all bits zero from now until end of storage, we are done bool done = true; for(size_t _idx = idx; _idx < _storage.size(); ++_idx) { if(_storage[_idx] != 0) { done = false; break; } } if(done) return false; } // Offset bits 13-0 uintptr_type offset = ((uintptr_type)(t & 0x3f) << 8); offset |= (uintptr_type) _storage[idx++] << 0; out += _sign_extend<13>(offset); return true; } } first = false; } } size_t _decode_count() const noexcept { uintptr_type out = 0; size_t idx = 0, ret = 0; while(_decode(out, idx)) { ++ret; } return ret; } protected: explicit packed_backtrace(span::span<const char> storage) : _storage(reinterpret_cast<uint8_t *>(const_cast<char *>(storage.data())), storage.size()) , _count(_decode_count()) { } explicit packed_backtrace(span::span<char> storage, std::nullptr_t) : _storage(reinterpret_cast<uint8_t *>(storage.data()), storage.size()) , _count(0) { } public: //! The type stored in the container using value_type = FramePtrType; //! The const type stored in the container using const_value_type = typename detail::constify<FramePtrType>::type; //! The size type using size_type = size_t; //! The difference type using difference_type = ptrdiff_t; //! The reference type using reference = FramePtrType; //! The const reference type using const_reference = const FramePtrType; //! The pointer type using pointer = FramePtrType *; //! The const pointer type using const_pointer = const FramePtrType *; //! The iterator type class iterator { friend class packed_backtrace; public: using iterator_category = std::forward_iterator_tag; using value_type = typename packed_backtrace::value_type; using difference_type = typename packed_backtrace::difference_type; using pointer = typename packed_backtrace::pointer; using reference = typename packed_backtrace::reference; private: packed_backtrace *_parent; size_t _idx; value_type _v; iterator &_inc() noexcept { if(_parent) { uintptr_type v = reinterpret_cast<uintptr_type>(_v); if(_parent->_decode(v, _idx)) _v = reinterpret_cast<value_type>(v); else { _parent = nullptr; _idx = (size_t) -1; _v = nullptr; } } return *this; } iterator(packed_backtrace *parent) noexcept : _parent(parent), _idx(0), _v(nullptr) { _inc(); } public: constexpr iterator() noexcept : _parent(nullptr), _idx((size_t) -1), _v(nullptr) {} iterator(const iterator &) = default; iterator(iterator &&) noexcept = default; iterator &operator=(const iterator &) = default; iterator &operator=(iterator &&) noexcept = default; void swap(iterator &o) noexcept { std::swap(_parent, o._parent); std::swap(_idx, o._idx); std::swap(_v, o._v); } bool operator==(const iterator &o) const noexcept { return _parent == o._parent && _idx == o._idx; } bool operator!=(const iterator &o) const noexcept { return _parent != o._parent || _idx != o._idx; } value_type operator*() noexcept { if(!_parent) { abort(); } return _v; } const value_type operator*() const noexcept { if(!_parent) { abort(); } return _v; } iterator &operator++() noexcept { return _inc(); } iterator operator++(int) noexcept { iterator ret(*this); ++*this; return ret; } bool operator<(const iterator &o) const noexcept { if(!_parent && !o._parent) return false; if(!_parent && o._parent) return true; if(_parent && !o._parent) return false; return _idx < o._idx; } bool operator>(const iterator &o) const noexcept { if(!_parent && !o._parent) return false; if(!_parent && o._parent) return false; if(_parent && !o._parent) return true; return _idx > o._idx; } bool operator<=(const iterator &o) const noexcept { return !(o > *this); } bool operator>=(const iterator &o) const noexcept { return !(o < *this); } }; friend class iterator; //! The const iterator type using const_iterator = iterator; //! The reverse iterator type using reverse_iterator = std::reverse_iterator<iterator>; //! The const reverse iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; //! Returns true if the index is empty bool empty() const noexcept { return _storage.empty(); } //! Returns the number of items in the backtrace size_type size() const noexcept { return _count; } //! Returns the maximum number of items in the backtrace size_type max_size() const noexcept { return _count; } //! Returns an iterator to the first item in the backtrace. iterator begin() noexcept { return iterator(this); } //! Returns an iterator to the first item in the backtrace. const_iterator begin() const noexcept { return iterator(this); } //! Returns an iterator to the first item in the backtrace. const_iterator cbegin() const noexcept { return iterator(this); } //! Returns an iterator to the item after the last in the backtrace. iterator end() noexcept { return iterator(); } //! Returns an iterator to the item after the last in the backtrace. const_iterator end() const noexcept { return iterator(); } //! Returns an iterator to the item after the last in the backtrace. const_iterator cend() const noexcept { return iterator(); } //! Returns the specified element, unchecked. value_type operator[](size_type i) const noexcept { uintptr_type out = 0; size_t idx = 0; for(size_type n = 0; n <= i; n++) { if(!_decode(out, idx)) return nullptr; } return reinterpret_cast<value_type>(out); } //! Returns the specified element, checked. value_type at(size_type i) const { uintptr_type out = 0; size_t idx = 0; for(size_type n = 0; n <= i; n++) { if(!_decode(out, idx)) { abort(); // out of range } } return reinterpret_cast<value_type>(out); } //! Swaps with another instance void swap(packed_backtrace &o) noexcept { using std::swap; swap(_storage, o._storage); swap(_count, o._count); } //! Assigns a raw stack backtrace to the packed storage void assign(span::span<const_value_type> input) noexcept { uintptr_type out = 0; size_t idx = 0; memset(_storage.data(), 0, _storage.size()); _count = 0; for(const auto &_i : input) { size_t startidx = idx; uintptr_type i = reinterpret_cast<uintptr_type>(_i); uintptr_type delta = i & bits63_43; if((out & bits63_43) != delta) { if(idx > _storage.size() - 3) return; // std::cout << "For entry " << _i << " encoding bits 63-43: " << (void *) delta << std::endl; _storage[idx++] = 0xc0 | ((delta >> 59) & 0x3f); _storage[idx++] = (delta >> 51) & 0xff; _storage[idx++] = (delta >> 43) & 0xff; out &= bits42_0; out |= delta; } delta = i & bits42_21; if((out & bits42_21) != delta) { if(idx > _storage.size() - 3) { memset(_storage.data() + startidx, 0, idx - startidx); return; } // std::cout << "For entry " << _i << " encoding bits 42-21: " << (void *) delta << std::endl; _storage[idx++] = 0x80 | ((delta >> 37) & 0x3f); _storage[idx++] = (delta >> 29) & 0xff; _storage[idx++] = (delta >> 21) & 0xff; out &= bits63_43; out |= bit20; out |= delta; } if(i - out >= (1 << 13) && out - i >= (1 << 13)) { if(idx > _storage.size() - 3) { memset(_storage.data() + startidx, 0, idx - startidx); return; } delta = static_cast<uintptr_type>(i - out); // std::cout << "For entry " << _i << " with diff " << (intptr_t) delta << " encoding three byte delta: " << (void *) delta << std::endl; _storage[idx++] = 0x40 | ((delta >> 16) & 0x3f); _storage[idx++] = (delta >> 8) & 0xff; _storage[idx++] = (delta >> 0) & 0xff; out = i; } else { if(idx > _storage.size() - 2) { memset(_storage.data() + startidx, 0, idx - startidx); return; } delta = static_cast<uintptr_type>(i - out); // std::cout << "For entry " << _i << " with diff " << (intptr_t) delta << " encoding two byte delta: " << (void *) delta << std::endl; _storage[idx++] = (delta >> 8) & 0x3f; _storage[idx++] = (delta >> 0) & 0xff; out = i; } _count++; } } }; } /*! \class packed_backtrace \brief A space packed stack backtrace letting you store twice or more stack frames in the same space. \tparam FramePtrType The type each stack backtrace frame ought to be represented as. \note Use `make_packed_backtrace()` to create one of these from a raw backtrace. Construct an instance on a byte span to load in the packed data so you can parse it. 64 bit address stack backtraces tend to waste a lot of storage which can be a problem when storing lengthy backtraces. Most 64 bit architectures only use the first 43 bits of address space wasting 2.5 bytes per entry, plus stack backtraces tend to be within a few megabytes and even kilobytes from one another. Intelligently packing the bits based on this knowledge can double or more the number of items you can store for a given number of bytes with virtually no runtime overhead, unlike compression. On 32 bit architectures this class simply stores the stack normally, but otherwise works the same. Performance: - GCC 7.1 on x64 3.1Ghz Skylake: Can construct and read 106188139 packed stacktraces/sec - VS2017 on x64 3.1Ghz Skylake: Can construct and read 79755133 packed stacktraces/sec The 64-bit coding scheme is quite straightforward: - Top bits are 11 when it's bits 63-43 of a 64 bit absolute address (3 bytes) - Top bits are 10 when it's bits 42-21 of a 64 bit absolute address (3 bytes) - Note that this resets bits 20-0 to 0x100000 (bit 20 set, bits 19-0 cleared) - Top bits are 01 when it's a 22 bit offset from previous (3 bytes) (+- 0x40`0000, 4Mb) - Top bits are 00 when it's a 14 bit offset from previous (2 bytes) (+- 0x4000, 16Kb) - Potential improvement: 12 to 18 items in 40 bytes instead of 5 items Sample 1: ~~~ 0000`07fe`fd4e`10ac - 6 bytes 0000`07fe`f48b`ffc7 - 3 bytes 0000`07fe`f48b`ff70 - 2 bytes 0000`07fe`f48b`fe23 - 2 bytes 0000`07fe`f48d`51d8 - 3 bytes 0000`07fe`f499`5249 - 3 bytes 0000`07fe`f48a`ef28 - 3 bytes 0000`07fe`f48a`ecc9 - 2 bytes 0000`07fe`f071`244c - 6 bytes 0000`07fe`f071`11b5 - 2 bytes 0000`07ff`0015`0acf - 6 bytes 0000`07ff`0015`098c - 2 bytes (40 bytes, 12 items, usually 96 bytes, 58% reduction) ~~~ Sample 2: ~~~ 0000003d06e34950 - 6 bytes 0000000000400bcd - 6 bytes 0000000000400bf5 - 2 bytes 0000003d06e1ffe0 - 6 bytes 00000000004009f9 - 6 bytes (26 bytes, 5 items, usually 40 bytes, 35% reduction) ~~~ */ template <class FramePtrType = void *> class packed_backtrace : public impl::packed_backtrace<FramePtrType, sizeof(FramePtrType)> { using base = impl::packed_backtrace<FramePtrType, sizeof(FramePtrType)>; public: //! \brief Construct a packed backtrace view, parsing the given byte storage explicit packed_backtrace(span::span<const char> storage) : base(storage) { } //! \brief Construct a packed backtrace view, not parsing the given byte storage explicit packed_backtrace(span::span<char> storage, std::nullptr_t) : base(storage, nullptr) { } //! \brief Default copy constructor packed_backtrace(const packed_backtrace &) = default; //! \brief Default move constructor packed_backtrace(packed_backtrace &&) = default; //! \brief Default copy assignment packed_backtrace &operator=(const packed_backtrace &) = default; //! \brief Default move assignment packed_backtrace &operator=(packed_backtrace &&) = default; }; //! \brief Pack a stack backtrace into byte storage inline packed_backtrace<void *> make_packed_backtrace(span::span<char> output, span::span<const void *> input) { packed_backtrace<void *> ret(output, nullptr); ret.assign(input); return ret; } } QUICKCPPLIB_NAMESPACE_END #endif
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/byte/CMakeLists.txt
# Copyright 2017-2019 by Martin Moene # # https://github.com/martinmoene/byte-lite # # 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) cmake_minimum_required( VERSION 3.5 FATAL_ERROR ) # byte-lite project and version, updated by script/update-version.py: project( byte_lite VERSION 0.3.0 # DESCRIPTION "A C++17-like byte type for C++98, C++11 and later in a single-file header-only library" # HOMEPAGE_URL "https://github.com/martinmoene/byte-lite" LANGUAGES CXX ) # Package information: set( unit_name "byte" ) set( package_nspace "nonstd" ) set( package_name "${unit_name}-lite" ) set( package_version "${${PROJECT_NAME}_VERSION}" ) message( STATUS "Project '${PROJECT_NAME}', package '${package_name}' version: '${package_version}'") # Toplevel or subproject: if ( CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME ) set( byte_IS_TOPLEVEL_PROJECT TRUE ) else() set( byte_IS_TOPLEVEL_PROJECT FALSE ) endif() # If toplevel project, enable building and performing of tests, disable building of examples: option( BYTE_LITE_OPT_BUILD_TESTS "Build and perform byte-lite tests" ${byte_IS_TOPLEVEL_PROJECT} ) option( BYTE_LITE_OPT_BUILD_EXAMPLES "Build byte-lite examples" OFF ) option( BYTE_LITE_OPT_SELECT_STD "Select std::byte" OFF ) option( BYTE_LITE_OPT_SELECT_NONSTD "Select nonstd::byte" OFF ) # If requested, build and perform tests, build examples: if ( BYTE_LITE_OPT_BUILD_TESTS ) enable_testing() add_subdirectory( test ) endif() if ( BYTE_LITE_OPT_BUILD_EXAMPLES ) add_subdirectory( example ) endif() # # Interface, installation and packaging # # CMake helpers: include( GNUInstallDirs ) include( CMakePackageConfigHelpers ) # Interface library: add_library( ${package_name} INTERFACE ) add_library( ${package_nspace}::${package_name} ALIAS ${package_name} ) target_include_directories( ${package_name} INTERFACE "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>" "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>" ) # Package configuration: # Note: package_name and package_target are used in package_config_in set( package_folder "${package_name}" ) set( package_target "${package_name}-targets" ) set( package_config "${package_name}-config.cmake" ) set( package_config_in "${package_name}-config.cmake.in" ) set( package_config_version "${package_name}-config-version.cmake" ) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/${package_config_in}" "${CMAKE_CURRENT_BINARY_DIR}/${package_config}" INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}" ) configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/${package_config_version}.in" "${CMAKE_CURRENT_BINARY_DIR}/${package_config_version}" @ONLY ) # Installation: install( TARGETS ${package_name} EXPORT ${package_target} # INCLUDES DESTINATION "${...}" # already set via target_include_directories() ) install( EXPORT ${package_target} NAMESPACE ${package_nspace}:: DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}" ) install( FILES "${CMAKE_CURRENT_BINARY_DIR}/${package_config}" "${CMAKE_CURRENT_BINARY_DIR}/${package_config_version}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}" ) install( DIRECTORY "include/" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) export( EXPORT ${package_target} NAMESPACE ${package_nspace}:: FILE "${CMAKE_CURRENT_BINARY_DIR}/${package_name}-targets.cmake" ) # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/byte/LICENSE.txt
Boost Software License - Version 1.0 - August 17th, 2003 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: 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. 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.
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/byte/README.md
# byte lite: A single-file header-only C++17-like byte type for C++98, C++11 and later [![Language](https://img.shields.io/badge/C%2B%2B-98/11/14/17-blue.svg)](https://en.wikipedia.org/wiki/C%2B%2B#Standardization) [![License](https://img.shields.io/badge/license-BSL-blue.svg)](https://opensource.org/licenses/BSL-1.0) [![Build Status](https://travis-ci.org/martinmoene/byte-lite.svg?branch=master)](https://travis-ci.org/martinmoene/byte-lite) [![Build status](https://ci.appveyor.com/api/projects/status/gpmw4gt271itoy2n?svg=true)](https://ci.appveyor.com/project/martinmoene/byte-lite) [![Version](https://badge.fury.io/gh/martinmoene%2Fbyte-lite.svg)](https://github.com/martinmoene/byte-lite/releases) [![download](https://img.shields.io/badge/latest-download-blue.svg)](https://raw.githubusercontent.com/martinmoene/byte-lite/master/include/nonstd/byte.hpp) [![Conan](https://img.shields.io/badge/on-conan-blue.svg)](https://conan.io/center/byte-lite) [![Try it online](https://img.shields.io/badge/on-wandbox-blue.svg)](https://wandbox.org/permlink/6wTFn0svYP4dQYhV) [![Try it on godbolt online](https://img.shields.io/badge/on-godbolt-blue.svg)](https://godbolt.org/z/xjekHR) **Contents** - [Example usage](#example-usage) - [In a nutshell](#in-a-nutshell) - [License](#license) - [Dependencies](#dependencies) - [Installation](#installation) - [Synopsis](#synopsis) - [Features](#features) - [Reported to work with](#reported-to-work-with) - [Building the tests](#building-the-tests) - [Other implementations of byte](#other-implementations-of-byte) - [Notes and references](#notes-and-references) - [Appendix](#appendix) Example usage ------------- ```Cpp #include "nonstd/byte.hpp" #include <cassert> using namespace nonstd; int main() { byte b1 = to_byte( 0x5a ); // to_byte() is non-standard, needed for pre-C++17 byte b2 = to_byte( 0xa5 ); byte r1 = b1 ^ b2; assert( 0xff == to_integer( r1 ) ); // not (yet) standard, needs C++11 byte r2 = b1 ^ b2; assert( 0xff == to_integer<unsigned int>( r2 ) ); } ``` ### Compile and run ``` prompt> g++ -std=c++11 -Wall -I../include -o 01-basic 01-basic.cpp && 01-basic ``` Or to run with [Buck](https://buckbuild.com/): ``` prompt> buck run example:01-basic ``` In a nutshell ------------- **byte lite** is a single-file header-only library to provide a [C++17-like distinct byte type](http://en.cppreference.com/w/cpp/types/byte) for use with C++98 and later. **Features and properties of byte lite** are are ease of installation (single header), freedom of dependencies other than the standard library. **A limitation of byte lite** is that you need to use function `to_byte(v)` to construct a `byte` from an intergal value `v`, when C++17's relaxation of the enum value construction rule is not available. License ------- *byte lite* is distributed under the [Boost Software License](https://github.com/martinmoene/XXXX-lite/blob/master/LICENSE.txt). Dependencies ------------ *byte lite* has no other dependencies than the [C++ standard library](http://en.cppreference.com/w/cpp/header). Installation ------------ *byte lite* is a single-file header-only library. Put `byte.hpp` in the [include](include) folder directly into the project source tree or somewhere reachable from your project. Synopsis -------- **Contents** - [Types in namespace nonstd](#types-in-namespace-nonstd) - [Algorithms for *byte lite*](#algorithms-for-byte-lite) - [Configuration macros](#configuration-macros) ### Types in namespace nonstd | Purpose | Type | Std | Notes | |--------------------|:--------------------|:-------:|:-------| | Distinct byte type | enum class **byte** | >=C++17 | &nbsp; | | &nbsp; | struct **byte** | < C++17 | &nbsp; | ### Algorithms for *byte lite* | Kind | Std | Function | Result | |-------------------|:-------:|----------|--------| | Shift-assign | &nbsp; | template< class IntegerType ><br>constexpr byte & **operator<<=**( byte & b, IntegerType shift ) noexcept | left-shifted b | | &nbsp; | &nbsp; | template< class IntegerType ><br>constexpr byte & **operator>>=**( byte & b, IntegerType shift ) noexcept | right-shifted b | | Shift | &nbsp; | template< class IntegerType ><br>constexpr byte **operator<<**( byte b, IntegerType shift ) noexcept | left-shifted byte | | &nbsp; | &nbsp; | template< class IntegerType ><br>constexpr byte **operator>>**( byte b, IntegerType shift ) noexcept | right-shifted byte | | Bitwise-op-assign | &nbsp; | template< class IntegerType ><br>constexpr byte & **operator&#166;=**( byte & l, byte r ) noexcept | bitwise-or-ed b | | &nbsp; | &nbsp; | template< class IntegerType ><br>constexpr byte & **operator&amp;=**( byte & l, byte r ) noexcept | bitwise-xor-ed b | | &nbsp; | &nbsp; | template< class IntegerType ><br>constexpr byte & **operator&Hat;=**( byte & l, byte r ) noexcept | bitwise-and-ed b | | Bitwise-op | &nbsp; | template< class IntegerType ><br>constexpr byte & **operator&#166;**( byte l, byte r ) noexcept | bitwise-or-ed byte | | &nbsp; | &nbsp; | template< class IntegerType ><br>constexpr byte & **operator&amp;**( byte l, byte r ) noexcept | bitwise-xor-ed byte | | &nbsp; | &nbsp; | template< class IntegerType ><br>constexpr byte & **operator&Hat;**( byte l, byte r ) noexcept | bitwise-and-ed byte| | Conversion | non-std | template< class IntegerType ><br>constexpr byte **to_byte**( IntegerType v ) | byte with value v| | &nbsp; | >=C++11 | template< class IntegerType = *underlying-type* ><br>constexpr IntegerType **to_integer**( byte b ) | byte's value, note&nbsp;2,&nbsp;3| | &nbsp; | < C++11 | template< class IntegerType ><br>constexpr IntegerType **to_integer**( byte b ) | byte's value, note&nbsp;3 | **Note 1**: the algrithms use an extra level of casting to prevent undefined behaviour, as mentioned by Thomas Köppe on mailing list isocpp-lib, subject "std::byte operations are hard to use correctly", on 16 March 2017. **Note 2**: default template parameter as suggested by Zhihao Yuan on mailing list isocpp-lib, subject "std::byte to_integer<>", on 10 March 2017. **Note 3**: use `to_integer()` to compute a byte's hash value. ### Configuration macros #### Standard selection macro \-D<b>byte\_CPLUSPLUS</b>=199711L Define this macro to override the auto-detection of the supported C++ standard, if your compiler does not set the `__cpluplus` macro correctly. #### Select `std::byte` or `nonstd::byte` At default, *byte lite* uses `std::byte` if it is available and lets you use it via namespace `nonstd`. You can however override this default and explicitly request to use `std::byte` or byte lite's `nonstd::byte` as `nonstd::byte` via the following macros. -D<b>byte\_CONFIG\_SELECT\_BYTE</b>=byte_BYTE_DEFAULT Define this to `byte_BYTE_STD` to select `std::byte` as `nonstd::byte`. Define this to `byte_BYTE_NONSTD` to select `nonstd::byte` as `nonstd::byte`. Default is undefined, which has the same effect as defining to `byte_BYTE_DEFAULT`. Reported to work with --------------------- The table below mentions the compiler versions *byte lite* is reported to work with. OS | Compiler | Versions | ---------:|:-----------|:---------| Windows | Clang/LLVM | ? | &nbsp; | GCC | 5.2.0 | &nbsp; | Visual C++<br>(Visual Studio)| 6 (6), 8 (2005), 9 (2008), 10 (2010),<br>11 (2012), 12 (2013), 14 (2015), 15 (2017) | GNU/Linux | Clang/LLVM | 3.5 - 6.0 | &nbsp; | GCC | 4.8 - 8 | OS X | Clang/LLVM | Xcode 6, Xcode 7, Xcode 8, Xcode 9 | Building the tests ------------------ To build the tests you need: - [CMake](http://cmake.org), version 2.8.12 or later to be installed and in your PATH. - A [suitable compiler](#reported-to-work-with). The [*lest* test framework](https://github.com/martinmoene/lest) is included in the [test folder](test). The following steps assume that the [*byte lite* source code](https://github.com/martinmoene/byte-lite) has been cloned into a directory named `c:\byte-lite`. 1. Create a directory for the build outputs for a particular architecture. Here we use c:\byte-lite\build-win-x86-vc10. cd c:\byte-lite md build-win-x86-vc10 cd build-win-x86-vc10 2. Configure CMake to use the compiler of your choice (run `cmake --help` for a list). cmake -G "Visual Studio 10 2010" -DBYTE_LITE_OPT_BUILD_TESTS=ON .. 3. Build the test suite in the Debug configuration (alternatively use Release). cmake --build . --config Debug 4. Run the test suite. ctest -V -C Debug All tests should pass, indicating your platform is supported and you are ready to use *byte lite*. Other implementations of byte ---------------------------- - Martin Moene. [gsl lite](https://github.com/martinmoene/gsl-lite). C++98 and later. - Microsoft. [Guideline Support Library (GSL)](https://github.com/microsoft/gsl). C++14 (supports MSVC 2013 and 2015). Notes and References -------------------- [1] CppReference. [byte](http://en.cppreference.com/w/cpp/types/byte). [2] ISO/IEC WG21. [N4659, section 21.2.1, Header <cstddef> synopsis](http://wg21.link/n4659#page=492). March 2017. [3] Neil MacIntosh. [P0298: A byte type definition (Revision 3)](http://wg21.link/p0298). March 2017. Appendix -------- ### A.1 Compile-time information The version of *byte lite* is available via tag `[.version]`. The following tags are available for information on the compiler and on the C++ standard library used: `[.compiler]`, `[.stdc++]`, `[.stdlanguage]` and `[.stdlibrary]`. ### A.2 Byte lite test specification ``` byte: Allows to construct from integral via static cast (C++17) byte: Allows to construct from integral via byte() (C++17) byte: Allows to construct from integral via to_byte() byte: Allows to convert to integral via to_integer() byte: Allows to convert to integral via to_integer(), using default type byte: Allows comparison operations byte: Allows bitwise or operation byte: Allows bitwise and operation byte: Allows bitwise x-or operation byte: Allows bitwise or assignment byte: Allows bitwise and assignment byte: Allows bitwise x-or assignment byte: Allows shift-left operation byte: Allows shift-right operation byte: Allows shift-left assignment byte: Allows shift-right assignment byte: Allows strict aliasing byte: Provides constexpr non-assignment operations (C++11) byte: Provides constexpr assignment operations (C++14) ```
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/byte/appveyor.yml
version: "{branch} #{build}" shallow_clone: true image: - Visual Studio 2017 - Visual Studio 2015 platform: - Win32 - x64 configuration: - Debug - Release build: parallel: true environment: matrix: - generator: "Visual Studio 15 2017" - generator: "Visual Studio 14 2015" - generator: "Visual Studio 12 2013" - generator: "Visual Studio 11 2012" - generator: "Visual Studio 10 2010" - generator: "Visual Studio 9 2008" matrix: exclude: - image: Visual Studio 2015 generator: "Visual Studio 15 2017" - image: Visual Studio 2017 generator: "Visual Studio 14 2015" - image: Visual Studio 2017 generator: "Visual Studio 12 2013" - image: Visual Studio 2017 generator: "Visual Studio 11 2012" - image: Visual Studio 2017 generator: "Visual Studio 10 2010" - image: Visual Studio 2017 generator: "Visual Studio 9 2008" - image: Visual Studio 2015 platform: x64 generator: "Visual Studio 9 2008" before_build: - mkdir build && cd build - cmake -A %platform% -G "%generator%" -DBYTE_LITE_OPT_SELECT_NONSTD=ON -DBYTE_LITE_OPT_BUILD_TESTS=ON -DBYTE_LITE_OPT_BUILD_EXAMPLES=OFF .. build_script: - cmake --build . --config %configuration% test_script: - ctest --output-on-failure -C %configuration%
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/byte/conanfile.py
from conans import ConanFile, CMake class ByteLiteConan(ConanFile): version = "0.3.0" name = "byte-lite" description = "byte" license = "Boost Software License - Version 1.0. http://www.boost.org/LICENSE_1_0.txt" url = "https://github.com/martinmoene/byte-lite.git" exports_sources = "include/nonstd/*", "CMakeLists.txt", "cmake/*", "LICENSE.txt" settings = "compiler", "build_type", "arch" build_policy = "missing" author = "Martin Moene" def build(self): """Avoid warning on build step""" pass def package(self): """Run CMake install""" cmake = CMake(self) cmake.definitions["BYTE_LITE_OPT_BUILD_TESTS"] = "OFF" cmake.definitions["BYTE_LITE_OPT_BUILD_EXAMPLES"] = "OFF" cmake.configure() cmake.install() def package_info(self): self.info.header_only()
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/byte/.travis.yml
os: linux dist: trusty sudo: false group: travis_latest language: c++ cache: ccache addons: apt: sources: &apt_sources - ubuntu-toolchain-r-test - llvm-toolchain-precise-3.5 - llvm-toolchain-precise-3.6 - llvm-toolchain-precise-3.7 - llvm-toolchain-precise-3.8 - llvm-toolchain-trusty-3.9 - llvm-toolchain-trusty-4.0 - llvm-toolchain-trusty-5.0 - llvm-toolchain-trusty-6.0 matrix: include: - os: linux env: COMPILER=g++-4.8 compiler: gcc addons: &gcc4_8 apt: packages: ["g++-4.8", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-4.9 compiler: gcc addons: &gcc4_9 apt: packages: ["g++-4.9", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-5 compiler: gcc addons: &gcc5 apt: packages: ["g++-5", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-6 compiler: gcc addons: &gcc6 apt: packages: ["g++-6", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-7 compiler: gcc addons: &gcc7 apt: packages: ["g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-8 compiler: gcc addons: &gcc8 apt: packages: ["g++-8", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.5 compiler: clang addons: &clang3_5 apt: packages: ["clang-3.5", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.6 compiler: clang addons: &clang3_6 apt: packages: ["clang-3.6", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.7 compiler: clang addons: &clang3-7 apt: packages: ["clang-3.7", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.8 compiler: clang addons: &clang3_8 apt: packages: ["clang-3.8", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.9 compiler: clang addons: &clang3_9 apt: packages: ["clang-3.9", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-4.0 compiler: clang addons: &clang4_0 apt: packages: ["clang-4.0", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-5.0 compiler: clang addons: &clang5_0 apt: packages: ["clang-5.0", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-6.0 compiler: clang addons: &clang6_0 apt: packages: ["clang-6.0", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: osx osx_image: xcode7.3 compiler: clang env: COMPILER='clang++' - os: osx osx_image: xcode8 compiler: clang env: COMPILER='clang++' - os: osx osx_image: xcode9 compiler: clang env: COMPILER='clang++' - os: osx osx_image: xcode10 compiler: clang env: COMPILER='clang++' script: - export CXX=${COMPILER} - JOBS=2 # Travis machines have 2 cores. - mkdir build && cd build - cmake -G "Unix Makefiles" -DBYTE_LITE_OPT_SELECT_NONSTD=ON -DBYTE_LITE_OPT_BUILD_TESTS=ON -DBYTE_LITE_OPT_BUILD_EXAMPLES=OFF .. - cmake --build . -- -j${JOBS} - ctest --output-on-failure -j${JOBS}
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte/include
repos/outcome/test/quickcpplib/include/quickcpplib/byte/include/nonstd/byte.hpp
// // byte-lite, a C++17-like byte type for C++98 and later. // For more information see https://github.com/martinmoene/byte-lite // // Copyright 2017-2019 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) #pragma once #ifndef NONSTD_BYTE_LITE_HPP #define NONSTD_BYTE_LITE_HPP #define byte_lite_MAJOR 0 #define byte_lite_MINOR 3 #define byte_lite_PATCH 0 #define byte_lite_VERSION byte_STRINGIFY(byte_lite_MAJOR) "." byte_STRINGIFY(byte_lite_MINOR) "." byte_STRINGIFY(byte_lite_PATCH) #define byte_STRINGIFY( x ) byte_STRINGIFY_( x ) #define byte_STRINGIFY_( x ) #x // byte-lite configuration: #define byte_BYTE_DEFAULT 0 #define byte_BYTE_NONSTD 1 #define byte_BYTE_STD 2 #if !defined( byte_CONFIG_SELECT_BYTE ) # define byte_CONFIG_SELECT_BYTE ( byte_HAVE_STD_BYTE ? byte_BYTE_STD : byte_BYTE_NONSTD ) #endif // C++ language version detection (C++20 is speculative): // Note: VC14.0/1900 (VS2015) lacks too much from C++14. #ifndef byte_CPLUSPLUS # if defined(_MSVC_LANG ) && !defined(__clang__) # define byte_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) # else # define byte_CPLUSPLUS __cplusplus # endif #endif #define byte_CPP98_OR_GREATER ( byte_CPLUSPLUS >= 199711L ) #define byte_CPP11_OR_GREATER ( byte_CPLUSPLUS >= 201103L ) #define byte_CPP11_OR_GREATER_ ( byte_CPLUSPLUS >= 201103L ) #define byte_CPP14_OR_GREATER ( byte_CPLUSPLUS >= 201402L ) #define byte_CPP17_OR_GREATER ( byte_CPLUSPLUS >= 201703L ) #define byte_CPP20_OR_GREATER ( byte_CPLUSPLUS >= 202000L ) // use C++17 std::byte if available and requested: #if byte_CPP17_OR_GREATER # define byte_HAVE_STD_BYTE 1 #else # define byte_HAVE_STD_BYTE 0 #endif #define byte_USES_STD_BYTE ( (byte_CONFIG_SELECT_BYTE == byte_BYTE_STD) || ((byte_CONFIG_SELECT_BYTE == byte_BYTE_DEFAULT) && byte_HAVE_STD_BYTE) ) // // Using std::byte: // #if byte_USES_STD_BYTE #include <cstddef> #include <type_traits> namespace nonstd { using std::byte; using std::to_integer; // Provide compatibility with nonstd::byte: template < class IntegerType , class = typename std::enable_if<std::is_integral<IntegerType>::value>::type > inline constexpr byte to_byte( IntegerType v ) noexcept { return static_cast<byte>( v ); } inline constexpr unsigned char to_uchar( byte b ) noexcept { return to_integer<unsigned char>( b ); } } // namespace nonstd #else // byte_USES_STD_BYTE // half-open range [lo..hi): #define byte_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) // Compiler versions: // // MSVC++ 6.0 _MSC_VER == 1200 byte_COMPILER_MSVC_VERSION == 60 (Visual Studio 6.0) // MSVC++ 7.0 _MSC_VER == 1300 byte_COMPILER_MSVC_VERSION == 70 (Visual Studio .NET 2002) // MSVC++ 7.1 _MSC_VER == 1310 byte_COMPILER_MSVC_VERSION == 71 (Visual Studio .NET 2003) // MSVC++ 8.0 _MSC_VER == 1400 byte_COMPILER_MSVC_VERSION == 80 (Visual Studio 2005) // MSVC++ 9.0 _MSC_VER == 1500 byte_COMPILER_MSVC_VERSION == 90 (Visual Studio 2008) // MSVC++ 10.0 _MSC_VER == 1600 byte_COMPILER_MSVC_VERSION == 100 (Visual Studio 2010) // MSVC++ 11.0 _MSC_VER == 1700 byte_COMPILER_MSVC_VERSION == 110 (Visual Studio 2012) // MSVC++ 12.0 _MSC_VER == 1800 byte_COMPILER_MSVC_VERSION == 120 (Visual Studio 2013) // MSVC++ 14.0 _MSC_VER == 1900 byte_COMPILER_MSVC_VERSION == 140 (Visual Studio 2015) // MSVC++ 14.1 _MSC_VER >= 1910 byte_COMPILER_MSVC_VERSION == 141 (Visual Studio 2017) // MSVC++ 14.2 _MSC_VER >= 1920 byte_COMPILER_MSVC_VERSION == 142 (Visual Studio 2019) #if defined(_MSC_VER ) && !defined(__clang__) # define byte_COMPILER_MSVC_VER (_MSC_VER ) # define byte_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) #else # define byte_COMPILER_MSVC_VER 0 # define byte_COMPILER_MSVC_VERSION 0 #endif #define byte_COMPILER_VERSION( major, minor, patch ) ( 10 * ( 10 * (major) + (minor) ) + (patch) ) #if defined(__clang__) # define byte_COMPILER_CLANG_VERSION byte_COMPILER_VERSION( __clang_major__, __clang_minor__, __clang_patchlevel__ ) #else # define byte_COMPILER_CLANG_VERSION 0 #endif #if defined(__GNUC__) && !defined(__clang__) # define byte_COMPILER_GNUC_VERSION byte_COMPILER_VERSION( __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__ ) #else # define byte_COMPILER_GNUC_VERSION 0 #endif #if byte_BETWEEN( byte_COMPILER_MSVC_VER, 1300, 1900 ) # pragma warning( push ) # pragma warning( disable: 4345 ) // initialization behavior changed #endif // Compiler non-strict aliasing: #if defined(__clang__) || defined(__GNUC__) # define byte_may_alias __attribute__((__may_alias__)) #else # define byte_may_alias #endif // Presence of language and library features: #ifdef _HAS_CPP0X # define byte_HAS_CPP0X _HAS_CPP0X #else # define byte_HAS_CPP0X 0 #endif // Unless defined otherwise below, consider VC14 as C++11 for variant-lite: #if byte_COMPILER_MSVC_VER >= 1900 # undef byte_CPP11_OR_GREATER # define byte_CPP11_OR_GREATER 1 #endif #define byte_CPP11_90 (byte_CPP11_OR_GREATER_ || byte_COMPILER_MSVC_VER >= 1500) #define byte_CPP11_100 (byte_CPP11_OR_GREATER_ || byte_COMPILER_MSVC_VER >= 1600) #define byte_CPP11_110 (byte_CPP11_OR_GREATER_ || byte_COMPILER_MSVC_VER >= 1700) #define byte_CPP11_120 (byte_CPP11_OR_GREATER_ || byte_COMPILER_MSVC_VER >= 1800) #define byte_CPP11_140 (byte_CPP11_OR_GREATER_ || byte_COMPILER_MSVC_VER >= 1900) #define byte_CPP11_141 (byte_CPP11_OR_GREATER_ || byte_COMPILER_MSVC_VER >= 1910) #define byte_CPP14_000 (byte_CPP14_OR_GREATER) #define byte_CPP17_000 (byte_CPP17_OR_GREATER) // Presence of C++11 language features: #define byte_HAVE_CONSTEXPR_11 byte_CPP11_140 #define byte_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG byte_CPP11_120 #define byte_HAVE_NOEXCEPT byte_CPP11_140 // Presence of C++14 language features: #define byte_HAVE_CONSTEXPR_14 byte_CPP14_000 // Presence of C++17 language features: #define byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE byte_CPP17_000 // Presence of C++ library features: #define byte_HAVE_TYPE_TRAITS byte_CPP11_90 // C++ feature usage: #if byte_HAVE_CONSTEXPR_11 # define byte_constexpr constexpr #else # define byte_constexpr /*constexpr*/ #endif #if byte_HAVE_CONSTEXPR_14 # define byte_constexpr14 constexpr #else # define byte_constexpr14 /*constexpr*/ #endif #if byte_HAVE_NOEXCEPT # define byte_noexcept noexcept #else # define byte_noexcept /*noexcept*/ #endif // additional includes: #if byte_HAVE_TYPE_TRAITS # include <type_traits> #endif // conditionally enabling: #if byte_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG # define byte_ENABLE_IF_INTEGRAL_T(T) \ , class = typename std::enable_if<std::is_integral<T>::value>::type #else # define byte_ENABLE_IF_INTEGRAL_T(T) #endif #if byte_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG # define byte_DEFAULT_TEMPLATE_ARG(T) \ = T #else # define byte_DEFAULT_TEMPLATE_ARG(T) #endif namespace nonstd { namespace detail { } #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE enum class byte_may_alias byte : unsigned char {}; #else struct byte_may_alias byte { typedef unsigned char type; type v; }; #endif template< class IntegerType byte_ENABLE_IF_INTEGRAL_T( IntegerType ) > inline byte_constexpr byte to_byte( IntegerType v ) byte_noexcept { #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE return static_cast<byte>( v ); #elif byte_HAVE_CONSTEXPR_11 return { static_cast<typename byte::type>( v ) }; #else byte b = { static_cast<typename byte::type>( v ) }; return b; #endif } #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE template< class IntegerType = typename std::underlying_type<byte>::type byte_ENABLE_IF_INTEGRAL_T( IntegerType ) > inline byte_constexpr IntegerType to_integer( byte b ) byte_noexcept { return static_cast<IntegerType>( b ); } #elif byte_CPP11_OR_GREATER template< class IntegerType byte_DEFAULT_TEMPLATE_ARG(typename byte::type) byte_ENABLE_IF_INTEGRAL_T( IntegerType ) > inline byte_constexpr IntegerType to_integer( byte b ) byte_noexcept { return b.v; } #else // for C++98: template< class IntegerType > inline byte_constexpr IntegerType to_integer( byte b ) byte_noexcept { return b.v; } inline byte_constexpr unsigned char to_integer( byte b ) byte_noexcept { return to_integer<unsigned char >( b ); } #endif inline byte_constexpr unsigned char to_uchar( byte b ) byte_noexcept { return to_integer<unsigned char>( b ); } inline byte_constexpr unsigned char to_uchar( int i ) byte_noexcept { return static_cast<unsigned char>( i ); } #if ! byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE inline byte_constexpr bool operator==( byte l, byte r ) byte_noexcept { return l.v == r.v; } inline byte_constexpr bool operator!=( byte l, byte r ) byte_noexcept { return !( l == r ); } inline byte_constexpr bool operator< ( byte l, byte r ) byte_noexcept { return l.v < r.v; } inline byte_constexpr bool operator<=( byte l, byte r ) byte_noexcept { return !( r < l ); } inline byte_constexpr bool operator> ( byte l, byte r ) byte_noexcept { return ( r < l ); } inline byte_constexpr bool operator>=( byte l, byte r ) byte_noexcept { return !( l < r ); } #endif template< class IntegerType byte_ENABLE_IF_INTEGRAL_T( IntegerType ) > inline byte_constexpr14 byte & operator<<=( byte & b, IntegerType shift ) byte_noexcept { #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE return b = to_byte( to_uchar( b ) << shift ); #else b.v = to_uchar( b.v << shift ); return b; #endif } template< class IntegerType byte_ENABLE_IF_INTEGRAL_T( IntegerType ) > inline byte_constexpr14 byte & operator>>=( byte & b, IntegerType shift ) byte_noexcept { #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE return b = to_byte( to_uchar( b ) >> shift ); #else b.v = to_uchar( b.v >> shift ); return b; #endif } template< class IntegerType byte_ENABLE_IF_INTEGRAL_T( IntegerType ) > inline byte_constexpr byte operator<<( byte b, IntegerType shift ) byte_noexcept { return to_byte( to_uchar( b ) << shift ); } template< class IntegerType byte_ENABLE_IF_INTEGRAL_T( IntegerType ) > inline byte_constexpr byte operator>>( byte b, IntegerType shift ) byte_noexcept { return to_byte( to_uchar( b ) >> shift ); } inline byte_constexpr14 byte & operator|=( byte & l, byte r ) byte_noexcept { #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE return l = to_byte( to_uchar( l ) | to_uchar( r ) ); #else l.v = to_uchar( l ) | to_uchar( r ); return l; #endif } inline byte_constexpr14 byte & operator&=( byte & l, byte r ) byte_noexcept { #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE return l = to_byte( to_uchar( l ) & to_uchar( r ) ); #else l.v = to_uchar( l ) & to_uchar( r ); return l; #endif } inline byte_constexpr14 byte & operator^=( byte & l, byte r ) byte_noexcept { #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE return l = to_byte( to_uchar( l ) ^ to_uchar (r ) ); #else l.v = to_uchar( l ) ^ to_uchar (r ); return l; #endif } inline byte_constexpr byte operator|( byte l, byte r ) byte_noexcept { return to_byte( to_uchar( l ) | to_uchar( r ) ); } inline byte_constexpr byte operator&( byte l, byte r ) byte_noexcept { return to_byte( to_uchar( l ) & to_uchar( r ) ); } inline byte_constexpr byte operator^( byte l, byte r ) byte_noexcept { return to_byte( to_uchar( l ) ^ to_uchar( r ) ); } inline byte_constexpr byte operator~( byte b ) byte_noexcept { return to_byte( ~to_uchar( b ) ); } } // namespace nonstd #endif // byte_USES_STD_BYTE #endif // NONSTD_BYTE_LITE_HPP // end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/example/01-basic.cpp
#include "nonstd/byte.hpp" #include <cassert> using namespace nonstd; int main() { byte b1 = to_byte( 0x5a ); // to_byte() is non-standard, needed for pre-C++17 byte b2 = to_byte( 0xa5 ); byte r1 = b1 ^ b2; assert( 0xff == to_integer( r1 ) ); // not (yet) standard, needs C++11 byte r2 = b1 ^ b2; assert( 0xff == to_integer<unsigned int>( r2 ) ); } // cl -nologo -EHsc -I../include 01-basic.cpp && 01-basic // g++ -std=c++11 -Wall -I../include -o 01-basic 01-basic.cpp && 01-basic
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/script/update-version.py
#!/usr/bin/env python # # Copyright 2017-2019 by 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) # # script/update-version.py # from __future__ import print_function import argparse import os import re import sys # Configuration: table = ( # path, substitute find, substitute format ( 'CMakeLists.txt' , r'\W{2,4}VERSION\W+([0-9]+\.[0-9]+\.[0-9]+)\W*$' , ' VERSION {major}.{minor}.{patch}' ) , ( 'CMakeLists.txt' , r'set\W+byte_lite_version\W+"([0-9]+\.[0-9]+\.[0-9]+)"\W+$' , 'set( byte_lite_version "{major}.{minor}.{patch}" )\n' ) # , ( 'example/cmake-pkg/CMakeLists.txt' # , r'set\W+byte_lite_version\W+"([0-9]+\.[0-9]+(\.[0-9]+)?)"\W+$' # , 'set( byte_lite_version "{major}.{minor}" )\n' ) # # , ( 'script/install-xxx-pkg.py' # , r'\byte_lite_version\s+=\s+"([0-9]+\.[0-9]+\.[0-9]+)"\s*$' # , 'byte_lite_version = "{major}.{minor}.{patch}"\n' ) , ( 'conanfile.py' , r'version\s+=\s+"([0-9]+\.[0-9]+\.[0-9]+)"\s*$' , 'version = "{major}.{minor}.{patch}"' ) , ( 'include/nonstd/byte.hpp' , r'\#define\s+byte_lite_MAJOR\s+[0-9]+\s*$' , '#define byte_lite_MAJOR {major}' ) , ( 'include/nonstd/byte.hpp' , r'\#define\s+byte_lite_MINOR\s+[0-9]+\s*$' , '#define byte_lite_MINOR {minor}' ) , ( 'include/nonstd/byte.hpp' , r'\#define\s+byte_lite_PATCH\s+[0-9]+\s*$' , '#define byte_lite_PATCH {patch}\n' ) ) # End configuration. def readFile( in_path ): """Return content of file at given path""" with open( in_path, 'r' ) as in_file: contents = in_file.read() return contents def writeFile( out_path, contents ): """Write contents to file at given path""" with open( out_path, 'w' ) as out_file: out_file.write( contents ) def replaceFile( output_path, input_path ): # prevent race-condition (Python 3.3): if sys.version_info >= (3, 3): os.replace( output_path, input_path ) else: os.remove( input_path ) os.rename( output_path, input_path ) def editFileToVersion( version, info, verbose ): """Update version given file path, version regexp and new version format in info""" major, minor, patch = version.split('.') in_path, ver_re, ver_fmt = info out_path = in_path + '.tmp' new_text = ver_fmt.format( major=major, minor=minor, patch=patch ) if verbose: print( "- {path} => '{text}':".format( path=in_path, text=new_text.strip('\n') ) ) writeFile( out_path, re.sub( ver_re, new_text, readFile( in_path ) , count=0, flags=re.MULTILINE ) ) replaceFile( out_path, in_path ) def editFilesToVersion( version, table, verbose ): if verbose: print( "Editing files to version {v}:".format(v=version) ) for item in table: editFileToVersion( version, item, verbose ) def editFilesToVersionFromCommandLine(): """Update version number given on command line in paths from configuration table.""" parser = argparse.ArgumentParser( description='Update version number in files.', epilog="""""", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument( 'version', metavar='version', type=str, nargs=1, help='new version number, like 1.2.3') parser.add_argument( '-v', '--verbose', action='store_true', help='report the name of the file being processed') args = parser.parse_args() editFilesToVersion( args.version[0], table, args.verbose ) if __name__ == '__main__': editFilesToVersionFromCommandLine() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/script/create-cov-rpt.py
#!/usr/bin/env python # # Copyright 2019-2019 by 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) # # script/create-cov-rpt.py, Python 3.4 and later # import argparse import os import re import sys import subprocess # Configuration: cfg_github_project = 'byte-lite' cfg_github_user = 'martinmoene' cfg_prj_folder_level = 3 tpl_coverage_cmd = 'opencppcoverage --no_aggregate_by_file --sources {src} -- {exe}' # End configuration. def project_folder( f, args ): """Project root""" if args.prj_folder: return args.prj_folder return os.path.normpath( os.path.join( os.path.dirname( os.path.abspath(f) ), '../' * args.prj_folder_level ) ) def executable_folder( f ): """Folder where the xecutable is""" return os.path.dirname( os.path.abspath(f) ) def executable_name( f ): """Folder where the executable is""" return os.path.basename( f ) def createCoverageReport( f, args ): print( "Creating coverage report for project '{usr}/{prj}', '{file}':". format( usr=args.user, prj=args.project, file=f ) ) cmd = tpl_coverage_cmd.format( folder=executable_folder(f), src=project_folder(f, args), exe=executable_name(f) ) if args.verbose: print( "> {}".format(cmd) ) if not args.dry_run: os.chdir( executable_folder(f) ) subprocess.call( cmd, shell=False ) os.chdir( project_folder(f, args) ) def createCoverageReports( args ): for f in args.executable: createCoverageReport( f, args ) def createCoverageReportFromCommandLine(): """Collect arguments from the commandline and create coverage report.""" parser = argparse.ArgumentParser( description='Create coverage report.', epilog="""""", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'executable', metavar='executable', type=str, nargs=1, help='executable to report on') parser.add_argument( '-n', '--dry-run', action='store_true', help='do not execute conan commands') parser.add_argument( '-v', '--verbose', action='count', default=0, help='level of progress reporting') parser.add_argument( '--user', metavar='u', type=str, default=cfg_github_user, help='github user name') parser.add_argument( '--project', metavar='p', type=str, default=cfg_github_project, help='github project name') parser.add_argument( '--prj-folder', metavar='f', type=str, default=None, help='project root folder') parser.add_argument( '--prj-folder-level', metavar='n', type=int, default=cfg_prj_folder_level, help='project root folder level from executable') createCoverageReports( parser.parse_args() ) if __name__ == '__main__': createCoverageReportFromCommandLine() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/script/upload-conan.py
#!/usr/bin/env python # # Copyright 2019-2019 by 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) # # script/upload-conan.py # from __future__ import print_function import argparse import os import re import sys import subprocess # Configuration: def_conan_project = 'byte-lite' def_conan_user = 'nonstd-lite' def_conan_channel = 'stable' cfg_conanfile = 'conanfile.py' tpl_conan_create = 'conan create . {usr}/{chn}' tpl_conan_upload = 'conan upload --remote {usr} {prj}/{ver}@{usr}/{chn}' # End configuration. def versionFrom( filename ): """Obtain version from conanfile.py""" with open( filename ) as f: content = f.read() version = re.search(r'version\s=\s"(.*)"', content).group(1) return version def createConanPackage( args ): """Create conan package and upload it.""" cmd = tpl_conan_create.format(usr=args.user, chn=args.channel) if args.verbose: print( "> {}".format(cmd) ) if not args.dry_run: subprocess.call( cmd, shell=False ) def uploadConanPackage( args ): """Create conan package and upload it.""" cmd = tpl_conan_upload.format(prj=args.project, usr=args.user, chn=args.channel, ver=args.version) if args.verbose: print( "> {}".format(cmd) ) if not args.dry_run: subprocess.call( cmd, shell=False ) def uploadToConan( args ): """Create conan package and upload it.""" print( "Updating project '{prj}' to user '{usr}', channel '{chn}', version {ver}:". format(prj=args.project, usr=args.user, chn=args.channel, ver=args.version) ) createConanPackage( args ) uploadConanPackage( args ) def uploadToConanFromCommandLine(): """Collect arguments from the commandline and create conan package and upload it.""" parser = argparse.ArgumentParser( description='Create conan package and upload it to conan.', epilog="""""", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-n', '--dry-run', action='store_true', help='do not execute conan commands') parser.add_argument( '-v', '--verbose', action='count', default=0, help='level of progress reporting') parser.add_argument( '--project', metavar='p', type=str, default=def_conan_project, help='conan project') parser.add_argument( '--user', metavar='u', type=str, default=def_conan_user, help='conan user') parser.add_argument( '--channel', metavar='c', type=str, default=def_conan_channel, help='conan channel') parser.add_argument( '--version', metavar='v', type=str, default=versionFrom( cfg_conanfile ), help='version number [from conanfile.py]') uploadToConan( parser.parse_args() ) if __name__ == '__main__': uploadToConanFromCommandLine() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/script/create-vcpkg.py
#!/usr/bin/env python # # Copyright 2019-2019 by 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) # # script/upload-conan.py, Python 3.4 and later # import argparse import os import re import sys import subprocess # Configuration: cfg_github_project = 'byte-lite' cfg_github_user = 'martinmoene' cfg_description = '(unused)' cfg_cmakelists = 'CMakeLists.txt' cfg_readme = 'Readme.md' cfg_license = 'LICENSE.txt' cfg_ref_prefix = 'v' cfg_sha512 = 'dadeda' cfg_vcpkg_description = '(no description found)' cfg_vcpkg_root = os.environ['VCPKG_ROOT'] cfg_cmake_optpfx = "BYTE_LITE" # End configuration. # vcpkg control and port templates: tpl_path_vcpkg_control = '{vcpkg}/ports/{prj}/CONTROL' tpl_path_vcpkg_portfile = '{vcpkg}/ports/{prj}/portfile.cmake' tpl_vcpkg_control =\ """Source: {prj} Version: {ver} Description: {desc}""" tpl_vcpkg_portfile =\ """include(vcpkg_common_functions) vcpkg_from_github( OUT_SOURCE_PATH SOURCE_PATH REPO {usr}/{prj} REF {ref} SHA512 {sha} ) vcpkg_configure_cmake( SOURCE_PATH ${{SOURCE_PATH}} PREFER_NINJA OPTIONS -D{optpfx}_OPT_BUILD_TESTS=OFF -D{optpfx}_OPT_BUILD_EXAMPLES=OFF ) vcpkg_install_cmake() vcpkg_fixup_cmake_targets( CONFIG_PATH lib/cmake/${{PORT}} ) file(REMOVE_RECURSE ${{CURRENT_PACKAGES_DIR}}/debug ${{CURRENT_PACKAGES_DIR}}/lib ) file(INSTALL ${{SOURCE_PATH}}/{lic} DESTINATION ${{CURRENT_PACKAGES_DIR}}/share/${{PORT}} RENAME copyright )""" tpl_vcpkg_note_sha =\ """ Next actions: - Obtain package SHA: 'vcpkg install {prj}', copy SHA mentioned in 'Actual hash: [...]' - Add SHA to package: 'script\create-vcpkg --sha={sha}' - Install package : 'vcpkg install {prj}'""" tpl_vcpkg_note_install =\ """ Next actions: - Install package: 'vcpkg install {prj}'""" # End of vcpkg templates def versionFrom( filename ): """Obtain version from CMakeLists.txt""" with open( filename, 'r' ) as f: content = f.read() version = re.search(r'VERSION\s(\d+\.\d+\.\d+)', content).group(1) return version def descriptionFrom( filename ): """Obtain description from CMakeLists.txt""" with open( filename, 'r' ) as f: content = f.read() description = re.search(r'DESCRIPTION\s"(.*)"', content).group(1) return description if description else cfg_vcpkg_description def vcpkgRootFrom( path ): return path if path else './vcpkg' def to_ref( version ): """Add prefix to version/tag, like v1.2.3""" return cfg_ref_prefix + version def control_path( args ): """Create path like vcpks/ports/_project_/CONTROL""" return tpl_path_vcpkg_control.format( vcpkg=args.vcpkg_root, prj=args.project ) def portfile_path( args ): """Create path like vcpks/ports/_project_/portfile.cmake""" return tpl_path_vcpkg_portfile.format( vcpkg=args.vcpkg_root, prj=args.project ) def createControl( args ): """Create vcpkg CONTROL file""" output = tpl_vcpkg_control.format( prj=args.project, ver=args.version, desc=args.description ) if args.verbose: print( "Creating control file '{f}':".format( f=control_path( args ) ) ) if args.verbose > 1: print( output ) os.makedirs( os.path.dirname( control_path( args ) ), exist_ok=True ) with open( control_path( args ), 'w') as f: print( output, file=f ) def createPortfile( args ): """Create vcpkg portfile""" output = tpl_vcpkg_portfile.format( optpfx=cfg_cmake_optpfx, usr=args.user, prj=args.project, ref=to_ref(args.version), sha=args.sha, lic=cfg_license ) if args.verbose: print( "Creating portfile '{f}':".format( f=portfile_path( args ) ) ) if args.verbose > 1: print( output ) os.makedirs( os.path.dirname( portfile_path( args ) ), exist_ok=True ) with open( portfile_path( args ), 'w') as f: print( output, file=f ) def printNotes( args ): if args.sha == cfg_sha512: print( tpl_vcpkg_note_sha. format( prj=args.project, sha='...' ) ) else: print( tpl_vcpkg_note_install. format( prj=args.project ) ) def createVcpkg( args ): print( "Creating vcpkg for '{usr}/{prj}', version '{ver}' in folder '{vcpkg}':". format( usr=args.user, prj=args.project, ver=args.version, vcpkg=args.vcpkg_root, ) ) createControl( args ) createPortfile( args ) printNotes( args ) def createVcpkgFromCommandLine(): """Collect arguments from the commandline and create vcpkg.""" parser = argparse.ArgumentParser( description='Create microsoft vcpkg.', epilog="""""", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-v', '--verbose', action='count', default=0, help='level of progress reporting') parser.add_argument( '--user', metavar='u', type=str, default=cfg_github_user, help='github user name') parser.add_argument( '--project', metavar='p', type=str, default=cfg_github_project, help='github project name') parser.add_argument( '--description', metavar='d', type=str, # default=cfg_description, default=descriptionFrom( cfg_cmakelists ), help='vcpkg description [from ' + cfg_cmakelists + ']') parser.add_argument( '--version', metavar='v', type=str, default=versionFrom( cfg_cmakelists ), help='version number [from ' + cfg_cmakelists + ']') parser.add_argument( '--sha', metavar='s', type=str, default=cfg_sha512, help='sha of package') parser.add_argument( '--vcpkg-root', metavar='r', type=str, default=vcpkgRootFrom( cfg_vcpkg_root ), help='parent folder containing ports to write files to') createVcpkg( parser.parse_args() ) if __name__ == '__main__': createVcpkgFromCommandLine() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/tg-all.bat
@for %%s in ( c++98 c++03 c++11 c++14 c++17 ) do ( call tg.bat %%s )
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/byte.t.cpp
// // byte-lite, a C++17-like byte type for C++98 and later. // For more information see https://github.com/martinmoene/gsl-lite // // Copyright 2017-2019 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) #include "byte-main.t.hpp" // Use nonstd::byte instead of plain byte to prevent collisions with // other byte declarations, such as in rpcndr.h (Windows kit). // We have a chicken & egg problem here: // verifying operations via to_integer() that has yet to verified itself... using namespace nonstd; CASE( "byte: Allows to construct from integral via static cast (C++17)" ) { #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE nonstd::byte b = static_cast<nonstd::byte>( 4 ); EXPECT( static_cast<unsigned char>(b) == 4 ); EXPECT( to_integer<int>( b ) == 4 ); #else EXPECT( !!"enum class is not constructible from underlying type (no C++17)" ); #endif } CASE( "byte: Allows to construct from integral via byte() (C++17)" ) { #if byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE nonstd::byte b = nonstd::byte( 4 ); EXPECT( to_integer<int>( b ) == 4 ); #else EXPECT( !!"enum class is not constructible from underlying type (no C++17)" ); #endif } CASE( "byte: Allows to construct from integral via to_byte()" ) { nonstd::byte b = to_byte( 4 ); EXPECT( to_integer<int>( b ) == 4 ); } CASE( "byte: Allows to convert to integral via to_integer()" ) { nonstd::byte b = to_byte( 4 ); EXPECT( to_integer<int>( b ) == 4 ); } CASE( "byte: Allows to convert to integral via to_integer(), using default type" ) { #if byte_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG nonstd::byte b = to_byte( 4 ); EXPECT( to_integer( b ) == 4 ); #else EXPECT( !!"No default function template argument (no C++11)" ); #endif } CASE( "byte: Allows comparison operations" ) { nonstd::byte a = to_byte( 3 ); nonstd::byte b = to_byte( 7 ); EXPECT( a == a ); EXPECT( a != b ); EXPECT( a < b ); EXPECT( a <= a ); EXPECT( a <= b ); EXPECT( b > a ); EXPECT( b >= a ); EXPECT( b >= b ); EXPECT_NOT( a == b ); EXPECT_NOT( a != a ); EXPECT_NOT( b < a ); EXPECT_NOT( a > b ); } CASE( "byte: Allows bitwise or operation" ) { nonstd::byte const b = to_byte( 0xa5 ); EXPECT( ( b | b ) == b ); EXPECT( ( b | to_byte( 0x00 ) ) == b ); EXPECT( ( b | to_byte( 0xff ) ) == to_byte( 0xff ) ); } CASE( "byte: Allows bitwise and operation" ) { nonstd::byte const b = to_byte( 0xa5 ); EXPECT( ( b & b ) == b ); EXPECT( ( b & to_byte( 0xff ) ) == b ); EXPECT( ( b & to_byte( 0x00 ) ) == to_byte( 0x00 ) ); } CASE( "byte: Allows bitwise x-or operation" ) { nonstd::byte const b = to_byte( 0xa5 ); EXPECT( ( b ^ b ) == to_byte( 0 ) ); EXPECT( ( b ^ to_byte( 0x00 ) ) == b ); EXPECT( ( b ^ to_byte( 0xff ) ) == ~b ); } CASE( "byte: Allows bitwise or assignment" ) { SETUP("") { nonstd::byte const b_org = to_byte( 0xa5 ); nonstd::byte b = b_org; SECTION("Identity") { EXPECT( ( b |= b ) == b_org ); } SECTION("Identity") { EXPECT( ( b |= to_byte( 0x00 ) ) == b_org ); } SECTION("Saturate") { EXPECT( ( b |= to_byte( 0xff ) ) == to_byte( 0xff ) ); } } } CASE( "byte: Allows bitwise and assignment" ) { SETUP("") { nonstd::byte const b_org = to_byte( 0xa5 ); nonstd::byte b = b_org; SECTION("Identity") { EXPECT( ( b &= b ) == b_org ); } SECTION("Identity") { EXPECT( ( b &= to_byte( 0xff ) ) == b_org ); } SECTION("Clear" ) { EXPECT( ( b &= to_byte( 0x00 ) ) == to_byte( 0x00 ) ); } } } CASE( "byte: Allows bitwise x-or assignment" ) { SETUP("") { nonstd::byte const b_org = to_byte( 0xa5 ); nonstd::byte b = b_org; SECTION("Identity") { EXPECT( ( b ^= b ) == to_byte( 0 ) ); } SECTION("Identity") { EXPECT( ( b ^= to_byte( 0x00 ) ) == b_org ); } SECTION("Invert" ) { EXPECT( ( b ^= to_byte( 0xff ) ) == ~b_org ); } } } CASE( "byte: Allows shift-left operation" ) { nonstd::byte const b = to_byte( 0xa5 ); EXPECT( ( b << 3 ) == to_byte( to_uchar( b ) << 3 ) ); } CASE( "byte: Allows shift-right operation" ) { nonstd::byte const b = to_byte( 0xa5 ); EXPECT( ( b >> 3 ) == to_byte( to_uchar( b ) >> 3 ) ); } CASE( "byte: Allows shift-left assignment" ) { nonstd::byte const b_org = to_byte( 0xa5 ); nonstd::byte b = b_org; EXPECT( ( b <<= 3 ) == to_byte( to_uchar( b_org ) << 3 ) ); } CASE( "byte: Allows shift-right assignment" ) { nonstd::byte const b_org = to_byte( 0xa5 ); nonstd::byte b = b_org; EXPECT( ( b >>= 3 ) == to_byte( to_uchar( b_org ) >> 3 ) ); } CASE( "byte: Allows strict aliasing" ) { struct F { static int f( int & i, nonstd::byte & r ) { i = 7; r <<= 1; return i; } }; int i; EXPECT( 14 == F::f( i, reinterpret_cast<nonstd::byte&>( i ) ) ); } CASE( "byte: Provides constexpr non-assignment operations (C++11)" ) { #if byte_HAVE_CONSTEXPR_11 static_assert( to_byte( 0xa5 ) == to_byte( 0xa5 ) , "" ); static_assert( 0xa5 == to_integer<int>( to_byte( 0xa5 ) ), "" ); static_assert( to_byte( 0x02 ) == ( to_byte( 0x01 ) << 1 ), "" ); static_assert( to_byte( 0x01 ) == ( to_byte( 0x02 ) >> 1 ), "" ); static_assert( to_byte( 0x01 ) == ( to_byte( 0x03 ) & to_byte( 0x01 ) ), "" ); static_assert( to_byte( 0x01 ) == ( to_byte( 0x00 ) | to_byte( 0x01 ) ), "" ); static_assert( to_byte( 0x00 ) == ( to_byte( 0x01 ) ^ to_byte( 0x01 ) ), "" ); static_assert( to_byte( 0xff ) == ~to_byte( 0x00 ), "" ); #endif } CASE( "byte: Provides constexpr assignment operations (C++14)" ) { #if byte_HAVE_CONSTEXPR_14 // ... #endif } // end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/tc.bat
@echo off & setlocal enableextensions enabledelayedexpansion :: :: tc.bat - compile & run tests (clang). :: set unit=byte :: if no std is given, use c++14 set std=%1 if "%std%"=="" set std=c++14 set clang=clang call :CompilerVersion version echo %clang% %version%: %std% set UCAP=%unit% call :toupper UCAP set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_DEFAULT ::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_NONSTD ::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_STD set unit_config= rem -flto / -fwhole-program set optflags=-O2 set warnflags=-Wall -Wextra -Wpedantic -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-missing-noreturn -Wno-documentation-unknown-command -Wno-documentation-deprecated-sync -Wno-documentation -Wno-weak-vtables -Wno-missing-prototypes -Wno-missing-variable-declarations -Wno-exit-time-destructors -Wno-global-constructors "%clang%" -m32 -std=%std% %optflags% %warnflags% %unit_select% %unit_config% -fms-compatibility-version=19.00 -isystem "%VCInstallDir%include" -isystem "%WindowsSdkDir_71A%include" -isystem lest -I../include -o %unit%-main.t.exe %unit%-main.t.cpp %unit%.t.cpp && %unit%-main.t.exe endlocal & goto :EOF :: subroutines: :CompilerVersion version echo off & setlocal enableextensions set tmpprogram=_getcompilerversion.tmp set tmpsource=%tmpprogram%.c echo #include ^<stdio.h^> > %tmpsource% echo int main(){printf("%%d.%%d.%%d\n",__clang_major__,__clang_minor__,__clang_patchlevel__);} >> %tmpsource% "%clang%" -m32 -o %tmpprogram% %tmpsource% >nul for /f %%x in ('%tmpprogram%') do set version=%%x del %tmpprogram%.* >nul endlocal & set %1=%version%& goto :EOF :: toupper; makes use of the fact that string :: replacement (via SET) is not case sensitive :toupper for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L! goto :EOF
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/tc-cl.bat
@echo off & setlocal enableextensions enabledelayedexpansion :: :: tc-cl.bat - compile & run tests (clang-cl). :: set unit=byte set unit_file=%unit% :: if no std is given, use c++14 set std=c++14 if NOT "%1" == "" set std=%1 & shift set UCAP=%unit% call :toupper UCAP set unit_select=%unit%_%UCAP%_NONSTD ::set unit_select=%unit%_CONFIG_SELECT_%UCAP%_NONSTD if NOT "%1" == "" set unit_select=%1 & shift set args=%1 %2 %3 %4 %5 %6 %7 %8 %9 set clang=clang-cl call :CompilerVersion version echo %clang% %version%: %std% %unit_select% %args% set unit_config=^ -D%unit%_%UCAP%_HEADER=\"nonstd/%unit%.hpp\" ^ -D%unit%_TEST_NODISCARD=0 ^ -D%unit%_CONFIG_SELECT_%UCAP%=%unit_select% rem -flto / -fwhole-program set optflags=-O2 set warnflags=-Wall -Wextra -Wpedantic -Weverything -Wshadow -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-missing-noreturn -Wno-documentation-unknown-command -Wno-documentation-deprecated-sync -Wno-documentation -Wno-weak-vtables -Wno-missing-prototypes -Wno-missing-variable-declarations -Wno-exit-time-destructors -Wno-global-constructors -Wno-sign-conversion -Wno-sign-compare -Wno-implicit-int-conversion -Wno-deprecated-declarations -Wno-date-time "%clang%" -EHsc -std:%std% %optflags% %warnflags% %unit_config% -fms-compatibility-version=19.00 /imsvc lest -I../include -Ics_string -I. -o %unit_file%-main.t.exe %unit_file%-main.t.cpp %unit_file%.t.cpp && %unit_file%-main.t.exe endlocal & goto :EOF :: subroutines: :CompilerVersion version echo off & setlocal enableextensions set tmpprogram=_getcompilerversion.tmp set tmpsource=%tmpprogram%.c echo #include ^<stdio.h^> > %tmpsource% echo int main(){printf("%%d.%%d.%%d\n",__clang_major__,__clang_minor__,__clang_patchlevel__);} >> %tmpsource% "%clang%" -m32 -o %tmpprogram% %tmpsource% >nul for /f %%x in ('%tmpprogram%') do set version=%%x del %tmpprogram%.* >nul endlocal & set %1=%version%& goto :EOF :: toupper; makes use of the fact that string :: replacement (via SET) is not case sensitive :toupper for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L! goto :EOF
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/tg.bat
@echo off & setlocal enableextensions enabledelayedexpansion :: :: tg.bat - compile & run tests (GNUC). :: set unit=byte :: if no std is given, use c++11 set std=%1 set args=%2 %3 %4 %5 %6 %7 %8 %9 if "%1" == "" set std=c++11 set gpp=g++ call :CompilerVersion version echo %gpp% %version%: %std% %args% set UCAP=%unit% call :toupper UCAP set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_DEFAULT ::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_NONSTD ::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_STD set unit_config= rem -flto / -fwhole-program set optflags=-O2 set warnflags=-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wno-padded -Wno-missing-noreturn %gpp% -std=%std% %optflags% %warnflags% %unit_select% %unit_config% -o %unit%-main.t.exe -isystem lest -I../include %unit%-main.t.cpp %unit%.t.cpp && %unit%-main.t.exe endlocal & goto :EOF :: subroutines: :CompilerVersion version echo off & setlocal enableextensions set tmpprogram=_getcompilerversion.tmp set tmpsource=%tmpprogram%.c echo #include ^<stdio.h^> > %tmpsource% echo int main(){printf("%%d.%%d.%%d\n",__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__);} >> %tmpsource% %gpp% -o %tmpprogram% %tmpsource% >nul for /f %%x in ('%tmpprogram%') do set version=%%x del %tmpprogram%.* >nul endlocal & set %1=%version%& goto :EOF :: toupper; makes use of the fact that string :: replacement (via SET) is not case sensitive :toupper for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L! goto :EOF
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/CMakeLists.txt
# Copyright 2017-2019 by Martin Moene # # https://github.com/martinmoene/byte-lite # # 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) if( NOT DEFINED CMAKE_MINIMUM_REQUIRED_VERSION ) cmake_minimum_required( VERSION 3.5 FATAL_ERROR ) endif() # byte-lite version, updated by script/update-version.py: project( test LANGUAGES CXX ) set( unit_name "byte" ) set( PACKAGE ${unit_name}-lite ) set( PROGRAM ${unit_name}-lite ) set( SOURCES ${unit_name}-main.t.cpp ${unit_name}.t.cpp ) message( STATUS "Subproject '${PROJECT_NAME}', programs '${PROGRAM}-*'") # Configure byte-lite for testing: set( DEFCMN "" ) set( OPTIONS "" ) set( HAS_STD_FLAGS FALSE ) set( HAS_CPP98_FLAG FALSE ) set( HAS_CPP11_FLAG FALSE ) set( HAS_CPP14_FLAG FALSE ) set( HAS_CPP17_FLAG FALSE ) set( HAS_CPP20_FLAG FALSE ) set( HAS_CPPLATEST_FLAG FALSE ) if( MSVC ) message( STATUS "Matched: MSVC") set( HAS_STD_FLAGS TRUE ) set( OPTIONS -W3 -EHsc ) set( DEFINITIONS -D_SCL_SECURE_NO_WARNINGS ${DEFCMN} ) if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.00 ) set( HAS_CPP14_FLAG TRUE ) set( HAS_CPPLATEST_FLAG TRUE ) endif() if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.11 ) set( HAS_CPP17_FLAG TRUE ) endif() elseif( CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang" ) message( STATUS "CompilerId: '${CMAKE_CXX_COMPILER_ID}'") set( HAS_STD_FLAGS TRUE ) set( HAS_CPP98_FLAG TRUE ) set( OPTIONS -O2 -Wall -Wno-missing-braces -Wconversion -Wsign-conversion # -Wno-string-conversion -fno-elide-constructors -fstrict-aliasing -Wstrict-aliasing=2 ) set( DEFINITIONS ${DEFCMN} ) # GNU: available -std flags depends on version if( CMAKE_CXX_COMPILER_ID MATCHES "GNU" ) message( STATUS "Matched: GNU") if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8.0 ) set( HAS_CPP11_FLAG TRUE ) endif() if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9.2 ) set( HAS_CPP14_FLAG TRUE ) endif() if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.1.0 ) set( HAS_CPP17_FLAG TRUE ) endif() # AppleClang: available -std flags depends on version elseif( CMAKE_CXX_COMPILER_ID MATCHES "AppleClang" ) message( STATUS "Matched: AppleClang") if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0.0 ) set( HAS_CPP11_FLAG TRUE ) endif() if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.1.0 ) set( HAS_CPP14_FLAG TRUE ) endif() if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9.2.0 ) set( HAS_CPP17_FLAG TRUE ) endif() # Clang: available -std flags depends on version elseif( CMAKE_CXX_COMPILER_ID MATCHES "Clang" ) message( STATUS "Matched: Clang") if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.3.0 ) set( HAS_CPP11_FLAG TRUE ) endif() if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4.0 ) set( HAS_CPP14_FLAG TRUE ) endif() if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0.0 ) set( HAS_CPP17_FLAG TRUE ) endif() endif() elseif( CMAKE_CXX_COMPILER_ID MATCHES "Intel" ) # as is message( STATUS "Matched: Intel") else() # as is message( STATUS "Matched: nothing") endif() # enable MS C++ Core Guidelines checker if MSVC: function( enable_msvs_guideline_checker target ) if( MSVC ) set_target_properties( ${target} PROPERTIES VS_GLOBAL_EnableCppCoreCheck true VS_GLOBAL_CodeAnalysisRuleSet CppCoreCheckRules.ruleset VS_GLOBAL_RunCodeAnalysis true ) endif() endfunction() # make target, compile for given standard if specified: function( make_target target std ) message( STATUS "Make target: '${std}'" ) add_executable ( ${target} ${SOURCES} ) target_include_directories( ${target} SYSTEM PRIVATE lest ) target_link_libraries ( ${target} PRIVATE ${PACKAGE} ) target_compile_options ( ${target} PRIVATE ${OPTIONS} ) target_compile_definitions( ${target} PRIVATE ${DEFINITIONS} ) if( std ) if( MSVC ) target_compile_options( ${target} PRIVATE -std:c++${std} ) else() # Necessary for clang 3.x: target_compile_options( ${target} PRIVATE -std=c++${std} ) # Ok for clang 4 and later: # set( CMAKE_CXX_STANDARD ${std} ) # set( CMAKE_CXX_STANDARD_REQUIRED ON ) # set( CMAKE_CXX_EXTENSIONS OFF ) endif() endif() endfunction() # add generic executable, unless -std flags can be specified: if( NOT HAS_STD_FLAGS ) make_target( ${PROGRAM}.t "" ) else() # unconditionally add C++98 variant as MSVC has no option for it: if( HAS_CPP98_FLAG ) make_target( ${PROGRAM}-cpp98.t 98 ) else() make_target( ${PROGRAM}-cpp98.t "" ) endif() if( HAS_CPP11_FLAG ) make_target( ${PROGRAM}-cpp11.t 11 ) endif() if( HAS_CPP14_FLAG ) make_target( ${PROGRAM}-cpp14.t 14 ) endif() if( HAS_CPP17_FLAG ) set( std17 17 ) if( CMAKE_CXX_COMPILER_ID MATCHES "AppleClang" ) set( std17 1z ) endif() make_target( ${PROGRAM}-cpp17.t ${std17} ) enable_msvs_guideline_checker( ${PROGRAM}-cpp17.t ) endif() if( HAS_CPPLATEST_FLAG ) make_target( ${PROGRAM}-cpplatest.t latest ) endif() endif() # with C++17, honour explicit request for std::byte or nonstd::byte: if( HAS_CPP17_FLAG ) set( WHICH byte_BYTE_DEFAULT ) if( BYTE_LITE_OPT_SELECT_STD ) set( WHICH byte_BYTE_STD ) elseif( BYTE_LITE_OPT_SELECT_NONSTD ) set( WHICH byte_BYTE_NONSTD ) endif() target_compile_definitions( ${PROGRAM}-cpp17.t PRIVATE byte_CONFIG_SELECT_BYTE=${WHICH} ) if( HAS_CPPLATEST_FLAG ) target_compile_definitions( ${PROGRAM}-cpplatest.t PRIVATE byte_CONFIG_SELECT_BYTE=${WHICH} ) endif() endif() # configure unit tests via CTest: enable_testing() if( HAS_STD_FLAGS ) # unconditionally add C++98 variant for MSVC: add_test( NAME test-cpp98 COMMAND ${PROGRAM}-cpp98.t ) if( HAS_CPP11_FLAG ) add_test( NAME test-cpp11 COMMAND ${PROGRAM}-cpp11.t ) endif() if( HAS_CPP14_FLAG ) add_test( NAME test-cpp14 COMMAND ${PROGRAM}-cpp14.t ) endif() if( HAS_CPP17_FLAG ) add_test( NAME test-cpp17 COMMAND ${PROGRAM}-cpp17.t ) endif() if( HAS_CPPLATEST_FLAG ) add_test( NAME test-cpplatest COMMAND ${PROGRAM}-cpplatest.t ) endif() else() add_test( NAME test COMMAND ${PROGRAM}.t --pass ) add_test( NAME list_version COMMAND ${PROGRAM}.t --version ) add_test( NAME list_tags COMMAND ${PROGRAM}.t --list-tags ) add_test( NAME list_tests COMMAND ${PROGRAM}.t --list-tests ) endif() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/byte-main.t.hpp
// Copyright 2017-2019 Martin Moene // // https://github.com/martinmoene/byte-lite // // 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) #pragma once #ifndef TEST_byte_LITE_H_INCLUDED #define TEST_byte_LITE_H_INCLUDED #include "nonstd/byte.hpp" // Compiler warning suppression for usage of lest: #ifdef __clang__ # pragma clang diagnostic ignored "-Wstring-conversion" # pragma clang diagnostic ignored "-Wunused-parameter" # pragma clang diagnostic ignored "-Wunused-template" # pragma clang diagnostic ignored "-Wunused-function" # pragma clang diagnostic ignored "-Wunused-member-function" #elif defined __GNUC__ # pragma GCC diagnostic ignored "-Wunused-parameter" # pragma GCC diagnostic ignored "-Wunused-function" #endif #include <iostream> namespace nonstd { // use oparator<< instead of to_string() overload; // see http://stackoverflow.com/a/10651752/437272 inline std::ostream & operator<<( std::ostream & os, byte const & v ) { return os << "[byte:" << std::hex << "0x" << to_integer<int>( v ) << "]"; } } namespace lest { using ::nonstd::operator<<; } // namespace lest #include "lest_cpp03.hpp" extern lest::tests & specification(); #define CASE( name ) lest_CASE( specification(), name ) #endif // TEST_byte_LITE_H_INCLUDED // end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/byte-main.t.cpp
// Copyright 2017-2019 Martin Moene // // https://github.com/martinmoene/byte-lite // // 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) #include "byte-main.t.hpp" #define byte_PRESENT( x ) \ std::cout << #x << ": " << x << "\n" #define byte_ABSENT( x ) \ std::cout << #x << ": (undefined)\n" lest::tests & specification() { static lest::tests tests; return tests; } CASE( "byte-lite version" "[.byte][.version]" ) { byte_PRESENT( byte_lite_MAJOR ); byte_PRESENT( byte_lite_MINOR ); byte_PRESENT( byte_lite_PATCH ); byte_PRESENT( byte_lite_VERSION ); } CASE( "byte configuration" "[.byte][.config]" ) { byte_PRESENT( byte_HAVE_STD_BYTE ); byte_PRESENT( byte_USES_STD_BYTE ); byte_PRESENT( byte_BYTE_DEFAULT ); byte_PRESENT( byte_BYTE_NONSTD ); byte_PRESENT( byte_BYTE_STD ); byte_PRESENT( byte_CONFIG_SELECT_BYTE ); byte_PRESENT( byte_CPLUSPLUS ); } CASE( "__cplusplus" "[.stdc++]" ) { byte_PRESENT( __cplusplus ); } CASE( "compiler version" "[.compiler]" ) { #if byte_USES_STD_BYTE std::cout << "(Compiler version not available: using std::byte)\n"; #else byte_PRESENT( byte_COMPILER_CLANG_VERSION ); byte_PRESENT( byte_COMPILER_GNUC_VERSION ); byte_PRESENT( byte_COMPILER_MSVC_VERSION ); #endif } CASE( "Presence of C++ language features" "[.stdlanguage]" ) { #if byte_USES_STD_BYTE std::cout << "(Presence of C++ language features not available: using std::byte)\n"; #else byte_PRESENT( byte_HAVE_CONSTEXPR_11 ); byte_PRESENT( byte_HAVE_CONSTEXPR_14 ); byte_PRESENT( byte_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG ); byte_PRESENT( byte_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE ); byte_PRESENT( byte_HAVE_NOEXCEPT ); #endif } CASE( "Presence of C++ library features" "[.stdlibrary]" ) { #if byte_USES_STD_BYTE std::cout << "(Presence of C++ library features not available: using std::byte)\n"; #else byte_PRESENT( byte_HAVE_TYPE_TRAITS ); #endif #if defined _HAS_CPP0X byte_PRESENT( _HAS_CPP0X ); #else byte_ABSENT( _HAS_CPP0X ); #endif } int main( int argc, char * argv[] ) { return lest::run( specification(), argc, argv ); } #if 0 g++ -I../include -o byte-main.t.exe byte-main.t.cpp byte.t.cpp && byte-main.t.exe --pass g++ -std=c++98 -I../include -o byte-main.t.exe byte-main.t.cpp byte.t.cpp && byte-main.t.exe --pass g++ -std=c++03 -I../include -o byte-main.t.exe byte-main.t.cpp byte.t.cpp && byte-main.t.exe --pass g++ -std=c++0x -I../include -o byte-main.t.exe byte-main.t.cpp byte.t.cpp && byte-main.t.exe --pass g++ -std=c++11 -I../include -o byte-main.t.exe byte-main.t.cpp byte.t.cpp && byte-main.t.exe --pass g++ -std=c++14 -I../include -o byte-main.t.exe byte-main.t.cpp byte.t.cpp && byte-main.t.exe --pass g++ -std=c++17 -I../include -o byte-main.t.exe byte-main.t.cpp byte.t.cpp && byte-main.t.exe --pass cl -EHsc -I../include byte-main.t.cpp byte.t.cpp && byte-main.t.exe --pass #endif // end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/t.bat
@echo off & setlocal enableextensions enabledelayedexpansion :: :: t.bat - compile & run tests (MSVC). :: set unit=byte :: if no std is given, use compiler default set std=%1 if not "%std%"=="" set std=-std:%std% call :CompilerVersion version echo VC%version%: %args% set UCAP=%unit% call :toupper UCAP set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_DEFAULT ::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_NONSTD ::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_STD set unit_config= set msvc_defines=^ -D_CRT_SECURE_NO_WARNINGS ^ -D_SCL_SECURE_NO_WARNINGS set CppCoreCheckInclude=%VCINSTALLDIR%\Auxiliary\VS\include cl -nologo -W3 -EHsc %std% %unit_select% %unit_config% %msvc_defines% -I"%CppCoreCheckInclude%" -Ilest -I../include -I. %unit%-main.t.cpp %unit%.t.cpp && %unit%-main.t.exe endlocal & goto :EOF :: subroutines: :CompilerVersion version @echo off & setlocal enableextensions set tmpprogram=_getcompilerversion.tmp set tmpsource=%tmpprogram%.c echo #include ^<stdio.h^> >%tmpsource% echo int main(){printf("%%d\n",_MSC_VER);} >>%tmpsource% cl /nologo %tmpsource% >nul for /f %%x in ('%tmpprogram%') do set version=%%x del %tmpprogram%.* >nul set offset=0 if %version% LSS 1900 set /a offset=1 set /a version="version / 10 - 10 * ( 5 + offset )" endlocal & set %1=%version%& goto :EOF :: toupper; makes use of the fact that string :: replacement (via SET) is not case sensitive :toupper for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L! goto :EOF
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test
repos/outcome/test/quickcpplib/include/quickcpplib/byte/test/lest/lest_cpp03.hpp
// Copyright 2013-2018 by Martin Moene // // lest is based on ideas by Kevlin Henney, see video at // http://skillsmatter.com/podcast/agile-testing/kevlin-henney-rethinking-unit-testing-in-c-plus-plus // // 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) #ifndef LEST_LEST_HPP_INCLUDED #define LEST_LEST_HPP_INCLUDED #include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <sstream> #include <stdexcept> #include <set> #include <string> #include <utility> #include <vector> #include <cctype> #include <cmath> #include <cstddef> #include <cstdlib> #include <ctime> #define lest_MAJOR 1 #define lest_MINOR 35 #define lest_PATCH 1 #define lest_VERSION lest_STRINGIFY(lest_MAJOR) "." lest_STRINGIFY(lest_MINOR) "." lest_STRINGIFY(lest_PATCH) #ifndef lest_FEATURE_COLOURISE # define lest_FEATURE_COLOURISE 0 #endif #ifndef lest_FEATURE_LITERAL_SUFFIX # define lest_FEATURE_LITERAL_SUFFIX 0 #endif #ifndef lest_FEATURE_REGEX_SEARCH # define lest_FEATURE_REGEX_SEARCH 0 #endif #ifndef lest_FEATURE_TIME # define lest_FEATURE_TIME 1 #endif #ifndef lest_FEATURE_TIME_PRECISION #define lest_FEATURE_TIME_PRECISION 0 #endif #ifdef _WIN32 # define lest_PLATFORM_IS_WINDOWS 1 #else # define lest_PLATFORM_IS_WINDOWS 0 #endif #if lest_FEATURE_REGEX_SEARCH # include <regex> #endif #if lest_FEATURE_TIME # if lest_PLATFORM_IS_WINDOWS # include <iomanip> # include <Windows.h> # else # include <iomanip> # include <sys/time.h> # endif #endif // Compiler warning suppression: #if defined (__clang__) # pragma clang diagnostic ignored "-Waggregate-return" # pragma clang diagnostic ignored "-Woverloaded-shift-op-parentheses" # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wdate-time" #elif defined (__GNUC__) # pragma GCC diagnostic ignored "-Waggregate-return" # pragma GCC diagnostic push #endif // Suppress shadow and unused-value warning for sections: #if defined (__clang__) # define lest_SUPPRESS_WSHADOW _Pragma( "clang diagnostic push" ) \ _Pragma( "clang diagnostic ignored \"-Wshadow\"" ) # define lest_SUPPRESS_WUNUSED _Pragma( "clang diagnostic push" ) \ _Pragma( "clang diagnostic ignored \"-Wunused-value\"" ) # define lest_RESTORE_WARNINGS _Pragma( "clang diagnostic pop" ) #elif defined (__GNUC__) # define lest_SUPPRESS_WSHADOW _Pragma( "GCC diagnostic push" ) \ _Pragma( "GCC diagnostic ignored \"-Wshadow\"" ) # define lest_SUPPRESS_WUNUSED _Pragma( "GCC diagnostic push" ) \ _Pragma( "GCC diagnostic ignored \"-Wunused-value\"" ) # define lest_RESTORE_WARNINGS _Pragma( "GCC diagnostic pop" ) #else # define lest_SUPPRESS_WSHADOW /*empty*/ # define lest_SUPPRESS_WUNUSED /*empty*/ # define lest_RESTORE_WARNINGS /*empty*/ #endif // Stringify: #define lest_STRINGIFY( x ) lest_STRINGIFY_( x ) #define lest_STRINGIFY_( x ) #x // Compiler versions: #if defined( _MSC_VER ) && !defined( __clang__ ) # define lest_COMPILER_MSVC_VERSION ( _MSC_VER / 10 - 10 * ( 5 + ( _MSC_VER < 1900 ) ) ) #else # define lest_COMPILER_MSVC_VERSION 0 #endif #define lest_COMPILER_VERSION( major, minor, patch ) ( 10 * ( 10 * major + minor ) + patch ) #if defined (__clang__) # define lest_COMPILER_CLANG_VERSION lest_COMPILER_VERSION( __clang_major__, __clang_minor__, __clang_patchlevel__ ) #else # define lest_COMPILER_CLANG_VERSION 0 #endif #if defined (__GNUC__) # define lest_COMPILER_GNUC_VERSION lest_COMPILER_VERSION( __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__ ) #else # define lest_COMPILER_GNUC_VERSION 0 #endif // C++ language version detection (C++20 is speculative): // Note: VC14.0/1900 (VS2015) lacks too much from C++14. #ifndef lest_CPLUSPLUS # if defined(_MSVC_LANG ) && !defined(__clang__) # define lest_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) # else # define lest_CPLUSPLUS __cplusplus # endif #endif #define lest_CPP98_OR_GREATER ( lest_CPLUSPLUS >= 199711L ) #define lest_CPP11_OR_GREATER ( lest_CPLUSPLUS >= 201103L || lest_COMPILER_MSVC_VERSION >= 120 ) #define lest_CPP14_OR_GREATER ( lest_CPLUSPLUS >= 201402L ) #define lest_CPP17_OR_GREATER ( lest_CPLUSPLUS >= 201703L ) #define lest_CPP20_OR_GREATER ( lest_CPLUSPLUS >= 202000L ) #define lest_CPP11_100 (lest_CPP11_OR_GREATER || lest_COMPILER_MSVC_VERSION >= 100) #ifndef __has_cpp_attribute # define __has_cpp_attribute(name) 0 #endif // Indicate argument as possibly unused, if possible: #if __has_cpp_attribute(maybe_unused) && lest_CPP17_OR_GREATER # define lest_MAYBE_UNUSED(ARG) [[maybe_unused]] ARG #elif defined (__GNUC__) # define lest_MAYBE_UNUSED(ARG) ARG __attribute((unused)) #else # define lest_MAYBE_UNUSED(ARG) ARG #endif // Presence of language and library features: #define lest_HAVE(FEATURE) ( lest_HAVE_##FEATURE ) // Presence of C++11 language features: #define lest_HAVE_NOEXCEPT ( lest_CPP11_100 ) #define lest_HAVE_NULLPTR ( lest_CPP11_100 ) // C++ feature usage: #if lest_HAVE( NULLPTR ) # define lest_nullptr nullptr #else # define lest_nullptr NULL #endif // Additional includes and tie: #if lest_CPP11_100 # include <cstdint> # include <random> # include <tuple> namespace lest { using std::tie; } #else # if !defined(__clang__) && defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Weffc++" # endif namespace lest { // tie: template< typename T1, typename T2 > struct Tie { Tie( T1 & first_, T2 & second_) : first( first_), second( second_) {} std::pair<T1, T2> const & operator=( std::pair<T1, T2> const & rhs ) { first = rhs.first; second = rhs.second; return rhs; } private: void operator=( Tie const & ); T1 & first; T2 & second; }; template< typename T1, typename T2 > inline Tie<T1,T2> tie( T1 & first, T2 & second ) { return Tie<T1, T2>( first, second ); } } # if !defined(__clang__) && defined(__GNUC__) # pragma GCC diagnostic pop # endif #endif // lest_CPP11_100 namespace lest { using std::abs; using std::min; using std::strtol; using std::rand; using std::srand; } #if ! defined( lest_NO_SHORT_MACRO_NAMES ) && ! defined( lest_NO_SHORT_ASSERTION_NAMES ) # define SETUP lest_SETUP # define SECTION lest_SECTION # define EXPECT lest_EXPECT # define EXPECT_NOT lest_EXPECT_NOT # define EXPECT_NO_THROW lest_EXPECT_NO_THROW # define EXPECT_THROWS lest_EXPECT_THROWS # define EXPECT_THROWS_AS lest_EXPECT_THROWS_AS # define SCENARIO lest_SCENARIO # define GIVEN lest_GIVEN # define WHEN lest_WHEN # define THEN lest_THEN # define AND_WHEN lest_AND_WHEN # define AND_THEN lest_AND_THEN #endif #define lest_SCENARIO( specification, sketch ) \ lest_CASE( specification, lest::text("Scenario: ") + sketch ) #define lest_GIVEN( context ) lest_SETUP( lest::text(" Given: ") + context ) #define lest_WHEN( story ) lest_SECTION( lest::text(" When: ") + story ) #define lest_THEN( story ) lest_SECTION( lest::text(" Then: ") + story ) #define lest_AND_WHEN( story ) lest_SECTION( lest::text("And then: ") + story ) #define lest_AND_THEN( story ) lest_SECTION( lest::text("And then: ") + story ) #define lest_CASE( specification, proposition ) \ static void lest_FUNCTION( lest::env & ); \ namespace { lest::add_test lest_REGISTRAR( specification, lest::test( proposition, lest_FUNCTION ) ); } \ static void lest_FUNCTION( lest_MAYBE_UNUSED( lest::env & lest_env ) ) #define lest_ADD_TEST( specification, test ) \ specification.push_back( test ) #define lest_SETUP( context ) \ for ( int lest__section = 0, lest__count = 1; lest__section < lest__count; lest__count -= 0==lest__section++ ) \ for ( lest::ctx lest__ctx_setup( lest_env, context ); lest__ctx_setup; ) #define lest_SECTION( proposition ) \ lest_SUPPRESS_WSHADOW \ static int lest_UNIQUE( id ) = 0; \ if ( lest::guard( lest_UNIQUE( id ), lest__section, lest__count ) ) \ for ( int lest__section = 0, lest__count = 1; lest__section < lest__count; lest__count -= 0==lest__section++ ) \ for ( lest::ctx lest__ctx_section( lest_env, proposition ); lest__ctx_section; ) \ lest_RESTORE_WARNINGS #define lest_EXPECT( expr ) \ do { \ try \ { \ if ( lest::result score = lest_DECOMPOSE( expr ) ) \ throw lest::failure( lest_LOCATION, #expr, score.decomposition ); \ else if ( lest_env.pass() ) \ lest::report( lest_env.os, lest::passing( lest_LOCATION, #expr, score.decomposition, lest_env.zen() ), lest_env.context() ); \ } \ catch(...) \ { \ lest::inform( lest_LOCATION, #expr ); \ } \ } while ( lest::is_false() ) #define lest_EXPECT_NOT( expr ) \ do { \ try \ { \ if ( lest::result score = lest_DECOMPOSE( expr ) ) \ { \ if ( lest_env.pass() ) \ lest::report( lest_env.os, lest::passing( lest_LOCATION, lest::not_expr( #expr ), lest::not_expr( score.decomposition ), lest_env.zen() ), lest_env.context() ); \ } \ else \ throw lest::failure( lest_LOCATION, lest::not_expr( #expr ), lest::not_expr( score.decomposition ) ); \ } \ catch(...) \ { \ lest::inform( lest_LOCATION, lest::not_expr( #expr ) ); \ } \ } while ( lest::is_false() ) #define lest_EXPECT_NO_THROW( expr ) \ do \ { \ try \ { \ lest_SUPPRESS_WUNUSED \ expr; \ lest_RESTORE_WARNINGS \ } \ catch (...) { lest::inform( lest_LOCATION, #expr ); } \ if ( lest_env.pass() ) \ lest::report( lest_env.os, lest::got_none( lest_LOCATION, #expr ), lest_env.context() ); \ } while ( lest::is_false() ) #define lest_EXPECT_THROWS( expr ) \ do \ { \ try \ { \ lest_SUPPRESS_WUNUSED \ expr; \ lest_RESTORE_WARNINGS \ } \ catch (...) \ { \ if ( lest_env.pass() ) \ lest::report( lest_env.os, lest::got( lest_LOCATION, #expr ), lest_env.context() ); \ break; \ } \ throw lest::expected( lest_LOCATION, #expr ); \ } \ while ( lest::is_false() ) #define lest_EXPECT_THROWS_AS( expr, excpt ) \ do \ { \ try \ { \ lest_SUPPRESS_WUNUSED \ expr; \ lest_RESTORE_WARNINGS \ } \ catch ( excpt & ) \ { \ if ( lest_env.pass() ) \ lest::report( lest_env.os, lest::got( lest_LOCATION, #expr, lest::of_type( #excpt ) ), lest_env.context() ); \ break; \ } \ catch (...) {} \ throw lest::expected( lest_LOCATION, #expr, lest::of_type( #excpt ) ); \ } \ while ( lest::is_false() ) #define lest_DECOMPOSE( expr ) ( lest::expression_decomposer() << expr ) #define lest_STRING( name ) lest_STRING2( name ) #define lest_STRING2( name ) #name #define lest_UNIQUE( name ) lest_UNIQUE2( name, __LINE__ ) #define lest_UNIQUE2( name, line ) lest_UNIQUE3( name, line ) #define lest_UNIQUE3( name, line ) name ## line #define lest_LOCATION lest::location(__FILE__, __LINE__) #define lest_FUNCTION lest_UNIQUE(__lest_function__ ) #define lest_REGISTRAR lest_UNIQUE(__lest_registrar__ ) #define lest_DIMENSION_OF( a ) ( sizeof(a) / sizeof(0[a]) ) namespace lest { const int exit_max_value = 255; typedef std::string text; typedef std::vector<text> texts; struct env; struct test { text name; void (* behaviour)( env & ); test( text name_, void (* behaviour_)( env & ) ) : name( name_), behaviour( behaviour_) {} }; typedef std::vector<test> tests; typedef tests test_specification; struct add_test { add_test( tests & specification, test const & test_case ) { specification.push_back( test_case ); } }; struct result { const bool passed; const text decomposition; template< typename T > result( T const & passed_, text decomposition_) : passed( !!passed_), decomposition( decomposition_) {} operator bool() { return ! passed; } }; struct location { const text file; const int line; location( text file_, int line_) : file( file_), line( line_) {} }; struct comment { const text info; comment( text info_) : info( info_) {} operator bool() { return ! info.empty(); } }; struct message : std::runtime_error { const text kind; const location where; const comment note; #if ! lest_CPP11_OR_GREATER ~message() throw() {} #endif message( text kind_, location where_, text expr_, text note_ = "" ) : std::runtime_error( expr_), kind( kind_), where( where_), note( note_) {} }; struct failure : message { failure( location where_, text expr_, text decomposition_) : message( "failed", where_, expr_ + " for " + decomposition_) {} }; struct success : message { success( text kind_, location where_, text expr_, text note_ = "" ) : message( kind_, where_, expr_, note_) {} }; struct passing : success { passing( location where_, text expr_, text decomposition_, bool zen ) : success( "passed", where_, expr_ + (zen ? "":" for " + decomposition_) ) {} }; struct got_none : success { got_none( location where_, text expr_) : success( "passed: got no exception", where_, expr_) {} }; struct got : success { got( location where_, text expr_) : success( "passed: got exception", where_, expr_) {} got( location where_, text expr_, text excpt_) : success( "passed: got exception " + excpt_, where_, expr_) {} }; struct expected : message { expected( location where_, text expr_, text excpt_ = "" ) : message( "failed: didn't get exception", where_, expr_, excpt_) {} }; struct unexpected : message { unexpected( location where_, text expr_, text note_ = "" ) : message( "failed: got unexpected exception", where_, expr_, note_) {} }; struct guard { int & id; int const & section; guard( int & id_, int const & section_, int & count ) : id( id_ ), section( section_ ) { if ( section == 0 ) id = count++ - 1; } operator bool() { return id == section; } }; class approx { public: explicit approx ( double magnitude ) : epsilon_ ( 100.0 * static_cast<double>( std::numeric_limits<float>::epsilon() ) ) , scale_ ( 1.0 ) , magnitude_( magnitude ) {} static approx custom() { return approx( 0 ); } approx operator()( double new_magnitude ) { approx appr( new_magnitude ); appr.epsilon( epsilon_ ); appr.scale ( scale_ ); return appr; } double magnitude() const { return magnitude_; } approx & epsilon( double epsilon ) { epsilon_ = epsilon; return *this; } approx & scale ( double scale ) { scale_ = scale; return *this; } friend bool operator == ( double lhs, approx const & rhs ) { // Thanks to Richard Harris for his help refining this formula. return lest::abs( lhs - rhs.magnitude_ ) < rhs.epsilon_ * ( rhs.scale_ + (lest::min)( lest::abs( lhs ), lest::abs( rhs.magnitude_ ) ) ); } friend bool operator == ( approx const & lhs, double rhs ) { return operator==( rhs, lhs ); } friend bool operator != ( double lhs, approx const & rhs ) { return !operator==( lhs, rhs ); } friend bool operator != ( approx const & lhs, double rhs ) { return !operator==( rhs, lhs ); } friend bool operator <= ( double lhs, approx const & rhs ) { return lhs < rhs.magnitude_ || lhs == rhs; } friend bool operator <= ( approx const & lhs, double rhs ) { return lhs.magnitude_ < rhs || lhs == rhs; } friend bool operator >= ( double lhs, approx const & rhs ) { return lhs > rhs.magnitude_ || lhs == rhs; } friend bool operator >= ( approx const & lhs, double rhs ) { return lhs.magnitude_ > rhs || lhs == rhs; } private: double epsilon_; double scale_; double magnitude_; }; inline bool is_false( ) { return false; } inline bool is_true ( bool flag ) { return flag; } inline text not_expr( text message ) { return "! ( " + message + " )"; } inline text with_message( text message ) { return "with message \"" + message + "\""; } inline text of_type( text type ) { return "of type " + type; } inline void inform( location where, text expr ) { try { throw; } catch( failure const & ) { throw; } catch( std::exception const & e ) { throw unexpected( where, expr, with_message( e.what() ) ); \ } catch(...) { throw unexpected( where, expr, "of unknown type" ); \ } } // Expression decomposition: inline bool unprintable( char c ) { return 0 <= c && c < ' '; } inline std::string to_hex_string(char c) { std::ostringstream os; os << "\\x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>( static_cast<unsigned char>(c) ); return os.str(); } inline std::string transformed( char chr ) { struct Tr { char chr; char const * str; } table[] = { {'\\', "\\\\" }, {'\r', "\\r" }, {'\f', "\\f" }, {'\n', "\\n" }, {'\t', "\\t" }, }; for ( Tr * pos = table; pos != table + lest_DIMENSION_OF( table ); ++pos ) { if ( chr == pos->chr ) return pos->str; } return unprintable( chr ) ? to_hex_string( chr ) : std::string( 1, chr ); } inline std::string make_tran_string( std::string const & txt ) { std::ostringstream os; for( std::string::const_iterator pos = txt.begin(); pos != txt.end(); ++pos ) os << transformed( *pos ); return os.str(); } template< typename T > inline std::string to_string( T const & value ); #if lest_CPP11_OR_GREATER || lest_COMPILER_MSVC_VERSION >= 100 inline std::string to_string( std::nullptr_t const & ) { return "nullptr"; } #endif inline std::string to_string( std::string const & txt ) { return "\"" + make_tran_string( txt ) + "\""; } inline std::string to_string( char const * const & txt ) { return "\"" + make_tran_string( txt ) + "\""; } inline std::string to_string( char const & chr ) { return "'" + make_tran_string( std::string( 1, chr ) ) + "'"; } inline std::string to_string( signed char const & chr ) { return to_string( static_cast<char const &>( chr ) ); } inline std::string to_string( unsigned char const & chr ) { return to_string( static_cast<char const &>( chr ) ); } inline std::ostream & operator<<( std::ostream & os, approx const & appr ) { return os << appr.magnitude(); } template< typename T > inline std::string make_string( T const * ptr ) { // Note showbase affects the behavior of /integer/ output; std::ostringstream os; os << std::internal << std::hex << std::showbase << std::setw( 2 + 2 * sizeof(T*) ) << std::setfill('0') << reinterpret_cast<std::ptrdiff_t>( ptr ); return os.str(); } template< typename C, typename R > inline std::string make_string( R C::* ptr ) { std::ostringstream os; os << std::internal << std::hex << std::showbase << std::setw( 2 + 2 * sizeof(R C::* ) ) << std::setfill('0') << ptr; return os.str(); } template< typename T > struct string_maker { static std::string to_string( T const & value ) { std::ostringstream os; os << std::boolalpha << value; return os.str(); } }; template< typename T > struct string_maker< T* > { static std::string to_string( T const * ptr ) { return ! ptr ? lest_STRING( lest_nullptr ) : make_string( ptr ); } }; template< typename C, typename R > struct string_maker< R C::* > { static std::string to_string( R C::* ptr ) { return ! ptr ? lest_STRING( lest_nullptr ) : make_string( ptr ); } }; template< typename T > inline std::string to_string( T const & value ) { return string_maker<T>::to_string( value ); } template< typename T1, typename T2 > std::string to_string( std::pair<T1,T2> const & pair ) { std::ostringstream oss; oss << "{ " << to_string( pair.first ) << ", " << to_string( pair.second ) << " }"; return oss.str(); } #if lest_CPP11_OR_GREATER template< typename TU, std::size_t N > struct make_tuple_string { static std::string make( TU const & tuple ) { std::ostringstream os; os << to_string( std::get<N - 1>( tuple ) ) << ( N < std::tuple_size<TU>::value ? ", ": " "); return make_tuple_string<TU, N - 1>::make( tuple ) + os.str(); } }; template< typename TU > struct make_tuple_string<TU, 0> { static std::string make( TU const & ) { return ""; } }; template< typename ...TS > auto to_string( std::tuple<TS...> const & tuple ) -> std::string { return "{ " + make_tuple_string<std::tuple<TS...>, sizeof...(TS)>::make( tuple ) + "}"; } #endif // lest_CPP11_OR_GREATER template< typename L, typename R > std::string to_string( L const & lhs, std::string op, R const & rhs ) { std::ostringstream os; os << to_string( lhs ) << " " << op << " " << to_string( rhs ); return os.str(); } template< typename L > struct expression_lhs { L lhs; expression_lhs( L lhs_) : lhs( lhs_) {} operator result() { return result( !!lhs, to_string( lhs ) ); } template< typename R > result operator==( R const & rhs ) { return result( lhs == rhs, to_string( lhs, "==", rhs ) ); } template< typename R > result operator!=( R const & rhs ) { return result( lhs != rhs, to_string( lhs, "!=", rhs ) ); } template< typename R > result operator< ( R const & rhs ) { return result( lhs < rhs, to_string( lhs, "<" , rhs ) ); } template< typename R > result operator<=( R const & rhs ) { return result( lhs <= rhs, to_string( lhs, "<=", rhs ) ); } template< typename R > result operator> ( R const & rhs ) { return result( lhs > rhs, to_string( lhs, ">" , rhs ) ); } template< typename R > result operator>=( R const & rhs ) { return result( lhs >= rhs, to_string( lhs, ">=", rhs ) ); } }; struct expression_decomposer { template< typename L > expression_lhs<L const &> operator<< ( L const & operand ) { return expression_lhs<L const &>( operand ); } }; // Reporter: #if lest_FEATURE_COLOURISE inline text red ( text words ) { return "\033[1;31m" + words + "\033[0m"; } inline text green( text words ) { return "\033[1;32m" + words + "\033[0m"; } inline text gray ( text words ) { return "\033[1;30m" + words + "\033[0m"; } inline bool starts_with( text words, text with ) { return 0 == words.find( with ); } inline text replace( text words, text from, text to ) { size_t pos = words.find( from ); return pos == std::string::npos ? words : words.replace( pos, from.length(), to ); } inline text colour( text words ) { if ( starts_with( words, "failed" ) ) return replace( words, "failed", red ( "failed" ) ); else if ( starts_with( words, "passed" ) ) return replace( words, "passed", green( "passed" ) ); return replace( words, "for", gray( "for" ) ); } inline bool is_cout( std::ostream & os ) { return &os == &std::cout; } struct colourise { const text words; colourise( text words ) : words( words ) {} // only colourise for std::cout, not for a stringstream as used in tests: std::ostream & operator()( std::ostream & os ) const { return is_cout( os ) ? os << colour( words ) : os << words; } }; inline std::ostream & operator<<( std::ostream & os, colourise words ) { return words( os ); } #else inline text colourise( text words ) { return words; } #endif inline text pluralise( text word,int n ) { return n == 1 ? word : word + "s"; } inline std::ostream & operator<<( std::ostream & os, comment note ) { return os << (note ? " " + note.info : "" ); } inline std::ostream & operator<<( std::ostream & os, location where ) { #ifdef __GNUG__ return os << where.file << ":" << where.line; #else return os << where.file << "(" << where.line << ")"; #endif } inline void report( std::ostream & os, message const & e, text test ) { os << e.where << ": " << colourise( e.kind ) << e.note << ": " << test << ": " << colourise( e.what() ) << std::endl; } // Test runner: #if lest_FEATURE_REGEX_SEARCH inline bool search( text re, text line ) { return std::regex_search( line, std::regex( re ) ); } #else inline bool case_insensitive_equal( char a, char b ) { return tolower( a ) == tolower( b ); } inline bool search( text part, text line ) { return std::search( line.begin(), line.end(), part.begin(), part.end(), case_insensitive_equal ) != line.end(); } #endif inline bool match( texts whats, text line ) { for ( texts::iterator what = whats.begin(); what != whats.end() ; ++what ) { if ( search( *what, line ) ) return true; } return false; } inline bool hidden( text name ) { #if lest_FEATURE_REGEX_SEARCH texts skipped; skipped.push_back( "\\[\\.\\]" ); skipped.push_back( "\\[hide\\]" ); #else texts skipped; skipped.push_back( "[." ); skipped.push_back( "[hide]" ); #endif return match( skipped, name ); } inline bool none( texts args ) { return args.size() == 0; } inline bool select( text name, texts include ) { if ( none( include ) ) { return ! hidden( name ); } bool any = false; for ( texts::reverse_iterator pos = include.rbegin(); pos != include.rend(); ++pos ) { text & part = *pos; if ( part == "@" || part == "*" ) return true; if ( search( part, name ) ) return true; if ( '!' == part[0] ) { any = true; if ( search( part.substr(1), name ) ) return false; } else { any = false; } } return any && ! hidden( name ); } inline int indefinite( int repeat ) { return repeat == -1; } #if lest_CPP11_OR_GREATER typedef std::mt19937::result_type seed_t; #else typedef unsigned int seed_t; #endif struct options { options() : help(false), abort(false), count(false), list(false), tags(false), time(false) , pass(false), zen(false), lexical(false), random(false), verbose(false), version(false), repeat(1), seed(0) {} bool help; bool abort; bool count; bool list; bool tags; bool time; bool pass; bool zen; bool lexical; bool random; bool verbose; bool version; int repeat; seed_t seed; }; struct env { std::ostream & os; options opt; text testing; std::vector< text > ctx; env( std::ostream & out, options option ) : os( out ), opt( option ), testing(), ctx() {} env & operator()( text test ) { clear(); testing = test; return *this; } bool abort() { return opt.abort; } bool pass() { return opt.pass; } bool zen() { return opt.zen; } void clear() { ctx.clear(); } void pop() { ctx.pop_back(); } void push( text proposition ) { ctx.push_back( proposition ); } text context() { return testing + sections(); } text sections() { if ( ! opt.verbose ) return ""; text msg; for( size_t i = 0; i != ctx.size(); ++i ) { msg += "\n " + ctx[i]; } return msg; } }; struct ctx { env & environment; bool once; ctx( env & environment_, text proposition_ ) : environment( environment_), once( true ) { environment.push( proposition_); } ~ctx() { #if lest_CPP17_OR_GREATER if ( std::uncaught_exceptions() == 0 ) #else if ( ! std::uncaught_exception() ) #endif { environment.pop(); } } operator bool() { bool result = once; once = false; return result; } }; struct action { std::ostream & os; action( std::ostream & out ) : os( out ) {} operator int() { return 0; } bool abort() { return false; } action & operator()( test ) { return *this; } private: action( action const & ); void operator=( action const & ); }; struct print : action { print( std::ostream & out ) : action( out ) {} print & operator()( test testing ) { os << testing.name << "\n"; return *this; } }; inline texts tags( text name, texts result = texts() ) { size_t none = std::string::npos; size_t lb = name.find_first_of( "[" ); size_t rb = name.find_first_of( "]" ); if ( lb == none || rb == none ) return result; result.push_back( name.substr( lb, rb - lb + 1 ) ); return tags( name.substr( rb + 1 ), result ); } struct ptags : action { std::set<text> result; ptags( std::ostream & out ) : action( out ), result() {} ptags & operator()( test testing ) { texts tags_( tags( testing.name ) ); for ( texts::iterator pos = tags_.begin(); pos != tags_.end() ; ++pos ) result.insert( *pos ); return *this; } ~ptags() { std::copy( result.begin(), result.end(), std::ostream_iterator<text>( os, "\n" ) ); } }; struct count : action { int n; count( std::ostream & out ) : action( out ), n( 0 ) {} count & operator()( test ) { ++n; return *this; } ~count() { os << n << " selected " << pluralise("test", n) << "\n"; } }; #if lest_FEATURE_TIME #if lest_PLATFORM_IS_WINDOWS # if ! lest_CPP11_OR_GREATER && ! lest_COMPILER_MSVC_VERSION typedef unsigned long uint64_t; # elif lest_COMPILER_MSVC_VERSION >= 60 && lest_COMPILER_MSVC_VERSION < 100 typedef /*un*/signed __int64 uint64_t; # else using ::uint64_t; # endif #else # if ! lest_CPP11_OR_GREATER typedef unsigned long long uint64_t; # endif #endif #if lest_PLATFORM_IS_WINDOWS inline uint64_t current_ticks() { static LARGE_INTEGER hz = {{ 0,0 }}, hzo = {{ 0,0 }}; if ( ! hz.QuadPart ) { QueryPerformanceFrequency( &hz ); QueryPerformanceCounter ( &hzo ); } LARGE_INTEGER t = {{ 0,0 }}; QueryPerformanceCounter( &t ); return uint64_t( ( ( t.QuadPart - hzo.QuadPart ) * 1000000 ) / hz.QuadPart ); } #else inline uint64_t current_ticks() { timeval t; gettimeofday( &t, lest_nullptr ); return static_cast<uint64_t>( t.tv_sec ) * 1000000ull + static_cast<uint64_t>( t.tv_usec ); } #endif struct timer { const uint64_t start_ticks; timer() : start_ticks( current_ticks() ) {} double elapsed_seconds() const { return static_cast<double>( current_ticks() - start_ticks ) / 1e6; } }; struct times : action { env output; int selected; int failures; timer total; times( std::ostream & out, options option ) : action( out ), output( out, option ), selected( 0 ), failures( 0 ), total() { os << std::setfill(' ') << std::fixed << std::setprecision( lest_FEATURE_TIME_PRECISION ); } operator int() { return failures; } bool abort() { return output.abort() && failures > 0; } times & operator()( test testing ) { timer t; try { testing.behaviour( output( testing.name ) ); } catch( message const & ) { ++failures; } os << std::setw(5) << ( 1000 * t.elapsed_seconds() ) << " ms: " << testing.name << "\n"; return *this; } ~times() { os << "Elapsed time: " << std::setprecision(1) << total.elapsed_seconds() << " s\n"; } }; #else struct times : action { times( std::ostream & out, options ) : action( out ) {} }; #endif struct confirm : action { env output; int selected; int failures; confirm( std::ostream & out, options option ) : action( out ), output( out, option ), selected( 0 ), failures( 0 ) {} operator int() { return failures; } bool abort() { return output.abort() && failures > 0; } confirm & operator()( test testing ) { try { ++selected; testing.behaviour( output( testing.name ) ); } catch( message const & e ) { ++failures; report( os, e, output.context() ); } return *this; } ~confirm() { if ( failures > 0 ) { os << failures << " out of " << selected << " selected " << pluralise("test", selected) << " " << colourise( "failed.\n" ); } else if ( output.pass() ) { os << "All " << selected << " selected " << pluralise("test", selected) << " " << colourise( "passed.\n" ); } } }; template< typename Action > bool abort( Action & perform ) { return perform.abort(); } template< typename Action > Action & for_test( tests specification, texts in, Action & perform, int n = 1 ) { for ( int i = 0; indefinite( n ) || i < n; ++i ) { for ( tests::iterator pos = specification.begin(); pos != specification.end() ; ++pos ) { test & testing = *pos; if ( select( testing.name, in ) ) if ( abort( perform( testing ) ) ) return perform; } } return perform; } inline bool test_less( test const & a, test const & b ) { return a.name < b.name; } inline void sort( tests & specification ) { std::sort( specification.begin(), specification.end(), test_less ); } // Use struct to avoid VC6 error C2664 when using free function: struct rng { int operator()( int n ) { return lest::rand() % n; } }; inline void shuffle( tests & specification, options option ) { #if lest_CPP11_OR_GREATER std::shuffle( specification.begin(), specification.end(), std::mt19937( option.seed ) ); #else lest::srand( option.seed ); rng generator; std::random_shuffle( specification.begin(), specification.end(), generator ); #endif } inline int stoi( text num ) { return static_cast<int>( lest::strtol( num.c_str(), lest_nullptr, 10 ) ); } inline bool is_number( text arg ) { const text digits = "0123456789"; return text::npos != arg.find_first_of ( digits ) && text::npos == arg.find_first_not_of( digits ); } inline seed_t seed( text opt, text arg ) { // std::time_t: implementation dependent if ( arg == "time" ) return static_cast<seed_t>( time( lest_nullptr ) ); if ( is_number( arg ) ) return static_cast<seed_t>( lest::stoi( arg ) ); throw std::runtime_error( "expecting 'time' or positive number with option '" + opt + "', got '" + arg + "' (try option --help)" ); } inline int repeat( text opt, text arg ) { const int num = lest::stoi( arg ); if ( indefinite( num ) || num >= 0 ) return num; throw std::runtime_error( "expecting '-1' or positive number with option '" + opt + "', got '" + arg + "' (try option --help)" ); } inline std::pair<text, text> split_option( text arg ) { text::size_type pos = arg.rfind( '=' ); return pos == text::npos ? std::make_pair( arg, text() ) : std::make_pair( arg.substr( 0, pos ), arg.substr( pos + 1 ) ); } inline std::pair<options, texts> split_arguments( texts args ) { options option; texts in; bool in_options = true; for ( texts::iterator pos = args.begin(); pos != args.end() ; ++pos ) { text opt, val, arg = *pos; tie( opt, val ) = split_option( arg ); if ( in_options ) { if ( opt[0] != '-' ) { in_options = false; } else if ( opt == "--" ) { in_options = false; continue; } else if ( opt == "-h" || "--help" == opt ) { option.help = true; continue; } else if ( opt == "-a" || "--abort" == opt ) { option.abort = true; continue; } else if ( opt == "-c" || "--count" == opt ) { option.count = true; continue; } else if ( opt == "-g" || "--list-tags" == opt ) { option.tags = true; continue; } else if ( opt == "-l" || "--list-tests" == opt ) { option.list = true; continue; } else if ( opt == "-t" || "--time" == opt ) { option.time = true; continue; } else if ( opt == "-p" || "--pass" == opt ) { option.pass = true; continue; } else if ( opt == "-z" || "--pass-zen" == opt ) { option.zen = true; continue; } else if ( opt == "-v" || "--verbose" == opt ) { option.verbose = true; continue; } else if ( "--version" == opt ) { option.version = true; continue; } else if ( opt == "--order" && "declared" == val ) { /* by definition */ ; continue; } else if ( opt == "--order" && "lexical" == val ) { option.lexical = true; continue; } else if ( opt == "--order" && "random" == val ) { option.random = true; continue; } else if ( opt == "--random-seed" ) { option.seed = seed ( "--random-seed", val ); continue; } else if ( opt == "--repeat" ) { option.repeat = repeat( "--repeat" , val ); continue; } else throw std::runtime_error( "unrecognised option '" + opt + "' (try option --help)" ); } in.push_back( arg ); } option.pass = option.pass || option.zen; return std::make_pair( option, in ); } inline int usage( std::ostream & os ) { os << "\nUsage: test [options] [test-spec ...]\n" "\n" "Options:\n" " -h, --help this help message\n" " -a, --abort abort at first failure\n" " -c, --count count selected tests\n" " -g, --list-tags list tags of selected tests\n" " -l, --list-tests list selected tests\n" " -p, --pass also report passing tests\n" " -z, --pass-zen ... without expansion\n" #if lest_FEATURE_TIME " -t, --time list duration of selected tests\n" #endif " -v, --verbose also report passing or failing sections\n" " --order=declared use source code test order (default)\n" " --order=lexical use lexical sort test order\n" " --order=random use random test order\n" " --random-seed=n use n for random generator seed\n" " --random-seed=time use time for random generator seed\n" " --repeat=n repeat selected tests n times (-1: indefinite)\n" " --version report lest version and compiler used\n" " -- end options\n" "\n" "Test specification:\n" " \"@\", \"*\" all tests, unless excluded\n" " empty all tests, unless tagged [hide] or [.optional-name]\n" #if lest_FEATURE_REGEX_SEARCH " \"re\" select tests that match regular expression\n" " \"!re\" omit tests that match regular expression\n" #else " \"text\" select tests that contain text (case insensitive)\n" " \"!text\" omit tests that contain text (case insensitive)\n" #endif ; return 0; } inline text compiler() { std::ostringstream os; #if defined (__clang__ ) os << "clang " << __clang_version__; #elif defined (__GNUC__ ) os << "gcc " << __GNUC__ << "." << __GNUC_MINOR__ << "." << __GNUC_PATCHLEVEL__; #elif defined ( _MSC_VER ) os << "MSVC " << lest_COMPILER_MSVC_VERSION << " (" << _MSC_VER << ")"; #else os << "[compiler]"; #endif return os.str(); } inline int version( std::ostream & os ) { os << "lest version " << lest_VERSION << "\n" << "Compiled with " << compiler() << " on " << __DATE__ << " at " << __TIME__ << ".\n" << "For more information, see https://github.com/martinmoene/lest.\n"; return 0; } inline int run( tests specification, texts arguments, std::ostream & os = std::cout ) { try { options option; texts in; tie( option, in ) = split_arguments( arguments ); if ( option.lexical ) { sort( specification ); } if ( option.random ) { shuffle( specification, option ); } if ( option.help ) { return usage ( os ); } if ( option.version ) { return version( os ); } if ( option.count ) { count count_( os ); return for_test( specification, in, count_ ); } if ( option.list ) { print print_( os ); return for_test( specification, in, print_ ); } if ( option.tags ) { ptags ptags_( os ); return for_test( specification, in, ptags_ ); } if ( option.time ) { times times_( os, option ); return for_test( specification, in, times_ ); } { confirm confirm_( os, option ); return for_test( specification, in, confirm_, option.repeat ); } } catch ( std::exception const & e ) { os << "Error: " << e.what() << "\n"; return 1; } } // VC6: make<cont>(first,last) replaces cont(first,last) template< typename C, typename T > C make( T const * first, T const * const last ) { C result; for ( ; first != last; ++first ) { result.push_back( *first ); } return result; } inline tests make_tests( test const * first, test const * const last ) { return make<tests>( first, last ); } inline texts make_texts( char const * const * first, char const * const * last ) { return make<texts>( first, last ); } // Traversal of test[N] (test_specification[N]) set up to also work with MSVC6: template< typename C > test const * test_begin( C const & c ) { return &*c; } template< typename C > test const * test_end( C const & c ) { return test_begin( c ) + lest_DIMENSION_OF( c ); } template< typename C > char const * const * text_begin( C const & c ) { return &*c; } template< typename C > char const * const * text_end( C const & c ) { return text_begin( c ) + lest_DIMENSION_OF( c ); } template< typename C > tests make_tests( C const & c ) { return make_tests( test_begin( c ), test_end( c ) ); } template< typename C > texts make_texts( C const & c ) { return make_texts( text_begin( c ), text_end( c ) ); } inline int run( tests const & specification, int argc, char ** argv, std::ostream & os = std::cout ) { return run( specification, make_texts( argv + 1, argv + argc ), os ); } inline int run( tests const & specification, std::ostream & os = std::cout ) { std::cout.sync_with_stdio( false ); return (min)( run( specification, texts(), os ), exit_max_value ); } template< typename C > int run( C const & specification, texts args, std::ostream & os = std::cout ) { return run( make_tests( specification ), args, os ); } template< typename C > int run( C const & specification, int argc, char ** argv, std::ostream & os = std::cout ) { return run( make_tests( specification ), argv, argc, os ); } template< typename C > int run( C const & specification, std::ostream & os = std::cout ) { return run( make_tests( specification ), os ); } } // namespace lest #if defined (__clang__) # pragma clang diagnostic pop #elif defined (__GNUC__) # pragma GCC diagnostic pop #endif #endif // LEST_LEST_HPP_INCLUDED
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/cmake/byte-lite-config.cmake.in
@PACKAGE_INIT@ # Only include targets once: if( NOT TARGET @package_name@::@package_name@ ) include( "${CMAKE_CURRENT_LIST_DIR}/@[email protected]" ) endif()
0
repos/outcome/test/quickcpplib/include/quickcpplib/byte
repos/outcome/test/quickcpplib/include/quickcpplib/byte/cmake/byte-lite-config-version.cmake.in
# Adapted from write_basic_package_version_file(... COMPATIBILITY SameMajorVersion) output # ARCH_INDEPENDENT is only present in cmake 3.14 and onwards set( PACKAGE_VERSION "@package_version@" ) if( PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION ) set( PACKAGE_VERSION_COMPATIBLE FALSE ) else() if( "@package_version@" MATCHES "^([0-9]+)\\." ) set( CVF_VERSION_MAJOR "${CMAKE_MATCH_1}" ) else() set( CVF_VERSION_MAJOR "@package_version@" ) endif() if( PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR ) set( PACKAGE_VERSION_COMPATIBLE TRUE ) else() set( PACKAGE_VERSION_COMPATIBLE FALSE ) endif() if( PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION ) set( PACKAGE_VERSION_EXACT TRUE ) endif() endif()
0
repos/outcome/test/quickcpplib/include/quickcpplib/boost
repos/outcome/test/quickcpplib/include/quickcpplib/boost/test/unit_test.hpp
/* Provides lightweight Boost.Test macros (C) 2014-2020 Niall Douglas <http://www.nedproductions.biz/> (26 commits) File Created: Nov 2014 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_BOOST_UNIT_TEST_HPP #define QUICKCPPLIB_BOOST_UNIT_TEST_HPP #include "../../config.hpp" /*! \defgroup unittesting Unit test suites QuickCppLib comes with a minimal emulation of Boost.Test based on one of two underlying unit test engines: <dl> <dt>`QUICKCPPLIB_BOOST_UNIT_TEST_IMPL` = 0 (the default)</dt> <dd>An internal extremely lightweight engine which works well with exceptions and RTTI disabled. It works fine with multithreaded test cases, and can write results to a JUnit XML file for consumption by Jenkins etc. Its implementation is less than two hundred lines of C++, so it isn't particularly configurable nor flexible. In particular it maintains no history of checks, no stdio redirection, no trapping of signals, no interception of failed asserts etc. If a check fails it simply prints immediately what failed to stderr and increments a fail counter. Despite its simplicity you'll probably find it works plenty well for most use cases and it has almost zero overhead either at compile or runtime. Note that if exceptions are disabled, those checks and requires testing that things throw are implement as no ops for obvious reasons. \warning A requirement failure is handled by throwing a magic exception type to abort the test case and prevent execution of later code, unwinding the stack and releasing any resources allocated up to that point. If exceptions are disabled, `longjmp()` is used instead and therefore stack unwinding does not occur, leaking any stack based resources. \note Almost all the macros used by this internal engine can be redefined before including the header file. It's been deliberately made highly customisable. </dd> <dt>`QUICKCPPLIB_BOOST_UNIT_TEST_IMPL` = 1</dt> <dd>Use Phil Nash's CATCH (https://github.com/philsquared/Catch) header only test engine. The Boost.Test macros simply call CATCH equivalents. The CATCH used is actually a fork of Phil's with a giant mutex poked in so multiple threads can do checks concurrently.</dd> </dl> */ //! @{ #ifndef QUICKCPPLIB_BOOST_UNIT_TEST_IMPL #define QUICKCPPLIB_BOOST_UNIT_TEST_IMPL 0 // default to lightweight #endif #if QUICKCPPLIB_BOOST_UNIT_TEST_IMPL == 1 // CATCH #ifdef __has_include #if !__has_include("../../CATCH/single_include/catch.hpp") #error Cannot find the CATCH git submodule. Did you do git submodule update --init --recursive? #endif #endif #ifndef __cpp_exceptions #error CATCH unit test suite requires C++ exceptions to be enabled #endif #endif // If we are to use our own noexcept capable implementation as the underlying unit test engine #if QUICKCPPLIB_BOOST_UNIT_TEST_IMPL == 0 // std::terminate #include <atomic> #include <chrono> #include <cstring> // for strstr #include <fstream> #include <iostream> #include <regex> #include <vector> #include "../../console_colours.hpp" //#ifdef _WIN32 //#include "../../execinfo_win64.h" //#else //#include <execinfo.h> //#endif #ifndef __cpp_exceptions #include <setjmp.h> #endif QUICKCPPLIB_NAMESPACE_BEGIN namespace unit_test { using namespace console_colours; struct requirement_failed { }; #ifndef __cpp_exceptions extern inline jmp_buf &test_case_failed() { static jmp_buf b; return b; } #endif struct test_case { const char *name, *desc; void (*func)(); std::chrono::steady_clock::duration duration; std::atomic<size_t> passes, fails; bool skipped, requirement_failed; constexpr test_case(const char *_name, const char *_desc, void (*_func)()) : name(_name) , desc(_desc) , func(_func) , duration() , passes(0) , fails(0) , skipped(false) , requirement_failed(false) { } test_case(test_case &&o) noexcept : name(o.name) , desc(o.desc) , func(o.func) , duration(static_cast<std::chrono::steady_clock::duration &&>(o.duration)) , passes(static_cast<size_t>(o.passes)) , fails(static_cast<size_t>(o.fails)) , skipped(o.skipped) , requirement_failed(o.requirement_failed) { } test_case &operator=(test_case &&o) noexcept { this->~test_case(); new(this) test_case(std::move(o)); return *this; } }; struct test_suite { const char *name; std::vector<test_case> test_cases; test_suite(const char *_name) : name(_name) { } }; extern inline std::vector<test_suite> &test_suites() { static std::vector<test_suite> v; return v; } extern inline test_suite *&current_test_suite() { static test_suite *v; return v; } extern inline test_case *&current_test_case() { static test_case default_test_case("unnamed", "Default test case for unit test which don't declare test cases", nullptr); static test_case *v = &default_test_case; return v; } extern inline int run(int argc, const char *const argv[]) { std::regex enabled(".*"), disabled; bool list_tests = false; std::string output_xml; for(int n = 1; n < argc; n++) { // Double -- means it's a flag if(argv[n][0] == '-' && argv[n][1] == '-') { if(strstr(argv[n] + 2, "help")) { std::cout << "\nQuickCppLib minimal unit test framework\n\n" // << "Usage: " << argv[0] << " [options] [<regex for tests to run, defaults to .*>] [-<regex for tests to not run>]\n\n" // << " --help : Prints this help\n" // << " --list-tests : List matching tests\n" // << " --reporter <format> : Reporter to use, only format possible is junit\n" // << " --out <filename> : Write JUnit XML test report to filename\n" // << std::endl; return 0; } else if(strstr(argv[n] + 2, "list-tests")) { list_tests = true; } else if(strstr(argv[n] + 2, "reporter")) { if(n + 1 >= argc || strcmp(argv[n + 1], "junit")) { std::cerr << "--reporter must be followed by 'junit'" << std::endl; return 1; } n++; } else if(strstr(argv[n] + 2, "out")) { if(n + 1 >= argc) { std::cerr << "--out must be followed by the output filename" << std::endl; return 1; } output_xml = argv[n + 1]; n++; } } else { // -regex is disabled, otherwise it's an enabled if(argv[n][0] == '-') disabled.assign(argv[n] + 1); else enabled.assign(argv[n]); } } if(list_tests) { size_t maxname = 0; for(const auto &j : test_suites()) { for(const auto &i : j.test_cases) { if(strlen(i.name) > maxname) maxname = strlen(i.name); } } for(const auto &j : test_suites()) { std::cout << "\n" << j.name << ":\n"; for(const auto &i : j.test_cases) { if(std::regex_match(i.name, enabled) && !std::regex_match(i.name, disabled)) { std::string padding(maxname - strlen(i.name), ' '); std::cout << " " << i.name << padding << " (" << i.desc << ")\n"; } } } std::cout << std::endl; return 0; } for(auto &j : test_suites()) { for(auto &i : j.test_cases) { if(std::regex_match(i.name, enabled) && !std::regex_match(i.name, disabled)) { current_test_case() = &i; std::cout << std::endl << bold << blue << i.name << white << " : " << i.desc << normal << std::endl; std::chrono::steady_clock::time_point begin, end; #ifdef __cpp_exceptions try { #else if(setjmp(test_case_failed())) { end = std::chrono::steady_clock::now(); i.requirement_failed = true; } else #endif { begin = std::chrono::steady_clock::now(); i.func(); end = std::chrono::steady_clock::now(); } #ifdef __cpp_exceptions } catch(const requirement_failed &) { end = std::chrono::steady_clock::now(); i.requirement_failed = true; } catch(const std::exception &e) { end = std::chrono::steady_clock::now(); ++i.fails; std::cerr << red << "FAILURE: std::exception '" << e.what() << "' thrown out of test case" << normal << std::endl; } catch(...) { end = std::chrono::steady_clock::now(); ++i.fails; std::cerr << red << "FAILURE: Exception thrown out of test case" << normal << std::endl; } #endif i.duration = end - begin; if(i.passes) std::cout << green << i.passes << " checks passed "; if(i.fails) std::cout << red << i.fails << " checks failed "; std::cout << normal << "duration " << std::chrono::duration_cast<std::chrono::milliseconds>(i.duration).count() << " ms" << std::endl; } else i.skipped = true; } } current_test_case() = nullptr; std::ofstream oh; if(!output_xml.empty()) { oh.open(output_xml); oh << R"(<?xml version="1.0" encoding="UTF-8"?> <testsuites> )"; } size_t totalpassed = 0, totalfailed = 0, totalskipped = 0; double totaltime = 0; for(const auto &j : test_suites()) { size_t passed = 0, failed = 0, skipped = 0; double time = 0; for(const auto &i : j.test_cases) { if(i.skipped) ++skipped; else if(i.fails) ++failed; else ++passed; time += std::chrono::duration_cast<std::chrono::duration<double>>(i.duration).count(); } if(!output_xml.empty()) { oh << " <testsuite name=\"" << j.name << "\" errors=\"" << 0 << "\" failures=\"" << failed << "\" skipped=\"" << skipped << "\" tests=\"" << j.test_cases.size() << "\" hostname=\"\" time=\"" << time << "\" timestamp=\"\">\n"; for(const auto &i : j.test_cases) { oh << " <testcase classname=\"\" name=\"" << i.name << "\" time=\"" << std::chrono::duration_cast<std::chrono::duration<double>>(i.duration).count() << "\">"; if(i.skipped) oh << "<skipped/>"; else if(i.fails) oh << "<failure/>"; oh << "</testcase>\n"; } oh << " </testsuite>\n"; } totalpassed += passed; totalfailed += failed; totalskipped += skipped; totaltime += time; } if(!output_xml.empty()) { oh << R"(</testsuites> )"; } std::cout << bold << white << "\n\nTest case summary: " << green << totalpassed << " passed " << red << totalfailed << " failed " << yellow << totalskipped << " skipped" << normal << "\nTotal duration: " << totaltime << " seconds." << std::endl; return totalfailed > 0; } struct test_suite_registration { const char *name; test_suite_registration(const char *_name) noexcept : name(_name) { auto it = std::find_if(test_suites().begin(), test_suites().end(), [this](const test_suite &i) { return !strcmp(i.name, name); }); if(it == test_suites().end()) { test_suites().push_back(test_suite(name)); it = --test_suites().end(); } current_test_suite() = &(*it); } }; struct test_case_registration { size_t suite_idx; void (*func)(); test_case_registration(const char *name, const char *desc, void (*_func)()) noexcept : func(_func) { if(test_suites().empty()) { // No BOOST_AUTO_TEST_SUITE() has been declared yet, so fake one test_suite_registration("unset_testsuite"); } suite_idx = current_test_suite() - test_suites().data(); test_suite *suite = test_suites().data() + suite_idx; suite->test_cases.push_back(test_case(name, desc, func)); } ~test_case_registration() { test_suite *suite = test_suites().data() + suite_idx; auto it = std::remove_if(suite->test_cases.begin(), suite->test_cases.end(), [this](const test_case &i) { return i.func == func; }); suite->test_cases.erase(it); } }; } QUICKCPPLIB_NAMESPACE_END #ifndef QUICKCPPLIB_BOOST_UNIT_TEST_FAIL #ifdef __cpp_exceptions #define QUICKCPPLIB_BOOST_UNIT_TEST_FAIL throw QUICKCPPLIB_NAMESPACE::unit_test::requirement_failed() // NOLINT #else #define QUICKCPPLIB_BOOST_UNIT_TEST_FAIL longjmp(QUICKCPPLIB_NAMESPACE::unit_test::test_case_failed(), 1) #endif #endif #ifndef QUICKCPPLIB_BOOST_UNIT_CHECK_FAIL #define QUICKCPPLIB_BOOST_UNIT_CHECK_FAIL(type, expr) \ ++QUICKCPPLIB_NAMESPACE::unit_test::current_test_case()->fails; \ std::cerr << QUICKCPPLIB_NAMESPACE::unit_test::yellow << "CHECK " type "(" #expr ") FAILED" << QUICKCPPLIB_NAMESPACE::unit_test::white << " at " << __FILE__ << ":" << __LINE__ << std::endl #endif #ifndef QUICKCPPLIB_BOOST_UNIT_CHECK_PASS #define QUICKCPPLIB_BOOST_UNIT_CHECK_PASS(type, expr) ++QUICKCPPLIB_NAMESPACE::unit_test::current_test_case()->passes #endif #ifndef QUICKCPPLIB_BOOST_UNIT_REQUIRE_FAIL #define QUICKCPPLIB_BOOST_UNIT_REQUIRE_FAIL(type, expr) \ ++QUICKCPPLIB_NAMESPACE::unit_test::current_test_case()->fails; \ std::cerr << QUICKCPPLIB_NAMESPACE::unit_test::red << "REQUIRE " type "(" #expr ") FAILED" << QUICKCPPLIB_NAMESPACE::unit_test::white << " at " << __FILE__ << ":" << __LINE__ << std::endl; \ QUICKCPPLIB_BOOST_UNIT_TEST_FAIL #endif #ifndef QUICKCPPLIB_BOOST_UNIT_REQUIRE_PASS #define QUICKCPPLIB_BOOST_UNIT_REQUIRE_PASS(type, expr) ++QUICKCPPLIB_NAMESPACE::unit_test::current_test_case()->passes #endif #define BOOST_TEST_MESSAGE(msg) std::cout << "INFO: " << msg << std::endl #define BOOST_WARN_MESSAGE(pred, msg) \ if(!(pred)) \ std::cerr << QUICKCPPLIB_NAMESPACE::unit_test::yellow << "WARNING: " << msg << QUICKCPPLIB_NAMESPACE::unit_test::normal << std::endl #define BOOST_FAIL(msg) \ std::cerr << QUICKCPPLIB_NAMESPACE::unit_test::red << "FAILURE: " << msg << QUICKCPPLIB_NAMESPACE::unit_test::normal << std::endl; \ QUICKCPPLIB_BOOST_UNIT_TEST_FAIL #define BOOST_CHECK_MESSAGE(pred, msg) \ if(!(pred)) \ std::cout << "INFO: " << msg << std::endl #define BOOST_CHECK(expr) \ if(!(expr)) \ { \ QUICKCPPLIB_BOOST_UNIT_CHECK_FAIL(, expr); \ } \ \ else \ { \ QUICKCPPLIB_BOOST_UNIT_CHECK_PASS(, expr); \ } #define BOOST_CHECK_EQUAL(expr1, expr2) BOOST_CHECK((expr1) == (expr2)) #ifdef __cpp_exceptions #define BOOST_CHECK_THROWS(expr) \ try \ \ { \ (expr); \ QUICKCPPLIB_BOOST_UNIT_CHECK_FAIL("THROWS ", expr); \ \ } \ \ catch(const QUICKCPPLIB_NAMESPACE::unit_test::requirement_failed &) \ { \ throw; \ } \ \ catch(...) \ \ { \ QUICKCPPLIB_BOOST_UNIT_CHECK_PASS("THROWS ", expr); \ \ } #define BOOST_CHECK_THROW(expr, type) \ try \ { \ (expr); \ QUICKCPPLIB_BOOST_UNIT_CHECK_FAIL("THROW " #type " ", expr); \ } \ \ catch(const QUICKCPPLIB_NAMESPACE::unit_test::requirement_failed &) \ { \ throw; \ } \ \ catch(const type &) \ { \ QUICKCPPLIB_BOOST_UNIT_CHECK_PASS("THROW " #type " ", expr); \ } \ catch(...) { QUICKCPPLIB_BOOST_UNIT_CHECK_FAIL("THROW " #type " ", expr); } #define BOOST_CHECK_NO_THROW(expr) \ try \ { \ (expr); \ QUICKCPPLIB_BOOST_UNIT_CHECK_PASS("NO THROW ", expr); \ } \ \ catch(const QUICKCPPLIB_NAMESPACE::unit_test::requirement_failed &) \ { \ throw; \ } \ catch(...) { QUICKCPPLIB_BOOST_UNIT_CHECK_FAIL("NO THROW ", expr); } #else #define BOOST_CHECK_THROWS(expr) #define BOOST_CHECK_THROW(expr, type) #define BOOST_CHECK_NO_THROW(expr) expr #endif #define BOOST_REQUIRE(expr) \ if(!(expr)) \ { \ QUICKCPPLIB_BOOST_UNIT_REQUIRE_FAIL(, expr); \ } \ \ { \ QUICKCPPLIB_BOOST_UNIT_REQUIRE_PASS(, expr); \ \ } #ifdef __cpp_exceptions #define BOOST_REQUIRE_THROWS(expr) \ try \ \ { \ (expr); \ QUICKCPPLIB_BOOST_UNIT_REQUIRE_FAIL("THROWS ", expr); \ \ } \ \ catch(const QUICKCPPLIB_NAMESPACE::unit_test::requirement_failed &) \ { \ throw; \ } \ \ catch(...) \ \ { \ QUICKCPPLIB_BOOST_UNIT_REQUIRE_PASS("THROWS ", expr); \ \ } #define BOOST_CHECK_REQUIRE(expr, type) \ try \ { \ (expr); \ QUICKCPPLIB_BOOST_UNIT_REQUIRE_FAIL("THROW " #type " ", expr); \ } \ \ catch(const QUICKCPPLIB_NAMESPACE::unit_test::requirement_failed &) \ { \ throw; \ } \ catch(const type &) { QUICKCPPLIB_BOOST_UNIT_REQUIRE_PASS("THROW " #type " ", expr); } \ catch(...) { QUICKCPPLIB_BOOST_UNIT_REQUIRE_FAIL("THROW " #type " ", expr); } #define BOOST_REQUIRE_NO_THROW(expr) \ try \ { \ (expr); \ QUICKCPPLIB_BOOST_UNIT_REQUIRE_PASS("NO THROW ", expr); \ } \ \ catch(const QUICKCPPLIB_NAMESPACE::unit_test::requirement_failed &) \ { \ throw; \ } \ catch(...) { QUICKCPPLIB_BOOST_UNIT_REQUIRE_FAIL("NO THROW ", expr); } #else #define BOOST_REQUIRE_THROWS(expr) #define BOOST_CHECK_REQUIRE(expr, type) #define BOOST_REQUIRE_NO_THROW(expr) expr #endif #define BOOST_AUTO_TEST_SUITE3(a, b) a##b #define BOOST_AUTO_TEST_SUITE2(a, b) BOOST_AUTO_TEST_SUITE3(a, b) #define BOOST_AUTO_TEST_SUITE(name) \ namespace BOOST_AUTO_TEST_SUITE2(boostlite_auto_test_suite, __COUNTER__) \ { \ static QUICKCPPLIB_NAMESPACE::unit_test::test_suite_registration boostlite_auto_test_suite_registration(#name); // #define BOOST_AUTO_TEST_SUITE_END() } #ifndef QUICKCPPLIB_BOOST_UNIT_TEST_CASE_NAME #define QUICKCPPLIB_BOOST_UNIT_TEST_CASE_NAME(name) #name #endif #define QUICKCPPLIB_BOOST_UNIT_TEST_CASE_UNIQUE(prefix) BOOST_AUTO_TEST_SUITE2(prefix, __COUNTER__) #define BOOST_AUTO_TEST_CASE2(test_name, desc, func_name) \ \ static void \ func_name(); \ \ static QUICKCPPLIB_NAMESPACE::unit_test::test_case_registration BOOST_AUTO_TEST_SUITE2(func_name, _registration)(static_cast<const char *>(test_name), static_cast<const char *>(desc), func_name); \ \ static void \ func_name() #define BOOST_AUTO_TEST_CASE(test_name, desc) BOOST_AUTO_TEST_CASE2(QUICKCPPLIB_BOOST_UNIT_TEST_CASE_NAME(test_name), desc, QUICKCPPLIB_BOOST_UNIT_TEST_CASE_UNIQUE(boostlite_auto_test_case)) #define QUICKCPPLIB_BOOST_UNIT_TEST_RUN_TESTS(argc, argv) QUICKCPPLIB_NAMESPACE::unit_test::run(argc, argv) #endif // If we are to use threadsafe CATCH as the underlying unit test engine #if QUICKCPPLIB_BOOST_UNIT_TEST_IMPL == 1 #include <atomic> #include <mutex> #define CATCH_CONFIG_PREFIX_ALL #define CATCH_CONFIG_RUNNER #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4100 4702) #endif #include "../../CATCH/single_include/catch.hpp" #ifdef _MSC_VER #pragma warning(pop) #endif #define BOOST_TEST_MESSAGE(msg) CATCH_INFO(msg) #define BOOST_WARN_MESSAGE(pred, msg) \ if(!(pred)) \ CATCH_WARN(msg) #define BOOST_FAIL(msg) CATCH_FAIL(msg) #define BOOST_CHECK_MESSAGE(pred, msg) \ if(!(pred)) \ CATCH_INFO(msg) #define BOOST_CHECK(expr) CATCH_CHECK(expr) #define BOOST_CHECK_EQUAL(expr1, expr2) BOOST_CHECK((expr1) == (expr2)) #define BOOST_CHECK_THROWS(expr) CATCH_CHECK_THROWS(expr) #define BOOST_CHECK_THROW(expr, type) CATCH_CHECK_THROWS_AS(expr, const type &) #define BOOST_CHECK_NO_THROW(expr) CATCH_CHECK_NOTHROW(expr) #define BOOST_REQUIRE(expr) CATCH_REQUIRE(expr) #define BOOST_REQUIRE_THROWS(expr) CATCH_REQUIRE_THROWS(expr) #define BOOST_CHECK_REQUIRE(expr, type) CATCH_REQUIRE_THROWS_AS(expr, const type &) #define BOOST_REQUIRE_NO_THROW(expr) CATCH_REQUIRE_NOTHROW(expr) #define BOOST_AUTO_TEST_SUITE3(a, b) a##b #define BOOST_AUTO_TEST_SUITE2(a, b) BOOST_AUTO_TEST_SUITE3(a, b) #define BOOST_AUTO_TEST_SUITE(name) \ namespace BOOST_AUTO_TEST_SUITE2(boostlite_auto_test_suite, __COUNTER__) \ { // #define BOOST_AUTO_TEST_SUITE_END() } #ifndef QUICKCPPLIB_BOOST_UNIT_TEST_CASE_NAME #define QUICKCPPLIB_BOOST_UNIT_TEST_CASE_NAME(name) #name #endif #define BOOST_AUTO_TEST_CASE(test_name, desc) CATCH_TEST_CASE(QUICKCPPLIB_BOOST_UNIT_TEST_CASE_NAME(test_name), desc) #define QUICKCPPLIB_BOOST_UNIT_TEST_RUN_TESTS(argc, argv) Catch::Session().run(argc, argv) #endif #if defined _MSC_VER #define BOOST_BINDLIB_ENABLE_MULTIPLE_DEFINITIONS #elif defined __MINGW32__ #define BOOST_BINDLIB_ENABLE_MULTIPLE_DEFINITIONS #elif defined __GNUC__ #define BOOST_BINDLIB_ENABLE_MULTIPLE_DEFINITIONS __attribute__((weak)) #else #define BOOST_BINDLIB_ENABLE_MULTIPLE_DEFINITIONS inline #endif #ifndef QUICKCPPLIB_BOOST_UNIT_TEST_CUSTOM_MAIN_DEFINED #ifdef _MSC_VER extern inline int quickcpplib_unit_testing_main(int argc, const char* const argv[]) { int result = QUICKCPPLIB_BOOST_UNIT_TEST_RUN_TESTS(argc, argv); return result; } #if(defined(__x86_64__) || defined(_M_X64)) || (defined(__aarch64__) || defined(_M_ARM64)) #pragma comment(linker, "/alternatename:main=?quickcpplib_unit_testing_main@@YAHHQEBQEBD@Z") #elif defined(__x86__) || defined(_M_IX86) || defined(__i386__) #pragma comment(linker, "/alternatename:_main=?quickcpplib_unit_testing_main@@YAHHQBQBD@Z") #elif defined(__arm__) || defined(_M_ARM) #pragma comment(linker, "/alternatename:main=?quickcpplib_unit_testing_main@@YAHHQBQBD@Z") #else #error Unknown architecture #endif #else BOOST_BINDLIB_ENABLE_MULTIPLE_DEFINITIONS int main(int argc, const char *const argv[]) { int result = QUICKCPPLIB_BOOST_UNIT_TEST_RUN_TESTS(argc, argv); return result; } #endif #endif //! @} #endif
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/detail/preprocessor_macro_overload.h
/* MSVC capable preprocessor macro overloading (C) 2014-2017 Niall Douglas <http://www.nedproductions.biz/> (3 commits) File Created: Aug 2014 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef QUICKCPPLIB_PREPROCESSOR_MACRO_OVERLOAD_H #define QUICKCPPLIB_PREPROCESSOR_MACRO_OVERLOAD_H #define QUICKCPPLIB_GLUE(x, y) x y #define QUICKCPPLIB_RETURN_ARG_COUNT(_1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, count, ...) count #define QUICKCPPLIB_EXPAND_ARGS(args) QUICKCPPLIB_RETURN_ARG_COUNT args #define QUICKCPPLIB_COUNT_ARGS_MAX8(...) QUICKCPPLIB_EXPAND_ARGS((__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0)) #define QUICKCPPLIB_OVERLOAD_MACRO2(name, count) name##count #define QUICKCPPLIB_OVERLOAD_MACRO1(name, count) QUICKCPPLIB_OVERLOAD_MACRO2(name, count) #define QUICKCPPLIB_OVERLOAD_MACRO(name, count) QUICKCPPLIB_OVERLOAD_MACRO1(name, count) #define QUICKCPPLIB_CALL_OVERLOAD(name, ...) QUICKCPPLIB_GLUE(QUICKCPPLIB_OVERLOAD_MACRO(name, QUICKCPPLIB_COUNT_ARGS_MAX8(__VA_ARGS__)), (__VA_ARGS__)) #define QUICKCPPLIB_GLUE_(x, y) x y #define QUICKCPPLIB_RETURN_ARG_COUNT_(_1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, count, ...) count #define QUICKCPPLIB_EXPAND_ARGS_(args) QUICKCPPLIB_RETURN_ARG_COUNT_ args #define QUICKCPPLIB_COUNT_ARGS_MAX8_(...) QUICKCPPLIB_EXPAND_ARGS_((__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0)) #define QUICKCPPLIB_OVERLOAD_MACRO2_(name, count) name##count #define QUICKCPPLIB_OVERLOAD_MACRO1_(name, count) QUICKCPPLIB_OVERLOAD_MACRO2_(name, count) #define QUICKCPPLIB_OVERLOAD_MACRO_(name, count) QUICKCPPLIB_OVERLOAD_MACRO1_(name, count) #define QUICKCPPLIB_CALL_OVERLOAD_(name, ...) QUICKCPPLIB_GLUE_(QUICKCPPLIB_OVERLOAD_MACRO_(name, QUICKCPPLIB_COUNT_ARGS_MAX8_(__VA_ARGS__)), (__VA_ARGS__)) #endif
0
repos/outcome/test/quickcpplib/include/quickcpplib/detail
repos/outcome/test/quickcpplib/include/quickcpplib/detail/impl/execinfo_win64.ipp
/* Implements backtrace() et al from glibc on win64 (C) 2016-2017 Niall Douglas <http://www.nedproductions.biz/> (14 commits) File Created: Mar 2016 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../include/quickcpplib/execinfo_win64.h" #include <atomic> #include <stdlib.h> // for abort #include <string.h> // To avoid including windows.h, this source has been macro expanded and win32 function shimmed for C++ only #if defined(__cplusplus) && !defined(__clang__) namespace win32 { extern _Ret_maybenull_ void *__stdcall LoadLibraryA(_In_ const char *lpLibFileName); typedef int(__stdcall *GetProcAddress_returntype)(); extern GetProcAddress_returntype __stdcall GetProcAddress(_In_ void *hModule, _In_ const char *lpProcName); extern _Success_(return != 0) unsigned short __stdcall RtlCaptureStackBackTrace(_In_ unsigned long FramesToSkip, _In_ unsigned long FramesToCapture, _Out_writes_to_(FramesToCapture, return ) void **BackTrace, _Out_opt_ unsigned long *BackTraceHash); extern _Success_(return != 0) _When_((cchWideChar == -1) && (cbMultiByte != 0), _Post_equal_to_(_String_length_(lpMultiByteStr) + 1)) int __stdcall WideCharToMultiByte(_In_ unsigned int CodePage, _In_ unsigned long dwFlags, const wchar_t *lpWideCharStr, _In_ int cchWideChar, _Out_writes_bytes_to_opt_(cbMultiByte, return ) char *lpMultiByteStr, _In_ int cbMultiByte, _In_opt_ const char *lpDefaultChar, _Out_opt_ int *lpUsedDefaultChar); #pragma comment(lib, "kernel32.lib") #if(defined(__x86_64__) || defined(_M_X64)) || (defined(__aarch64__) || defined(_M_ARM64)) #pragma comment(linker, "/alternatename:?LoadLibraryA@win32@@YAPEAXPEBD@Z=LoadLibraryA") #pragma comment(linker, "/alternatename:?GetProcAddress@win32@@YAP6AHXZPEAXPEBD@Z=GetProcAddress") #pragma comment(linker, "/alternatename:?RtlCaptureStackBackTrace@win32@@YAGKKPEAPEAXPEAK@Z=RtlCaptureStackBackTrace") #pragma comment(linker, "/alternatename:?WideCharToMultiByte@win32@@YAHIKPEB_WHPEADHPEBDPEAH@Z=WideCharToMultiByte") #elif defined(__x86__) || defined(_M_IX86) || defined(__i386__) #pragma comment(linker, "/alternatename:?LoadLibraryA@win32@@YGPAXPBD@Z=__imp__LoadLibraryA@4") #pragma comment(linker, "/alternatename:?GetProcAddress@win32@@YGP6GHXZPAXPBD@Z=__imp__GetProcAddress@8") #pragma comment(linker, "/alternatename:?RtlCaptureStackBackTrace@win32@@YGGKKPAPAXPAK@Z=__imp__RtlCaptureStackBackTrace@16") #pragma comment(linker, "/alternatename:?WideCharToMultiByte@win32@@YGHIKPB_WHPADHPBDPAH@Z=__imp__WideCharToMultiByte@32") #elif defined(__arm__) || defined(_M_ARM) #pragma comment(linker, "/alternatename:?LoadLibraryA@win32@@YAPAXPBD@Z=LoadLibraryA") #pragma comment(linker, "/alternatename:?GetProcAddress@win32@@YAP6AHXZPAXPBD@Z=GetProcAddress") #pragma comment(linker, "/alternatename:?RtlCaptureStackBackTrace@win32@@YAGKKPAPAXPAK@Z=RtlCaptureStackBackTrace") #pragma comment(linker, "/alternatename:?WideCharToMultiByte@win32@@YAHIKPB_WHPADHPBDPAH@Z=WideCharToMultiByte") #else #error Unknown architecture #endif } // namespace win32 #else #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #include <Windows.h> #endif #ifdef __cplusplus namespace { #endif typedef struct _IMAGEHLP_LINE64 { unsigned long SizeOfStruct; void *Key; unsigned long LineNumber; wchar_t *FileName; unsigned long long int Address; } IMAGEHLP_LINE64, *PIMAGEHLP_LINE64; typedef int(__stdcall *SymInitialize_t)(_In_ void *hProcess, _In_opt_ const wchar_t *UserSearchPath, _In_ int fInvadeProcess); typedef int(__stdcall *SymGetLineFromAddr64_t)(_In_ void *hProcess, _In_ unsigned long long int dwAddr, _Out_ unsigned long *pdwDisplacement, _Out_ PIMAGEHLP_LINE64 Line); static std::atomic<unsigned> dbghelp_init_lock; #if defined(__cplusplus) && !defined(__clang__) static void *dbghelp; #else static HMODULE dbghelp; #endif static SymInitialize_t SymInitialize; static SymGetLineFromAddr64_t SymGetLineFromAddr64; static void load_dbghelp() { #if defined(__cplusplus) && !defined(__clang__) using win32::GetProcAddress; using win32::LoadLibraryA; #endif while(dbghelp_init_lock.exchange(1, std::memory_order_acq_rel)) ; if(dbghelp) { dbghelp_init_lock.store(0, std::memory_order_release); return; } dbghelp = LoadLibraryA("DBGHELP.DLL"); if(dbghelp) { SymInitialize = (SymInitialize_t) GetProcAddress(dbghelp, "SymInitializeW"); if(!SymInitialize) abort(); if(!SymInitialize((void *) (size_t) -1 /*GetCurrentProcess()*/, NULL, 1)) abort(); SymGetLineFromAddr64 = (SymGetLineFromAddr64_t) GetProcAddress(dbghelp, "SymGetLineFromAddrW64"); if(!SymGetLineFromAddr64) abort(); } dbghelp_init_lock.store(0, std::memory_order_release); } #ifdef __cplusplus } #endif #ifdef __cplusplus extern "C" { #endif _Check_return_ size_t backtrace(_Out_writes_(len) void **bt, _In_ size_t len) { #if defined(__cplusplus) && !defined(__clang__) using win32::RtlCaptureStackBackTrace; #endif return RtlCaptureStackBackTrace(1, (unsigned long) len, bt, NULL); } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 6385 6386) // MSVC static analyser can't grok this function. clang's analyser gives it thumbs up. #endif _Check_return_ _Ret_writes_maybenull_(len) char **backtrace_symbols(_In_reads_(len) void *const *bt, _In_ size_t len) { #if defined(__cplusplus) && !defined(__clang__) using win32::WideCharToMultiByte; #endif size_t bytes = (len + 1) * sizeof(void *) + 256, n; if(!len) return NULL; else { char **ret = (char **) malloc(bytes); char *p = (char *) (ret + len + 1), *end = (char *) ret + bytes; if(!ret) return NULL; for(n = 0; n < len + 1; n++) ret[n] = NULL; load_dbghelp(); for(n = 0; n < len; n++) { unsigned long displ; IMAGEHLP_LINE64 ihl; memset(&ihl, 0, sizeof(ihl)); ihl.SizeOfStruct = sizeof(IMAGEHLP_LINE64); int please_realloc = 0; if(!bt[n]) { ret[n] = NULL; } else { // Keep offset till later ret[n] = (char *) ((char *) p - (char *) ret); { static std::atomic<unsigned> symlock(0); while(symlock.exchange(1, std::memory_order_acq_rel)) ; if(!SymGetLineFromAddr64 || !SymGetLineFromAddr64((void *) (size_t) -1 /*GetCurrentProcess()*/, (size_t) bt[n], &displ, &ihl)) { symlock.store(0, std::memory_order_release); if(n == 0) { free(ret); return NULL; } ihl.FileName = (wchar_t *) L"unknown"; ihl.LineNumber = 0; } else { symlock.store(0, std::memory_order_release); } } retry: if(please_realloc) { char **temp = (char **) realloc(ret, bytes + 256); if(!temp) { free(ret); return NULL; } p = (char *) temp + (p - (char *) ret); ret = temp; bytes += 256; end = (char *) ret + bytes; } if(ihl.FileName && ihl.FileName[0]) { int plen = WideCharToMultiByte(65001 /*CP_UTF8*/, 0, ihl.FileName, -1, p, (int) (end - p), NULL, NULL); if(!plen) { please_realloc = 1; goto retry; } p[plen - 1] = 0; p += plen - 1; } else { if(end - p < 16) { please_realloc = 1; goto retry; } _ui64toa_s((size_t) bt[n], p, end - p, 16); p = strchr(p, 0); } if(end - p < 16) { please_realloc = 1; goto retry; } *p++ = ':'; _itoa_s(ihl.LineNumber, p, end - p, 10); p = strchr(p, 0) + 1; } } for(n = 0; n < len; n++) { if(ret[n]) ret[n] = (char *) ret + (size_t) ret[n]; } return ret; } } #ifdef _MSC_VER #pragma warning(pop) #endif // extern void backtrace_symbols_fd(void *const *bt, size_t len, int fd); #ifdef __cplusplus } #endif
0
repos/outcome/test/quickcpplib/include/quickcpplib/detail
repos/outcome/test/quickcpplib/include/quickcpplib/detail/impl/signal_guard.ipp
/* Signal guard support (C) 2018-2021 Niall Douglas <http://www.nedproductions.biz/> (4 commits) File Created: June 2018 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License in the accompanying file Licence.txt or at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Distributed under the Boost Software License, Version 1.0. (See accompanying file Licence.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "../include/quickcpplib/signal_guard.hpp" #include "../include/quickcpplib/scope.hpp" #include "../include/quickcpplib/spinlock.hpp" #include <cstring> // for memset etc #include <system_error> // for system_error #ifndef _WIN32 #include <time.h> // for timers #include <unistd.h> // for write() #endif /* On Windows, the terminate handler is per thread, and therefore we need to install the handler upon creation of every new thread irrespective of whether terminations are ever handled using this facility. This has been found to cause unhelpful interactions with time travel debugging, so until the fix_signal_guard branch gets merged into trunk, we need to provide a facility for disabling the global per thread terminate handler. Obviously disabling this will cause signal_guard to no longer be able to intercept terminations on Windows. */ #ifndef QUICKCPPLIB_SIGNAL_GUARD_DISABLE_INSTALLING_GLOBAL_PER_THREAD_TERMINATE_HANDLER #define QUICKCPPLIB_SIGNAL_GUARD_DISABLE_INSTALLING_GLOBAL_PER_THREAD_TERMINATE_HANDLER 0 #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4190) // C-linkage with UDTs #endif extern "C" union raised_signal_info_value thrd_signal_guard_call(const sigset_t *signals, thrd_signal_guard_guarded_t guarded, thrd_signal_guard_recover_t recovery, thrd_signal_guard_decide_t decider, union raised_signal_info_value value) { using namespace QUICKCPPLIB_NAMESPACE::signal_guard; signalc_set mask; for(size_t n = 0; n < 31; n++) { if(sigismember(signals, n)) { mask |= static_cast<signalc_set>(1ULL << n); } } return signal_guard(mask, guarded, recovery, decider, value); } #ifdef _MSC_VER #pragma warning(pop) #endif extern "C" bool thrd_raise_signal(int signo, void *raw_info, void *raw_context) { using namespace QUICKCPPLIB_NAMESPACE::signal_guard; return thrd_raise_signal(static_cast<signalc>(1U << signo), raw_info, raw_context); } extern "C" void *signal_guard_create(const sigset_t *guarded) { using namespace QUICKCPPLIB_NAMESPACE::signal_guard; signalc_set mask; for(size_t n = 0; n < 31; n++) { if(sigismember(guarded, n)) { mask |= static_cast<signalc_set>(1ULL << n); } } return new(std::nothrow) QUICKCPPLIB_NAMESPACE::signal_guard::signal_guard_install(mask); } extern "C" bool signal_guard_destroy(void *i) { auto *p = (QUICKCPPLIB_NAMESPACE::signal_guard::signal_guard_install *) i; delete p; return true; } QUICKCPPLIB_NAMESPACE_BEGIN namespace signal_guard { namespace detail { struct signal_guard_decider_callable { thrd_signal_guard_decide_t decider; raised_signal_info_value value; bool operator()(raised_signal_info *rsi) const noexcept { rsi->value = value; return decider(rsi); } }; } // namespace detail } // namespace signal_guard QUICKCPPLIB_NAMESPACE_END extern "C" void *signal_guard_decider_create(const sigset_t *guarded, bool callfirst, thrd_signal_guard_decide_t decider, union raised_signal_info_value value) { using namespace QUICKCPPLIB_NAMESPACE::signal_guard; signalc_set mask; for(size_t n = 0; n < 31; n++) { if(sigismember(guarded, n)) { mask |= static_cast<signalc_set>(1ULL << n); } } return new(std::nothrow) signal_guard_global_decider<detail::signal_guard_decider_callable>(mask, detail::signal_guard_decider_callable{decider, value}, callfirst); } extern "C" bool signal_guard_decider_destroy(void *decider) { using namespace QUICKCPPLIB_NAMESPACE::signal_guard; auto *p = (signal_guard_global_decider<detail::signal_guard_decider_callable> *) decider; delete p; return true; } QUICKCPPLIB_NAMESPACE_BEGIN namespace signal_guard { namespace detail { struct global_signal_decider { global_signal_decider *next, *prev; signalc_set guarded; thrd_signal_guard_decide_t decider; raised_signal_info_value value; }; extern QUICKCPPLIB_SYMBOL_VISIBLE inline thread_local_signal_guard *&_current_thread_local_signal_handler() noexcept { static thread_local thread_local_signal_guard *v; return v; } extern QUICKCPPLIB_SYMBOL_VISIBLE inline std::terminate_handler &terminate_handler_old() noexcept { #ifdef _MSC_VER static thread_local std::terminate_handler v; #else static std::terminate_handler v; #endif return v; } struct _state_t { configurable_spinlock::spinlock<uintptr_t> lock; unsigned new_handler_count{0}, terminate_handler_count{0}; std::new_handler new_handler_old{}; global_signal_decider *global_signal_deciders_front{nullptr}, *global_signal_deciders_back{nullptr}; #ifdef _WIN32 unsigned win32_console_ctrl_handler_count{0}; void *win32_global_signal_decider1{nullptr}; void *win32_global_signal_decider2{nullptr}; #endif }; extern QUICKCPPLIB_SYMBOL_VISIBLE inline _state_t &_state() noexcept { static _state_t v; return v; } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wattributes" #endif SIGNALGUARD_FUNC_DECL QUICKCPPLIB_NOINLINE void push_thread_local_signal_handler(thread_local_signal_guard *g) noexcept { g->previous = _current_thread_local_signal_handler(); _current_thread_local_signal_handler() = g; } SIGNALGUARD_FUNC_DECL QUICKCPPLIB_NOINLINE void pop_thread_local_signal_handler(thread_local_signal_guard *g) noexcept { assert(_current_thread_local_signal_handler() == g); if(_current_thread_local_signal_handler() != g) { abort(); } _current_thread_local_signal_handler() = g->previous; } SIGNALGUARD_FUNC_DECL QUICKCPPLIB_NOINLINE thread_local_signal_guard *current_thread_local_signal_handler() noexcept { return _current_thread_local_signal_handler(); } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif SIGNALGUARD_FUNC_DECL const char *signalc_to_string(signalc code) noexcept { static constexpr const struct { signalc code; const char *string; } strings[] = { // {signalc::none, "none"}, // {signalc::abort_process, "Signal abort process"}, // {signalc::undefined_memory_access, "Signal undefined memory access"}, // {signalc::illegal_instruction, "Signal illegal instruction"}, // {signalc::interrupt, "Signal interrupt"}, // {signalc::broken_pipe, "Signal broken pipe"}, // {signalc::segmentation_fault, "Signal segmentation fault"}, // {signalc::floating_point_error, "Signal floating point error"}, // {signalc::process_terminate, "Process termination requested"}, // #ifndef _WIN32 {signalc::timer_expire, "Timer has expired"}, // {signalc::child_exit, "Child has exited"}, // {signalc::process_continue, "Process is being continued"}, // {signalc::tty_hangup, "Controlling terminal has hung up"}, // {signalc::process_kill, "Process has received kill signal"}, // #ifdef SIGPOLL {signalc::pollable_event, "i/o is now possible"}, // #endif {signalc::profile_event, "Profiling timer expired"}, // {signalc::process_quit, "Process is being quit"}, // {signalc::process_stop, "Process is being stopped"}, // {signalc::tty_stop, "Terminal requests stop"}, // {signalc::bad_system_call, "Bad system call"}, // {signalc::process_trap, "Process has reached a breakpoint"}, // {signalc::tty_input, "Terminal has input"}, // {signalc::tty_output, "Terminal ready for output"}, // {signalc::urgent_condition, "Urgent condition"}, // {signalc::user_defined1, "User defined 1"}, // {signalc::user_defined2, "User defined 2"}, // {signalc::virtual_alarm_clock, "Virtual alarm clock"}, // {signalc::cpu_time_limit_exceeded, "CPU time limit exceeded"}, // {signalc::file_size_limit_exceeded, "File size limit exceeded"}, // #endif {signalc::cxx_out_of_memory, "C++ out of memory"}, // {signalc::cxx_termination, "C++ termination"} // }; for(auto &i : strings) { if(code == i.code) return i.string; } return "unknown"; } // Overload for when a C++ signal is being raised inline bool set_siginfo(thread_local_signal_guard *g, signalc _cppsignal) { auto cppsignal = static_cast<signalc_set>(1ULL << static_cast<int>(_cppsignal)); if(g->guarded & cppsignal) { g->info.signo = static_cast<int>(_cppsignal); g->info.error_code = 0; // no system error code for C++ signals g->info.addr = 0; // no address for OOM nor terminate g->info.value.ptr_value = nullptr; g->info.raw_info = nullptr; g->info.raw_context = nullptr; return true; } return false; } #ifdef _WIN32 // WARNING: Always called from a separate thread! inline int __stdcall win32_console_ctrl_handler(unsigned long dwCtrlType) { signalc signo; switch(dwCtrlType) { case 0: // CTRL_C_EVENT case 1: // CTRL_BREAK_EVENT { signo = signalc::interrupt; break; } case 2: // CTRL_CLOSE_EVENT { signo = signalc::process_terminate; break; } default: return 0; // not handled } for(auto *shi = current_thread_local_signal_handler(); shi != nullptr; shi = shi->previous) { if(set_siginfo(shi, signo)) { shi->call_continuer(); } } _state().lock.lock(); if(_state().global_signal_deciders_front != nullptr) { raised_signal_info rsi; memset(&rsi, 0, sizeof(rsi)); rsi.signo = static_cast<int>(signo); auto *d = _state().global_signal_deciders_front; for(size_t n = 0; d != nullptr; n++) { size_t i = 0; for(d = _state().global_signal_deciders_front; d != nullptr; d = d->next) { if(i++ == n) { if(d->guarded & (1ULL << static_cast<int>(signo))) { rsi.value = d->value; _state().lock.unlock(); d->decider(&rsi); _state().lock.lock(); break; } n++; } } } } return 0; // call other handlers } #endif inline void new_handler() { for(auto *shi = current_thread_local_signal_handler(); shi != nullptr; shi = shi->previous) { if(set_siginfo(shi, signalc::cxx_out_of_memory)) { if(!shi->call_continuer()) { longjmp(shi->info.buf, 1); } } } _state().lock.lock(); if(_state().global_signal_deciders_front != nullptr) { raised_signal_info rsi; memset(&rsi, 0, sizeof(rsi)); rsi.signo = static_cast<int>(signalc::cxx_out_of_memory); auto *d = _state().global_signal_deciders_front; for(size_t n = 0; d != nullptr; n++) { size_t i = 0; for(d = _state().global_signal_deciders_front; d != nullptr; d = d->next) { if(i++ == n) { if(d->guarded & (1ULL << static_cast<int>(signalc::cxx_out_of_memory))) { rsi.value = d->value; _state().lock.unlock(); if(d->decider(&rsi)) { // Cannot continue OOM abort(); } _state().lock.lock(); break; } n++; } } } } if(_state().new_handler_old != nullptr) { auto *h = _state().new_handler_old; _state().lock.unlock(); h(); } else { _state().lock.unlock(); throw std::bad_alloc(); } } inline void terminate_handler() { for(auto *shi = current_thread_local_signal_handler(); shi != nullptr; shi = shi->previous) { if(set_siginfo(shi, signalc::cxx_termination)) { if(!shi->call_continuer()) { longjmp(shi->info.buf, 1); } } } _state().lock.lock(); if(_state().global_signal_deciders_front != nullptr) { raised_signal_info rsi; memset(&rsi, 0, sizeof(rsi)); rsi.signo = static_cast<int>(signalc::cxx_termination); auto *d = _state().global_signal_deciders_front; for(size_t n = 0; d != nullptr; n++) { size_t i = 0; for(d = _state().global_signal_deciders_front; d != nullptr; d = d->next) { if(i++ == n) { if(d->guarded & (1ULL << static_cast<int>(signalc::cxx_termination))) { rsi.value = d->value; _state().lock.unlock(); if(d->decider(&rsi)) { // Cannot continue termination abort(); } _state().lock.lock(); break; } n++; } } } } if(terminate_handler_old() != nullptr) { auto *h = terminate_handler_old(); assert(h != terminate_handler); _state().lock.unlock(); h(); } else { _state().lock.unlock(); std::abort(); } } #if defined(_MSC_VER) && QUICKCPPLIB_SIGNAL_GUARD_DISABLE_INSTALLING_GLOBAL_PER_THREAD_TERMINATE_HANDLER static thread_local struct _win32_set_terminate_handler_per_thread_t { _win32_set_terminate_handler_per_thread_t() { // On MSVC, the terminate handler is thread local, so we have no choice but to always // set it for every thread if(std::get_terminate() != terminate_handler) { terminate_handler_old() = std::set_terminate(terminate_handler); } } } _win32_set_terminate_handler_per_thread; #endif #ifdef _WIN32 namespace win32 { typedef struct _EXCEPTION_RECORD { unsigned long ExceptionCode; unsigned long ExceptionFlags; struct _EXCEPTION_RECORD *ExceptionRecord; void *ExceptionAddress; unsigned long NumberParameters; unsigned long long ExceptionInformation[15]; } EXCEPTION_RECORD; typedef EXCEPTION_RECORD *PEXCEPTION_RECORD; struct CONTEXT; typedef CONTEXT *PCONTEXT; typedef struct _EXCEPTION_POINTERS { PEXCEPTION_RECORD ExceptionRecord; PCONTEXT ContextRecord; } EXCEPTION_POINTERS, *PEXCEPTION_POINTERS; typedef long(__stdcall *PVECTORED_EXCEPTION_HANDLER)(struct _EXCEPTION_POINTERS *ExceptionInfo); typedef int(__stdcall *PHANDLER_ROUTINE)(unsigned long dwCtrlType); typedef struct _OVERLAPPED OVERLAPPED, *LPOVERLAPPED; typedef struct _SECURITY_ATTRIBUTES SECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; typedef unsigned long(__stdcall *LPTHREAD_START_ROUTINE)(void *lpParameter); typedef void(__stdcall *PAPCFUNC)(uintptr_t); extern void __stdcall RaiseException(unsigned long dwExceptionCode, unsigned long dwExceptionFlags, unsigned long nNumberOfArguments, const unsigned long long *lpArguments); extern PVECTORED_EXCEPTION_HANDLER __stdcall SetUnhandledExceptionFilter(PVECTORED_EXCEPTION_HANDLER Handler); extern void *__stdcall AddVectoredContinueHandler(unsigned long First, PVECTORED_EXCEPTION_HANDLER Handler); extern unsigned long __stdcall RemoveVectoredContinueHandler(void *Handle); extern unsigned long __stdcall GetLastError(); extern int __stdcall SetConsoleCtrlHandler(PHANDLER_ROUTINE HandlerRoutine, int Add); extern int __stdcall TerminateProcess(void *hProcess, unsigned int uExitCode); extern void *__stdcall GetStdHandle(unsigned long); extern int __stdcall WriteFile(void *hFile, const void *lpBuffer, unsigned long nNumberOfBytesToWrite, unsigned long *lpNumberOfBytesWritten, OVERLAPPED *lpOverlapped); extern void *__stdcall CreateThread(SECURITY_ATTRIBUTES *lpThreadAttributes, size_t dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, void *lpParameter, unsigned long dwCreationFlags, unsigned long *lpThreadId); extern unsigned long __stdcall QueueUserAPC(PAPCFUNC pfnAPC, void *hThread, uintptr_t dwData); extern unsigned long __stdcall SleepEx(unsigned long dwMillseconds, int bAlertable); extern int __stdcall CloseHandle(void *hObject); extern unsigned long long __stdcall GetTickCount64(); #pragma comment(lib, "kernel32.lib") #ifndef QUICKCPPLIB_DISABLE_ABI_PERMUTATION #define QUICKCPPLIB_SIGNAL_GUARD_SYMBOL2(a, b, c) a #b c #define QUICKCPPLIB_SIGNAL_GUARD_SYMBOL1(a, b, c) QUICKCPPLIB_SIGNAL_GUARD_SYMBOL2(a, b, c) #define QUICKCPPLIB_SIGNAL_GUARD_SYMBOL(a, b) QUICKCPPLIB_SIGNAL_GUARD_SYMBOL1(a, QUICKCPPLIB_PREVIOUS_COMMIT_UNIQUE, b) #if(defined(__x86_64__) || defined(_M_X64)) || (defined(__aarch64__) || defined(_M_ARM64)) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?RaiseException@win32@detail@signal_guard@_", "@quickcpplib@@YAXKKKPEB_K@Z=RaiseException")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SetUnhandledExceptionFilter@win32@detail@signal_guard@_", \ "@quickcpplib@@YAP6AJPEAU_EXCEPTION_POINTERS@12345@@ZP6AJ0@Z@Z=SetUnhandledExceptionFilter")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?AddVectoredContinueHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YAPEAXKP6AJPEAU_EXCEPTION_POINTERS@12345@@Z@Z=AddVectoredContinueHandler")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?RemoveVectoredContinueHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YAKPEAX@Z=RemoveVectoredContinueHandler")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetLastError@win32@detail@signal_guard@_", "@quickcpplib@@YAKXZ=GetLastError")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SetConsoleCtrlHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YAHP6AHK@ZH@Z=SetConsoleCtrlHandler")) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?TerminateProcess@win32@detail@signal_guard@_", "@quickcpplib@@YAHPEAXI@Z=TerminateProcess")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetStdHandle@win32@detail@signal_guard@_", "@quickcpplib@@YAPEAXK@Z=GetStdHandle")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?WriteFile@win32@detail@signal_guard@_", \ "@quickcpplib@@YAHPEAXPEBXKPEAKPEAU_OVERLAPPED@12345@@Z=WriteFile")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?WriteFile@win32@detail@signal_guard@_", \ "@quickcpplib@@YAHPEAXPEBXKPEAKPEAU_OVERLAPPED@@@Z=WriteFile")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CreateThread@win32@detail@signal_guard@_", \ "@quickcpplib@@YAPEAXPEAU_SECURITY_ATTRIBUTES@12345@_KP6AKPEAX@Z2KPEAK@Z=CreateThread")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CreateThread@win32@detail@signal_guard@_", \ "@quickcpplib@@YAPEAXPEAU_SECURITY_ATTRIBUTES@@_KP6AKPEAX@Z2KPEAK@Z=CreateThread")) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?QueueUserAPC@win32@detail@signal_guard@_", "@quickcpplib@@YAKP6AX_K@ZPEAX0@Z=QueueUserAPC")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SleepEx@win32@detail@signal_guard@_", "@quickcpplib@@YAKKH@Z=SleepEx")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CloseHandle@win32@detail@signal_guard@_", "@quickcpplib@@YAHPEAX@Z=CloseHandle")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetTickCount64@win32@detail@signal_guard@_", "@quickcpplib@@YA_KXZ=GetTickCount64")) #elif defined(__x86__) || defined(_M_IX86) || defined(__i386__) #pragma comment( \ linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?RaiseException@win32@detail@signal_guard@_", "@quickcpplib@@YGXKKKPB_K@Z=__imp__RaiseException@16")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SetUnhandledExceptionFilter@win32@detail@signal_guard@_", \ "@quickcpplib@@YGP6GJPAU_EXCEPTION_POINTERS@12345@@ZP6GJ0@Z@Z=__imp__SetUnhandledExceptionFilter@4")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?AddVectoredContinueHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YGPAXKP6GJPAU_EXCEPTION_POINTERS@12345@@Z@Z=__imp__AddVectoredContinueHandler@8")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?RemoveVectoredContinueHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YGKPAX@Z=__imp__RemoveVectoredContinueHandler@4")) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetLastError@win32@detail@signal_guard@_", "@quickcpplib@@YGKXZ=__imp__GetLastError@0")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SetConsoleCtrlHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YGHP6GHK@ZH@Z=__imp__SetConsoleCtrlHandler@8")) #pragma comment( \ linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?TerminateProcess@win32@detail@signal_guard@_", "@quickcpplib@@YGHPAXI@Z=__imp__TerminateProcess@8")) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetStdHandle@win32@detail@signal_guard@_", "@quickcpplib@@YGPAXK@Z=__imp__GetStdHandle@4")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?WriteFile@win32@detail@signal_guard@_", \ "@quickcpplib@@YGHPAXPBXKPAKPAU_OVERLAPPED@12345@@Z=__imp__WriteFile@20")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?WriteFile@win32@detail@signal_guard@_", \ "@quickcpplib@@YGHPAXPBXKPAKPAU_OVERLAPPED@@@Z=__imp__WriteFile@20")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CreateThread@win32@detail@signal_guard@_", \ "@quickcpplib@@YGPAXPAU_SECURITY_ATTRIBUTES@12345@IP6GKPAX@Z1KPAK@Z=__imp__CreateThread@24")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CreateThread@win32@detail@signal_guard@_", \ "@quickcpplib@@YGPAXPAU_SECURITY_ATTRIBUTES@@IP6GKPAX@Z1KPAK@Z=__imp__CreateThread@24")) #pragma comment( \ linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?QueueUserAPC@win32@detail@signal_guard@_", "@quickcpplib@@YGKP6GXI@ZPAXI@Z=__imp__QueueUserAPC@12")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SleepEx@win32@detail@signal_guard@_", "@quickcpplib@@YGKKH@Z=__imp__SleepEx@8")) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CloseHandle@win32@detail@signal_guard@_", "@quickcpplib@@YGHPAX@Z=__imp__CloseHandle@4")) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetTickCount64@win32@detail@signal_guard@_", "@quickcpplib@@YG_KXZ=__imp__GetTickCount64@0")) #elif defined(__arm__) || defined(_M_ARM) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?RaiseException@win32@detail@signal_guard@_", "@quickcpplib@@YAXKKKPB_K@Z=RaiseException")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SetUnhandledExceptionFilter@win32@detail@signal_guard@_", \ "@quickcpplib@@YAP6AJPAU_EXCEPTION_POINTERS@12345@@ZP6AJ0@Z@Z=SetUnhandledExceptionFilter")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?AddVectoredContinueHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YAPAXKP6AJPAU_EXCEPTION_POINTERS@12345@@Z@Z=AddVectoredContinueHandler")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?RemoveVectoredContinueHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YAKPAX@Z=RemoveVectoredContinueHandler")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetLastError@win32@detail@signal_guard@_", "@quickcpplib@@YAKXZ=GetLastError")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SetConsoleCtrlHandler@win32@detail@signal_guard@_", \ "@quickcpplib@@YAHP6AHK@ZH@Z=SetConsoleCtrlHandler")) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?TerminateProcess@win32@detail@signal_guard@_", "@quickcpplib@@YAHPAXI@Z=TerminateProcess")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetStdHandle@win32@detail@signal_guard@_", "@quickcpplib@@YAPAXK@Z=GetStdHandle")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?WriteFile@win32@detail@signal_guard@_", \ "@quickcpplib@@YAHPAXPBXKPAKPAUOVERLAPPED@12345@@Z=WriteFile")) #pragma comment( \ linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?WriteFile@win32@detail@signal_guard@_", "@quickcpplib@@YAHPAXPBXKPAKPAUOVERLAPPED@@@Z=WriteFile")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CreateThread@win32@detail@signal_guard@_", \ "@quickcpplib@@YAPAXPAU_SECURITY_ATTRIBUTES@12345@IP6AKPAX@Z1KPAK@Z=CreateThread")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CreateThread@win32@detail@signal_guard@_", \ "@quickcpplib@@YAPAXPAU_SECURITY_ATTRIBUTES@@IP6AKPAX@Z1KPAK@Z=CreateThread")) #pragma comment(linker, \ QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?QueueUserAPC@win32@detail@signal_guard@_", "@quickcpplib@@YAKP6AXI@ZPAXI@Z=QueueUserAPC")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?SleepEx@win32@detail@signal_guard@_", "@quickcpplib@@YAKKH@Z=SleepEx")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?CloseHandle@win32@detail@signal_guard@_", "@quickcpplib@@YAHPAX@Z=CloseHandle")) #pragma comment(linker, QUICKCPPLIB_SIGNAL_GUARD_SYMBOL("/alternatename:?GetTickCount64@win32@detail@signal_guard@_", "@quickcpplib@@YA_KXZ=GetTickCount64")) #else #error Unknown architecture #endif #else #if(defined(__x86_64__) || defined(_M_X64)) || (defined(__aarch64__) || defined(_M_ARM64)) #pragma comment(linker, "/alternatename:?RaiseException@win32@detail@signal_guard@quickcpplib@@YAXKKKPEB_K@Z=RaiseException") #pragma comment( \ linker, \ "/alternatename:?SetUnhandledExceptionFilter@win32@detail@signal_guard@quickcpplib@@YAP6AJPEAU_EXCEPTION_POINTERS@1234@@ZP6AJ0@Z@Z=SetUnhandledExceptionFilter") #pragma comment( \ linker, \ "/alternatename:?AddVectoredContinueHandler@win32@detail@signal_guard@quickcpplib@@YAPEAXKP6AJPEAU_EXCEPTION_POINTERS@1234@@Z@Z=AddVectoredContinueHandler") #pragma comment(linker, "/alternatename:?RemoveVectoredContinueHandler@win32@detail@signal_guard@quickcpplib@@YAKPEAX@Z=RemoveVectoredContinueHandler") #pragma comment(linker, "/alternatename:?GetLastError@win32@detail@signal_guard@quickcpplib@@YAKXZ=GetLastError") #pragma comment(linker, "/alternatename:?SetConsoleCtrlHandler@win32@detail@signal_guard@quickcpplib@@YAHP6AHK@ZH@Z=SetConsoleCtrlHandler") #pragma comment(linker, "/alternatename:?TerminateProcess@win32@detail@signal_guard@quickcpplib@@YAHPEAXI@Z=TerminateProcess") #pragma comment(linker, "/alternatename:?GetStdHandle@win32@detail@signal_guard@quickcpplib@@YAPEAXK@Z=GetStdHandle") #pragma comment(linker, "/alternatename:?WriteFile@win32@detail@signal_guard@quickcpplib@@YAHPEAXPEBXKPEAKPEAU_OVERLAPPED@1234@@Z=WriteFile") #pragma comment(linker, "/alternatename:?WriteFile@win32@detail@signal_guard@quickcpplib@@YAHPEAXPEBXKPEAKPEAU_OVERLAPPED@@@Z=WriteFile") #pragma comment(linker, \ "/alternatename:?CreateThread@win32@detail@signal_guard@quickcpplib@@YAPEAXPEAU_SECURITY_ATTRIBUTES@1234@_KP6AKPEAX@Z2KPEAK@Z=CreateThread") #pragma comment(linker, "/alternatename:?CreateThread@win32@detail@signal_guard@quickcpplib@@YAPEAXPEAU_SECURITY_ATTRIBUTES@@_KP6AKPEAX@Z2KPEAK@Z=CreateThread") #pragma comment(linker, "/alternatename:?QueueUserAPC@win32@detail@signal_guard@quickcpplib@@YAKP6AX_K@ZPEAX0@Z=QueueUserAPC") #pragma comment(linker, "/alternatename:?SleepEx@win32@detail@signal_guard@quickcpplib@@YAKKH@Z=SleepEx") #pragma comment(linker, "/alternatename:?CloseHandle@win32@detail@signal_guard@quickcpplib@@YAHPEAX@Z=CloseHandle") #pragma comment(linker, "/alternatename:?GetTickCount64@win32@detail@signal_guard@quickcpplib@@YA_KXZ=GetTickCount64") #elif defined(__x86__) || defined(_M_IX86) || defined(__i386__) #pragma comment(linker, "/alternatename:?RaiseException@win32@detail@signal_guard@quickcpplib@@YGXKKKPB_K@Z=__imp__RaiseException@16") #pragma comment( \ linker, \ "/alternatename:?SetUnhandledExceptionFilter@win32@detail@signal_guard@quickcpplib@@YGP6GJPAU_EXCEPTION_POINTERS@@@ZP6GJ0@Z@Z=__imp__SetUnhandledExceptionFilter@4") #pragma comment( \ linker, \ "/alternatename:?AddVectoredContinueHandler@win32@detail@signal_guard@quickcpplib@@YGPAXKP6GJPAU_EXCEPTION_POINTERS@@@Z@Z=__imp__AddVectoredContinueHandler@8") #pragma comment(linker, "/alternatename:?RemoveVectoredContinueHandler@win32@detail@signal_guard@quickcpplib@@YGKPAX@Z=__imp__RemoveVectoredContinueHandler@4") #pragma comment(linker, "/alternatename:?GetLastError@win32@detail@signal_guard@quickcpplib@@YGKXZ=__imp__GetLastError@0") #pragma comment(linker, "/alternatename:?SetConsoleCtrlHandler@win32@detail@signal_guard@quickcpplib@@YGHP6GHK@ZH@Z=__imp__SetConsoleCtrlHandler@8") #pragma comment(linker, "/alternatename:?TerminateProcess@win32@detail@signal_guard@quickcpplib@@YGHPAXI@Z=__imp__TerminateProcess@8") #pragma comment(linker, "/alternatename:?GetStdHandle@win32@detail@signal_guard@quickcpplib@@YGPAXK@Z=__imp__GetStdHandle@4") #pragma comment(linker, "/alternatename:?WriteFile@win32@detail@signal_guard@quickcpplib@@YGHPAXPBXKPAKPAU_OVERLAPPED@1234@@Z=__imp__WriteFile@20") #pragma comment(linker, "/alternatename:?WriteFile@win32@detail@signal_guard@quickcpplib@@YGHPAXPBXKPAKPAU_OVERLAPPED@@@Z=__imp__WriteFile@20") #pragma comment( \ linker, "/alternatename:?CreateThread@win32@detail@signal_guard@quickcpplib@@YGPAXPAU_SECURITY_ATTRIBUTES@1234@IP6GKPAX@Z1KPAK@Z=__imp__CreateThread@24") #pragma comment(linker, \ "/alternatename:?CreateThread@win32@detail@signal_guard@quickcpplib@@YGPAXPAU_SECURITY_ATTRIBUTES@@IP6GKPAX@Z1KPAK@Z=__imp__CreateThread@24") #pragma comment(linker, "/alternatename:?QueueUserAPC@win32@detail@signal_guard@quickcpplib@@YGKP6GXI@ZPAXI@Z=__imp__QueueUserAPC@12") #pragma comment(linker, "/alternatename:?SleepEx@win32@detail@signal_guard@quickcpplib@@YGKKH@Z=__imp__SleepEx@8") #pragma comment(linker, "/alternatename:?CloseHandle@win32@detail@signal_guard@quickcpplib@@YGHPAX@Z=__imp__CloseHandle@4") #pragma comment(linker, "/alternatename:?GetTickCount64@win32@detail@signal_guard@quickcpplib@@YG_KXZ=__imp__GetTickCount64@0") #elif defined(__arm__) || defined(_M_ARM) #pragma comment(linker, "/alternatename:?RaiseException@win32@detail@signal_guard@quickcpplib@@YAXKKKPB_K@Z=RaiseException") #pragma comment( \ linker, \ "/alternatename:?SetUnhandledExceptionFilter@win32@detail@signal_guard@quickcpplib@@YAP6AJPAU_EXCEPTION_POINTERS@1234@@ZP6AJ0@Z@Z=SetUnhandledExceptionFilter") #pragma comment( \ linker, \ "/alternatename:?AddVectoredContinueHandler@win32@detail@signal_guard@quickcpplib@@YAPAXKP6AJPAU_EXCEPTION_POINTERS@1234@@Z@Z=AddVectoredContinueHandler") #pragma comment(linker, "/alternatename:?RemoveVectoredContinueHandler@win32@detail@signal_guard@quickcpplib@@YAKPAX@Z=RemoveVectoredContinueHandler") #pragma comment(linker, "/alternatename:?GetLastError@win32@detail@signal_guard@quickcpplib@@YAKXZ=GetLastError") #pragma comment(linker, "/alternatename:?SetConsoleCtrlHandler@win32@detail@signal_guard@quickcpplib@@YAHP6AHK@ZH@Z=SetConsoleCtrlHandler") #pragma comment(linker, "/alternatename:?TerminateProcess@win32@detail@signal_guard@quickcpplib@@YAHPAXI@Z=TerminateProcess") #pragma comment(linker, "/alternatename:?GetStdHandle@win32@detail@signal_guard@quickcpplib@@YAPAXK@Z=GetStdHandle") #pragma comment(linker, "/alternatename:?WriteFile@win32@detail@signal_guard@quickcpplib@@YAHPAXPBXKPAKPAUOVERLAPPED@1234@@Z=WriteFile") #pragma comment(linker, "/alternatename:?WriteFile@win32@detail@signal_guard@quickcpplib@@YAHPAXPBXKPAKPAUOVERLAPPED@@@Z=WriteFile") #pragma comment(linker, "/alternatename:?CreateThread@win32@detail@signal_guard@quickcpplib@@YAPAXPAU_SECURITY_ATTRIBUTES@1234@IP6AKPAX@Z1KPAK@Z=CreateThread") #pragma comment(linker, "/alternatename:?CreateThread@win32@detail@signal_guard@quickcpplib@@YAPAXPAU_SECURITY_ATTRIBUTES@@IP6AKPAX@Z1KPAK@Z=CreateThread") #pragma comment(linker, "/alternatename:?QueueUserAPC@win32@detail@signal_guard@quickcpplib@@YAKP6AXI@ZPAXI@Z=QueueUserAPC") #pragma comment(linker, "/alternatename:?SleepEx@win32@detail@signal_guard@quickcpplib@@YAKKH@Z=SleepEx") #pragma comment(linker, "/alternatename:?CloseHandle@win32@detail@signal_guard@quickcpplib@@YAHPAX@Z=CloseHandle") #pragma comment(linker, "/alternatename:?GetTickCount64@win32@detail@signal_guard@quickcpplib@@YA_KXZ=GetTickCount64") #else #error Unknown architecture #endif #endif } // namespace win32 inline unsigned long win32_exception_code_from_signalc(signalc c) { switch(c) { default: abort(); case signalc::abort_process: return ((unsigned long) 0xC0000025L) /*EXCEPTION_NONCONTINUABLE_EXCEPTION*/; case signalc::undefined_memory_access: return ((unsigned long) 0xC0000006L) /*EXCEPTION_IN_PAGE_ERROR*/; case signalc::illegal_instruction: return ((unsigned long) 0xC000001DL) /*EXCEPTION_ILLEGAL_INSTRUCTION*/; // case signalc::interrupt: // return SIGINT; // case signalc::broken_pipe: // return SIGPIPE; case signalc::segmentation_fault: return ((unsigned long) 0xC0000005L) /*EXCEPTION_ACCESS_VIOLATION*/; case signalc::floating_point_error: return ((unsigned long) 0xC0000090L) /*EXCEPTION_FLT_INVALID_OPERATION*/; } } inline signalc signalc_from_win32_exception_code(unsigned long c) { switch(c) { case((unsigned long) 0xC0000025L) /*EXCEPTION_NONCONTINUABLE_EXCEPTION*/: return signalc::abort_process; case((unsigned long) 0xC0000006L) /*EXCEPTION_IN_PAGE_ERROR*/: return signalc::undefined_memory_access; case((unsigned long) 0xC000001DL) /*EXCEPTION_ILLEGAL_INSTRUCTION*/: return signalc::illegal_instruction; // case SIGINT: // return signalc::interrupt; // case SIGPIPE: // return signalc::broken_pipe; case((unsigned long) 0xC0000005L) /*EXCEPTION_ACCESS_VIOLATION*/: return signalc::segmentation_fault; case((unsigned long) 0xC000008DL) /*EXCEPTION_FLT_DENORMAL_OPERAND*/: case((unsigned long) 0xC000008EL) /*EXCEPTION_FLT_DIVIDE_BY_ZERO*/: case((unsigned long) 0xC000008FL) /*EXCEPTION_FLT_INEXACT_RESULT*/: case((unsigned long) 0xC0000090L) /*EXCEPTION_FLT_INVALID_OPERATION*/: case((unsigned long) 0xC0000091L) /*EXCEPTION_FLT_OVERFLOW*/: case((unsigned long) 0xC0000092L) /*EXCEPTION_FLT_STACK_CHECK*/: case((unsigned long) 0xC0000093L) /*EXCEPTION_FLT_UNDERFLOW*/: return signalc::floating_point_error; case((unsigned long) 0xC00000FDL) /*EXCEPTION_STACK_OVERFLOW*/: return signalc::cxx_out_of_memory; default: return signalc::none; } } // Overload for when a Win32 exception is being raised inline bool set_siginfo(thread_local_signal_guard *g, unsigned long code, win32::PEXCEPTION_RECORD raw_info, win32::PCONTEXT raw_context) { auto signo = signalc_from_win32_exception_code(code); auto signalset = static_cast<signalc_set>(1ULL << static_cast<int>(signo)); if(g->guarded & signalset) { g->info.signo = static_cast<int>(signo); g->info.error_code = (long) raw_info->ExceptionInformation[2]; g->info.addr = (void *) raw_info->ExceptionInformation[1]; g->info.value.ptr_value = nullptr; g->info.raw_info = raw_info; g->info.raw_context = raw_context; return true; } return false; } SIGNALGUARD_FUNC_DECL long win32_exception_filter_function(unsigned long code, win32::_EXCEPTION_POINTERS *ptrs) noexcept { for(auto *shi = current_thread_local_signal_handler(); shi != nullptr; shi = shi->previous) { if(set_siginfo(shi, code, ptrs->ExceptionRecord, ptrs->ContextRecord)) { if(shi->call_continuer()) { // continue execution return (long) -1 /*EXCEPTION_CONTINUE_EXECUTION*/; } else { // invoke longjmp return 1 /*EXCEPTION_EXECUTE_HANDLER*/; } } } return 0 /*EXCEPTION_CONTINUE_SEARCH*/; } SIGNALGUARD_FUNC_DECL long __stdcall win32_vectored_exception_function(win32::_EXCEPTION_POINTERS *ptrs) noexcept { _state().lock.lock(); if(_state().global_signal_deciders_front != nullptr) { auto *raw_info = ptrs->ExceptionRecord; auto *raw_context = ptrs->ContextRecord; const auto signo = signalc_from_win32_exception_code(raw_info->ExceptionCode); const signalc_set signo_set = 1ULL << static_cast<int>(signo); raised_signal_info rsi; memset(&rsi, 0, sizeof(rsi)); rsi.signo = static_cast<int>(signo); rsi.error_code = (long) raw_info->ExceptionInformation[2]; rsi.addr = (void *) raw_info->ExceptionInformation[1]; rsi.raw_info = raw_info; rsi.raw_context = raw_context; auto *d = _state().global_signal_deciders_front; for(size_t n = 0; d != nullptr; n++) { size_t i = 0; for(d = _state().global_signal_deciders_front; d != nullptr; d = d->next) { if(i++ == n) { if(d->guarded & signo_set) { rsi.value = d->value; _state().lock.unlock(); if(d->decider(&rsi)) { return (long) -1 /*EXCEPTION_CONTINUE_EXECUTION*/; } _state().lock.lock(); break; } n++; } } } } _state().lock.unlock(); return 0 /*EXCEPTION_CONTINUE_SEARCH*/; } #else struct installed_signal_handler { unsigned count; // number of signal_install instances for this signal struct sigaction former; }; static installed_signal_handler handler_counts[32]; // indexed by signal number // Simulate the raising of a signal inline bool do_raise_signal(int signo, struct sigaction &sa, siginfo_t *_info, void *_context) { void (*h1)(int signo, siginfo_t *info, void *context) = nullptr; void (*h2)(int signo) = nullptr; siginfo_t info; ucontext_t context; // std::cout << "do_raise_signal(" << signo << ", " << (void *) sa.sa_handler << ", " << info << ", " << context << ")" << std::endl; if(sa.sa_handler == SIG_IGN) { // std::cout << "ignore" << std::endl; return false; } else if(sa.sa_handler == SIG_DFL) { // std::cout << "default" << std::endl; // Default action for these is to ignore if(signo == SIGCHLD || signo == SIGURG #ifdef SIGWINCH || signo == SIGWINCH #endif #if !defined(__linux__) && defined(SIGIO) || signo == SIGIO #endif #ifdef SIGINFO || signo == SIGINFO #endif ) return false; #if 1 // Simulate invoke the default handler. We preserve semantics - ish. // Default ignored signals already are handled above, so just disambiguate between core dumping, terminate, and immediate exit signals switch(signo) { // Core dump signals case SIGABRT: case SIGBUS: case SIGFPE: case SIGILL: case SIGQUIT: case SIGSEGV: case SIGSYS: case SIGTRAP: #ifdef __linux__ case SIGXCPU: case SIGXFSZ: #endif // glibc's abort() implementation does a ton of stuff to ensure it always works no matter from where it is called :) abort(); // Termination signals case SIGSTOP: case SIGTSTP: case SIGTTIN: case SIGTTOU: case SIGPIPE: case SIGALRM: case SIGTERM: #ifdef __linux__ case SIGIO: #endif #if defined(__FreeBSD__) || defined(__APPLE__) case SIGXCPU: case SIGXFSZ: #endif #ifdef SIGVTALRM case SIGVTALRM: #endif #ifdef SIGPROF case SIGPROF: #endif case SIGUSR1: case SIGUSR2: #ifdef SIGTHR case SIGTHR: #endif #ifdef SIGLIBRT case SIGLIBRT: #endif #ifdef SIGEMT case SIGEMT: #endif #ifdef SIGPWR case SIGPWR: #endif // Immediate exit without running cleanup _exit(127); // compatibility code with glibc's default signal handler // Immediate exit running cleanup default: ::exit(EXIT_SUCCESS); } #else // This is the original implementation which appears to sometimes hang in pthread_kill() for no obvious reason // Ok, need to invoke the default handler. NOTE: The following code is racy wrt other threads manipulating the global signal handlers struct sigaction dfl, myformer; memset(&dfl, 0, sizeof(dfl)); dfl.sa_handler = SIG_DFL; sigaction(signo, &dfl, &myformer); // restore action to default // Unblock this signal for this thread sigset_t myformer2; sigset_t def2; sigemptyset(&def2); sigaddset(&def2, signo); pthread_sigmask(SIG_UNBLOCK, &def2, &myformer2); // Raise this signal for this thread, invoking the default action pthread_kill(pthread_self(), signo); // Very likely never returns sigaction(signo, &myformer, nullptr); // but if it does, restore the previous action #endif return true; // and return true to indicate that we executed some signal handler } else if(sa.sa_flags & SA_SIGINFO) { h1 = sa.sa_sigaction; if(nullptr != _info) { info = *_info; } if(nullptr != _context) { context = *(const ucontext_t *) _context; } } else { h2 = sa.sa_handler; } // std::cout << "handler" << std::endl; if(sa.sa_flags & SA_ONSTACK) { // Not implemented yet abort(); } if(sa.sa_flags & SA_RESETHAND) { struct sigaction dfl; memset(&dfl, 0, sizeof(dfl)); dfl.sa_handler = SIG_DFL; sigaction(signo, &dfl, nullptr); } if(!(sa.sa_flags & (SA_RESETHAND | SA_NODEFER))) { sigaddset(&sa.sa_mask, signo); } sigset_t oldset; pthread_sigmask(SIG_BLOCK, &sa.sa_mask, &oldset); if(h1 != nullptr) h1(signo, (nullptr != _info) ? &info : nullptr, (nullptr != _context) ? &context : nullptr); else h2(signo); pthread_sigmask(SIG_SETMASK, &oldset, nullptr); return true; } // Overload for when a POSIX signal is being raised inline bool set_siginfo(thread_local_signal_guard *g, int signo, siginfo_t *raw_info, void *raw_context) { auto signalset = static_cast<signalc_set>(1ULL << signo); if(g->guarded & signalset) { g->info.signo = signo; g->info.error_code = (nullptr != raw_info) ? raw_info->si_errno : 0; g->info.addr = (nullptr != raw_info) ? raw_info->si_addr : nullptr; g->info.value.ptr_value = nullptr; g->info.raw_info = raw_info; g->info.raw_context = raw_context; return true; } return false; } // Called by POSIX to handle a raised signal inline void raw_signal_handler(int signo, siginfo_t *info, void *context) { // std::cout << "raw_signal_handler(" << signo << ", " << info << ", " << context << ") shi=" << shi << std::endl; for(auto *shi = current_thread_local_signal_handler(); shi != nullptr; shi = shi->previous) { if(set_siginfo(shi, signo, info, context)) { if(!shi->call_continuer()) { longjmp(shi->info.buf, 1); } } } _state().lock.lock(); if(_state().global_signal_deciders_front != nullptr) { raised_signal_info rsi; memset(&rsi, 0, sizeof(rsi)); rsi.signo = signo; rsi.error_code = (nullptr != info) ? info->si_errno : 0; rsi.addr = (nullptr != info) ? info->si_addr : nullptr; rsi.raw_info = info; rsi.raw_context = context; auto *d = _state().global_signal_deciders_front; for(size_t n = 0; d != nullptr; n++) { size_t i = 0; for(d = _state().global_signal_deciders_front; d != nullptr; d = d->next) { if(i++ == n) { if(d->guarded & (1ULL << signo)) { rsi.value = d->value; _state().lock.unlock(); if(d->decider(&rsi)) { return; // resume execution } _state().lock.lock(); break; } n++; } } } } // Otherwise, call the previous signal handler if(handler_counts[signo].count > 0) { struct sigaction sa; sa = handler_counts[signo].former; _state().lock.unlock(); do_raise_signal(signo, sa, info, context); } else { _state().lock.unlock(); } } #endif } // namespace detail SIGNALGUARD_MEMFUNC_DECL signal_guard_install::signal_guard_install(signalc_set guarded) : _guarded(guarded) { #ifndef _WIN32 sigset_t set; sigemptyset(&set); detail::_state().lock.lock(); for(int signo = 0; signo < 32; signo++) { if((static_cast<uint64_t>(guarded) & (1 << signo)) != 0) { if(!detail::handler_counts[signo].count++) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = detail::raw_signal_handler; sa.sa_flags = SA_SIGINFO | SA_NODEFER; if(-1 == sigaction(signo, &sa, &detail::handler_counts[signo].former)) { detail::handler_counts[signo].count--; detail::_state().lock.unlock(); throw std::system_error(errno, std::system_category()); } } } if(detail::handler_counts[signo].count > 0) { sigaddset(&set, signo); } } // Globally enable all signals we have installed handlers for if(-1 == sigprocmask(SIG_UNBLOCK, &set, nullptr)) { detail::_state().lock.unlock(); throw std::system_error(errno, std::system_category()); } detail::signal_guards_installed().store(detail::signal_guards_installed().load(std::memory_order_relaxed) | guarded, std::memory_order_relaxed); detail::_state().lock.unlock(); #endif if((guarded & signalc_set::cxx_out_of_memory) || (guarded & signalc_set::cxx_termination) #ifdef _WIN32 || (guarded & signalc_set::interrupt) || (guarded & signalc_set::process_terminate) #endif ) { detail::_state().lock.lock(); if(guarded & signalc_set::cxx_out_of_memory) { if(!detail::_state().new_handler_count++) { detail::_state().new_handler_old = std::set_new_handler(detail::new_handler); } } if(guarded & signalc_set::cxx_termination) { if(!detail::_state().terminate_handler_count++) { #ifndef _MSC_VER if(std::get_terminate() != detail::terminate_handler) { detail::terminate_handler_old() = std::set_terminate(detail::terminate_handler); } #endif } } #ifdef _WIN32 if((guarded & signalc_set::interrupt) || (guarded & signalc_set::process_terminate)) { if(!detail::_state().win32_console_ctrl_handler_count++) { if(!detail::win32::SetConsoleCtrlHandler(detail::win32_console_ctrl_handler, true)) { throw std::system_error(detail::win32::GetLastError(), std::system_category()); } } } #endif detail::_state().lock.unlock(); } } SIGNALGUARD_MEMFUNC_DECL signal_guard_install::~signal_guard_install() { if((_guarded & signalc_set::cxx_out_of_memory) || (_guarded & signalc_set::cxx_termination) #ifdef _WIN32 || (_guarded & signalc_set::interrupt) || (_guarded & signalc_set::process_terminate) #endif ) { detail::_state().lock.lock(); if(_guarded & signalc_set::cxx_out_of_memory) { if(!--detail::_state().new_handler_count) { std::set_new_handler(detail::_state().new_handler_old); } } if(_guarded & signalc_set::cxx_termination) { if(!--detail::_state().terminate_handler_count) { #ifndef _MSC_VER std::set_terminate(detail::terminate_handler_old()); #endif } } #ifdef _WIN32 if((_guarded & signalc_set::interrupt) || (_guarded & signalc_set::process_terminate)) { if(!--detail::_state().win32_console_ctrl_handler_count) { detail::win32::SetConsoleCtrlHandler(detail::win32_console_ctrl_handler, false); } } #endif detail::_state().lock.unlock(); } #ifndef _WIN32 uint64_t handlers_installed = 0; sigset_t set; sigemptyset(&set); bool setsigprocmask = false; detail::_state().lock.lock(); for(int signo = 0; signo < 32; signo++) { if((static_cast<uint64_t>(_guarded) & (1 << signo)) != 0) { int ret = 0; if(!--detail::handler_counts[signo].count) { ret = sigaction(signo, &detail::handler_counts[signo].former, nullptr); if(ret == -1) { detail::_state().lock.unlock(); abort(); detail::_state().lock.lock(); } sigaddset(&set, signo); setsigprocmask = true; } } if(detail::handler_counts[signo].count > 0) { handlers_installed |= (1ULL << signo); } } if(detail::_state().new_handler_count > 0) { handlers_installed |= signalc_set::cxx_out_of_memory; } if(detail::_state().terminate_handler_count > 0) { handlers_installed |= signalc_set::cxx_termination; } detail::signal_guards_installed().store(static_cast<signalc_set>(handlers_installed), std::memory_order_relaxed); detail::_state().lock.unlock(); if(setsigprocmask) { sigprocmask(SIG_BLOCK, &set, nullptr); } #endif } namespace detail { static inline bool signal_guard_global_decider_impl_indirect(raised_signal_info *rsi) { auto *p = (signal_guard_global_decider_impl *) rsi->value.ptr_value; return p->_call(rsi); } SIGNALGUARD_MEMFUNC_DECL signal_guard_global_decider_impl::signal_guard_global_decider_impl(signalc_set guarded, bool callfirst) : _install(guarded) { auto *p = new global_signal_decider; _p = p; p->guarded = guarded; p->decider = signal_guard_global_decider_impl_indirect; p->value.ptr_value = this; _state().lock.lock(); global_signal_decider **a, **b; if(_state().global_signal_deciders_front == nullptr) { a = &_state().global_signal_deciders_front; b = &_state().global_signal_deciders_back; } else if(callfirst) { a = &_state().global_signal_deciders_front; b = &_state().global_signal_deciders_front->prev; } else { a = &_state().global_signal_deciders_back->next; b = &_state().global_signal_deciders_back; } p->next = *a; p->prev = *b; *a = p; *b = p; #ifdef _WIN32 if(nullptr == _state().win32_global_signal_decider2) { /* The interaction between AddVectoredContinueHandler, AddVectoredExceptionHandler, UnhandledExceptionFilter, and frame-based EH is completely undocumented in Microsoft documentation. The following is the truth, as determined by empirical testing: 1. Vectored exception handlers get called first, before anything else, including frame-based EH. This is not what the MSDN documentation hints at. 2. Frame-based EH filters are now run. 3. UnhandledExceptionFilter() is now called. On older Windows, this invokes the debugger if being run under the debugger, otherwise continues search. But as of at least Windows 7 onwards, if no debugger is attached, it invokes Windows Error Reporting to send a core dump to Microsoft. 4. Vectored continue handlers now get called, AFTER the frame-based EH. Again, not what MSDN hints at. The change in the default non-debugger behaviour of UnhandledExceptionFilter() effectively makes vectored continue handlers useless. I suspect whomever made the change at Microsoft didn't realise that vectored continue handlers are invoked AFTER the unhandled exception filter, because that's really non-obvious from the documentation. Anyway this is why we install for both the continue handler and the unhandled exception filters. The unhandled exception filter will be called when not running under a debugger. The vectored continue handler will be called when running under a debugger, as the UnhandledExceptionFilter() function never calls the installed unhandled exception filter function if under a debugger. */ _state().win32_global_signal_decider1 = (void *) win32::SetUnhandledExceptionFilter(win32_vectored_exception_function); _state().win32_global_signal_decider2 = (void *) win32::AddVectoredContinueHandler(1, win32_vectored_exception_function); } #endif _state().lock.unlock(); } SIGNALGUARD_MEMFUNC_DECL signal_guard_global_decider_impl::signal_guard_global_decider_impl(signal_guard_global_decider_impl &&o) noexcept : _install(static_cast<signal_guard_global_decider_impl &&>(o)._install) , _p(o._p) { _state().lock.lock(); auto *p = (global_signal_decider *) _p; p->value.ptr_value = this; _state().lock.unlock(); o._p = nullptr; } SIGNALGUARD_MEMFUNC_DECL signal_guard_global_decider_impl::~signal_guard_global_decider_impl() { if(_p != nullptr) { auto *p = (global_signal_decider *) _p; _state().lock.lock(); global_signal_decider **a = (nullptr == p->prev) ? &_state().global_signal_deciders_front : &p->prev->next; global_signal_decider **b = (nullptr == p->next) ? &_state().global_signal_deciders_back : &p->next->prev; *a = p->next; *b = p->prev; #ifdef _WIN32 if(nullptr == _state().global_signal_deciders_front) { win32::RemoveVectoredContinueHandler(_state().win32_global_signal_decider2); win32::SetUnhandledExceptionFilter((win32::PVECTORED_EXCEPTION_HANDLER) _state().win32_global_signal_decider1); _state().win32_global_signal_decider1 = nullptr; _state().win32_global_signal_decider2 = nullptr; } #endif _state().lock.unlock(); delete p; _p = nullptr; } } } // namespace detail SIGNALGUARD_FUNC_DECL bool thrd_raise_signal(signalc signo, void *_info, void *_context) { if(signo == signalc::cxx_out_of_memory) { if(std::get_new_handler() == nullptr) { std::terminate(); } std::get_new_handler()(); return true; } else if(signo == signalc::cxx_termination) { std::terminate(); } #ifdef _WIN32 using detail::win32::_EXCEPTION_RECORD; using detail::win32::RaiseException; auto win32sehcode = detail::win32_exception_code_from_signalc(signo); if((unsigned long) -1 == win32sehcode) throw std::runtime_error("Unknown signal"); (void) _context; const auto *info = (const _EXCEPTION_RECORD *) _info; // info->ExceptionInformation[0] = 0=read 1=write 8=DEP // info->ExceptionInformation[1] = causing address // info->ExceptionInformation[2] = NTSTATUS causing exception if(info != nullptr) { RaiseException(win32sehcode, info->ExceptionFlags, info->NumberParameters, info->ExceptionInformation); } else { RaiseException(win32sehcode, 0, 0, nullptr); } return false; #else auto *info = (siginfo_t *) _info; // Fetch the current handler, and simulate the raise struct sigaction sa; sigaction(static_cast<int>(signo), nullptr, &sa); return detail::do_raise_signal(static_cast<int>(signo), sa, info, _context); #endif } SIGNALGUARD_FUNC_DECL void terminate_process_immediately(const char *msg) noexcept { static const char s[] = "\nProcess fail fast terminated\n"; if(msg == nullptr) { msg = s; } #ifdef _WIN32 if(msg != nullptr && msg[0] != 0) { unsigned long written = 0; (void) detail::win32::WriteFile(detail::win32::GetStdHandle((unsigned long) -12 /*STD_ERROR_HANDLE*/), msg, (unsigned long) strlen(msg), &written, nullptr); } detail::win32::TerminateProcess((void *) -1, 1); #else if(msg != nullptr && msg[0] != 0) { if(-1 == ::write(2, msg, strlen(msg))) { volatile int a = 1; // shut up GCC (void) a; } } _exit(1); #endif // We promised we would never, ever, return. for(;;) { } } namespace detail { static struct watchdog_decider_t { configurable_spinlock::spinlock<uintptr_t> lock; signal_guard_watchdog_impl *next{nullptr}; bool check() noexcept { bool ret = false; #ifdef _WIN32 auto now = detail::win32::GetTickCount64(); #else struct timespec ts; memset(&ts, 0, sizeof(ts)); (void) ::clock_gettime(CLOCK_MONOTONIC, &ts); auto now = ((uint64_t) ts.tv_sec * 1000ULL + (uint64_t) ts.tv_nsec / 1000000ULL); #endif lock.lock(); auto *d = next; for(size_t n = 0; d != nullptr; n++) { size_t i = 0; for(d = next; d != nullptr; d = d->_next) { if(i++ == n) { if(now >= d->_deadline_ms && !d->_alreadycalled) { d->_alreadycalled = true; lock.unlock(); d->_call(); ret = true; lock.lock(); break; } n++; } } } lock.unlock(); return ret; } } watchdog_decider; #ifdef _WIN32 static thread_local bool _win32_signal_guard_watchdog_impl_apcfunc_called = false; static inline void __stdcall _win32_signal_guard_watchdog_impl_apcfunc(uintptr_t /*unused*/) { _win32_signal_guard_watchdog_impl_apcfunc_called = true; } static inline unsigned long __stdcall _win32_signal_guard_watchdog_impl_thread(void *lpParameter) { detail::win32::SleepEx((unsigned long) (uintptr_t) lpParameter, true); if(!_win32_signal_guard_watchdog_impl_apcfunc_called) { watchdog_decider.check(); } return 0; } #else static auto posix_signal_guard_watchdog_decider_install = make_signal_guard_global_decider(signalc_set::timer_expire, [](raised_signal_info * /*unused*/) -> bool { return watchdog_decider.check(); }); #endif SIGNALGUARD_MEMFUNC_DECL void signal_guard_watchdog_impl::_detach() noexcept { watchdog_decider.lock.lock(); if(_prev == nullptr) { assert(watchdog_decider.next == this); watchdog_decider.next = _next; } else { assert(_prev->_next == this); _prev->_next = _next; _prev = nullptr; } if(_next != nullptr) { assert(_next->_prev == this); _next->_prev = _prev; _next = nullptr; } watchdog_decider.lock.unlock(); } SIGNALGUARD_MEMFUNC_DECL signal_guard_watchdog_impl::signal_guard_watchdog_impl(unsigned ms) { watchdog_decider.lock.lock(); if(watchdog_decider.next != nullptr) { assert(watchdog_decider.next->_prev == nullptr); watchdog_decider.next->_prev = this; _next = watchdog_decider.next; _prev = nullptr; watchdog_decider.next = this; } else { _next = _prev = nullptr; watchdog_decider.next = this; } watchdog_decider.lock.unlock(); auto uninstall = QUICKCPPLIB_NAMESPACE::scope::make_scope_fail([this]() noexcept { _detach(); }); #ifdef _WIN32 unsigned long threadid; _deadline_ms = detail::win32::GetTickCount64() + ms; _threadh = detail::win32::CreateThread(nullptr, 0, _win32_signal_guard_watchdog_impl_thread, (void *) (uintptr_t) ms, 0, &threadid); if(_threadh == nullptr) { throw std::system_error(detail::win32::GetLastError(), std::system_category()); } _inuse = true; #else struct timespec ts; memset(&ts, 0, sizeof(ts)); if(-1 == ::clock_gettime(CLOCK_MONOTONIC, &ts)) { throw std::system_error(errno, std::system_category()); } #ifdef __APPLE__ (void) ms; throw std::runtime_error("signal_guard_watchdog not implemented on Mac OS due to lack of POSIX timers"); #else timer_t timerid = nullptr; if(-1 == ::timer_create(CLOCK_MONOTONIC, nullptr, &timerid)) { throw std::system_error(errno, std::system_category()); } _deadline_ms = ((uint64_t) ts.tv_sec * 1000ULL + (uint64_t) ts.tv_nsec / 1000000ULL) + ms; _timerid = timerid; _inuse = true; struct itimerspec newtimer; memset(&newtimer, 0, sizeof(newtimer)); newtimer.it_value.tv_sec = ms / 1000; newtimer.it_value.tv_nsec = (ms % 1000) * 1000000LL; if(-1 == ::timer_settime(timerid, 0, &newtimer, nullptr)) { throw std::system_error(errno, std::system_category()); } #endif #endif } SIGNALGUARD_MEMFUNC_DECL signal_guard_watchdog_impl::signal_guard_watchdog_impl(signal_guard_watchdog_impl &&o) noexcept : #ifdef _WIN32 _threadh(o._threadh) #else _timerid(o._timerid) #endif , _prev(o._prev) , _next(o._next) , _deadline_ms(o._deadline_ms) , _inuse(o._inuse) , _alreadycalled(o._alreadycalled) { if(_inuse) { watchdog_decider.lock.lock(); if(_prev == nullptr) { assert(watchdog_decider.next == &o); watchdog_decider.next = this; } else { assert(_prev->_next == &o); _prev->_next = this; } if(_next != nullptr) { assert(_next->_prev == &o); _next->_prev = this; } o._prev = o._next = nullptr; o._inuse = false; #ifdef _WIN32 o._threadh = nullptr; #else o._timerid = nullptr; #endif watchdog_decider.lock.unlock(); } } SIGNALGUARD_MEMFUNC_DECL void signal_guard_watchdog_impl::release() { if(_inuse) { #ifdef _WIN32 if(!detail::win32::QueueUserAPC(_win32_signal_guard_watchdog_impl_apcfunc, _threadh, 0)) { throw std::system_error(detail::win32::GetLastError(), std::system_category()); } if(!detail::win32::CloseHandle(_threadh)) { throw std::system_error(detail::win32::GetLastError(), std::system_category()); } _threadh = nullptr; #else #ifndef __APPLE__ if(-1 == ::timer_delete(_timerid)) { throw std::system_error(errno, std::system_category()); } #endif _timerid = nullptr; #endif _inuse = false; _detach(); } } } // namespace detail } // namespace signal_guard QUICKCPPLIB_NAMESPACE_END
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/CMakeLists.txt
# Copyright 2018-2019 by Martin Moene # # https://github.com/martinmoene/span-lite # # 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) cmake_minimum_required( VERSION 3.8 FATAL_ERROR ) # span-lite project and version, updated by script/update-version.py: project( span_lite VERSION 0.10.3 # DESCRIPTION "A C++20-like span for C++98, C++11 and later in a single-file header-only library" # HOMEPAGE_URL "https://github.com/martinmoene/span-lite" LANGUAGES CXX ) # Package information: set( unit_name "span" ) set( package_nspace "nonstd" ) set( package_name "${unit_name}-lite" ) set( package_version "${${PROJECT_NAME}_VERSION}" ) message( STATUS "Project '${PROJECT_NAME}', package '${package_name}' version: '${package_version}'") # Toplevel or subproject: if ( CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME ) set( span_IS_TOPLEVEL_PROJECT TRUE ) else() set( span_IS_TOPLEVEL_PROJECT FALSE ) endif() # If toplevel project, enable building and performing of tests, disable building of examples: option( SPAN_LITE_OPT_BUILD_TESTS "Build and perform span-lite tests" ${span_IS_TOPLEVEL_PROJECT} ) option( SPAN_LITE_OPT_BUILD_EXAMPLES "Build span-lite examples" OFF ) option( SPAN_LITE_EXPORT_PACKAGE "Export span-lite package globally" ${span_IS_TOPLEVEL_PROJECT} ) option( SPAN_LITE_COLOURISE_TEST "Colourise test output" OFF ) option( SPAN_LITE_OPT_SELECT_STD "Select std::span" OFF ) option( SPAN_LITE_OPT_SELECT_NONSTD "Select nonstd::span" OFF ) # If requested, build and perform tests, build examples: if ( SPAN_LITE_OPT_BUILD_TESTS ) enable_testing() add_subdirectory( test ) endif() if ( SPAN_LITE_OPT_BUILD_EXAMPLES ) enable_testing() add_subdirectory( example ) endif() # # Interface, installation and packaging # # CMake helpers: include( GNUInstallDirs ) include( CMakePackageConfigHelpers ) # Interface library: add_library( ${package_name} INTERFACE ) add_library( ${package_nspace}::${package_name} ALIAS ${package_name} ) target_include_directories( ${package_name} INTERFACE "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>" "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>" ) # Package configuration: # Note: package_name and package_target are used in package_config_in set( package_folder "${package_name}" ) set( package_target "${package_name}-targets" ) set( package_config "${package_name}-config.cmake" ) set( package_config_in "${package_name}-config.cmake.in" ) set( package_config_version "${package_name}-config-version.cmake" ) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/${package_config_in}" "${CMAKE_CURRENT_BINARY_DIR}/${package_config}" INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}" ) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/cmake/${package_config_version}.in" "${CMAKE_CURRENT_BINARY_DIR}/${package_config_version}" @ONLY) # Installation: install( TARGETS ${package_name} EXPORT ${package_target} # INCLUDES DESTINATION "${...}" # already set via target_include_directories() ) install( EXPORT ${package_target} NAMESPACE ${package_nspace}:: DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}" ) install( FILES "${CMAKE_CURRENT_BINARY_DIR}/${package_config}" "${CMAKE_CURRENT_BINARY_DIR}/${package_config_version}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}" ) install( DIRECTORY "include/" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) export( EXPORT ${package_target} NAMESPACE ${package_nspace}:: FILE "${CMAKE_CURRENT_BINARY_DIR}/${package_name}-targets.cmake" ) # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/LICENSE.txt
Boost Software License - Version 1.0 - August 17th, 2003 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: 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. 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.
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/README.md
<a id="top"></a> # span lite: A single-file header-only version of a C++20-like span for C++98, C++11 and later [![Language](https://img.shields.io/badge/C%2B%2B-98/11/14/17/20-blue.svg)](https://en.wikipedia.org/wiki/C%2B%2B#Standardization) [![License](https://img.shields.io/badge/license-BSL-blue.svg)](https://opensource.org/licenses/BSL-1.0) [![Build Status](https://github.com/martinmoene/span-lite/actions/workflows/ci.yml/badge.svg)](https://github.com/martinmoene/span-lite/actions/workflows/ci.yml) [![Build Status](https://travis-ci.org/martinmoene/span-lite.svg?branch=master)](https://travis-ci.org/martinmoene/span-lite) [![Build status](https://ci.appveyor.com/api/projects/status/1ha3wnxtam547m8p?svg=true)](https://ci.appveyor.com/project/martinmoene/span-lite) [![Version](https://badge.fury.io/gh/martinmoene%2Fspan-lite.svg)](https://github.com/martinmoene/span-lite/releases) [![download](https://img.shields.io/badge/latest-download-blue.svg)](https://github.com/martinmoene/span-lite/blob/master/include/nonstd/span.hpp) [![Conan](https://img.shields.io/badge/on-conan-blue.svg)](https://conan.io/center/span-lite) [![Try it on wandbox](https://img.shields.io/badge/on-wandbox-blue.svg)](https://wandbox.org/permlink/venR3Ko2Q4tlvcVk) [![Try it on godbolt online](https://img.shields.io/badge/on-godbolt-blue.svg)](https://godbolt.org/z/htwpnb) **Contents** - [Example usage](#example-usage) - [In a nutshell](#in-a-nutshell) - [License](#license) - [Dependencies](#dependencies) - [Installation and use](#installation-and-use) - [Synopsis](#synopsis) - [Reported to work with](#reported-to-work-with) - [Building the tests](#building-the-tests) - [Other implementations of span](#other-implementations-of-span) - [Notes and references](#notes-and-references) - [Appendix](#appendix) ## Example usage ```cpp #include "nonstd/span.hpp" #include <array> #include <vector> #include <iostream> std::ptrdiff_t size( nonstd::span<const int> spn ) { return spn.size(); } int main() { int arr[] = { 1, }; std::cout << "C-array:" << size( arr ) << " array:" << size( std::array <int, 2>{ 1, 2, } ) << " vector:" << size( std::vector<int >{ 1, 2, 3, } ); } ``` ### Compile and run ```bash prompt> g++ -std=c++11 -Wall -I../include -o 01-basic.exe 01-basic.cpp && 01-basic.exe C-array:1 array:2 vector:3 ``` ## In a nutshell **span lite** is a single-file header-only library to provide a bounds-safe view for sequences of objects. The library provides a [C++20-like span](http://en.cppreference.com/w/cpp/container/span) for use with C++98 and later. If available, `std::span` is used, unless [configured otherwise](#configuration). *span-lite* can detect the presence of [*byte-lite*](https://github.com/martinmoene/byte-lite) and if present, it provides `as_bytes()` and `as_writable_bytes()` also for C++14 and earlier. **Features and properties of span lite** are ease of installation (single header), freedom of dependencies other than the standard library. To compensate for the class template argument deduction that is missing from pre-C++17 compilers, `nonstd::span` can provide `make_span` functions. See [configuration](#configuration). ## License *span lite* is distributed under the [Boost Software License](https://github.com/martinmoene/span-lite/blob/master/LICENSE.txt). ## Dependencies *span lite* has no other dependencies than the [C++ standard library](http://en.cppreference.com/w/cpp/header). ## Installation and use *span lite* is a single-file header-only library. Put `span.hpp` in the [include](include) folder directly into the project source tree or somewhere reachable from your project. ## Synopsis **Contents** [Documentation of `std::span`](#documentation-of-stdspan) [Later additions](#later-additions) [Non-standard extensions](#non-standard-extensions) [Configuration](#configuration) ## Documentation of `std::span` Depending on the compiler and C++-standard used, `nonstd::span` behaves less or more like `std::span`. To get an idea of the capabilities of `nonstd::span` with your configuration, look at the output of the [tests](test/span.t.cpp), issuing `span-main.t --pass @`. For `std::span`, see its [documentation at cppreference](http://en.cppreference.com/w/cpp/container/span). ## Later additions ### `back()` and `front()` *span lite* can provide `back()` and `front()` member functions for element access. See the table below and section [configuration](#configuration). ## Non-standard extensions ### Construct from std::initializer_list (p2447) *span lite* can provide construction from a std::initializer_list<> as a constant set of values as proposed in [p2447](https://wg21.link/p2447). See the table below and section [configuration](#configuration). ### Construct from container To construct a span from a container with compilers that cannot constrain such a single-parameter constructor to containers, *span lite* provides a constructor that takes an additional parameter of type `with_container_t`. Use `with_container` as value for this parameter. See the table below and section [configuration](#configuration). ### Construct from `std::array` with const data *span lite* can provide construction of a span from a `std::array` with const data. See the table below and section [configuration](#configuration). ### `operator()` *span lite* can provide member function call `operator()` for element access. It is equivalent to `operator[]` and has been marked `[[deprecated]]`. Its main purpose is to provide a migration path. ### `at()` *span lite* can provide member function `at()` for element access. Unless exceptions have been disabled, `at()` throws std::out_of_range if the index falls outside the span. With exceptions disabled, `at(index_t)` delegates bounds checking to `operator[](index_t)`. See the table below and sections [configuration](#configuration) and [disable exceptions](#disable-exceptions). ### `swap()` *span lite* can provide a `swap()`member function. See the table below and section [configuration](#configuration). ### `operator==()` and other comparison functions *span lite* can provide functions to compare the content of two spans. However, C++20's span will not provide comparison and _span lite_ will omit comparison at default in the near future. See the table below and section [configuration](#configuration). See also [Revisiting Regular Types](#regtyp). ### `same()` *span lite* can provide function `same()` to determine if two spans refer as identical spans to the same data via the same type. If `same()` is enabled, `operator==()` incorporates it in its comparison. See the table below and section [configuration](#configuration). ### `first()`, `last()` and `subspan()` *span lite* can provide functions `first()`, `last()` and `subspan()` to avoid having to use the *dot template* syntax when the span is a dependent type. See the table below and section [configuration](#configuration). ### `make_span()` *span lite* can provide `make_span()` creator functions to compensate for the class template argument deduction that is missing from pre-C++17 compilers. See the table below and section [configuration](#configuration). ### `byte_span()` *span lite* can provide `byte_span()` creator functions to represent an object as a span of bytes. This requires the C++17 type `std::byte` to be available. See the table below and section [configuration](#configuration). | Kind | std | Function or method | |--------------------|------|--------------------| | **Macro** |&nbsp;| macro **`span_FEATURE_WITH_INITIALIZER_LIST_P2447`** | | **Constructor**<br>&nbsp; |&nbsp;| constexpr explicit **span**( std::initializer_list&lt;value_type> il ) noexcept<br>explicit for non-dynamic extent | | &nbsp; |&nbsp;| &nbsp; | | **Macro**<br>&nbsp;|&nbsp;| macro **`span_FEATURE_WITH_CONTAINER`**<br>macro **`span_FEATURE_WITH_CONTAINER_TO_STD`** | | **Types** |&nbsp;| **with_container_t** type to disambiguate below constructors | | **Objects** |&nbsp;| **with_container** value to disambiguate below constructors | | **Constructors** |&nbsp;| macro **`span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE`**| | &nbsp; |&nbsp;| template&lt;class Container><br>constexpr **span**(with_container_t, Container & cont) | | &nbsp; |&nbsp;| template&lt;class Container><br>constexpr **span**(with_container_t, Container const & cont) | | &nbsp; |&nbsp;| &nbsp; | | **Methods** |&nbsp;| macro **`span_FEATURE_MEMBER_CALL_OPERATOR`** | | &nbsp; |&nbsp;| constexpr reference **operator()**(index_t idx) const<br>Equivalent to **operator[]**(), marked `[[deprecated]]` | | &nbsp; |&nbsp;| &nbsp; | | **Methods** |&nbsp;| macro **`span_FEATURE_MEMBER_AT`** | | &nbsp; |&nbsp;| constexpr reference **at**(index_t idx) const<br>May throw std::out_of_range exception | | &nbsp; |&nbsp;| &nbsp; | | **Methods** |&nbsp;| macro **`span_FEATURE_MEMBER_BACK_FRONT`** (on since v0.5.0) | | &nbsp; |&nbsp;| constexpr reference **back()** const noexcept | | &nbsp; |&nbsp;| constexpr reference **front()** const noexcept | | &nbsp; |&nbsp;| &nbsp; | | **Method** |&nbsp;| macro **`span_FEATURE_MEMBER_SWAP`** | | &nbsp; |&nbsp;| constexpr void **swap**(span & other) noexcept | | &nbsp; |&nbsp;| &nbsp; | | **Free functions** |&nbsp;| macro **`span_FEATURE_COMPARISON`** | |<br><br>== != < > <= >= |&nbsp;| template&lt;class T1, index_t E1, class T2, index_t E2><br>constexpr bool<br>**operator==**( span<T1,E1> const & l, span<T2,E2> const & r) noexcept | | &nbsp; |&nbsp;| &nbsp; | | **Free function** |&nbsp;| macro **`span_FEATURE_SAME`** | | &nbsp; |&nbsp;| template&lt;class T1, index_t E1, class T2, index_t E2><br>constexpr bool<br>**same**( span<T1,E1> const & l, span<T2,E2> const & r) noexcept | | &nbsp; |&nbsp;| &nbsp; | | **Free functions**<br>&nbsp;<br>&nbsp; |&nbsp;| macros **`span_FEATURE_NON_MEMBER_FIRST_LAST_SUB`**,<br>**`span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN`**,<br>**`span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER`** | | &nbsp; |&nbsp;| &nbsp; | | **Free functions** |&nbsp;| macro **`span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN`** | | &nbsp; | &nbsp; | template&lt;extent_t Count, class T, extent_t Extent><br>constexpr span&lt;T,Count><br>**first**(span&lt;T,Extent> spn) | | &nbsp; | &nbsp; | template&lt;class T, extent_t Extent ><br>constexpr span&lt;T><br>**first**(span&lt;T,Extent> spn, size_t count) | | &nbsp; | &nbsp; | template&lt;extent_t Count, class T, extent_t Extent><br>constexpr span&lt;T,Count><br>**last**(span&lt;T,Extent> spn) | | &nbsp; | &nbsp; | template&lt;class T, extent_t Extent ><br>constexpr span&lt;T><br>**last**(span&lt;T,Extent> spn, size_t count) | | &nbsp; | &nbsp; | template&lt;size_t Offset, extent_t Count, class T, extent_t Extent><br>constexpr span&lt;T, Count><br>**subspan**(span&lt;T, Extent> spn) | | &nbsp; | &nbsp; | template&lt;class T, extent_t Extent><br>constexpr span&lt;T><br>**subspan**( span&lt;T, Extent> spn, size_t offset, extent_t count = dynamic_extent) | | &nbsp; |&nbsp;| &nbsp; | | **Free functions** |&nbsp;| macro **`span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER`** | | &nbsp; | >= C++11 | template&lt;extent_t Count, class T><br>constexpr auto<br>**first**(T & t) ->... | | &nbsp; | >= C++11 | template&lt;class T><br>constexpr auto<br>**first**(T & t, index_t count) ->... | | &nbsp; | >= C++11 | template&lt;extent_t Count, class T><br>constexpr auto<br>**last**(T & t) ->... | | &nbsp; | >= C++11 | template&lt;class T><br>constexpr auto<br>**last**(T & t, extent_t count) ->... | | &nbsp; | >= C++11 | template&lt;index_t Offset, extent_t Count = dynamic_extent, class T><br>constexpr auto<br>**subspan**(T & t) ->... | | &nbsp; | >= C++11 | template&lt;class T><br>constexpr auto<br>**subspan**(T & t, index_t offset, extent_t count = dynamic_extent) ->... | | &nbsp; | &nbsp; | &nbsp; | | **Free functions**<br>&nbsp; |&nbsp;| macro **`span_FEATURE_MAKE_SPAN`**<br>macro **`span_FEATURE_MAKE_SPAN_TO_STD`** | | &nbsp; | &nbsp; | template&lt;class T><br>constexpr span&lt;T><br>**make_span**(T \* first, T \* last) noexcept | | &nbsp; | &nbsp; | template&lt;class T><br>constexpr span&lt;T><br>**make_span**(T \* ptr, index_t count) noexcept | | &nbsp; | &nbsp; | template&lt;class T, size_t N><br>constexpr span&lt;T,N><br>**make_span**(T (&arr)[N]) noexcept | | &nbsp; | >= C++11 | template&lt;class T, size_t N><br>constexpr span&lt;T,N><br>**make_span**(std::array&lt;T,N> & arr) noexcept | | &nbsp; | >= C++11 | template&lt;class T, size_t N><br>constexpr span&lt;const T,N><br>**make_span**(std::array&lt;T,N > const & arr) noexcept | | &nbsp; | >= C++11 | template&lt;class T><br>constexpr span&lt;T><br>**make_span**(std::initializer_list&lt;T> il) noexcept | | &nbsp; | >= C++11 | template&lt;class Container><br>constexpr auto<br>**make_span**(Container & cont) -><br>&emsp;span&lt;typename Container::value_type> noexcept | | &nbsp; | >= C++11 | template&lt;class Container><br>constexpr auto<br>**make_span**(Container const & cont) -><br>&emsp;span&lt;const typename Container::value_type> noexcept | | &nbsp; | &nbsp; | template&lt;class Container><br>span&lt;typename Container::value_type><br>**make_span**( with_container_t, Container & cont ) | | &nbsp; | &nbsp; | template&lt;class Container><br>span&lt;const typename Container::value_type><br>**make_span**( with_container_t, Container const & cont ) | | &nbsp; | < C++11 | template&lt;class T, Allocator><br>span&lt;T><br>**make_span**(std::vector&lt;T, Allocator> & cont) | | &nbsp; | < C++11 | template&lt;class T, Allocator><br>span&lt;const T><br>**make_span**(std::vector&lt;T, Allocator> const & cont) | | &nbsp; | &nbsp; | &nbsp; | | **Free functions** |&nbsp;| macro **`span_FEATURE_BYTE_SPAN`** | | &nbsp; | >= C++11 | template&lt;class T><br>span&lt;T, sizeof(T)><br>**byte_span**(T & t) | | &nbsp; | >= C++11 | template&lt;class T><br>span&lt;const T, sizeof(T)><br>**byte_span**(T const & t) | ## Configuration ### Tweak header If the compiler supports [`__has_include()`](https://en.cppreference.com/w/cpp/preprocessor/include), *span lite* supports the [tweak header](https://vector-of-bool.github.io/2020/10/04/lib-configuration.html) mechanism. Provide your *tweak header* as `nonstd/span.tweak.hpp` in a folder in the include-search-path. In the tweak header, provide definitions as documented below, like `#define span_CONFIG_NO_EXCEPTIONS 1`. ### Standard selection macro \-D<b>span\_CPLUSPLUS</b>=199711L Define this macro to override the auto-detection of the supported C++ standard, if your compiler does not set the `__cplusplus` macro correctly. ### Select `std::span` or `nonstd::span` At default, *span lite* uses `std::span` if it is available and lets you use it via namespace `nonstd`. You can however override this default and explicitly request to use `std::span` or span lite's `nonstd::span` as `nonstd::span` via the following macros. -D<b>span\_CONFIG\_SELECT\_SPAN</b>=span_SPAN_DEFAULT Define this to `span_SPAN_STD` to select `std::span` as `nonstd::span`. Define this to `span_SPAN_NONSTD` to select `nonstd::span` as `nonstd::span`. Default is undefined, which has the same effect as defining to `span_SPAN_DEFAULT`. ### Select extent type -D<b>span_CONFIG_EXTENT_TYPE</b>=std::size_t Define this to `std::ptrdiff_t` to use the signed type. The default is `std::size_t`, as in C++20 (since v0.7.0). ### Select size type -D<b>span_CONFIG_SIZE_TYPE</b>=std::size_t Define this to `std::ptrdiff_t` to use the signed type. The default is `std::size_t`, as in C++20 (since v0.7.0). Note `span_CONFIG_SIZE_TYPE` replaces `span_CONFIG_INDEX_TYPE` which is deprecated. ### Disable exceptions -D<b>span_CONFIG_NO_EXCEPTIONS</b>=0 Define this to 1 if you want to compile without exceptions. If not defined, the header tries and detect if exceptions have been disabled (e.g. via `-fno-exceptions`). Disabling exceptions will force contract violation to use termination, see [contract violation macros](#contract-violation-response-macros). Default is undefined. ### Provide construction from std::initializer_list (p2447) -D<b>span_FEATURE_WITH_INITIALIZER_LIST_P2447</b>=0 Define this to 1 to enable constructing a span from a std::initializer_list<> as a constant set of values. See proposal [p2447](https://wg21.link/p2447). Default is undefined. ### Provide construction using `with_container_t` -D<b>span_FEATURE_WITH_CONTAINER</b>=0 Define this to 1 to enable constructing a span using `with_container_t`. Note that `span_FEATURE_WITH_CONTAINER` takes precedence over `span_FEATURE_WITH_CONTAINER_TO_STD`. Default is undefined. -D<b>span_FEATURE_WITH_CONTAINER_TO_STD</b>=*n* Define this to the highest C++ language version for which to enable constructing a span using `with_container_t`, like 98, 03, 11, 14, 17, 20. You can use 99 for inclusion with any standard, but prefer to use `span_FEATURE_WITH_CONTAINER` for this. Note that `span_FEATURE_WITH_CONTAINER` takes precedence over `span_FEATURE_WITH_CONTAINER_TO_STD`. Default is undefined. ### Provide construction from `std::array` with const data -D<b>span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE</b>=0 Define this to 1 to enable constructing a span from a std::array with const data. Default is undefined. ### Provide `operator()` member function -D<b>span_FEATURE_MEMBER_CALL_OPERATOR</b>=0 Define this to 1 to provide member function `operator()`for element access. It is equivalent to `operator[]` and has been marked `[[deprecated]]`. Its main purpose is to provide a migration path. Default is undefined. ### Provide `at()` member function -D<b>span_FEATURE_MEMBER_AT</b>=0 Define this to 1 to provide member function `at()`. Define this to 2 to include index and size in message of std::out_of_range exception. Default is undefined. ### Provide `back()` and `front()` member functions -D<b>span_FEATURE_MEMBER_BACK_FRONT</b>=1 _(on since v0.5.0)_ Define this to 0 to omit member functions `back()` and `front()`. Default is undefined. ### Provide `swap()` member function -D<b>span_FEATURE_MEMBER_SWAP</b>=0 Define this to 1 to provide member function `swap()`. Default is undefined. ### Provide `operator==()` and other comparison functions -D<b>span_FEATURE_COMPARISON</b>=0 Define this to 1 to include the comparison functions to compare the content of two spans. C++20's span does not provide comparison and _span lite_ omits comparison from v0.7.0. Default is undefined. ### Provide `same()` function -D<b>span_FEATURE_SAME</b>=0 Define this to 1 to provide function `same()` to test if two spans refer as identical spans to the same data via the same type. If `same()` is enabled, `operator==()` incorporates it in its comparison. Default is undefined. ### Provide `first()`, `last()` and `subspan()` functions -D<b>span_FEATURE_NON_MEMBER_FIRST_LAST_SUB</b>=0 Define this to 1 to enable both `span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN` and `span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER`. Default is undefined. -D<b>span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN</b>=0 Define this to 1 to provide functions `first()`, `last()` and `subspan()` that take a `span<>` (work with C++98). This implies `span_FEATURE_MAKE_SPAN` to provide functions `make_span()` that are required for this feature. Default is undefined. -D<b>span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER</b>=0 Define this to 1 to provide functions `first()`, `last()` and `subspan()` that take a compatible container (requires C++11). This implies `span_FEATURE_MAKE_SPAN` to provide functions `make_span()` that are required for this feature. Default is undefined. ### Provide `make_span()` functions -D<b>span_FEATURE_MAKE_SPAN</b>=0 Define this to 1 to provide creator functions `nonstd::make_span()`. This feature is implied by using `span_FEATURE_NON_MEMBER_FIRST_LAST_SUB=1`. Note that `span_FEATURE_MAKE_SPAN` takes precedence over `span_FEATURE_MAKE_SPAN_TO_STD`. Default is undefined. -D<b>span_FEATURE_MAKE_SPAN_TO_STD</b>=*n* Define this to the highest C++ language version for which to provide creator functions `nonstd::make_span()`, like 98, 03, 11, 14, 17, 20. You can use 99 for inclusion with any standard, but prefer to use `span_FEATURE_MAKE_SPAN` for this. Note that `span_FEATURE_MAKE_SPAN` takes precedence over `span_FEATURE_MAKE_SPAN_TO_STD`. Default is undefined. ### Provide `byte_span()` functions -D<b>span_FEATURE_BYTE_SPAN</b>=0 Define this to 1 to provide creator functions `nonstd::byte_span()`. Default is undefined. ### Contract violation response macros *span-lite* provides contract violation response control as suggested in proposal [N4415](http://wg21.link/n4415). \-D<b>span\_CONFIG\_CONTRACT\_LEVEL\_ON</b> (*default*) Define this macro to include both `span_EXPECTS` and `span_ENSURES` in the code. This is the default case. \-D<b>span\_CONFIG\_CONTRACT\_LEVEL\_OFF</b> Define this macro to exclude both `span_EXPECTS` and `span_ENSURES` from the code. \-D<b>span\_CONFIG_CONTRACT\_LEVEL\_EXPECTS\_ONLY</b> Define this macro to include `span_EXPECTS` in the code and exclude `span_ENSURES` from the code. \-D<b>span\_CONFIG\_CONTRACT\_LEVEL\_ENSURES\_ONLY</b> Define this macro to exclude `span_EXPECTS` from the code and include `span_ENSURES` in the code. \-D<b>span\_CONFIG\_CONTRACT\_VIOLATION\_TERMINATES</b> (*default*) Define this macro to call `std::terminate()` on a contract violation in `span_EXPECTS`, `span_ENSURES`. This is the default case. \-D<b>span\_CONFIG\_CONTRACT\_VIOLATION\_THROWS</b> Define this macro to throw an exception of implementation-defined type that is derived from `std::runtime_exception` instead of calling `std::terminate()` on a contract violation in `span_EXPECTS` and `span_ENSURES`. See also [disable exceptions](#disable-exceptions). Reported to work with -------------------- The table below mentions the compiler versions *span lite* is reported to work with. OS | Compiler | Where | Versions | ------------:|:-----------|:--------|:---------| **GNU/Linux**| Clang/LLVM | Travis | 3.5.0, 3.6.2, 3.7.1, 3.8.0, 3.9.1, 4.0.1 | &nbsp; | GCC | Travis | 5.5.0, 6.4.0, 7.3.0 | **OS X** | ? | Local | ? | **Windows** | Clang/LLVM | Local | 6.0.0 | &nbsp; | GCC | Local | 7.2.0 | &nbsp; | Visual C++<br>(Visual Studio)| Local | 8 (2005), 10 (2010), 11 (2012),<br>12 (2013), 14 (2015), 15 (2017) | &nbsp; | Visual C++<br>(Visual Studio)| AppVeyor | 10 (2010), 11 (2012),<br>12 (2013), 14 (2015), 15 (2017) | ## Building the tests To build the tests you need: - [CMake](http://cmake.org), version 3.0 or later to be installed and in your PATH. - A [suitable compiler](#reported-to-work-with). The [*lest* test framework](https://github.com/martinmoene/lest) is included in the [test folder](test). The following steps assume that the [*span lite* source code](https://github.com/martinmoene/span-lite) has been cloned into a directory named `./span-lite`. 1. Create a directory for the build outputs. cd ./span-lite md build && cd build 2. Configure CMake to use the compiler of your choice (run `cmake --help` for a list). cmake -G "Unix Makefiles" -DSPAN_LITE_OPT_BUILD_TESTS=ON .. 3. Optional. You can control above configuration through the following options: `-DSPAN_LITE_OPT_BUILD_TESTS=ON`: build the tests for span, default off `-DSPAN_LITE_OPT_BUILD_EXAMPLES=OFF`: build the examples, default off 4. Build the test suite. cmake --build . 5. Run the test suite. ctest -V All tests should pass, indicating your platform is supported and you are ready to use *span lite*. ## Other implementations of span - *gsl-lite* [span](https://github.com/martinmoene/gsl-lite/blob/73c4f16f2b35fc174fc2f09d44d5ab13e5c638c3/include/gsl/gsl-lite.hpp#L1221). - Microsoft GSL [span](https://github.com/Microsoft/GSL/blob/master/include/gsl/span). - Google Abseil [span](https://github.com/abseil/abseil-cpp/blob/master/absl/types/span.h). - Marshall Clow's [libc++ span snippet](https://github.com/mclow/snippets/blob/master/span.cpp). - Tristan Brindle's [Implementation of C++20's std::span for older compilers](https://github.com/tcbrindle/span). - [Search _span c++_ on GitHub](https://github.com/search?l=C%2B%2B&q=span+c%2B%2B&type=Repositories&utf8=%E2%9C%93). ## Notes and references *Interface and specification* - [span on cppreference](https://en.cppreference.com/w/cpp/container/span). - [p0122 - C++20 Proposal](http://wg21.link/p0122). - [span in C++20 Working Draft](http://eel.is/c++draft/views). *Presentations* - TBD *Proposals* - [p0122 - span: bounds-safe views for sequences of objects](http://wg21.link/p0122). - [p1024 - Usability Enhancements for std::span](http://wg21.link/p1024). - [p1419 - A SFINAE-friendly trait to determine the extent of statically sized containers](http://wg21.link/p1419). - [p0805 - Comparing Containers](http://wg21.link/p0805). - [p1085 - Should Span be Regular?](http://wg21.link/p0805). - [p0091 - Template argument deduction for class templates](http://wg21.link/p0091). - [p0856 - Restrict Access Property for mdspan and span](http://wg21.link/p0856). - [p1428 - Subscripts and sizes should be signed](http://wg21.link/p1428). - [p1089 - Sizes Should Only span Unsigned](http://wg21.link/p1089). - [p1227 - Signed size() functions](http://wg21.link/p1227). - [p1872 - span should have size_type, not index_type](http://wg21.link/p1872). - [p2447 - std::span and the missing constructor](https://wg21.link/p2447). - [lwg 3101 - span's Container constructors need another constraint](https://cplusplus.github.io/LWG/issue3101). - [Reddit - 2018-06 Rapperswil ISO C++ Committee Trip Report](https://www.reddit.com/r/cpp/comments/8prqzm/2018_rapperswil_iso_c_committee_trip_report/) - [Reddit - 2018-11 San Diego ISO C++ Committee Trip Report](https://www.reddit.com/r/cpp/comments/9vwvbz/2018_san_diego_iso_c_committee_trip_report_ranges/). - [Reddit - 2019-02 Kona ISO C++ Committee Trip Report](https://www.reddit.com/r/cpp/comments/au0c4x/201902_kona_iso_c_committee_trip_report_c20/). - [Reddit - 2019-07 Cologne ISO C++ Committee Trip Report](https://www.reddit.com/r/cpp/comments/cfk9de/201907_cologne_iso_c_committee_trip_report_the/) - [Reddit - 2019-11 Belfast ISO C++ Committee Trip Report](https://www.reddit.com/r/cpp/comments/dtuov8/201911_belfast_iso_c_committee_trip_report/) - <a id="regtyp"></a>Titus Winters. [Revisiting Regular Types](https://abseil.io/blog/20180531-regular-types). Abseil Blog. 31 May 2018. ## Appendix ### A.1 Compile-time information The version of *span lite* is available via tag `[.version]`. The following tags are available for information on the compiler and on the C++ standard library used: `[.compiler]`, `[.stdc++]`, `[.stdlanguage]` and `[.stdlibrary]`. ### A.2 Span lite test specification <details> <summary>click to expand</summary> <p> ```Text span<>: Terminates construction from a nullptr and a non-zero size (C++11) span<>: Terminates construction from two pointers in the wrong order span<>: Terminates construction from a null pointer and a non-zero size span<>: Terminates creation of a sub span of the first n elements for n exceeding the span span<>: Terminates creation of a sub span of the last n elements for n exceeding the span span<>: Terminates creation of a sub span outside the span span<>: Terminates access outside the span span<>: Throws on access outside the span via at(): std::out_of_range [span_FEATURE_MEMBER_AT>0][span_CONFIG_NO_EXCEPTIONS=0] span<>: Termination throws std::logic_error-derived exception [span_CONFIG_CONTRACT_VIOLATION_THROWS=1] span<>: Allows to default-construct span<>: Allows to construct from a nullptr and a zero size (C++11) span<>: Allows to construct from two pointers span<>: Allows to construct from two iterators span<>: Allows to construct from two iterators - empty range span<>: Allows to construct from two iterators - move-only element span<>: Allows to construct from an iterator and a size span<>: Allows to construct from an iterator and a size - empty range span<>: Allows to construct from an iterator and a size - move-only element span<>: Allows to construct from two pointers to const span<>: Allows to construct from a non-null pointer and a size span<>: Allows to construct from a non-null pointer to const and a size span<>: Allows to construct from a temporary pointer and a size span<>: Allows to construct from a temporary pointer to const and a size span<>: Allows to construct from any pointer and a zero size (C++98) span<>: Allows to construct from a pointer and a size via a deduction guide (C++17) span<>: Allows to construct from an iterator and a size via a deduction guide (C++17) span<>: Allows to construct from two iterators via a deduction guide (C++17) span<>: Allows to construct from a C-array span<>: Allows to construct from a C-array via a deduction guide (C++17) span<>: Allows to construct from a const C-array span<>: Allows to construct from a C-array with size via decay to pointer (potentially dangerous) span<>: Allows to construct from a const C-array with size via decay to pointer (potentially dangerous) span<>: Allows to construct from a std::initializer_list<> (C++11) span<>: Allows to construct from a std::initializer_list<> as a constant set of values (C++11, p2447) span<>: Allows to construct from a std::array<> (C++11) span<>: Allows to construct from a std::array via a deduction guide (C++17) span<>: Allows to construct from a std::array<> with const data (C++11, span_FEATURE_CONSTR..._ELEMENT_TYPE=1) span<>: Allows to construct from an empty std::array<> (C++11) span<>: Allows to construct from a container (std::vector<>) span<>: Allows to construct from a container via a deduction guide (std::vector<>, C++17) span<>: Allows to tag-construct from a container (std::vector<>) span<>: Allows to tag-construct from a const container (std::vector<>) span<>: Allows to copy-construct from another span of the same type span<>: Allows to copy-construct from another span of a compatible type span<>: Allows to copy-construct from a temporary span of the same type (C++11) span<>: Allows to copy-assign from another span of the same type span<>: Allows to copy-assign from a temporary span of the same type (C++11) span<>: Allows to create a sub span of the first n elements span<>: Allows to create a sub span of the last n elements span<>: Allows to create a sub span starting at a given offset span<>: Allows to create a sub span starting at a given offset with a given length span<>: Allows to observe an element via array indexing span<>: Allows to observe an element via call indexing span<>: Allows to observe an element via at() [span_FEATURE_MEMBER_AT>0] span<>: Allows to observe an element via data() span<>: Allows to observe the first element via front() [span_FEATURE_MEMBER_BACK_FRONT=1] span<>: Allows to observe the last element via back() [span_FEATURE_MEMBER_BACK_FRONT=1] span<>: Allows to change an element via array indexing span<>: Allows to change an element via call indexing span<>: Allows to change an element via at() [span_FEATURE_MEMBER_AT>0] span<>: Allows to change an element via data() span<>: Allows to change the first element via front() [span_FEATURE_MEMBER_BACK_FRONT=1] span<>: Allows to change the last element via back() [span_FEATURE_MEMBER_BACK_FRONT=1] span<>: Allows to swap with another span [span_FEATURE_MEMBER_SWAP=1] span<>: Allows forward iteration span<>: Allows const forward iteration span<>: Allows reverse iteration span<>: Allows const reverse iteration span<>: Allows to identify if a span is the same as another span [span_FEATURE_SAME=1] span<>: Allows to compare equal to another span of the same type [span_FEATURE_COMPARISON=1] span<>: Allows to compare unequal to another span of the same type [span_FEATURE_COMPARISON=1] span<>: Allows to compare less than another span of the same type [span_FEATURE_COMPARISON=1] span<>: Allows to compare less than or equal to another span of the same type [span_FEATURE_COMPARISON=1] span<>: Allows to compare greater than another span of the same type [span_FEATURE_COMPARISON=1] span<>: Allows to compare greater than or equal to another span of the same type [span_FEATURE_COMPARISON=1] span<>: Allows to compare to another span of the same type and different cv-ness [span_FEATURE_SAME=0] span<>: Allows to compare empty spans as equal [span_FEATURE_COMPARISON=1] span<>: Allows to test for empty span via empty(), empty case span<>: Allows to test for empty span via empty(), non-empty case span<>: Allows to obtain the number of elements via size() span<>: Allows to obtain the number of elements via ssize() span<>: Allows to obtain the number of bytes via size_bytes() span<>: Allows to view the elements as read-only bytes span<>: Allows to view and change the elements as writable bytes make_span() [span_FEATURE_MAKE_SPAN_TO_STD=99] make_span(): Allows building from two pointers make_span(): Allows building from two const pointers make_span(): Allows building from a non-null pointer and a size make_span(): Allows building from a non-null const pointer and a size make_span(): Allows building from a C-array make_span(): Allows building from a const C-array make_span(): Allows building from a std::initializer_list<> (C++11) make_span(): Allows building from a std::initializer_list<> as a constant set of values (C++11) make_span(): Allows building from a std::array<> (C++11) make_span(): Allows building from a const std::array<> (C++11) make_span(): Allows building from a container (std::vector<>) make_span(): Allows building from a const container (std::vector<>) make_span(): Allows building from a container (with_container_t, std::vector<>) make_span(): Allows building from a const container (with_container_t, std::vector<>) byte_span() [span_FEATURE_BYTE_SPAN=1] byte_span(): Allows building a span of std::byte from a single object (C++17, byte-lite) byte_span(): Allows building a span of const std::byte from a single const object (C++17, byte-lite) first(), last(), subspan() [span_FEATURE_NON_MEMBER_FIRST_LAST_SUB=1] first(): Allows to create a sub span of the first n elements (span, template parameter) first(): Allows to create a sub span of the first n elements (span, function parameter) first(): Allows to create a sub span of the first n elements (compatible container, template parameter) first(): Allows to create a sub span of the first n elements (compatible container, function parameter) last(): Allows to create a sub span of the last n elements (span, template parameter) last(): Allows to create a sub span of the last n elements (span, function parameter) last(): Allows to create a sub span of the last n elements (compatible container, template parameter) last(): Allows to create a sub span of the last n elements (compatible container, function parameter) subspan(): Allows to create a sub span starting at a given offset (span, template parameter) subspan(): Allows to create a sub span starting at a given offset (span, function parameter) subspan(): Allows to create a sub span starting at a given offset (compatible container, template parameter) subspan(): Allows to create a sub span starting at a given offset (compatible container, function parameter) size(): Allows to obtain the number of elements via size() ssize(): Allows to obtain the number of elements via ssize() tuple_size<>: Allows to obtain the number of elements via std::tuple_size<> (C++11) tuple_element<>: Allows to obtain an element via std::tuple_element<> (C++11) tuple_element<>: Allows to obtain an element via std::tuple_element_t<> (C++11) get<I>(spn): Allows to access an element via std::get<>() tweak header: reads tweak header if supported [tweak] ``` </p> </details>
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/appveyor.yml
version: "{branch} #{build}" shallow_clone: true image: - Visual Studio 2019 - Visual Studio 2017 - Visual Studio 2015 platform: - Win32 - x64 configuration: - Debug - Release build: parallel: true environment: matrix: - generator: "Visual Studio 16 2019" select_sv: -DSPAN_LITE_OPT_SELECT_STD=ON - generator: "Visual Studio 16 2019" select_sv: -DSPAN_LITE_OPT_SELECT_NONSTD=ON - generator: "Visual Studio 15 2017" select_sv: -DSPAN_LITE_OPT_SELECT_STD=ON - generator: "Visual Studio 15 2017" select_sv: -DSPAN_LITE_OPT_SELECT_NONSTD=ON - generator: "Visual Studio 14 2015" - generator: "Visual Studio 12 2013" - generator: "Visual Studio 11 2012" - generator: "Visual Studio 10 2010" matrix: exclude: - image: Visual Studio 2015 generator: "Visual Studio 16 2019" - image: Visual Studio 2019 generator: "Visual Studio 15 2017" - image: Visual Studio 2019 generator: "Visual Studio 14 2015" - image: Visual Studio 2019 generator: "Visual Studio 12 2013" - image: Visual Studio 2019 generator: "Visual Studio 11 2012" - image: Visual Studio 2019 generator: "Visual Studio 10 2010" - image: Visual Studio 2015 generator: "Visual Studio 15 2017" - image: Visual Studio 2017 generator: "Visual Studio 16 2019" - image: Visual Studio 2017 generator: "Visual Studio 14 2015" - image: Visual Studio 2017 generator: "Visual Studio 12 2013" - image: Visual Studio 2017 generator: "Visual Studio 11 2012" - image: Visual Studio 2017 generator: "Visual Studio 10 2010" before_build: - mkdir build && cd build - cmake -A %platform% -G "%generator%" "%select_sv%" -DSPAN_LITE_OPT_BUILD_TESTS=ON -DSPAN_LITE_OPT_BUILD_EXAMPLES=OFF .. build_script: - cmake --build . --config %configuration% test_script: - ctest --output-on-failure -C %configuration%
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/conanfile.py
from conans import ConanFile, CMake class SpanLiteConan(ConanFile): version = "0.10.3" name = "span-lite" description = "A C++20-like span for C++98, C++11 and later in a single-file header-only library" license = "Boost Software License - Version 1.0. http://www.boost.org/LICENSE_1_0.txt" url = "https://github.com/martinmoene/span-lite.git" exports_sources = "include/nonstd/*", "CMakeLists.txt", "cmake/*", "LICENSE.txt" settings = "compiler", "build_type", "arch" build_policy = "missing" author = "Martin Moene" def build(self): """Avoid warning on build step""" pass def package(self): """Run CMake install""" cmake = CMake(self) cmake.definitions["SPAN_LITE_OPT_BUILD_TESTS"] = "OFF" cmake.definitions["SPAN_LITE_OPT_BUILD_EXAMPLES"] = "OFF" cmake.configure() cmake.install() def package_info(self): self.info.header_only()
0
repos/outcome/test/quickcpplib/include/quickcpplib
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/.travis.yml
os: linux dist: trusty sudo: false group: travis_latest language: c++ cache: ccache addons: apt: sources: &apt_sources - ubuntu-toolchain-r-test - llvm-toolchain-precise-3.5 - llvm-toolchain-precise-3.6 - llvm-toolchain-precise-3.7 - llvm-toolchain-precise-3.8 - llvm-toolchain-trusty-3.9 - llvm-toolchain-trusty-4.0 - llvm-toolchain-trusty-5.0 - llvm-toolchain-trusty-6.0 - llvm-toolchain-trusty-8 matrix: include: - os: linux env: COMPILER=g++-4.8 compiler: gcc addons: &gcc4_8 apt: packages: ["g++-4.8", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-4.9 compiler: gcc addons: &gcc4_9 apt: packages: ["g++-4.9", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-5 compiler: gcc addons: &gcc5 apt: packages: ["g++-5", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-6 compiler: gcc addons: &gcc6 apt: packages: ["g++-6", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-7 compiler: gcc addons: &gcc7 apt: packages: ["g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=g++-8 compiler: gcc addons: &gcc8 apt: packages: ["g++-8", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.5 compiler: clang addons: &clang3_5 apt: packages: ["clang-3.5", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.6 compiler: clang addons: &clang3_6 apt: packages: ["clang-3.6", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.7 compiler: clang addons: &clang3-7 apt: packages: ["clang-3.7", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.8 compiler: clang addons: &clang3_8 apt: packages: ["clang-3.8", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-3.9 compiler: clang addons: &clang3_9 apt: packages: ["clang-3.9", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-4.0 compiler: clang addons: &clang4_0 apt: packages: ["clang-4.0", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-5.0 compiler: clang addons: &clang5_0 apt: packages: ["clang-5.0", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-6.0 compiler: clang addons: &clang6_0 apt: packages: ["clang-6.0", "g++-7", "python3-pip", "lcov"] sources: *apt_sources - os: linux env: COMPILER=clang++-8 CXXFLAGS=-stdlib=libc++ compiler: clang addons: &clang8 apt: packages: ["clang-8", "g++-7", "python3-pip", "lcov", 'libc++-8-dev', 'libc++abi-8-dev'] sources: *apt_sources - os: osx osx_image: xcode7.3 compiler: clang env: COMPILER='clang++' - os: osx osx_image: xcode8 compiler: clang env: COMPILER='clang++' - os: osx osx_image: xcode9 compiler: clang env: COMPILER='clang++' - os: osx osx_image: xcode10 compiler: clang env: COMPILER='clang++' # allow_failures: # - osx_image: xcode10 fast_finish: true script: - export CXX=${COMPILER} - JOBS=2 # Travis machines have 2 cores. - mkdir build && cd build - cmake -G "Unix Makefiles" -DSPAN_LITE_OPT_SELECT_NONSTD=ON -DSPAN_LITE_OPT_BUILD_TESTS=ON -DSPAN_LITE_OPT_BUILD_EXAMPLES=OFF .. - cmake --build . -- -j${JOBS} - ctest --output-on-failure -j${JOBS}
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/include
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/include/nonstd/span.hpp
// // span for C++98 and later. // Based on http://wg21.link/p0122r7 // For more information see https://github.com/martinmoene/span-lite // // Copyright 2018-2021 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) #ifndef NONSTD_SPAN_HPP_INCLUDED #define NONSTD_SPAN_HPP_INCLUDED #define span_lite_MAJOR 0 #define span_lite_MINOR 10 #define span_lite_PATCH 3 #define span_lite_VERSION span_STRINGIFY(span_lite_MAJOR) "." span_STRINGIFY(span_lite_MINOR) "." span_STRINGIFY(span_lite_PATCH) #define span_STRINGIFY( x ) span_STRINGIFY_( x ) #define span_STRINGIFY_( x ) #x // span configuration: #define span_SPAN_DEFAULT 0 #define span_SPAN_NONSTD 1 #define span_SPAN_STD 2 // tweak header support: #ifdef __has_include # if __has_include(<nonstd/span.tweak.hpp>) # include <nonstd/span.tweak.hpp> # endif #define span_HAVE_TWEAK_HEADER 1 #else #define span_HAVE_TWEAK_HEADER 0 //# pragma message("span.hpp: Note: Tweak header not supported.") #endif // span selection and configuration: #define span_HAVE( feature ) ( span_HAVE_##feature ) #ifndef span_CONFIG_SELECT_SPAN # define span_CONFIG_SELECT_SPAN ( span_HAVE_STD_SPAN ? span_SPAN_STD : span_SPAN_NONSTD ) #endif #ifndef span_CONFIG_EXTENT_TYPE # define span_CONFIG_EXTENT_TYPE std::size_t #endif #ifndef span_CONFIG_SIZE_TYPE # define span_CONFIG_SIZE_TYPE std::size_t #endif #ifdef span_CONFIG_INDEX_TYPE # error `span_CONFIG_INDEX_TYPE` is deprecated since v0.7.0; it is replaced by `span_CONFIG_SIZE_TYPE`. #endif // span configuration (features): #ifndef span_FEATURE_WITH_INITIALIZER_LIST_P2447 # define span_FEATURE_WITH_INITIALIZER_LIST_P2447 0 #endif #ifndef span_FEATURE_WITH_CONTAINER #ifdef span_FEATURE_WITH_CONTAINER_TO_STD # define span_FEATURE_WITH_CONTAINER span_IN_STD( span_FEATURE_WITH_CONTAINER_TO_STD ) #else # define span_FEATURE_WITH_CONTAINER 0 # define span_FEATURE_WITH_CONTAINER_TO_STD 0 #endif #endif #ifndef span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE # define span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE 0 #endif #ifndef span_FEATURE_MEMBER_AT # define span_FEATURE_MEMBER_AT 0 #endif #ifndef span_FEATURE_MEMBER_BACK_FRONT # define span_FEATURE_MEMBER_BACK_FRONT 1 #endif #ifndef span_FEATURE_MEMBER_CALL_OPERATOR # define span_FEATURE_MEMBER_CALL_OPERATOR 0 #endif #ifndef span_FEATURE_MEMBER_SWAP # define span_FEATURE_MEMBER_SWAP 0 #endif #ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB # define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB 0 #elif span_FEATURE_NON_MEMBER_FIRST_LAST_SUB # define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN 1 # define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER 1 #endif #ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN # define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN 0 #endif #ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER # define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER 0 #endif #ifndef span_FEATURE_COMPARISON # define span_FEATURE_COMPARISON 0 // Note: C++20 does not provide comparison #endif #ifndef span_FEATURE_SAME # define span_FEATURE_SAME 0 #endif #if span_FEATURE_SAME && !span_FEATURE_COMPARISON # error `span_FEATURE_SAME` requires `span_FEATURE_COMPARISON` #endif #ifndef span_FEATURE_MAKE_SPAN #ifdef span_FEATURE_MAKE_SPAN_TO_STD # define span_FEATURE_MAKE_SPAN span_IN_STD( span_FEATURE_MAKE_SPAN_TO_STD ) #else # define span_FEATURE_MAKE_SPAN 0 # define span_FEATURE_MAKE_SPAN_TO_STD 0 #endif #endif #ifndef span_FEATURE_BYTE_SPAN # define span_FEATURE_BYTE_SPAN 0 #endif // Control presence of exception handling (try and auto discover): #ifndef span_CONFIG_NO_EXCEPTIONS # if defined(_MSC_VER) # include <cstddef> // for _HAS_EXCEPTIONS # endif # if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (_HAS_EXCEPTIONS) # define span_CONFIG_NO_EXCEPTIONS 0 # else # define span_CONFIG_NO_EXCEPTIONS 1 # undef span_CONFIG_CONTRACT_VIOLATION_THROWS # undef span_CONFIG_CONTRACT_VIOLATION_TERMINATES # define span_CONFIG_CONTRACT_VIOLATION_THROWS 0 # define span_CONFIG_CONTRACT_VIOLATION_TERMINATES 1 # endif #endif // Control pre- and postcondition violation behaviour: #if defined( span_CONFIG_CONTRACT_LEVEL_ON ) # define span_CONFIG_CONTRACT_LEVEL_MASK 0x11 #elif defined( span_CONFIG_CONTRACT_LEVEL_OFF ) # define span_CONFIG_CONTRACT_LEVEL_MASK 0x00 #elif defined( span_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY ) # define span_CONFIG_CONTRACT_LEVEL_MASK 0x01 #elif defined( span_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY ) # define span_CONFIG_CONTRACT_LEVEL_MASK 0x10 #else # define span_CONFIG_CONTRACT_LEVEL_MASK 0x11 #endif #if defined( span_CONFIG_CONTRACT_VIOLATION_THROWS ) # define span_CONFIG_CONTRACT_VIOLATION_THROWS_V span_CONFIG_CONTRACT_VIOLATION_THROWS #else # define span_CONFIG_CONTRACT_VIOLATION_THROWS_V 0 #endif #if defined( span_CONFIG_CONTRACT_VIOLATION_THROWS ) && span_CONFIG_CONTRACT_VIOLATION_THROWS && \ defined( span_CONFIG_CONTRACT_VIOLATION_TERMINATES ) && span_CONFIG_CONTRACT_VIOLATION_TERMINATES # error Please define none or one of span_CONFIG_CONTRACT_VIOLATION_THROWS and span_CONFIG_CONTRACT_VIOLATION_TERMINATES to 1, but not both. #endif // C++ language version detection (C++20 is speculative): // Note: VC14.0/1900 (VS2015) lacks too much from C++14. #ifndef span_CPLUSPLUS # if defined(_MSVC_LANG ) && !defined(__clang__) # define span_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) # else # define span_CPLUSPLUS __cplusplus # endif #endif #define span_CPP98_OR_GREATER ( span_CPLUSPLUS >= 199711L ) #define span_CPP11_OR_GREATER ( span_CPLUSPLUS >= 201103L ) #define span_CPP14_OR_GREATER ( span_CPLUSPLUS >= 201402L ) #define span_CPP17_OR_GREATER ( span_CPLUSPLUS >= 201703L ) #define span_CPP20_OR_GREATER ( span_CPLUSPLUS >= 202000L ) // C++ language version (represent 98 as 3): #define span_CPLUSPLUS_V ( span_CPLUSPLUS / 100 - (span_CPLUSPLUS > 200000 ? 2000 : 1994) ) #define span_IN_STD( v ) ( ((v) == 98 ? 3 : (v)) >= span_CPLUSPLUS_V ) #define span_CONFIG( feature ) ( span_CONFIG_##feature ) #define span_FEATURE( feature ) ( span_FEATURE_##feature ) #define span_FEATURE_TO_STD( feature ) ( span_IN_STD( span_FEATURE( feature##_TO_STD ) ) ) // Use C++20 std::span if available and requested: #if span_CPP20_OR_GREATER && defined(__has_include ) # if __has_include( <span> ) # define span_HAVE_STD_SPAN 1 # else # define span_HAVE_STD_SPAN 0 # endif #else # define span_HAVE_STD_SPAN 0 #endif #define span_USES_STD_SPAN ( (span_CONFIG_SELECT_SPAN == span_SPAN_STD) || ((span_CONFIG_SELECT_SPAN == span_SPAN_DEFAULT) && span_HAVE_STD_SPAN) ) // // Use C++20 std::span: // #if span_USES_STD_SPAN #include <span> namespace nonstd { using std::span; // Note: C++20 does not provide comparison // using std::operator==; // using std::operator!=; // using std::operator<; // using std::operator<=; // using std::operator>; // using std::operator>=; } // namespace nonstd #else // span_USES_STD_SPAN #include <algorithm> // Compiler versions: // // MSVC++ 6.0 _MSC_VER == 1200 span_COMPILER_MSVC_VERSION == 60 (Visual Studio 6.0) // MSVC++ 7.0 _MSC_VER == 1300 span_COMPILER_MSVC_VERSION == 70 (Visual Studio .NET 2002) // MSVC++ 7.1 _MSC_VER == 1310 span_COMPILER_MSVC_VERSION == 71 (Visual Studio .NET 2003) // MSVC++ 8.0 _MSC_VER == 1400 span_COMPILER_MSVC_VERSION == 80 (Visual Studio 2005) // MSVC++ 9.0 _MSC_VER == 1500 span_COMPILER_MSVC_VERSION == 90 (Visual Studio 2008) // MSVC++ 10.0 _MSC_VER == 1600 span_COMPILER_MSVC_VERSION == 100 (Visual Studio 2010) // MSVC++ 11.0 _MSC_VER == 1700 span_COMPILER_MSVC_VERSION == 110 (Visual Studio 2012) // MSVC++ 12.0 _MSC_VER == 1800 span_COMPILER_MSVC_VERSION == 120 (Visual Studio 2013) // MSVC++ 14.0 _MSC_VER == 1900 span_COMPILER_MSVC_VERSION == 140 (Visual Studio 2015) // MSVC++ 14.1 _MSC_VER >= 1910 span_COMPILER_MSVC_VERSION == 141 (Visual Studio 2017) // MSVC++ 14.2 _MSC_VER >= 1920 span_COMPILER_MSVC_VERSION == 142 (Visual Studio 2019) #if defined(_MSC_VER ) && !defined(__clang__) # define span_COMPILER_MSVC_VER (_MSC_VER ) # define span_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) #else # define span_COMPILER_MSVC_VER 0 # define span_COMPILER_MSVC_VERSION 0 #endif #define span_COMPILER_VERSION( major, minor, patch ) ( 10 * ( 10 * (major) + (minor) ) + (patch) ) #if defined(__clang__) # define span_COMPILER_CLANG_VERSION span_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) #else # define span_COMPILER_CLANG_VERSION 0 #endif #if defined(__GNUC__) && !defined(__clang__) # define span_COMPILER_GNUC_VERSION span_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #else # define span_COMPILER_GNUC_VERSION 0 #endif // half-open range [lo..hi): #define span_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) // Compiler warning suppression: #if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wundef" # pragma clang diagnostic ignored "-Wmismatched-tags" # define span_RESTORE_WARNINGS() _Pragma( "clang diagnostic pop" ) #elif defined __GNUC__ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wundef" # define span_RESTORE_WARNINGS() _Pragma( "GCC diagnostic pop" ) #elif span_COMPILER_MSVC_VER >= 1900 # define span_DISABLE_MSVC_WARNINGS(codes) __pragma(warning(push)) __pragma(warning(disable: codes)) # define span_RESTORE_WARNINGS() __pragma(warning(pop )) // Suppress the following MSVC GSL warnings: // - C26439, gsl::f.6 : special function 'function' can be declared 'noexcept' // - C26440, gsl::f.6 : function 'function' can be declared 'noexcept' // - C26472, gsl::t.1 : don't use a static_cast for arithmetic conversions; // use brace initialization, gsl::narrow_cast or gsl::narrow // - C26473: gsl::t.1 : don't cast between pointer types where the source type and the target type are the same // - C26481: gsl::b.1 : don't use pointer arithmetic. Use span instead // - C26490: gsl::t.1 : don't use reinterpret_cast span_DISABLE_MSVC_WARNINGS( 26439 26440 26472 26473 26481 26490 ) #else # define span_RESTORE_WARNINGS() /*empty*/ #endif // Presence of language and library features: #ifdef _HAS_CPP0X # define span_HAS_CPP0X _HAS_CPP0X #else # define span_HAS_CPP0X 0 #endif #define span_CPP11_80 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1400) #define span_CPP11_90 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1500) #define span_CPP11_100 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1600) #define span_CPP11_110 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1700) #define span_CPP11_120 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1800) #define span_CPP11_140 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1900) #define span_CPP14_000 (span_CPP14_OR_GREATER) #define span_CPP14_120 (span_CPP14_OR_GREATER || span_COMPILER_MSVC_VER >= 1800) #define span_CPP14_140 (span_CPP14_OR_GREATER || span_COMPILER_MSVC_VER >= 1900) #define span_CPP17_000 (span_CPP17_OR_GREATER) // Presence of C++11 language features: #define span_HAVE_ALIAS_TEMPLATE span_CPP11_140 #define span_HAVE_AUTO span_CPP11_100 #define span_HAVE_CONSTEXPR_11 span_CPP11_140 #define span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG span_CPP11_120 #define span_HAVE_EXPLICIT_CONVERSION span_CPP11_140 #define span_HAVE_INITIALIZER_LIST span_CPP11_120 #define span_HAVE_IS_DEFAULT span_CPP11_140 #define span_HAVE_IS_DELETE span_CPP11_140 #define span_HAVE_NOEXCEPT span_CPP11_140 #define span_HAVE_NULLPTR span_CPP11_100 #define span_HAVE_STATIC_ASSERT span_CPP11_100 // Presence of C++14 language features: #define span_HAVE_CONSTEXPR_14 span_CPP14_000 // Presence of C++17 language features: #define span_HAVE_DEPRECATED span_CPP17_000 #define span_HAVE_NODISCARD span_CPP17_000 #define span_HAVE_NORETURN span_CPP17_000 // MSVC: template parameter deduction guides since Visual Studio 2017 v15.7 #if defined(__cpp_deduction_guides) # define span_HAVE_DEDUCTION_GUIDES 1 #else # define span_HAVE_DEDUCTION_GUIDES (span_CPP17_OR_GREATER && ! span_BETWEEN( span_COMPILER_MSVC_VER, 1, 1913 )) #endif // Presence of C++ library features: #define span_HAVE_ADDRESSOF span_CPP17_000 #define span_HAVE_ARRAY span_CPP11_110 #define span_HAVE_BYTE span_CPP17_000 #define span_HAVE_CONDITIONAL span_CPP11_120 #define span_HAVE_CONTAINER_DATA_METHOD (span_CPP11_140 || ( span_COMPILER_MSVC_VER >= 1500 && span_HAS_CPP0X )) #define span_HAVE_DATA span_CPP17_000 #define span_HAVE_LONGLONG span_CPP11_80 #define span_HAVE_REMOVE_CONST span_CPP11_110 #define span_HAVE_SNPRINTF span_CPP11_140 #define span_HAVE_STRUCT_BINDING span_CPP11_120 #define span_HAVE_TYPE_TRAITS span_CPP11_90 // Presence of byte-lite: #ifdef NONSTD_BYTE_LITE_HPP # define span_HAVE_NONSTD_BYTE 1 #else # define span_HAVE_NONSTD_BYTE 0 #endif // C++ feature usage: #if span_HAVE_ADDRESSOF # define span_ADDRESSOF(x) std::addressof(x) #else # define span_ADDRESSOF(x) (&x) #endif #if span_HAVE_CONSTEXPR_11 # define span_constexpr constexpr #else # define span_constexpr /*span_constexpr*/ #endif #if span_HAVE_CONSTEXPR_14 # define span_constexpr14 constexpr #else # define span_constexpr14 /*span_constexpr*/ #endif #if span_HAVE_EXPLICIT_CONVERSION # define span_explicit explicit #else # define span_explicit /*explicit*/ #endif #if span_HAVE_IS_DELETE # define span_is_delete = delete #else # define span_is_delete #endif #if span_HAVE_IS_DELETE # define span_is_delete_access public #else # define span_is_delete_access private #endif #if span_HAVE_NOEXCEPT && ! span_CONFIG_CONTRACT_VIOLATION_THROWS_V # define span_noexcept noexcept #else # define span_noexcept /*noexcept*/ #endif #if span_HAVE_NULLPTR # define span_nullptr nullptr #else # define span_nullptr NULL #endif #if span_HAVE_DEPRECATED # define span_deprecated(msg) [[deprecated(msg)]] #else # define span_deprecated(msg) /*[[deprecated]]*/ #endif #if span_HAVE_NODISCARD # define span_nodiscard [[nodiscard]] #else # define span_nodiscard /*[[nodiscard]]*/ #endif #if span_HAVE_NORETURN # define span_noreturn [[noreturn]] #else # define span_noreturn /*[[noreturn]]*/ #endif // Other features: #define span_HAVE_CONSTRAINED_SPAN_CONTAINER_CTOR span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG #define span_HAVE_ITERATOR_CTOR span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG // Additional includes: #if span_HAVE( ADDRESSOF ) # include <memory> #endif #if span_HAVE( ARRAY ) # include <array> #endif #if span_HAVE( BYTE ) # include <cstddef> #endif #if span_HAVE( DATA ) # include <iterator> // for std::data(), std::size() #endif #if span_HAVE( TYPE_TRAITS ) # include <type_traits> #endif #if ! span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) # include <vector> #endif #if span_FEATURE( MEMBER_AT ) > 1 # include <cstdio> #endif #if ! span_CONFIG( NO_EXCEPTIONS ) # include <stdexcept> #endif // Contract violation #define span_ELIDE_CONTRACT_EXPECTS ( 0 == ( span_CONFIG_CONTRACT_LEVEL_MASK & 0x01 ) ) #define span_ELIDE_CONTRACT_ENSURES ( 0 == ( span_CONFIG_CONTRACT_LEVEL_MASK & 0x10 ) ) #if span_ELIDE_CONTRACT_EXPECTS # define span_constexpr_exp span_constexpr # define span_EXPECTS( cond ) /* Expect elided */ #else # define span_constexpr_exp span_constexpr14 # define span_EXPECTS( cond ) span_CONTRACT_CHECK( "Precondition", cond ) #endif #if span_ELIDE_CONTRACT_ENSURES # define span_constexpr_ens span_constexpr # define span_ENSURES( cond ) /* Ensures elided */ #else # define span_constexpr_ens span_constexpr14 # define span_ENSURES( cond ) span_CONTRACT_CHECK( "Postcondition", cond ) #endif #define span_CONTRACT_CHECK( type, cond ) \ cond ? static_cast< void >( 0 ) \ : nonstd::span_lite::detail::report_contract_violation( span_LOCATION( __FILE__, __LINE__ ) ": " type " violation." ) #ifdef __GNUG__ # define span_LOCATION( file, line ) file ":" span_STRINGIFY( line ) #else # define span_LOCATION( file, line ) file "(" span_STRINGIFY( line ) ")" #endif // Method enabling #if span_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) #define span_REQUIRES_0(VA) \ template< bool B = (VA), typename std::enable_if<B, int>::type = 0 > # if span_BETWEEN( span_COMPILER_MSVC_VERSION, 1, 140 ) // VS 2013 and earlier seem to have trouble with SFINAE for default non-type arguments # define span_REQUIRES_T(VA) \ , typename = typename std::enable_if< ( VA ), nonstd::span_lite::detail::enabler >::type # else # define span_REQUIRES_T(VA) \ , typename std::enable_if< (VA), int >::type = 0 # endif #define span_REQUIRES_R(R, VA) \ typename std::enable_if< (VA), R>::type #define span_REQUIRES_A(VA) \ , typename std::enable_if< (VA), void*>::type = nullptr #else # define span_REQUIRES_0(VA) /*empty*/ # define span_REQUIRES_T(VA) /*empty*/ # define span_REQUIRES_R(R, VA) R # define span_REQUIRES_A(VA) /*empty*/ #endif namespace nonstd { namespace span_lite { // [views.constants], constants typedef span_CONFIG_EXTENT_TYPE extent_t; typedef span_CONFIG_SIZE_TYPE size_t; span_constexpr const extent_t dynamic_extent = static_cast<extent_t>( -1 ); template< class T, extent_t Extent = dynamic_extent > class span; // Tag to select span constructor taking a container (prevent ms-gsl warning C26426): struct with_container_t { span_constexpr with_container_t() span_noexcept {} }; const span_constexpr with_container_t with_container; // C++11 emulation: namespace std11 { #if span_HAVE( REMOVE_CONST ) using std::remove_cv; using std::remove_const; using std::remove_volatile; #else template< class T > struct remove_const { typedef T type; }; template< class T > struct remove_const< T const > { typedef T type; }; template< class T > struct remove_volatile { typedef T type; }; template< class T > struct remove_volatile< T volatile > { typedef T type; }; template< class T > struct remove_cv { typedef typename std11::remove_volatile< typename std11::remove_const< T >::type >::type type; }; #endif // span_HAVE( REMOVE_CONST ) #if span_HAVE( TYPE_TRAITS ) using std::is_same; using std::is_signed; using std::integral_constant; using std::true_type; using std::false_type; using std::remove_reference; #else template< class T, T v > struct integral_constant { enum { value = v }; }; typedef integral_constant< bool, true > true_type; typedef integral_constant< bool, false > false_type; template< class T, class U > struct is_same : false_type{}; template< class T > struct is_same<T, T> : true_type{}; template< typename T > struct is_signed : false_type {}; template<> struct is_signed<signed char> : true_type {}; template<> struct is_signed<signed int > : true_type {}; template<> struct is_signed<signed long> : true_type {}; #endif } // namespace std11 // C++17 emulation: namespace std17 { template< bool v > struct bool_constant : std11::integral_constant<bool, v>{}; #if span_CPP11_120 template< class...> using void_t = void; #endif #if span_HAVE( DATA ) using std::data; using std::size; #elif span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) template< typename T, std::size_t N > inline span_constexpr auto size( const T(&)[N] ) span_noexcept -> size_t { return N; } template< typename C > inline span_constexpr auto size( C const & cont ) -> decltype( cont.size() ) { return cont.size(); } template< typename T, std::size_t N > inline span_constexpr auto data( T(&arr)[N] ) span_noexcept -> T* { return &arr[0]; } template< typename C > inline span_constexpr auto data( C & cont ) -> decltype( cont.data() ) { return cont.data(); } template< typename C > inline span_constexpr auto data( C const & cont ) -> decltype( cont.data() ) { return cont.data(); } template< typename E > inline span_constexpr auto data( std::initializer_list<E> il ) span_noexcept -> E const * { return il.begin(); } #endif // span_HAVE( DATA ) #if span_HAVE( BYTE ) using std::byte; #elif span_HAVE( NONSTD_BYTE ) using nonstd::byte; #endif } // namespace std17 // C++20 emulation: namespace std20 { #if span_HAVE( DEDUCTION_GUIDES ) template< class T > using iter_reference_t = decltype( *std::declval<T&>() ); #endif } // namespace std20 // Implementation details: namespace detail { /*enum*/ struct enabler{}; template< typename T > span_constexpr bool is_positive( T x ) { return std11::is_signed<T>::value ? x >= 0 : true; } #if span_HAVE( TYPE_TRAITS ) template< class Q > struct is_span_oracle : std::false_type{}; template< class T, span_CONFIG_EXTENT_TYPE Extent > struct is_span_oracle< span<T, Extent> > : std::true_type{}; template< class Q > struct is_span : is_span_oracle< typename std::remove_cv<Q>::type >{}; template< class Q > struct is_std_array_oracle : std::false_type{}; #if span_HAVE( ARRAY ) template< class T, std::size_t Extent > struct is_std_array_oracle< std::array<T, Extent> > : std::true_type{}; #endif template< class Q > struct is_std_array : is_std_array_oracle< typename std::remove_cv<Q>::type >{}; template< class Q > struct is_array : std::false_type {}; template< class T > struct is_array<T[]> : std::true_type {}; template< class T, std::size_t N > struct is_array<T[N]> : std::true_type {}; #if span_CPP11_140 && ! span_BETWEEN( span_COMPILER_GNUC_VERSION, 1, 500 ) template< class, class = void > struct has_size_and_data : std::false_type{}; template< class C > struct has_size_and_data < C, std17::void_t< decltype( std17::size(std::declval<C>()) ), decltype( std17::data(std::declval<C>()) ) > > : std::true_type{}; template< class, class, class = void > struct is_compatible_element : std::false_type {}; template< class C, class E > struct is_compatible_element < C, E, std17::void_t< decltype( std17::data(std::declval<C>()) ) > > : std::is_convertible< typename std::remove_pointer<decltype( std17::data( std::declval<C&>() ) )>::type(*)[], E(*)[] >{}; template< class C > struct is_container : std17::bool_constant < ! is_span< C >::value && ! is_array< C >::value && ! is_std_array< C >::value && has_size_and_data< C >::value >{}; template< class C, class E > struct is_compatible_container : std17::bool_constant < is_container<C>::value && is_compatible_element<C,E>::value >{}; #else // span_CPP11_140 template< class C, class E span_REQUIRES_T(( ! is_span< C >::value && ! is_array< C >::value && ! is_std_array< C >::value && ( std::is_convertible< typename std::remove_pointer<decltype( std17::data( std::declval<C&>() ) )>::type(*)[], E(*)[] >::value) // && has_size_and_data< C >::value )) , class = decltype( std17::size(std::declval<C>()) ) , class = decltype( std17::data(std::declval<C>()) ) > struct is_compatible_container : std::true_type{}; #endif // span_CPP11_140 #endif // span_HAVE( TYPE_TRAITS ) #if ! span_CONFIG( NO_EXCEPTIONS ) #if span_FEATURE( MEMBER_AT ) > 1 // format index and size: #if defined(__clang__) # pragma clang diagnostic ignored "-Wlong-long" #elif defined __GNUC__ # pragma GCC diagnostic ignored "-Wformat=ll" # pragma GCC diagnostic ignored "-Wlong-long" #endif span_noreturn inline void throw_out_of_range( size_t idx, size_t size ) { const char fmt[] = "span::at(): index '%lli' is out of range [0..%lli)"; char buffer[ 2 * 20 + sizeof fmt ]; sprintf( buffer, fmt, static_cast<long long>(idx), static_cast<long long>(size) ); throw std::out_of_range( buffer ); } #else // MEMBER_AT span_noreturn inline void throw_out_of_range( size_t /*idx*/, size_t /*size*/ ) { throw std::out_of_range( "span::at(): index outside span" ); } #endif // MEMBER_AT #endif // NO_EXCEPTIONS #if span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) struct contract_violation : std::logic_error { explicit contract_violation( char const * const message ) : std::logic_error( message ) {} }; inline void report_contract_violation( char const * msg ) { throw contract_violation( msg ); } #else // span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) span_noreturn inline void report_contract_violation( char const * /*msg*/ ) span_noexcept { std::terminate(); } #endif // span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) } // namespace detail // Prevent signed-unsigned mismatch: #define span_sizeof(T) static_cast<extent_t>( sizeof(T) ) template< class T > inline span_constexpr size_t to_size( T size ) { return static_cast<size_t>( size ); } // // [views.span] - A view over a contiguous, single-dimension sequence of objects // template< class T, extent_t Extent /*= dynamic_extent*/ > class span { public: // constants and types typedef T element_type; typedef typename std11::remove_cv< T >::type value_type; typedef T & reference; typedef T * pointer; typedef T const * const_pointer; typedef T const & const_reference; typedef size_t size_type; typedef extent_t extent_type; typedef pointer iterator; typedef const_pointer const_iterator; typedef std::ptrdiff_t difference_type; typedef std::reverse_iterator< iterator > reverse_iterator; typedef std::reverse_iterator< const_iterator > const_reverse_iterator; // static constexpr extent_type extent = Extent; enum { extent = Extent }; // 26.7.3.2 Constructors, copy, and assignment [span.cons] span_REQUIRES_0( ( Extent == 0 ) || ( Extent == dynamic_extent ) ) span_constexpr span() span_noexcept : data_( span_nullptr ) , size_( 0 ) { // span_EXPECTS( data() == span_nullptr ); // span_EXPECTS( size() == 0 ); } #if span_HAVE( ITERATOR_CTOR ) // Didn't yet succeed in combining the next two constructors: span_constexpr_exp span( std::nullptr_t, size_type count ) : data_( span_nullptr ) , size_( count ) { span_EXPECTS( data_ == span_nullptr && count == 0 ); } template< typename It span_REQUIRES_T(( std::is_convertible<decltype(*std::declval<It&>()), element_type &>::value )) > span_constexpr_exp span( It first, size_type count ) : data_( to_address( first ) ) , size_( count ) { span_EXPECTS( ( data_ == span_nullptr && count == 0 ) || ( data_ != span_nullptr && detail::is_positive( count ) ) ); } #else span_constexpr_exp span( pointer ptr, size_type count ) : data_( ptr ) , size_( count ) { span_EXPECTS( ( ptr == span_nullptr && count == 0 ) || ( ptr != span_nullptr && detail::is_positive( count ) ) ); } #endif #if span_HAVE( ITERATOR_CTOR ) template< typename It, typename End span_REQUIRES_T(( std::is_convertible<decltype(&*std::declval<It&>()), element_type *>::value && ! std::is_convertible<End, std::size_t>::value )) > span_constexpr_exp span( It first, End last ) : data_( to_address( first ) ) , size_( to_size( last - first ) ) { span_EXPECTS( last - first >= 0 ); } #else span_constexpr_exp span( pointer first, pointer last ) : data_( first ) , size_( to_size( last - first ) ) { span_EXPECTS( last - first >= 0 ); } #endif template< std::size_t N span_REQUIRES_T(( (Extent == dynamic_extent || Extent == static_cast<extent_t>(N)) && std::is_convertible< value_type(*)[], element_type(*)[] >::value )) > span_constexpr span( element_type ( &arr )[ N ] ) span_noexcept : data_( span_ADDRESSOF( arr[0] ) ) , size_( N ) {} #if span_HAVE( ARRAY ) template< std::size_t N span_REQUIRES_T(( (Extent == dynamic_extent || Extent == static_cast<extent_t>(N)) && std::is_convertible< value_type(*)[], element_type(*)[] >::value )) > # if span_FEATURE( CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE ) span_constexpr span( std::array< element_type, N > & arr ) span_noexcept # else span_constexpr span( std::array< value_type, N > & arr ) span_noexcept # endif : data_( arr.data() ) , size_( to_size( arr.size() ) ) {} template< std::size_t N # if span_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) span_REQUIRES_T(( (Extent == dynamic_extent || Extent == static_cast<extent_t>(N)) && std::is_convertible< value_type(*)[], element_type(*)[] >::value )) # endif > span_constexpr span( std::array< value_type, N> const & arr ) span_noexcept : data_( arr.data() ) , size_( to_size( arr.size() ) ) {} #endif // span_HAVE( ARRAY ) #if span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) template< class Container span_REQUIRES_T(( detail::is_compatible_container< Container, element_type >::value )) > span_constexpr span( Container & cont ) : data_( std17::data( cont ) ) , size_( to_size( std17::size( cont ) ) ) {} template< class Container span_REQUIRES_T(( std::is_const< element_type >::value && detail::is_compatible_container< Container, element_type >::value )) > span_constexpr span( Container const & cont ) : data_( std17::data( cont ) ) , size_( to_size( std17::size( cont ) ) ) {} #endif // span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) #if span_FEATURE( WITH_CONTAINER ) template< class Container > span_constexpr span( with_container_t, Container & cont ) : data_( cont.size() == 0 ? span_nullptr : span_ADDRESSOF( cont[0] ) ) , size_( to_size( cont.size() ) ) {} template< class Container > span_constexpr span( with_container_t, Container const & cont ) : data_( cont.size() == 0 ? span_nullptr : const_cast<pointer>( span_ADDRESSOF( cont[0] ) ) ) , size_( to_size( cont.size() ) ) {} #endif #if span_FEATURE( WITH_INITIALIZER_LIST_P2447 ) && span_HAVE( INITIALIZER_LIST ) // constexpr explicit(extent != dynamic_extent) span(std::initializer_list<value_type> il) noexcept; #if !span_BETWEEN( span_COMPILER_MSVC_VERSION, 120, 130 ) template< extent_t U = Extent span_REQUIRES_T(( U != dynamic_extent )) > #if span_COMPILER_GNUC_VERSION >= 900 // prevent GCC's "-Winit-list-lifetime" span_constexpr14 explicit span( std::initializer_list<value_type> il ) span_noexcept { data_ = il.begin(); size_ = il.size(); } #else span_constexpr explicit span( std::initializer_list<value_type> il ) span_noexcept : data_( il.begin() ) , size_( il.size() ) {} #endif #endif // MSVC 120 (VS2013) template< extent_t U = Extent span_REQUIRES_T(( U == dynamic_extent )) > #if span_COMPILER_GNUC_VERSION >= 900 // prevent GCC's "-Winit-list-lifetime" span_constexpr14 /*explicit*/ span( std::initializer_list<value_type> il ) span_noexcept { data_ = il.begin(); size_ = il.size(); } #else span_constexpr /*explicit*/ span( std::initializer_list<value_type> il ) span_noexcept : data_( il.begin() ) , size_( il.size() ) {} #endif #endif // P2447 #if span_HAVE( IS_DEFAULT ) span_constexpr span( span const & other ) span_noexcept = default; ~span() span_noexcept = default; span_constexpr14 span & operator=( span const & other ) span_noexcept = default; #else span_constexpr span( span const & other ) span_noexcept : data_( other.data_ ) , size_( other.size_ ) {} ~span() span_noexcept {} span_constexpr14 span & operator=( span const & other ) span_noexcept { data_ = other.data_; size_ = other.size_; return *this; } #endif template< class OtherElementType, extent_type OtherExtent span_REQUIRES_T(( (Extent == dynamic_extent || OtherExtent == dynamic_extent || Extent == OtherExtent) && std::is_convertible<OtherElementType(*)[], element_type(*)[]>::value )) > span_constexpr_exp span( span<OtherElementType, OtherExtent> const & other ) span_noexcept : data_( other.data() ) , size_( other.size() ) { span_EXPECTS( OtherExtent == dynamic_extent || other.size() == to_size(OtherExtent) ); } // 26.7.3.3 Subviews [span.sub] template< extent_type Count > span_constexpr_exp span< element_type, Count > first() const { span_EXPECTS( detail::is_positive( Count ) && Count <= size() ); return span< element_type, Count >( data(), Count ); } template< extent_type Count > span_constexpr_exp span< element_type, Count > last() const { span_EXPECTS( detail::is_positive( Count ) && Count <= size() ); return span< element_type, Count >( data() + (size() - Count), Count ); } #if span_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) template< size_type Offset, extent_type Count = dynamic_extent > #else template< size_type Offset, extent_type Count /*= dynamic_extent*/ > #endif span_constexpr_exp span< element_type, Count > subspan() const { span_EXPECTS( ( detail::is_positive( Offset ) && Offset <= size() ) && ( Count == dynamic_extent || (detail::is_positive( Count ) && Count + Offset <= size()) ) ); return span< element_type, Count >( data() + Offset, Count != dynamic_extent ? Count : (Extent != dynamic_extent ? Extent - Offset : size() - Offset) ); } span_constexpr_exp span< element_type, dynamic_extent > first( size_type count ) const { span_EXPECTS( detail::is_positive( count ) && count <= size() ); return span< element_type, dynamic_extent >( data(), count ); } span_constexpr_exp span< element_type, dynamic_extent > last( size_type count ) const { span_EXPECTS( detail::is_positive( count ) && count <= size() ); return span< element_type, dynamic_extent >( data() + ( size() - count ), count ); } span_constexpr_exp span< element_type, dynamic_extent > subspan( size_type offset, size_type count = static_cast<size_type>(dynamic_extent) ) const { span_EXPECTS( ( ( detail::is_positive( offset ) && offset <= size() ) ) && ( count == static_cast<size_type>(dynamic_extent) || ( detail::is_positive( count ) && offset + count <= size() ) ) ); return span< element_type, dynamic_extent >( data() + offset, count == static_cast<size_type>(dynamic_extent) ? size() - offset : count ); } // 26.7.3.4 Observers [span.obs] span_constexpr size_type size() const span_noexcept { return size_; } span_constexpr std::ptrdiff_t ssize() const span_noexcept { return static_cast<std::ptrdiff_t>( size_ ); } span_constexpr size_type size_bytes() const span_noexcept { return size() * to_size( sizeof( element_type ) ); } span_nodiscard span_constexpr bool empty() const span_noexcept { return size() == 0; } // 26.7.3.5 Element access [span.elem] span_constexpr_exp reference operator[]( size_type idx ) const { span_EXPECTS( detail::is_positive( idx ) && idx < size() ); return *( data() + idx ); } #if span_FEATURE( MEMBER_CALL_OPERATOR ) span_deprecated("replace operator() with operator[]") span_constexpr_exp reference operator()( size_type idx ) const { span_EXPECTS( detail::is_positive( idx ) && idx < size() ); return *( data() + idx ); } #endif #if span_FEATURE( MEMBER_AT ) span_constexpr14 reference at( size_type idx ) const { #if span_CONFIG( NO_EXCEPTIONS ) return this->operator[]( idx ); #else if ( !detail::is_positive( idx ) || size() <= idx ) { detail::throw_out_of_range( idx, size() ); } return *( data() + idx ); #endif } #endif span_constexpr pointer data() const span_noexcept { return data_; } #if span_FEATURE( MEMBER_BACK_FRONT ) span_constexpr_exp reference front() const span_noexcept { span_EXPECTS( ! empty() ); return *data(); } span_constexpr_exp reference back() const span_noexcept { span_EXPECTS( ! empty() ); return *( data() + size() - 1 ); } #endif // xx.x.x.x Modifiers [span.modifiers] #if span_FEATURE( MEMBER_SWAP ) span_constexpr14 void swap( span & other ) span_noexcept { using std::swap; swap( data_, other.data_ ); swap( size_, other.size_ ); } #endif // 26.7.3.6 Iterator support [span.iterators] span_constexpr iterator begin() const span_noexcept { #if span_CPP11_OR_GREATER return { data() }; #else return iterator( data() ); #endif } span_constexpr iterator end() const span_noexcept { #if span_CPP11_OR_GREATER return { data() + size() }; #else return iterator( data() + size() ); #endif } span_constexpr const_iterator cbegin() const span_noexcept { #if span_CPP11_OR_GREATER return { data() }; #else return const_iterator( data() ); #endif } span_constexpr const_iterator cend() const span_noexcept { #if span_CPP11_OR_GREATER return { data() + size() }; #else return const_iterator( data() + size() ); #endif } span_constexpr reverse_iterator rbegin() const span_noexcept { return reverse_iterator( end() ); } span_constexpr reverse_iterator rend() const span_noexcept { return reverse_iterator( begin() ); } span_constexpr const_reverse_iterator crbegin() const span_noexcept { return const_reverse_iterator ( cend() ); } span_constexpr const_reverse_iterator crend() const span_noexcept { return const_reverse_iterator( cbegin() ); } private: // Note: C++20 has std::pointer_traits<Ptr>::to_address( it ); #if span_HAVE( ITERATOR_CTOR ) static inline span_constexpr pointer to_address( std::nullptr_t ) span_noexcept { return nullptr; } template< typename U > static inline span_constexpr U * to_address( U * p ) span_noexcept { return p; } template< typename Ptr span_REQUIRES_T(( ! std::is_pointer<Ptr>::value )) > static inline span_constexpr pointer to_address( Ptr const & it ) span_noexcept { return to_address( it.operator->() ); } #endif // span_HAVE( ITERATOR_CTOR ) private: pointer data_; size_type size_; }; // class template argument deduction guides: #if span_HAVE( DEDUCTION_GUIDES ) template< class T, size_t N > span( T (&)[N] ) -> span<T, static_cast<extent_t>(N)>; template< class T, size_t N > span( std::array<T, N> & ) -> span<T, static_cast<extent_t>(N)>; template< class T, size_t N > span( std::array<T, N> const & ) -> span<const T, static_cast<extent_t>(N)>; #if span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) template< class Container > span( Container& ) -> span<typename Container::value_type>; template< class Container > span( Container const & ) -> span<const typename Container::value_type>; #endif // iterator: constraints: It satisfies contiguous_­iterator. template< class It, class EndOrSize > span( It, EndOrSize ) -> span< typename std11::remove_reference< typename std20::iter_reference_t<It> >::type >; #endif // span_HAVE( DEDUCTION_GUIDES ) // 26.7.3.7 Comparison operators [span.comparison] #if span_FEATURE( COMPARISON ) #if span_FEATURE( SAME ) template< class T1, extent_t E1, class T2, extent_t E2 > inline span_constexpr bool same( span<T1,E1> const & l, span<T2,E2> const & r ) span_noexcept { return std11::is_same<T1, T2>::value && l.size() == r.size() && static_cast<void const*>( l.data() ) == r.data(); } #endif template< class T1, extent_t E1, class T2, extent_t E2 > inline span_constexpr bool operator==( span<T1,E1> const & l, span<T2,E2> const & r ) { return #if span_FEATURE( SAME ) same( l, r ) || #endif ( l.size() == r.size() && std::equal( l.begin(), l.end(), r.begin() ) ); } template< class T1, extent_t E1, class T2, extent_t E2 > inline span_constexpr bool operator<( span<T1,E1> const & l, span<T2,E2> const & r ) { return std::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); } template< class T1, extent_t E1, class T2, extent_t E2 > inline span_constexpr bool operator!=( span<T1,E1> const & l, span<T2,E2> const & r ) { return !( l == r ); } template< class T1, extent_t E1, class T2, extent_t E2 > inline span_constexpr bool operator<=( span<T1,E1> const & l, span<T2,E2> const & r ) { return !( r < l ); } template< class T1, extent_t E1, class T2, extent_t E2 > inline span_constexpr bool operator>( span<T1,E1> const & l, span<T2,E2> const & r ) { return ( r < l ); } template< class T1, extent_t E1, class T2, extent_t E2 > inline span_constexpr bool operator>=( span<T1,E1> const & l, span<T2,E2> const & r ) { return !( l < r ); } #endif // span_FEATURE( COMPARISON ) // 26.7.2.6 views of object representation [span.objectrep] #if span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) // Avoid MSVC 14.1 (1910), VS 2017: warning C4307: '*': integral constant overflow: template< typename T, extent_t Extent > struct BytesExtent { #if span_CPP11_OR_GREATER enum ET : extent_t { value = span_sizeof(T) * Extent }; #else enum ET { value = span_sizeof(T) * Extent }; #endif }; template< typename T > struct BytesExtent< T, dynamic_extent > { #if span_CPP11_OR_GREATER enum ET : extent_t { value = dynamic_extent }; #else enum ET { value = dynamic_extent }; #endif }; template< class T, extent_t Extent > inline span_constexpr span< const std17::byte, BytesExtent<T, Extent>::value > as_bytes( span<T,Extent> spn ) span_noexcept { #if 0 return { reinterpret_cast< std17::byte const * >( spn.data() ), spn.size_bytes() }; #else return span< const std17::byte, BytesExtent<T, Extent>::value >( reinterpret_cast< std17::byte const * >( spn.data() ), spn.size_bytes() ); // NOLINT #endif } template< class T, extent_t Extent > inline span_constexpr span< std17::byte, BytesExtent<T, Extent>::value > as_writable_bytes( span<T,Extent> spn ) span_noexcept { #if 0 return { reinterpret_cast< std17::byte * >( spn.data() ), spn.size_bytes() }; #else return span< std17::byte, BytesExtent<T, Extent>::value >( reinterpret_cast< std17::byte * >( spn.data() ), spn.size_bytes() ); // NOLINT #endif } #endif // span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) // 27.8 Container and view access [iterator.container] template< class T, extent_t Extent /*= dynamic_extent*/ > span_constexpr std::size_t size( span<T,Extent> const & spn ) { return static_cast<std::size_t>( spn.size() ); } template< class T, extent_t Extent /*= dynamic_extent*/ > span_constexpr std::ptrdiff_t ssize( span<T,Extent> const & spn ) { return static_cast<std::ptrdiff_t>( spn.size() ); } } // namespace span_lite } // namespace nonstd // make available in nonstd: namespace nonstd { using span_lite::dynamic_extent; using span_lite::span; using span_lite::with_container; #if span_FEATURE( COMPARISON ) #if span_FEATURE( SAME ) using span_lite::same; #endif using span_lite::operator==; using span_lite::operator!=; using span_lite::operator<; using span_lite::operator<=; using span_lite::operator>; using span_lite::operator>=; #endif #if span_HAVE( BYTE ) using span_lite::as_bytes; using span_lite::as_writable_bytes; #endif using span_lite::size; using span_lite::ssize; } // namespace nonstd #endif // span_USES_STD_SPAN // make_span() [span-lite extension]: #if span_FEATURE( MAKE_SPAN ) || span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) || span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) #if span_USES_STD_SPAN # define span_constexpr constexpr # define span_noexcept noexcept # define span_nullptr nullptr # ifndef span_CONFIG_EXTENT_TYPE # define span_CONFIG_EXTENT_TYPE std::size_t # endif using extent_t = span_CONFIG_EXTENT_TYPE; #endif // span_USES_STD_SPAN namespace nonstd { namespace span_lite { template< class T > inline span_constexpr span<T> make_span( T * ptr, size_t count ) span_noexcept { return span<T>( ptr, count ); } template< class T > inline span_constexpr span<T> make_span( T * first, T * last ) span_noexcept { return span<T>( first, last ); } template< class T, std::size_t N > inline span_constexpr span<T, static_cast<extent_t>(N)> make_span( T ( &arr )[ N ] ) span_noexcept { return span<T, static_cast<extent_t>(N)>( &arr[ 0 ], N ); } #if span_USES_STD_SPAN || span_HAVE( ARRAY ) template< class T, std::size_t N > inline span_constexpr span<T, static_cast<extent_t>(N)> make_span( std::array< T, N > & arr ) span_noexcept { return span<T, static_cast<extent_t>(N)>( arr ); } template< class T, std::size_t N > inline span_constexpr span< const T, static_cast<extent_t>(N) > make_span( std::array< T, N > const & arr ) span_noexcept { return span<const T, static_cast<extent_t>(N)>( arr ); } #endif // span_HAVE( ARRAY ) #if span_USES_STD_SPAN || span_HAVE( INITIALIZER_LIST ) template< class T > inline span_constexpr span< const T > make_span( std::initializer_list<T> il ) span_noexcept { return span<const T>( il.begin(), il.size() ); } #endif // span_HAVE( INITIALIZER_LIST ) #if span_USES_STD_SPAN template< class Container, class EP = decltype( std::data(std::declval<Container&>())) > inline span_constexpr auto make_span( Container & cont ) span_noexcept -> span< typename std::remove_pointer<EP>::type > { return span< typename std::remove_pointer<EP>::type >( cont ); } template< class Container, class EP = decltype( std::data(std::declval<Container&>())) > inline span_constexpr auto make_span( Container const & cont ) span_noexcept -> span< const typename std::remove_pointer<EP>::type > { return span< const typename std::remove_pointer<EP>::type >( cont ); } #elif span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) && span_HAVE( AUTO ) template< class Container, class EP = decltype( std17::data(std::declval<Container&>())) > inline span_constexpr auto make_span( Container & cont ) span_noexcept -> span< typename std::remove_pointer<EP>::type > { return span< typename std::remove_pointer<EP>::type >( cont ); } template< class Container, class EP = decltype( std17::data(std::declval<Container&>())) > inline span_constexpr auto make_span( Container const & cont ) span_noexcept -> span< const typename std::remove_pointer<EP>::type > { return span< const typename std::remove_pointer<EP>::type >( cont ); } #else template< class T > inline span_constexpr span<T> make_span( span<T> spn ) span_noexcept { return spn; } template< class T, class Allocator > inline span_constexpr span<T> make_span( std::vector<T, Allocator> & cont ) span_noexcept { return span<T>( with_container, cont ); } template< class T, class Allocator > inline span_constexpr span<const T> make_span( std::vector<T, Allocator> const & cont ) span_noexcept { return span<const T>( with_container, cont ); } #endif // span_USES_STD_SPAN || ( ... ) #if ! span_USES_STD_SPAN && span_FEATURE( WITH_CONTAINER ) template< class Container > inline span_constexpr span<typename Container::value_type> make_span( with_container_t, Container & cont ) span_noexcept { return span< typename Container::value_type >( with_container, cont ); } template< class Container > inline span_constexpr span<const typename Container::value_type> make_span( with_container_t, Container const & cont ) span_noexcept { return span< const typename Container::value_type >( with_container, cont ); } #endif // ! span_USES_STD_SPAN && span_FEATURE( WITH_CONTAINER ) // extensions: non-member views: // this feature implies the presence of make_span() #if span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) template< extent_t Count, class T, extent_t Extent > span_constexpr span<T, Count> first( span<T, Extent> spn ) { return spn.template first<Count>(); } template< class T, extent_t Extent > span_constexpr span<T> first( span<T, Extent> spn, size_t count ) { return spn.first( count ); } template< extent_t Count, class T, extent_t Extent > span_constexpr span<T, Count> last( span<T, Extent> spn ) { return spn.template last<Count>(); } template< class T, extent_t Extent > span_constexpr span<T> last( span<T, Extent> spn, size_t count ) { return spn.last( count ); } template< size_t Offset, extent_t Count, class T, extent_t Extent > span_constexpr span<T, Count> subspan( span<T, Extent> spn ) { return spn.template subspan<Offset, Count>(); } template< class T, extent_t Extent > span_constexpr span<T> subspan( span<T, Extent> spn, size_t offset, extent_t count = dynamic_extent ) { return spn.subspan( offset, count ); } #endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) #if span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) && span_CPP11_120 template< extent_t Count, class T > span_constexpr auto first( T & t ) -> decltype( make_span(t).template first<Count>() ) { return make_span( t ).template first<Count>(); } template< class T > span_constexpr auto first( T & t, size_t count ) -> decltype( make_span(t).first(count) ) { return make_span( t ).first( count ); } template< extent_t Count, class T > span_constexpr auto last( T & t ) -> decltype( make_span(t).template last<Count>() ) { return make_span(t).template last<Count>(); } template< class T > span_constexpr auto last( T & t, extent_t count ) -> decltype( make_span(t).last(count) ) { return make_span( t ).last( count ); } template< size_t Offset, extent_t Count = dynamic_extent, class T > span_constexpr auto subspan( T & t ) -> decltype( make_span(t).template subspan<Offset, Count>() ) { return make_span( t ).template subspan<Offset, Count>(); } template< class T > span_constexpr auto subspan( T & t, size_t offset, extent_t count = dynamic_extent ) -> decltype( make_span(t).subspan(offset, count) ) { return make_span( t ).subspan( offset, count ); } #endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) } // namespace span_lite } // namespace nonstd // make available in nonstd: namespace nonstd { using span_lite::make_span; #if span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) || ( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) && span_CPP11_120 ) using span_lite::first; using span_lite::last; using span_lite::subspan; #endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_[SPAN|CONTAINER] ) } // namespace nonstd #endif // #if span_FEATURE_TO_STD( MAKE_SPAN ) #if span_CPP11_OR_GREATER && span_FEATURE( BYTE_SPAN ) && ( span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) ) namespace nonstd { namespace span_lite { template< class T > inline span_constexpr auto byte_span( T & t ) span_noexcept -> span< std17::byte, span_sizeof(T) > { return span< std17::byte, span_sizeof(t) >( reinterpret_cast< std17::byte * >( &t ), span_sizeof(T) ); } template< class T > inline span_constexpr auto byte_span( T const & t ) span_noexcept -> span< const std17::byte, span_sizeof(T) > { return span< const std17::byte, span_sizeof(t) >( reinterpret_cast< std17::byte const * >( &t ), span_sizeof(T) ); } } // namespace span_lite } // namespace nonstd // make available in nonstd: namespace nonstd { using span_lite::byte_span; } // namespace nonstd #endif // span_FEATURE( BYTE_SPAN ) #if span_HAVE( STRUCT_BINDING ) #if span_CPP14_OR_GREATER # include <tuple> #elif span_CPP11_OR_GREATER # include <tuple> namespace std { template< std::size_t I, typename T > using tuple_element_t = typename tuple_element<I, T>::type; } #else namespace std { template< typename T > class tuple_size; /*undefined*/ template< std::size_t I, typename T > class tuple_element; /* undefined */ } #endif // span_CPP14_OR_GREATER namespace std { // 26.7.X Tuple interface // std::tuple_size<>: template< typename ElementType, nonstd::span_lite::extent_t Extent > class tuple_size< nonstd::span<ElementType, Extent> > : public integral_constant<size_t, static_cast<size_t>(Extent)> {}; // std::tuple_size<>: Leave undefined for dynamic extent: template< typename ElementType > class tuple_size< nonstd::span<ElementType, nonstd::dynamic_extent> >; // std::tuple_element<>: template< size_t I, typename ElementType, nonstd::span_lite::extent_t Extent > class tuple_element< I, nonstd::span<ElementType, Extent> > { public: #if span_HAVE( STATIC_ASSERT ) static_assert( Extent != nonstd::dynamic_extent && I < Extent, "tuple_element<I,span>: dynamic extent or index out of range" ); #endif using type = ElementType; }; // std::get<>(), 2 variants: template< size_t I, typename ElementType, nonstd::span_lite::extent_t Extent > span_constexpr ElementType & get( nonstd::span<ElementType, Extent> & spn ) span_noexcept { #if span_HAVE( STATIC_ASSERT ) static_assert( Extent != nonstd::dynamic_extent && I < Extent, "get<>(span): dynamic extent or index out of range" ); #endif return spn[I]; } template< size_t I, typename ElementType, nonstd::span_lite::extent_t Extent > span_constexpr ElementType const & get( nonstd::span<ElementType, Extent> const & spn ) span_noexcept { #if span_HAVE( STATIC_ASSERT ) static_assert( Extent != nonstd::dynamic_extent && I < Extent, "get<>(span): dynamic extent or index out of range" ); #endif return spn[I]; } } // end namespace std #endif // span_HAVE( STRUCT_BINDING ) #if ! span_USES_STD_SPAN span_RESTORE_WARNINGS() #endif // span_USES_STD_SPAN #endif // NONSTD_SPAN_HPP_INCLUDED
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/example/CMakeLists.txt
# Copyright 2018-2021 by Martin Moene # # https://github.com/martinmoene/span-lite # # 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) if( NOT DEFINED CMAKE_MINIMUM_REQUIRED_VERSION ) cmake_minimum_required( VERSION 3.8 FATAL_ERROR ) endif() project( example LANGUAGES CXX ) set( unit_name "span" ) set( PACKAGE ${unit_name}-lite ) set( PROGRAM ${unit_name}-lite ) message( STATUS "Subproject '${PROJECT_NAME}', examples '${PROGRAM}-*'") # Target default options and definitions: set( OPTIONS "" ) #set( DEFINITIONS "" ) # Sources (.cpp), normal and no-exception, and their base names: set( SOURCES 01-basic.cpp 02-span.cpp ) set( SOURCES_NE ) string( REPLACE ".cpp" "" BASENAMES "${SOURCES}" ) string( REPLACE ".cpp" "" BASENAMES_NE "${SOURCES_NE}" ) # Determine options: if( MSVC ) message( STATUS "Matched: MSVC") set( BASE_OPTIONS -W3 ) set( EXCEPTIONS_OPTIONS ${BASE_OPTIONS} -EHsc ) set( NO_EXCEPTIONS_OPTIONS ${BASE_OPTIONS} ) elseif( CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang" ) message( STATUS "CompilerId: '${CMAKE_CXX_COMPILER_ID}'") set( BASE_OPTIONS -Wall -Wextra -Wconversion -Wsign-conversion -Wno-missing-braces -fno-elide-constructors ) set( EXCEPTIONS_OPTIONS ${BASE_OPTIONS} ) set( NO_EXCEPTIONS_OPTIONS -fno-exceptions ) elseif( CMAKE_CXX_COMPILER_ID MATCHES "Intel" ) # as is message( STATUS "Matched: Intel") else() # as is message( STATUS "Matched: nothing") endif() # Function to emulate ternary operaton `result = b ? x : y`: macro( ternary var boolean value1 value2 ) if( ${boolean} ) set( ${var} ${value1} ) else() set( ${var} ${value2} ) endif() endmacro() # Function to create a target: function( make_target name no_exceptions ) ternary( ne no_exceptions "-ne" "" ) add_executable ( ${PROGRAM}-${name}${ne} ${name}.cpp ) target_include_directories ( ${PROGRAM}-${name}${ne} PRIVATE ../../variant-lite/include ) target_link_libraries ( ${PROGRAM}-${name}${ne} PRIVATE ${PACKAGE} ) if ( no_exceptions ) target_compile_options ( ${PROGRAM}-${name}${ne} PRIVATE ${NO_EXCEPTIONS_OPTIONS} ) else() target_compile_options ( ${PROGRAM}-${name}${ne} PRIVATE ${EXCEPTIONS_OPTIONS} ) endif() endfunction() # Create targets: foreach( target ${BASENAMES} ) make_target( ${target} FALSE ) endforeach() foreach( target ${BASENAMES_NE} ) make_target( ${target} TRUE ) endforeach() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/example/01-basic.cpp
// Use span #include "nonstd/span.hpp" #include <array> #include <vector> #include <iostream> std::ptrdiff_t size( nonstd::span<const int> spn ) { return spn.size(); } int main() { int arr[] = { 1, }; std::cout << "C-array:" << size( arr ) << " array:" << size( std::array <int, 2>{ 1, 2, } ) << " vector:" << size( std::vector<int >{ 1, 2, 3, } ); } #if 0 cl -EHsc -I../include 01-basic.cpp && 01-basic.exe g++ -std=c++11 -Wall -I../include -o 01-basic.exe 01-basic.cpp && 01-basic.exe Output: C-array:1 array:2 vector:3 #endif
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/example/02-span.cpp
// Use span #include "nonstd/span.hpp" #include <iostream> #define span_DIMENSION_OF( a ) ( sizeof(a) / sizeof(0[a]) ) using namespace nonstd; int line = 0; void bad( int * arr, size_t num ) { std::cout << ++line << ": "; for ( size_t i = 0; i != num; ++i ) { std::cout << (i==0 ? "[":"") << arr[i] << (i!=num-1 ? ", ":"]\n"); } } void good( span<int> arr ) { std::cout << ++line << ": "; for ( size_t i = 0; i != arr.size(); ++i ) { std::cout << (i==0 ? "[":"") << arr[i] << (i!=arr.size()-1 ? ", ":"]\n"); } } int main() { int arr[] = { 1, 2, 3, 4, 5, }; good( arr ); // 1. Good: deduce length #if gsl_CPP11_OR_GREATER std::array<int, 6> ary = { 1, 2, 3, 4, 5, 6, }; std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, }; good( ary ); // 2. Good: single function handles good( vec ); // 3. C-array, std::array and containers such as std::vector #else line += 2; #endif bad( arr, span_DIMENSION_OF(arr) ); // 4. Avoid: specify elements and length separately bad( arr, 3 ); // 5. Avoid, but not wrong bad( arr, 7 ); // 6. Wrong, array length exceeded #if gsl_CPP11_OR_GREATER good( { arr, 3 } ); // 7. Avoid, but not wrong good( { arr, 7 } ); // 8. Wrong, array length exceeded #else good( span<int>( arr, 3 ) ); // 7. Avoid, but not wrong good( span<int>( arr, 7 ) ); // 8. Wrong, array length exceeded #endif span<int> s( arr ); good( s.first ( 3 ) ); // 9. Fine good( s.last ( 3 ) ); // 10. Fine good( s.subspan( 1 ) ); // 11. Fine good( s.subspan( 1, 3 ) ); // 12. Fine good( s.subspan( 1, 5 ) ); // 13. Run-time error, terminate } #if 0 cl -EHsc -I../include 02-span.cpp && 02-span.exe g++ -std=c++11 -Wall -I../include -o 02-span.exe 02-span.cpp && 02-span.exe #endif
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/example
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/example/nonstd/span.tweak.hpp
// Example span-lite tweak file example/nonstd/span.tweak.hpp // See also https://github.com/martinmoene/span-lite#configuration // // Select std::span or nonstd::span: // // #define span_CONFIG_SELECT_SPAN span_SPAN_DEFAULT // #define span_CONFIG_SELECT_SPAN span_SPAN_STD // #define span_CONFIG_SELECT_SPAN span_SPAN_NONSTD // // Define contract handling: // // #define span_CONFIG_CONTRACT_LEVEL_ON 1 // #define span_CONFIG_CONTRACT_LEVEL_OFF 1 // #define span_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY 1 // #define span_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY 1 // #define span_CONFIG_CONTRACT_VIOLATION_TERMINATES 1 // #define span_CONFIG_CONTRACT_VIOLATION_THROWS 1 // // Select available features: // // #define span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE 1 // #define span_FEATURE_WITH_INITIALIZER_LIST_P2447 1 // #define span_FEATURE_WITH_CONTAINER_TO_STD 99 // #define span_FEATURE_MEMBER_CALL_OPERATOR 1 // #define span_FEATURE_MEMBER_AT 2 // #define span_FEATURE_MEMBER_BACK_FRONT 1 // #define span_FEATURE_MEMBER_SWAP 1 // #define span_FEATURE_COMPARISON 1 // #define span_FEATURE_SAME 1 // #define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB 1 // #define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN 1 // #define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER 1 // #define span_FEATURE_MAKE_SPAN_TO_STD 99 // #define span_FEATURE_BYTE_SPAN 1 // Alternative flags: #define span_FEATURE_WITH_CONTAINER 1 // takes precedence over span_FEATURE_WITH_CONTAINER_TO_STD #define span_FEATURE_MAKE_SPAN 1 // takes precedence over span_FEATURE_MAKE_SPAN_TO_STD
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/script/update-version.py
#!/usr/bin/env python # # Copyright 2017-2019 by 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) # # script/update-version.py # from __future__ import print_function import argparse import os import re import sys # Configuration: table = ( # path, substitute find, substitute format ( 'CMakeLists.txt' , r'\W{2,4}VERSION\W+([0-9]+\.[0-9]+\.[0-9]+)\W*$' , ' VERSION {major}.{minor}.{patch}' ) , ( 'CMakeLists.txt' , r'set\W+span_lite_version\W+"([0-9]+\.[0-9]+\.[0-9]+)"\W+$' , 'set( span_lite_version "{major}.{minor}.{patch}" )\n' ) # , ( 'example/cmake-pkg/CMakeLists.txt' # , r'set\W+span_lite_version\W+"([0-9]+\.[0-9]+(\.[0-9]+)?)"\W+$' # , 'set( span_lite_version "{major}.{minor}" )\n' ) # # , ( 'script/install-xxx-pkg.py' # , r'\span_lite_version\s+=\s+"([0-9]+\.[0-9]+\.[0-9]+)"\s*$' # , 'span_lite_version = "{major}.{minor}.{patch}"\n' ) , ( 'conanfile.py' , r'version\s+=\s+"([0-9]+\.[0-9]+\.[0-9]+)"\s*$' , 'version = "{major}.{minor}.{patch}"' ) , ( 'include/nonstd/span.hpp' , r'\#define\s+span_lite_MAJOR\s+[0-9]+\s*$' , '#define span_lite_MAJOR {major}' ) , ( 'include/nonstd/span.hpp' , r'\#define\s+span_lite_MINOR\s+[0-9]+\s*$' , '#define span_lite_MINOR {minor}' ) , ( 'include/nonstd/span.hpp' , r'\#define\s+span_lite_PATCH\s+[0-9]+\s*$' , '#define span_lite_PATCH {patch}\n' ) ) # End configuration. def readFile( in_path ): """Return content of file at given path""" with open( in_path, 'r' ) as in_file: contents = in_file.read() return contents def writeFile( out_path, contents ): """Write contents to file at given path""" with open( out_path, 'w' ) as out_file: out_file.write( contents ) def replaceFile( output_path, input_path ): # prevent race-condition (Python 3.3): if sys.version_info >= (3, 3): os.replace( output_path, input_path ) else: os.remove( input_path ) os.rename( output_path, input_path ) def editFileToVersion( version, info, verbose ): """Update version given file path, version regexp and new version format in info""" major, minor, patch = version.split('.') in_path, ver_re, ver_fmt = info out_path = in_path + '.tmp' new_text = ver_fmt.format( major=major, minor=minor, patch=patch ) if verbose: print( "- {path} => '{text}':".format( path=in_path, text=new_text.strip('\n') ) ) writeFile( out_path, re.sub( ver_re, new_text, readFile( in_path ) , count=0, flags=re.MULTILINE ) ) replaceFile( out_path, in_path ) def editFilesToVersion( version, table, verbose ): if verbose: print( "Editing files to version {v}:".format(v=version) ) for item in table: editFileToVersion( version, item, verbose ) def editFilesToVersionFromCommandLine(): """Update version number given on command line in paths from configuration table.""" parser = argparse.ArgumentParser( description='Update version number in files.', epilog="""""", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument( 'version', metavar='version', type=str, nargs=1, help='new version number, like 1.2.3') parser.add_argument( '-v', '--verbose', action='store_true', help='report the name of the file being processed') args = parser.parse_args() editFilesToVersion( args.version[0], table, args.verbose ) if __name__ == '__main__': editFilesToVersionFromCommandLine() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/script/create-cov-rpt.py
#!/usr/bin/env python # # Copyright 2019-2019 by 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) # # script/create-cov-rpt.py, Python 3.4 and later # import argparse import os import re import sys import subprocess # Configuration: cfg_github_project = 'span-lite' cfg_github_user = 'martinmoene' cfg_prj_folder_level = 3 tpl_coverage_cmd = 'opencppcoverage --no_aggregate_by_file --sources {src} -- {exe}' # End configuration. def project_folder( f, args ): """Project root""" if args.prj_folder: return args.prj_folder return os.path.normpath( os.path.join( os.path.dirname( os.path.abspath(f) ), '../' * args.prj_folder_level ) ) def executable_folder( f ): """Folder where the xecutable is""" return os.path.dirname( os.path.abspath(f) ) def executable_name( f ): """Folder where the executable is""" return os.path.basename( f ) def createCoverageReport( f, args ): print( "Creating coverage report for project '{usr}/{prj}', '{file}':". format( usr=args.user, prj=args.project, file=f ) ) cmd = tpl_coverage_cmd.format( folder=executable_folder(f), src=project_folder(f, args), exe=executable_name(f) ) if args.verbose: print( "> {}".format(cmd) ) if not args.dry_run: os.chdir( executable_folder(f) ) subprocess.call( cmd, shell=False ) os.chdir( project_folder(f, args) ) def createCoverageReports( args ): for f in args.executable: createCoverageReport( f, args ) def createCoverageReportFromCommandLine(): """Collect arguments from the commandline and create coverage report.""" parser = argparse.ArgumentParser( description='Create coverage report.', epilog="""""", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'executable', metavar='executable', type=str, nargs=1, help='executable to report on') parser.add_argument( '-n', '--dry-run', action='store_true', help='do not execute conan commands') parser.add_argument( '-v', '--verbose', action='count', default=0, help='level of progress reporting') parser.add_argument( '--user', metavar='u', type=str, default=cfg_github_user, help='github user name') parser.add_argument( '--project', metavar='p', type=str, default=cfg_github_project, help='github project name') parser.add_argument( '--prj-folder', metavar='f', type=str, default=None, help='project root folder') parser.add_argument( '--prj-folder-level', metavar='n', type=int, default=cfg_prj_folder_level, help='project root folder level from executable') createCoverageReports( parser.parse_args() ) if __name__ == '__main__': createCoverageReportFromCommandLine() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/script/upload-conan.py
#!/usr/bin/env python # # Copyright 2019-2019 by 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) # # script/upload-conan.py # from __future__ import print_function import argparse import os import re import sys import subprocess # Configuration: def_conan_project = 'span-lite' def_conan_user = 'nonstd-lite' def_conan_channel = 'stable' cfg_conanfile = 'conanfile.py' tpl_conan_create = 'conan create . {usr}/{chn}' tpl_conan_upload = 'conan upload --remote {usr} {prj}/{ver}@{usr}/{chn}' # End configuration. def versionFrom( filename ): """Obtain version from conanfile.py""" with open( filename ) as f: content = f.read() version = re.search(r'version\s=\s"(.*)"', content).group(1) return version def createConanPackage( args ): """Create conan package and upload it.""" cmd = tpl_conan_create.format(usr=args.user, chn=args.channel) if args.verbose: print( "> {}".format(cmd) ) if not args.dry_run: subprocess.call( cmd, shell=False ) def uploadConanPackage( args ): """Create conan package and upload it.""" cmd = tpl_conan_upload.format(prj=args.project, usr=args.user, chn=args.channel, ver=args.version) if args.verbose: print( "> {}".format(cmd) ) if not args.dry_run: subprocess.call( cmd, shell=False ) def uploadToConan( args ): """Create conan package and upload it.""" print( "Updating project '{prj}' to user '{usr}', channel '{chn}', version {ver}:". format(prj=args.project, usr=args.user, chn=args.channel, ver=args.version) ) createConanPackage( args ) uploadConanPackage( args ) def uploadToConanFromCommandLine(): """Collect arguments from the commandline and create conan package and upload it.""" parser = argparse.ArgumentParser( description='Create conan package and upload it to conan.', epilog="""""", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-n', '--dry-run', action='store_true', help='do not execute conan commands') parser.add_argument( '-v', '--verbose', action='count', default=0, help='level of progress reporting') parser.add_argument( '--project', metavar='p', type=str, default=def_conan_project, help='conan project') parser.add_argument( '--user', metavar='u', type=str, default=def_conan_user, help='conan user') parser.add_argument( '--channel', metavar='c', type=str, default=def_conan_channel, help='conan channel') parser.add_argument( '--version', metavar='v', type=str, default=versionFrom( cfg_conanfile ), help='version number [from conanfile.py]') uploadToConan( parser.parse_args() ) if __name__ == '__main__': uploadToConanFromCommandLine() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/script/create-vcpkg.py
#!/usr/bin/env python # # Copyright 2019-2019 by 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) # # script/upload-conan.py, Python 3.4 and later # import argparse import os import re import sys import subprocess # Configuration: cfg_github_project = 'span-lite' cfg_github_user = 'martinmoene' cfg_description = '(unused)' cfg_cmakelists = 'CMakeLists.txt' cfg_readme = 'Readme.md' cfg_license = 'LICENSE.txt' cfg_ref_prefix = 'v' cfg_sha512 = 'dadeda' cfg_vcpkg_description = '(no description found)' cfg_vcpkg_root = os.environ['VCPKG_ROOT'] cfg_cmake_optpfx = "SPAN_LITE" # End configuration. # vcpkg control and port templates: tpl_path_vcpkg_control = '{vcpkg}/ports/{prj}/CONTROL' tpl_path_vcpkg_portfile = '{vcpkg}/ports/{prj}/portfile.cmake' tpl_vcpkg_control =\ """Source: {prj} Version: {ver} Description: {desc}""" tpl_vcpkg_portfile =\ """include(vcpkg_common_functions) vcpkg_from_github( OUT_SOURCE_PATH SOURCE_PATH REPO {usr}/{prj} REF {ref} SHA512 {sha} ) vcpkg_configure_cmake( SOURCE_PATH ${{SOURCE_PATH}} PREFER_NINJA OPTIONS -D{optpfx}_OPT_BUILD_TESTS=OFF -D{optpfx}_OPT_BUILD_EXAMPLES=OFF ) vcpkg_install_cmake() vcpkg_fixup_cmake_targets( CONFIG_PATH lib/cmake/${{PORT}} ) file(REMOVE_RECURSE ${{CURRENT_PACKAGES_DIR}}/debug ${{CURRENT_PACKAGES_DIR}}/lib ) file(INSTALL ${{SOURCE_PATH}}/{lic} DESTINATION ${{CURRENT_PACKAGES_DIR}}/share/${{PORT}} RENAME copyright )""" tpl_vcpkg_note_sha =\ """ Next actions: - Obtain package SHA: 'vcpkg install {prj}', copy SHA mentioned in 'Actual hash: [...]' - Add SHA to package: 'script\create-vcpkg --sha={sha}' - Install package : 'vcpkg install {prj}'""" tpl_vcpkg_note_install =\ """ Next actions: - Install package: 'vcpkg install {prj}'""" # End of vcpkg templates def versionFrom( filename ): """Obtain version from CMakeLists.txt""" with open( filename, 'r' ) as f: content = f.read() version = re.search(r'VERSION\s(\d+\.\d+\.\d+)', content).group(1) return version def descriptionFrom( filename ): """Obtain description from CMakeLists.txt""" with open( filename, 'r' ) as f: content = f.read() description = re.search(r'DESCRIPTION\s"(.*)"', content).group(1) return description if description else cfg_vcpkg_description def vcpkgRootFrom( path ): return path if path else './vcpkg' def to_ref( version ): """Add prefix to version/tag, like v1.2.3""" return cfg_ref_prefix + version def control_path( args ): """Create path like vcpks/ports/_project_/CONTROL""" return tpl_path_vcpkg_control.format( vcpkg=args.vcpkg_root, prj=args.project ) def portfile_path( args ): """Create path like vcpks/ports/_project_/portfile.cmake""" return tpl_path_vcpkg_portfile.format( vcpkg=args.vcpkg_root, prj=args.project ) def createControl( args ): """Create vcpkg CONTROL file""" output = tpl_vcpkg_control.format( prj=args.project, ver=args.version, desc=args.description ) if args.verbose: print( "Creating control file '{f}':".format( f=control_path( args ) ) ) if args.verbose > 1: print( output ) os.makedirs( os.path.dirname( control_path( args ) ), exist_ok=True ) with open( control_path( args ), 'w') as f: print( output, file=f ) def createPortfile( args ): """Create vcpkg portfile""" output = tpl_vcpkg_portfile.format( optpfx=cfg_cmake_optpfx, usr=args.user, prj=args.project, ref=to_ref(args.version), sha=args.sha, lic=cfg_license ) if args.verbose: print( "Creating portfile '{f}':".format( f=portfile_path( args ) ) ) if args.verbose > 1: print( output ) os.makedirs( os.path.dirname( portfile_path( args ) ), exist_ok=True ) with open( portfile_path( args ), 'w') as f: print( output, file=f ) def printNotes( args ): if args.sha == cfg_sha512: print( tpl_vcpkg_note_sha. format( prj=args.project, sha='...' ) ) else: print( tpl_vcpkg_note_install. format( prj=args.project ) ) def createVcpkg( args ): print( "Creating vcpkg for '{usr}/{prj}', version '{ver}' in folder '{vcpkg}':". format( usr=args.user, prj=args.project, ver=args.version, vcpkg=args.vcpkg_root, ) ) createControl( args ) createPortfile( args ) printNotes( args ) def createVcpkgFromCommandLine(): """Collect arguments from the commandline and create vcpkg.""" parser = argparse.ArgumentParser( description='Create microsoft vcpkg.', epilog="""""", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-v', '--verbose', action='count', default=0, help='level of progress reporting') parser.add_argument( '--user', metavar='u', type=str, default=cfg_github_user, help='github user name') parser.add_argument( '--project', metavar='p', type=str, default=cfg_github_project, help='github project name') parser.add_argument( '--description', metavar='d', type=str, # default=cfg_description, default=descriptionFrom( cfg_cmakelists ), help='vcpkg description [from ' + cfg_cmakelists + ']') parser.add_argument( '--version', metavar='v', type=str, default=versionFrom( cfg_cmakelists ), help='version number [from ' + cfg_cmakelists + ']') parser.add_argument( '--sha', metavar='s', type=str, default=cfg_sha512, help='sha of package') parser.add_argument( '--vcpkg-root', metavar='r', type=str, default=vcpkgRootFrom( cfg_vcpkg_root ), help='parent folder containing ports to write files to') createVcpkg( parser.parse_args() ) if __name__ == '__main__': createVcpkgFromCommandLine() # end of file
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/test/tg-all.bat
@for %%s in ( c++98 c++03 c++11 c++14 c++17 ) do ( call tg.bat %%s )
0
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite
repos/outcome/test/quickcpplib/include/quickcpplib/span-lite/test/span.t.cpp
// // span for C++98 and later. // Based on http://wg21.link/p0122r7 // For more information see https://github.com/martinmoene/span-lite // // Copyright 2015, 2018-2020 Martin Moene // Copyright 2015 Microsoft Corporation. All rights reserved. // // 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) #include <ciso646> #include <memory> // std::unique_ptr #include "span-main.t.hpp" #define DIMENSION_OF( a ) ( sizeof(a) / sizeof(0[a]) ) #define span_STD_OR( expr ) ( span_USES_STD_SPAN) || ( expr ) #define span_NONSTD_AND( expr ) (!span_USES_STD_SPAN) && ( expr ) using namespace nonstd; typedef span<int>::size_type size_type; typedef std::ptrdiff_t ssize_type; CASE( "span<>: Terminates construction from a nullptr and a non-zero size (C++11)" ) { #if span_NONSTD_AND( span_HAVE( NULLPTR ) ) struct F { static void blow() { span<int> v( nullptr, 42 ); } }; EXPECT_THROWS( F::blow() ); #else EXPECT( !!"nullptr is not available (no C++11), or no exception, using std::span)" ); #endif } CASE( "span<>: Terminates construction from two pointers in the wrong order" ) { #if !span_USES_STD_SPAN struct F { static void blow() { int a[2]; span<int> v( &a[1], &a[0] ); } }; EXPECT_THROWS( F::blow() ); #else EXPECT( !!"No exception, using std::span" ); #endif } CASE( "span<>: Terminates construction from a null pointer and a non-zero size" ) { #if !span_USES_STD_SPAN struct F { static void blow() { int * p = span_nullptr; span<int> v( p, 42 ); } }; EXPECT_THROWS( F::blow() ); #else EXPECT( !!"No exception, using std::span" ); #endif } CASE( "span<>: Terminates creation of a sub span of the first n elements for n exceeding the span" ) { #if !span_USES_STD_SPAN struct F { static void blow() { int arr[] = { 1, 2, 3, }; span<int> v( arr ); (void) v.first( 4 ); }}; EXPECT_THROWS( F::blow() ); #else EXPECT( !!"No exception, using std::span" ); #endif } CASE( "span<>: Terminates creation of a sub span of the last n elements for n exceeding the span" ) { #if !span_USES_STD_SPAN struct F { static void blow() { int arr[] = { 1, 2, 3, }; span<int> v( arr ); (void) v.last( 4 ); }}; EXPECT_THROWS( F::blow() ); #else EXPECT( !!"No exception, using std::span" ); #endif } CASE( "span<>: Terminates creation of a sub span outside the span" ) { #if !span_USES_STD_SPAN struct F { static void blow_offset() { int arr[] = { 1, 2, 3, }; span<int> v( arr ); (void) v.subspan( 4 ); } static void blow_count() { int arr[] = { 1, 2, 3, }; span<int> v( arr ); (void) v.subspan( 1, 3 ); } }; EXPECT_THROWS( F::blow_offset() ); EXPECT_THROWS( F::blow_count() ); #else EXPECT( !!"No exception, using std::span" ); #endif } CASE( "span<>: Terminates access outside the span" ) { #if !span_USES_STD_SPAN struct F { static void blow_ix(size_type i) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); (void) v[i]; } #if span_NONSTD_AND( span_FEATURE( MEMBER_CALL_OPERATOR ) ) static void blow_iv(size_type i) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); (void) v(i); } #endif #if span_NONSTD_AND( span_FEATURE( MEMBER_AT ) ) static void blow_at(size_type i) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); (void) v.at(i); } #endif }; EXPECT_NO_THROW( F::blow_ix(2) ); EXPECT_THROWS( F::blow_ix(3) ); #if span_NONSTD_AND( span_FEATURE( MEMBER_CALL_OPERATOR ) ) EXPECT_NO_THROW( F::blow_iv(2) ); EXPECT_THROWS( F::blow_iv(3) ); #endif #if span_NONSTD_AND( span_FEATURE( MEMBER_AT ) ) EXPECT_NO_THROW( F::blow_at(2) ); EXPECT_THROWS( F::blow_at(3) ); #endif #else EXPECT( !!"No exception, using std::span" ); #endif } CASE( "span<>: Throws on access outside the span via at(): std::out_of_range [span_FEATURE_MEMBER_AT>0][span_CONFIG_NO_EXCEPTIONS=0]" ) { #if span_NONSTD_AND( span_FEATURE( MEMBER_AT ) ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); EXPECT_THROWS_AS( v.at(42), std::out_of_range ); EXPECT_THROWS_AS( w.at(42), std::out_of_range ); struct F { static void fail(lest::env & lest_env) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); EXPECT( (v.at(42), true) ); }}; lest::test fail[] = { lest::test( "F", F::fail ) }; std::ostringstream os; EXPECT( 1 == run( fail, os ) ); #if span_FEATURE( MEMBER_AT ) > 1 EXPECT( std::string::npos != os.str().find("42") ); EXPECT( std::string::npos != os.str().find("3)") ); #else EXPECT( std::string::npos != os.str().find("index outside span") ); #endif #else EXPECT( !!"member at() is not available (span_FEATURE_MEMBER_AT=0, or using std::span)" ); #endif } CASE( "span<>: Termination throws std::logic_error-derived exception [span_CONFIG_CONTRACT_VIOLATION_THROWS=1]" ) { #if span_NONSTD_AND( span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) ) struct F { static void blow() { int arr[] = { 1, }; span<int> v( arr ); (void) v[1]; } }; EXPECT_THROWS_AS( F::blow(), nonstd::span_lite::detail::contract_violation ); #else EXPECT( !!"exception contract_violation is not available (non-throwing contract violation, or using std::span)" ); #endif } CASE( "span<>: Allows to default-construct" ) { span<int> v; span<int, 0> w; EXPECT( v.size() == size_type( 0 ) ); EXPECT( w.size() == size_type( 0 ) ); } CASE( "span<>: Allows to construct from a nullptr and a zero size (C++11)" ) { #if span_NONSTD_AND( span_HAVE( NULLPTR ) ) span< int> v( nullptr, size_type(0) ); span<const int> w( nullptr, size_type(0) ); EXPECT( v.size() == size_type( 0 ) ); EXPECT( w.size() == size_type( 0 ) ); #else EXPECT( !!"nullptr is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from two pointers" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< int> v( &arr[0], &arr[0] + DIMENSION_OF( arr ) ); span<const int> w( &arr[0], &arr[0] + DIMENSION_OF( arr ) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); EXPECT( std::equal( w.begin(), w.end(), &arr[0] ) ); } CASE( "span<>: Allows to construct from two iterators" ) { #if span_HAVE_ITERATOR_CTOR std::vector<int> v( 5, 123 ); span<int> s( v.begin(), v.end() ); EXPECT( std::equal( s.begin(), s.end(), v.begin() ) ); #else EXPECT( !!"construction from iterator is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from two iterators - empty range" ) { #if span_HAVE_ITERATOR_CTOR #if ! (span_COMPILER_MSVC_VER && defined(_DEBUG) ) std::vector<int> v; span<int> s( v.begin(), v.end() ); EXPECT( std::equal( s.begin(), s.end(), v.begin() ) ); #else EXPECT( !!"construction from empty range not available (MSVC Debug)" ); #endif #else EXPECT( !!"construction from iterator is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from two iterators - move-only element" ) { #if span_HAVE_ITERATOR_CTOR std::vector<std::unique_ptr<int> > v(5); nonstd::span<std::unique_ptr<int> > s{ v.begin(), v.end() }; EXPECT( s.size() == 5 ); #else EXPECT( !!"construction from iterator is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from an iterator and a size" ) { #if span_HAVE_ITERATOR_CTOR std::vector<int> v( 5, 123 ); span<int> s( v.begin(), v.size() ); EXPECT( std::equal( s.begin(), s.end(), v.begin() ) ); #else EXPECT( !!"construction from iterator is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from an iterator and a size - empty range" ) { #if span_HAVE_ITERATOR_CTOR #if ! (span_COMPILER_MSVC_VER && defined(_DEBUG) ) std::vector<int> v; span<int> s( v.begin(), v.size() ); EXPECT( std::equal( s.begin(), s.end(), v.begin() ) ); #else EXPECT( !!"construction from empty range not available (MSVC Debug)" ); #endif #else EXPECT( !!"construction from iterator is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from an iterator and a size - move-only element" ) { #if span_HAVE_ITERATOR_CTOR std::vector<std::unique_ptr<int> > v(5); nonstd::span<std::unique_ptr<int> > s{ v.begin(), v.size() }; EXPECT( s.size() == v.size() ); #else EXPECT( !!"construction from iterator is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from two pointers to const" ) { const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<const int> v( &arr[0], &arr[0] + DIMENSION_OF( arr ) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "span<>: Allows to construct from a non-null pointer and a size" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< int> v( &arr[0], DIMENSION_OF( arr ) ); span<const int> w( &arr[0], DIMENSION_OF( arr ) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); EXPECT( std::equal( w.begin(), w.end(), &arr[0] ) ); } CASE( "span<>: Allows to construct from a non-null pointer to const and a size" ) { const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<const int> v( &arr[0], DIMENSION_OF( arr ) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "span<>: Allows to construct from a temporary pointer and a size" ) { int x = 42; span< int> v( &x, 1 ); span<const int> w( &x, 1 ); EXPECT( std::equal( v.begin(), v.end(), &x ) ); EXPECT( std::equal( w.begin(), w.end(), &x ) ); } CASE( "span<>: Allows to construct from a temporary pointer to const and a size" ) { const int x = 42; span<const int> v( &x, 1 ); EXPECT( std::equal( v.begin(), v.end(), &x ) ); } CASE( "span<>: Allows to construct from any pointer and a zero size (C++98)" ) { #if !span_HAVE_ITERATOR_CTOR struct F { static void null() { int * p = span_nullptr; span<int> v( p, size_type( 0 ) ); } static void nonnull() { int i = 7; int * p = &i; span<int> v( p, size_type( 0 ) ); } }; EXPECT_NO_THROW( F::null() ); EXPECT_NO_THROW( F::nonnull() ); #else EXPECT( !!"Only with C++98" ); #endif } CASE( "span<>: Allows to construct from a pointer and a size via a deduction guide (C++17)" ) { #if span_STD_OR( span_HAVE( DEDUCTION_GUIDES ) ) char const * argv[] = { "prog", "arg1", "arg2" }; int const argc = DIMENSION_OF( argv ); span args( &argv[0], argc ); EXPECT( args.size() == DIMENSION_OF( argv ) ); #else EXPECT( !!"deduction guide is not available (no C++17)" ); #endif } CASE( "span<>: Allows to construct from an iterator and a size via a deduction guide (C++17)" ) { #if span_STD_OR( span_HAVE( DEDUCTION_GUIDES ) ) std::vector<int> v( 5, 123 ); span spn( v.begin(), v.size() ); EXPECT( spn.size() == v.size() ); #else EXPECT( !!"deduction guide is not available (no C++17)" ); #endif } CASE( "span<>: Allows to construct from two iterators via a deduction guide (C++17)" ) { #if span_STD_OR( span_HAVE( DEDUCTION_GUIDES ) ) std::vector<int> v( 5, 123 ); span spn( v.begin(), v.end() ); EXPECT( spn.size() == v.size() ); #else EXPECT( !!"deduction guide is not available (no C++17)" ); #endif } CASE( "span<>: Allows to construct from a C-array" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< int> v( arr ); span<const int> w( arr ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); EXPECT( std::equal( w.begin(), w.end(), &arr[0] ) ); } CASE( "span<>: Allows to construct from a C-array via a deduction guide (C++17)" ) { #if span_STD_OR( span_HAVE( DEDUCTION_GUIDES ) ) && !span_BETWEEN( _MSC_VER, 1, 1920 ) int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span v( arr ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); #else EXPECT( !!"deduction guide is not available (no C++17)" ); #endif } CASE( "span<>: Allows to construct from a const C-array" ) { const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<const int> v( arr ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "span<>: Allows to construct from a C-array with size via decay to pointer (potentially dangerous)" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; { span< int> v( &arr[0], DIMENSION_OF(arr) ); span<const int> w( &arr[0], DIMENSION_OF(arr) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); EXPECT( std::equal( w.begin(), w.end(), &arr[0] ) ); } #if span_CPP14_OR_GREATER { span< int> v( &arr[0], 3 ); span<const int> w( &arr[0], 3 ); EXPECT( std::equal( v.begin(), v.end(), &arr[0], &arr[0] + 3 ) ); EXPECT( std::equal( w.begin(), w.end(), &arr[0], &arr[0] + 3 ) ); } #endif } CASE( "span<>: Allows to construct from a const C-array with size via decay to pointer (potentially dangerous)" ) { const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; { span<const int> v( &arr[0], DIMENSION_OF(arr) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } #if span_CPP14_OR_GREATER { span<const int> w( &arr[0], 3 ); EXPECT( std::equal( w.begin(), w.end(), &arr[0], &arr[0] + 3 ) ); } #endif } CASE( "span<>: Allows to construct from a std::initializer_list<> (C++11)" ) { #if span_STD_OR( span_HAVE( INITIALIZER_LIST ) ) #if span_STD_OR( span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) ) SETUP("") { SECTION("empty initializer list") { std::initializer_list<int const> il = {}; span<int const> v( il ); #if span_BETWEEN( span_COMPILER_MSVC_VERSION, 120, 130 ) EXPECT( v.size() == 0u ); #else EXPECT( std::equal( v.begin(), v.end(), il.begin() ) ); #endif } SECTION("non-empty initializer list") { auto il = { 1, 2, 3, 4, 5, }; span<int const> v( il ); EXPECT( std::equal( v.begin(), v.end(), il.begin() ) ); }} #else EXPECT( !!"constrained construction from container is not available" ); #endif #else EXPECT( !!"std::initializer_list<> is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from a std::initializer_list<> as a constant set of values (C++11, p2447)" ) { #if span_HAVE( INITIALIZER_LIST ) #if span_NONSTD_AND( span_FEATURE( WITH_INITIALIZER_LIST_P2447 ) ) SETUP("") { SECTION("empty initializer list") { std::initializer_list<int const> il = {}; auto f = [&]( span<const int> spn ) { #if span_BETWEEN( span_COMPILER_MSVC_VERSION, 120, 130 ) EXPECT( spn.size() == 0u ); #else EXPECT( std::equal( spn.begin(), spn.end(), il.begin() ) ); #endif }; f({}); } SECTION("non-empty initializer list") { auto il = { 1, 2, 3, 4, 5, }; auto f = [&]( span<const int> spn ) { EXPECT( std::equal( spn.begin(), spn.end(), il.begin() ) ); }; f({ 1, 2, 3, 4, 5, }); }} #else EXPECT( !!"construction from std::initializer_list is not available (span_FEATURE_WITH_INITIALIZER_LIST_P2447, or using std::span)" ); #endif #else EXPECT( !!"std::initializer_list<> is not available, or std::span<> (no C++11)" ); #endif } CASE( "span<>: Allows to construct from a std::array<> (C++11)" ) { #if span_STD_OR( span_HAVE( ARRAY ) ) std::array<int,9> arr = {{ 1, 2, 3, 4, 5, 6, 7, 8, 9, }}; span< int> v( arr ); span<const int> w( arr ); EXPECT( std::equal( v.begin(), v.end(), arr.begin() ) ); EXPECT( std::equal( w.begin(), w.end(), arr.begin() ) ); #else EXPECT( !!"std::array<> is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from a std::array via a deduction guide (C++17)" ) { #if span_STD_OR( span_HAVE( DEDUCTION_GUIDES ) ) && !span_BETWEEN( _MSC_VER, 1, 1920 ) std::array<int,9> arr = {{ 1, 2, 3, 4, 5, 6, 7, 8, 9, }}; span v( arr ); EXPECT( std::equal( v.begin(), v.end(), arr.begin() ) ); #else EXPECT( !!"deduction guide is not available (no C++17)" ); #endif } CASE( "span<>: Allows to construct from a std::array<> with const data (C++11, span_FEATURE_CONSTR..._ELEMENT_TYPE=1)" ) { #if span_FEATURE( CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE ) # if span_HAVE( ARRAY ) std::array<const int,9> arr = {{ 1, 2, 3, 4, 5, 6, 7, 8, 9, }}; span<const int> v( arr ); span<const int> const w( arr ); EXPECT( std::equal( v.begin(), v.end(), arr.begin() ) ); EXPECT( std::equal( w.begin(), w.end(), arr.begin() ) ); # else EXPECT( !!"std::array<> is not available (no C++11)" ); # endif #else EXPECT( !!"construction is not available (span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE=0)" ); #endif } CASE( "span<>: Allows to construct from an empty std::array<> (C++11)" ) { #if span_STD_OR( span_HAVE( ARRAY ) ) std::array<int,0> arr; span< int> v( arr ); span<const int> w( arr ); EXPECT( std::equal( v.begin(), v.end(), arr.begin() ) ); EXPECT( std::equal( w.begin(), w.end(), arr.begin() ) ); #else EXPECT( !!"std::array<> is not available (no C++11)" ); #endif } CASE( "span<>: Allows to construct from a container (std::vector<>)" ) { #if span_STD_OR( span_HAVE( INITIALIZER_LIST ) ) std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; #else int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; std::vector<int> vec( arr, &arr[0] + DIMENSION_OF(arr) ); #endif #if span_STD_OR( span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) ) span< int> v( vec ); span<const int> w( vec ); EXPECT( std::equal( v.begin(), v.end(), vec.begin() ) ); EXPECT( std::equal( w.begin(), w.end(), vec.begin() ) ); #else EXPECT( !!"constrained construction from container is not available" ); #endif } CASE( "span<>: Allows to construct from a container via a deduction guide (std::vector<>, C++17)" ) { #if span_STD_OR( span_HAVE( DEDUCTION_GUIDES ) ) && !span_BETWEEN( _MSC_VER, 1, 1920 ) std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span v( vec ); EXPECT( std::equal( v.begin(), v.end(), vec.begin() ) ); #else EXPECT( !!"deduction guide is not available (no C++17)" ); #endif } CASE( "span<>: Allows to tag-construct from a container (std::vector<>)" ) { #if span_NONSTD_AND( span_FEATURE_TO_STD( WITH_CONTAINER ) ) # if span_HAVE( INITIALIZER_LIST ) std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; # else int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; std::vector<int> vec( arr, &arr[0] + DIMENSION_OF(arr) ); # endif span< int> v( with_container, vec ); span<const int> w( with_container, vec ); EXPECT( std::equal( v.begin(), v.end(), vec.begin() ) ); EXPECT( std::equal( w.begin(), w.end(), vec.begin() ) ); #else EXPECT( !!"with_container is not available (span_FEATURE_WITH_CONTAINER_TO_STD, or using std::span)" ); #endif } CASE( "span<>: Allows to tag-construct from a const container (std::vector<>)" ) { #if span_NONSTD_AND( span_FEATURE_TO_STD( WITH_CONTAINER ) ) # if span_HAVE( INITIALIZER_LIST ) const std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; # else const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; const std::vector<int> vec( arr, &arr[0] + DIMENSION_OF(arr) ); # endif span< int> v( with_container, vec ); span<const int> w( with_container, vec ); EXPECT( std::equal( v.begin(), v.end(), vec.begin() ) ); EXPECT( std::equal( w.begin(), w.end(), vec.begin() ) ); #else EXPECT( !!"with_container is not available (span_FEATURE_WITH_CONTAINER_TO_STD, or using std::span)" ); #endif } CASE( "span<>: Allows to copy-construct from another span of the same type" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< int> v( arr ); span<const int> w( arr ); span< int> x( v ); span<const int> y( w ); EXPECT( std::equal( x.begin(), x.end(), &arr[0] ) ); EXPECT( std::equal( y.begin(), y.end(), &arr[0] ) ); } CASE( "span<>: Allows to copy-construct from another span of a compatible type" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< int> v( arr ); span<const int> w( arr ); span<const volatile int> x( v ); span<const volatile int> y( v ); #ifndef _LIBCPP_VERSION EXPECT( std::equal( x.begin(), x.end(), &arr[0] ) ); EXPECT( std::equal( y.begin(), y.end(), &arr[0] ) ); #else for(size_t i = 0; i < x.size(); ++i) EXPECT(x[i] == arr[i]); for(size_t i = 0; i < y.size(); ++i) EXPECT(y[i] == arr[i]); #endif } CASE( "span<>: Allows to copy-construct from a temporary span of the same type (C++11)" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< int> v(( span< int>( arr ) )); // span< int> w(( span<const int>( arr ) )); span<const int> x(( span< int>( arr ) )); span<const int> y(( span<const int>( arr ) )); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); EXPECT( std::equal( x.begin(), x.end(), &arr[0] ) ); EXPECT( std::equal( y.begin(), y.end(), &arr[0] ) ); } CASE( "span<>: Allows to copy-assign from another span of the same type" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< int> v( arr ); span< int> s; span<const int> t; s = v; t = v; EXPECT( std::equal( s.begin(), s.end(), &arr[0] ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] ) ); } CASE( "span<>: Allows to copy-assign from a temporary span of the same type (C++11)" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< int> v; span<const int> w; v = span<int>( arr ); w = span<int>( arr ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); EXPECT( std::equal( w.begin(), w.end(), &arr[0] ) ); } CASE( "span<>: Allows to create a sub span of the first n elements" ) { int arr[] = { 1, 2, 3, 4, 5, }; span<int> v( arr ); size_type count = 3; span< int> s = v.first( count ); span<const int> t = v.first( count ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] ) ); } CASE( "span<>: Allows to create a sub span of the last n elements" ) { int arr[] = { 1, 2, 3, 4, 5, }; span<int> v( arr ); size_type count = 3; span< int> s = v.last( count ); span<const int> t = v.last( count ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + v.size() - count ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + v.size() - count ) ); } CASE( "span<>: Allows to create a sub span starting at a given offset" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); size_type offset = 1; span< int> s = v.subspan( offset ); span<const int> t = v.subspan( offset ); EXPECT( s.size() == v.size() - offset ); EXPECT( t.size() == v.size() - offset ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + offset ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + offset ) ); } CASE( "span<>: Allows to create a sub span starting at a given offset with a given length" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); size_type offset = 1; size_type length = 1; span< int> s = v.subspan( offset, length ); span<const int> t = v.subspan( offset, length ); EXPECT( s.size() == length ); EXPECT( t.size() == length ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + offset ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + offset ) ); } //CASE( "span<>: Allows to create an empty sub span at full offset" ) //{ // int arr[] = { 1, 2, 3, }; // span<int> v( arr ); // size_type offset = v.size() - 1; // // span< int> s = v.subspan( offset ); // span<const int> t = v.subspan( offset ); // // EXPECT( s.empty() ); // EXPECT( t.empty() ); //} //CASE( "span<>: Allows to create an empty sub span at full offset with zero length" ) //{ // int arr[] = { 1, 2, 3, }; // span<int> v( arr ); // size_type offset = v.size(); // size_type length = 0; // // span< int> s = v.subspan( offset, length ); // span<const int> t = v.subspan( offset, length ); // // EXPECT( s.empty() ); // EXPECT( t.empty() ); //} CASE( "span<>: Allows to observe an element via array indexing" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); for ( size_type i = 0; i < v.size(); ++i ) { EXPECT( v[i] == arr[i] ); EXPECT( w[i] == arr[i] ); } } CASE( "span<>: Allows to observe an element via call indexing" ) { #if span_NONSTD_AND( span_FEATURE( MEMBER_CALL_OPERATOR ) ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); for ( size_type i = 0; i < v.size(); ++i ) { EXPECT( v(i) == arr[i] ); EXPECT( w(i) == arr[i] ); } #else EXPECT( !!"member () is not available (span_FEATURE_MEMBER_CALL_OPERATOR=0, or using std::span)" ); #endif } CASE( "span<>: Allows to observe an element via at() [span_FEATURE_MEMBER_AT>0]" ) { #if span_NONSTD_AND( span_FEATURE( MEMBER_AT ) ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); for ( size_type i = 0; i < v.size(); ++i ) { EXPECT( v.at(i) == arr[i] ); EXPECT( w.at(i) == arr[i] ); } #else EXPECT( !!"member at() is not available (span_FEATURE_MEMBER_AT=0, or using std::span)" ); #endif } CASE( "span<>: Allows to observe an element via data()" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); EXPECT( *v.data() == *v.begin() ); EXPECT( *w.data() == *v.begin() ); for ( size_type i = 0; i < v.size(); ++i ) { EXPECT( v.data()[i] == arr[i] ); EXPECT( w.data()[i] == arr[i] ); } } CASE( "span<>: Allows to observe the first element via front() [span_FEATURE_MEMBER_BACK_FRONT=1]" ) { #if span_NONSTD_AND( span_FEATURE( MEMBER_BACK_FRONT ) ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); EXPECT( v.front() == 1 ); #else EXPECT( !!"front() is not available (span_FEATURE_MEMBER_BACK_FRONT undefined or 0)" ); #endif } CASE( "span<>: Allows to observe the last element via back() [span_FEATURE_MEMBER_BACK_FRONT=1]" ) { #if span_FEATURE( MEMBER_BACK_FRONT ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); EXPECT( v.back() == 3 ); #else EXPECT( !!"back()is not available (span_FEATURE_MEMBER_BACK_FRONT undefined or 0)" ); #endif } CASE( "span<>: Allows to change an element via array indexing" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); v[1] = 22; w[2] = 33; EXPECT( 22 == arr[1] ); EXPECT( 33 == arr[2] ); } CASE( "span<>: Allows to change an element via call indexing" ) { #if span_NONSTD_AND( span_FEATURE( MEMBER_CALL_OPERATOR ) ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); v(1) = 22; w(2) = 33; EXPECT( 22 == arr[1] ); EXPECT( 33 == arr[2] ); #else EXPECT( !!"member () is not available (span_FEATURE_MEMBER_CALL_OPERATOR=0, or using std::span)" ); #endif } CASE( "span<>: Allows to change an element via at() [span_FEATURE_MEMBER_AT>0]" ) { #if span_NONSTD_AND( span_FEATURE( MEMBER_AT ) ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); v.at(1) = 22; w.at(2) = 33; EXPECT( 22 == arr[1] ); EXPECT( 33 == arr[2] ); #else EXPECT( !!"member at() is not available (span_FEATURE_MEMBER_AT=0, or using std::span)" ); #endif } CASE( "span<>: Allows to change an element via data()" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); span<int> const w( arr ); *v.data() = 22; EXPECT( 22 == *v.data() ); *w.data() = 33; EXPECT( 33 == *w.data() ); } CASE( "span<>: Allows to change the first element via front() [span_FEATURE_MEMBER_BACK_FRONT=1]" ) { #if span_FEATURE( MEMBER_BACK_FRONT ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); v.front() = 42; EXPECT( v.front() == 42 ); #else EXPECT( !!"front() is not available (span_FEATURE_MEMBER_BACK_FRONT undefined or 0)" ); #endif } CASE( "span<>: Allows to change the last element via back() [span_FEATURE_MEMBER_BACK_FRONT=1]" ) { #if span_FEATURE( MEMBER_BACK_FRONT ) int arr[] = { 1, 2, 3, }; span<int> v( arr ); v.back() = 42; EXPECT( v.back() == 42 ); #else EXPECT( !!"back()is not available (span_FEATURE_MEMBER_BACK_FRONT undefined or 0)" ); #endif } CASE( "span<>: Allows to swap with another span [span_FEATURE_MEMBER_SWAP=1]" ) { #if span_NONSTD_AND( span_FEATURE( MEMBER_SWAP ) ) int arr[] = { 1, 2, 3, }; span<int> a( arr ); span<int> b = a.subspan( 1 ); a.swap( b ); EXPECT( a.size() == size_type(2) ); EXPECT( b.size() == size_type(3) ); EXPECT( a[0] == 2 ); EXPECT( b[0] == 1 ); #else EXPECT( !!"swap()is not available (span_FEATURE_MEMBER_SWAP undefined or 0, or using std::span)" ); #endif } CASE( "span<>: Allows forward iteration" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); for ( span<int>::iterator pos = v.begin(); pos != v.end(); ++pos ) { EXPECT( *pos == arr[ std::distance( v.begin(), pos )] ); } } CASE( "span<>: Allows const forward iteration" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); #if span_USES_STD_SPAN for ( auto pos = std::cbegin(v); pos != std::cend(v); ++pos ) { EXPECT( *pos == arr[ std::distance( std::cbegin(v), pos )] ); } #else for ( span<int>::const_iterator pos = v.cbegin(); pos != v.cend(); ++pos ) { EXPECT( *pos == arr[ std::distance( v.cbegin(), pos )] ); } #endif } CASE( "span<>: Allows reverse iteration" ) { int arr[] = { 1, 2, 3, }; span<int> v( arr ); for ( span<int>::reverse_iterator pos = v.rbegin(); pos != v.rend(); ++pos ) { // size_t dist = narrow<size_t>( std::distance(v.rbegin(), pos) ); size_type dist = static_cast<size_type>( std::distance(v.rbegin(), pos) ); EXPECT( *pos == arr[ v.size() - 1 - dist ] ); } } CASE( "span<>: Allows const reverse iteration" ) { int arr[] = { 1, 2, 3, }; const span<int> v( arr ); #if span_USES_STD_SPAN for ( auto pos = std::crbegin(v); pos != std::crend(v); ++pos ) { // size_t dist = narrow<size_t>( std::distance(v.crbegin(), pos) ); size_type dist = static_cast<size_type>( std::distance(std::crbegin(v), pos) ); EXPECT( *pos == arr[ v.size() - 1 - dist ] ); } #else for ( span<int>::const_reverse_iterator pos = v.crbegin(); pos != v.crend(); ++pos ) { // size_t dist = narrow<size_t>( std::distance(v.crbegin(), pos) ); size_type dist = static_cast<size_type>( std::distance(v.crbegin(), pos) ); EXPECT( *pos == arr[ v.size() - 1 - dist ] ); } #endif } CASE( "span<>: Allows to identify if a span is the same as another span [span_FEATURE_SAME=1]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON ) ) #if span_FEATURE( SAME ) int a[] = { 1 }, b[] = { 1 }, c[] = { 1, 2 }; char x[] = { '\x1' }; span<int > va( a ); span<int > vb( b ); span<int > vc( c ); span<char> vx( x ); span<unsigned char> vu( reinterpret_cast<unsigned char*>( &x[0] ), 1 ); EXPECT( same( va, va ) ); EXPECT_NOT( same( vb, va ) ); EXPECT_NOT( same( vc, va ) ); EXPECT_NOT( same( vx, va ) ); EXPECT_NOT( same( vx, vu ) ); EXPECT( va == va ); EXPECT( vb == va ); EXPECT_NOT( vc == va ); EXPECT( vx == va ); EXPECT( vx == vu ); #else EXPECT( !!"same() is not available (span_FEATURE_SAME=0)" ); #endif #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0, or using std::span)" ); #endif } CASE( "span<>: Allows to compare equal to another span of the same type [span_FEATURE_COMPARISON=1]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON ) ) int a[] = { 1 }, b[] = { 1 }, c[] = { 2 }, d[] = { 1, 2 }; span<int> va( a ); span<int> vb( b ); span<int> vc( c ); span<int> vd( d ); EXPECT( va == va ); EXPECT( vb == va ); EXPECT_NOT( vc == va ); EXPECT_NOT( vd == va ); #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0)" ); #endif } CASE( "span<>: Allows to compare unequal to another span of the same type [span_FEATURE_COMPARISON=1]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON )) int a[] = { 1 }, b[] = { 1 }, c[] = { 2 }, d[] = { 1, 2 }; span<int> va( a ); span<int> vb( b ); span<int> vc( c ); span<int> vd( d ); EXPECT_NOT( va != va ); EXPECT_NOT( vb != va ); EXPECT( vc != va ); EXPECT( vd != va ); #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0)" ); #endif } CASE( "span<>: Allows to compare less than another span of the same type [span_FEATURE_COMPARISON=1]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON )) int a[] = { 1 }, b[] = { 2 }, c[] = { 1, 2 }; span<int> va( a ); span<int> vb( b ); span<int> vc( c ); EXPECT_NOT( va < va ); EXPECT( va < vb ); EXPECT( va < vc ); #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0)" ); #endif } CASE( "span<>: Allows to compare less than or equal to another span of the same type [span_FEATURE_COMPARISON=1]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON )) int a[] = { 1 }, b[] = { 2 }, c[] = { 1, 2 }; span<int> va( a ); span<int> vb( b ); span<int> vc( c ); EXPECT_NOT( vb <= va ); EXPECT( va <= vb ); EXPECT( va <= vc ); #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0)" ); #endif } CASE( "span<>: Allows to compare greater than another span of the same type [span_FEATURE_COMPARISON=1]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON )) int a[] = { 1 }, b[] = { 2 }, c[] = { 1, 2 }; span<int> va( a ); span<int> vb( b ); span<int> vc( c ); EXPECT_NOT( va > va ); EXPECT( vb > va ); EXPECT( vc > va ); #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0)" ); #endif } CASE( "span<>: Allows to compare greater than or equal to another span of the same type [span_FEATURE_COMPARISON=1]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON )) int a[] = { 1 }, b[] = { 2 }, c[] = { 1, 2 }; span<int> va( a ); span<int> vb( b ); span<int> vc( c ); EXPECT_NOT( va >= vb ); EXPECT( vb >= va ); EXPECT( vc >= va ); #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0)" ); #endif } CASE( "span<>: Allows to compare to another span of the same type and different cv-ness [span_FEATURE_SAME=0]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON )) #if span_FEATURE( SAME ) EXPECT( !!"skipped as same() is provided via span_FEATURE_SAME=1" ); #else int aa[] = { 1 }, bb[] = { 2 }; span< int> a( aa ); span< const int> ca( aa ); span<volatile int> va( aa ); span< int> b( bb ); span< const int> cb( bb ); EXPECT( va == ca ); EXPECT( a == va ); EXPECT( a == ca ); EXPECT( a != cb ); EXPECT( a <= cb ); EXPECT( a < cb ); EXPECT( b >= ca ); EXPECT( b > ca ); #endif #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0)" ); #endif } CASE( "span<>: Allows to compare empty spans as equal [span_FEATURE_COMPARISON=1]" ) { #if span_NONSTD_AND( span_FEATURE( COMPARISON )) int a; span<int> p; span<int> q; span<int> r( &a, size_type( 0 ) ); EXPECT( p == q ); EXPECT( p == r ); #if span_STD_OR( span_HAVE( NULLPTR ) ) span<int> s( nullptr, size_type( 0 ) ); span<int> t( nullptr, size_type( 0 ) ); EXPECT( s == p ); EXPECT( s == r ); EXPECT( s == t ); #endif #else EXPECT( !!"comparison is not available (span_FEATURE_COMPARISON=0)" ); #endif } CASE( "span<>: Allows to test for empty span via empty(), empty case" ) { span<int> v; EXPECT( v.empty() ); } CASE( "span<>: Allows to test for empty span via empty(), non-empty case" ) { int a[] = { 1 }; span<int> v( a ); EXPECT_NOT( v.empty() ); } CASE( "span<>: Allows to obtain the number of elements via size()" ) { int a[] = { 1, 2, 3, }; int b[] = { 1, 2, 3, 4, 5, }; span<int> z; span<int> va( a ); span<int> vb( b ); EXPECT( va.size() == size_type( DIMENSION_OF( a ) ) ); EXPECT( vb.size() == size_type( DIMENSION_OF( b ) ) ); EXPECT( z.size() == size_type( 0 ) ); } CASE( "span<>: Allows to obtain the number of elements via ssize()" ) { #if !span_USES_STD_SPAN int a[] = { 1, 2, 3, }; int b[] = { 1, 2, 3, 4, 5, }; span<int> z; span<int> va( a ); span<int> vb( b ); EXPECT( va.ssize() == ssize_type( DIMENSION_OF( a ) ) ); EXPECT( vb.ssize() == ssize_type( DIMENSION_OF( b ) ) ); EXPECT( z.ssize() == 0 ); #else EXPECT( !!"member ssize() is not available (using std::span)" ); #endif } CASE( "span<>: Allows to obtain the number of bytes via size_bytes()" ) { int a[] = { 1, 2, 3, }; int b[] = { 1, 2, 3, 4, 5, }; span<int> z; span<int> va( a ); span<int> vb( b ); EXPECT( va.size_bytes() == size_type( DIMENSION_OF( a ) * sizeof(int) ) ); EXPECT( vb.size_bytes() == size_type( DIMENSION_OF( b ) * sizeof(int) ) ); EXPECT( z.size_bytes() == size_type( 0 * sizeof(int) ) ); } //CASE( "span<>: Allows to swap with another span of the same type" ) //{ // int a[] = { 1, 2, 3, }; // int b[] = { 1, 2, 3, 4, 5, }; // // span<int> va0( a ); // span<int> vb0( b ); // span<int> va( a ); // span<int> vb( b ); // // va.swap( vb ); // // EXPECT( va == vb0 ); // EXPECT( vb == va0 ); //} #if span_STD_OR( span_HAVE( BYTE ) ) || span_HAVE( NONSTD_BYTE ) static bool is_little_endian() { union U { U() : i(1) {} int i; char c[ sizeof(int) ]; }; return 1 != U().c[ sizeof(int) - 1 ]; } #endif CASE( "span<>: Allows to view the elements as read-only bytes" ) { #if span_CPP11_OR_GREATER && ( span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) ) using byte = xstd::byte; using type = std::int32_t; EXPECT( sizeof( type ) == size_t( 4 ) ); type a[] = { 0x12345678, }; byte be[] = { byte{0x12}, byte{0x34}, byte{0x56}, byte{0x78}, }; byte le[] = { byte{0x78}, byte{0x56}, byte{0x34}, byte{0x12}, }; xstd::byte * b = is_little_endian() ? &le[0] : &be[0]; span<type> va( a ); span<const xstd::byte> vb( as_bytes( va ) ); EXPECT( vb[0] == b[0] ); EXPECT( vb[1] == b[1] ); EXPECT( vb[2] == b[2] ); EXPECT( vb[3] == b[3] ); #else EXPECT( !!"(non)std::byte is not available (no C++17, no byte-lite); test requires C++11" ); #endif } CASE( "span<>: Allows to view and change the elements as writable bytes" ) { #if span_CPP11_OR_GREATER && ( span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) ) using byte = xstd::byte; using type = std::int32_t; EXPECT( sizeof(type) == size_t( 4 ) ); type a[] = { 0x0, }; span<type> va( a ); span<byte> vb( as_writable_bytes(va) ); for ( size_type i = 0; i < size_type( sizeof(type) ); ++i ) { EXPECT( vb[i] == byte{0} ); } vb[0] = byte{0x42}; EXPECT( vb[0] == byte{0x42} ); for ( size_type i = 1; i < size_type( sizeof(type) ); ++i ) { EXPECT( vb[i] == byte{0} ); } #else EXPECT( !!"(non)std::byte is not available (no C++17, no byte-lite); test requires C++11" ); #endif } //CASE( "span<>: Allows to view the elements as a span of another type" ) //{ //#if span_STD_OR( span_HAVE( SIZED_TYPES ) ) // typedef int32_t type1; // typedef int16_t type2; //#else // typedef int type1; // typedef short type2; //#endif // EXPECT( sizeof( type1 ) == size_t( 4 ) ); // EXPECT( sizeof( type2 ) == size_t( 2 ) ); // // type1 a[] = { 0x12345678, }; // type2 be[] = { type2(0x1234), type2(0x5678), }; // type2 le[] = { type2(0x5678), type2(0x1234), }; // // type2 * b = is_little_endian() ? le : be; // // span<type1> va( a ); // span<type2> vb( va ); // // EXPECT( vb[0] == b[0] ); // EXPECT( vb[1] == b[1] ); //} //CASE( "span<>: Allows to change the elements from a span of another type" ) //{ //#if span_STD_OR( span_HAVE( SIZED_TYPES ) ) // typedef int32_t type1; // typedef int16_t type2; //#else // typedef int type1; // typedef short type2; //#endif // EXPECT( sizeof( type1 ) == size_t( 4 ) ); // EXPECT( sizeof( type2 ) == size_t( 2 ) ); // // type1 a[] = { 0x0, }; // // span<type1> va( a ); //#if span_COMPILER_MSVC_VERSION == 60 // span<type2> vb( va.as_span( type2() ) ); //#else // span<type2> vb( va.as_span<type2>() ); //#endif // // {for ( size_t i = 0; i < sizeof(type2); ++i ) EXPECT( vb[i] == type2(0) ); } // // vb[0] = 0x42; // // EXPECT( vb[0] == type2(0x42) ); // {for ( size_t i = 1; i < sizeof(type2); ++i ) EXPECT( vb[i] == type2(0) ); } //} #if span_FEATURE_TO_STD( MAKE_SPAN ) CASE( "make_span() [span_FEATURE_MAKE_SPAN_TO_STD=99]" ) { EXPECT( !!"(avoid warning)" ); // suppress: unused parameter 'lest_env' [-Wunused-parameter] } CASE( "make_span(): Allows building from two pointers" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<int> v = make_span( &arr[0], &arr[0] + DIMENSION_OF( arr ) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "make_span(): Allows building from two const pointers" ) { const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<const int> v = make_span( &arr[0], &arr[0] + DIMENSION_OF( arr ) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "make_span(): Allows building from a non-null pointer and a size" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<int> v = make_span( &arr[0], DIMENSION_OF( arr ) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "make_span(): Allows building from a non-null const pointer and a size" ) { const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<const int> v = make_span( &arr[0], DIMENSION_OF( arr ) ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "make_span(): Allows building from a C-array" ) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<int> v = make_span( arr ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "make_span(): Allows building from a const C-array" ) { const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<const int> v = make_span( arr ); EXPECT( std::equal( v.begin(), v.end(), &arr[0] ) ); } CASE( "make_span(): Allows building from a std::initializer_list<> (C++11)" ) { #if span_STD_OR( span_HAVE( INITIALIZER_LIST ) ) #if span_STD_OR( span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) ) auto il = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span<int const> v = make_span( il ); EXPECT( std::equal( v.begin(), v.end(), il.begin() ) ); #else EXPECT( !!"constrained construction from container is not available" ); #endif #else EXPECT( !!"std::initializer_list<> is not available (no C++11)" ); #endif } CASE( "make_span(): Allows building from a std::initializer_list<> as a constant set of values (C++11)" ) { #if span_STD_OR( span_HAVE( INITIALIZER_LIST ) ) SETUP("") { SECTION("empty initializer list") { std::initializer_list<int const> il = {}; auto f = [&]( span<const int> v ){ #if span_BETWEEN( span_COMPILER_MSVC_VERSION, 120, 130 ) EXPECT( v.size() == 0u ); #else EXPECT( std::equal( v.begin(), v.end(), il.begin() ) ); #endif }; // f( make_span({}) ); // element type unknown f( make_span<int>({}) ); } SECTION("non-empty initializer list") { auto il = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; auto f = [&]( span<const int> v ){ EXPECT( std::equal( v.begin(), v.end(), il.begin() ) ); }; f( make_span({ 1, 2, 3, 4, 5, 6, 7, 8, 9, }) ); }} #else EXPECT( !!"std::initializer_list<> is not available (no C++11)" ); #endif } CASE( "make_span(): Allows building from a std::array<> (C++11)" ) { #if span_STD_OR( span_HAVE( ARRAY ) ) std::array<int,9> arr = {{ 1, 2, 3, 4, 5, 6, 7, 8, 9, }}; span<int> v = make_span( arr ); EXPECT( std::equal( v.begin(), v.end(), arr.begin() ) ); #else EXPECT( !!"std::array<> is not available (no C++11)" ); #endif } CASE( "make_span(): Allows building from a const std::array<> (C++11)" ) { #if span_STD_OR( span_HAVE( ARRAY ) ) const std::array<int,9> arr = {{ 1, 2, 3, 4, 5, 6, 7, 8, 9, }}; span<const int> v = make_span( arr ); EXPECT( std::equal( v.begin(), v.end(), arr.begin() ) ); #else EXPECT( !!"std::array<> is not available (no C++11)" ); #endif } CASE( "make_span(): Allows building from a container (std::vector<>)" ) { #if span_STD_OR( span_HAVE( INITIALIZER_LIST ) ) std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; #else std::vector<int> vec; {for ( int i = 1; i < 10; ++i ) vec.push_back(i); } #endif span<int> v = make_span( vec ); EXPECT( std::equal( v.begin(), v.end(), vec.begin() ) ); } CASE( "make_span(): Allows building from a const container (std::vector<>)" ) { #if span_STD_OR( span_HAVE( INITIALIZER_LIST ) ) const std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; #else const std::vector<int> vec( 10, 42 ); #endif span<const int> v = make_span( vec ); EXPECT( std::equal( v.begin(), v.end(), vec.begin() ) ); } CASE( "make_span(): Allows building from a container (with_container_t, std::vector<>)" ) { #if span_NONSTD_AND( span_FEATURE_TO_STD( WITH_CONTAINER ) ) #if span_STD_OR( span_HAVE( INITIALIZER_LIST ) ) std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; #else std::vector<int> vec; {for ( int i = 1; i < 10; ++i ) vec.push_back(i); } #endif span<int> v = make_span( with_container, vec ); EXPECT( std::equal( v.begin(), v.end(), vec.begin() ) ); #else EXPECT( !!"make_span(with_container,...) is not available (span_PROVIDE_WITH_CONTAINER_TO_STD=0, or using std::span)" ); #endif } CASE( "make_span(): Allows building from a const container (with_container_t, std::vector<>)" ) { #if span_NONSTD_AND( span_FEATURE_TO_STD( WITH_CONTAINER ) ) #if span_STD_OR( span_HAVE( INITIALIZER_LIST ) ) const std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; #else const std::vector<int> vec( 10, 42 ); #endif span<const int> v = make_span( with_container, vec ); EXPECT( std::equal( v.begin(), v.end(), vec.begin() ) ); #else EXPECT( !!"make_span(with_container,...) is not available (span_PROVIDE_WITH_CONTAINER_TO_STD=0, or using std::span)" ); #endif } #endif // span_FEATURE_MAKE_SPAN #if span_FEATURE( BYTE_SPAN ) CASE( "byte_span() [span_FEATURE_BYTE_SPAN=1]" ) { EXPECT( !!"(avoid warning)" ); // suppress: unused parameter 'lest_env' [-Wunused-parameter] } CASE( "byte_span(): Allows building a span of std::byte from a single object (C++17, byte-lite)" ) { #if span_CPP11_OR_GREATER && ( span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) ) int x = (std::numeric_limits<int>::max)(); span<xstd::byte> spn = byte_span( x ); EXPECT( spn.size() == size_type( sizeof x ) ); #if span_STD_OR( span_HAVE( NONSTD_BYTE ) ) EXPECT( spn[0] == to_byte( 0xff ) ); #else EXPECT( spn[0] == xstd::byte( 0xff ) ); #endif #else EXPECT( !!"(non)std::byte is not available (no C++17, no byte-lite); test requires C++11" ); #endif } CASE( "byte_span(): Allows building a span of const std::byte from a single const object (C++17, byte-lite)" ) { #if span_CPP11_OR_GREATER && ( span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) ) const int x = (std::numeric_limits<int>::max)(); span<const xstd::byte> spn = byte_span( x ); EXPECT( spn.size() == size_type( sizeof x ) ); #if span_STD_OR( span_HAVE( NONSTD_BYTE ) ) EXPECT( spn[0] == to_byte( 0xff ) ); #else EXPECT( spn[0] == xstd::byte( 0xff ) ); #endif #else EXPECT( !!"(non)std::byte is not available (no C++17, no byte-lite); test requires C++11" ); #endif } #endif // span_FEATURE( BYTE_SPAN ) CASE( "first(), last(), subspan() [span_FEATURE_NON_MEMBER_FIRST_LAST_SUB=1]" ) { EXPECT( !!"(avoid warning)" ); // suppress: unused parameter 'lest_env' [-Wunused-parameter] } CASE( "first(): Allows to create a sub span of the first n elements (span, template parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) ) int arr[] = { 1, 2, 3, 4, 5, }; span<int> spn( arr ); const size_type count = 3; span< int, count> s = first<count>( spn ); span<const int, count> t = first<count>( spn ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] ) ); #else EXPECT( !!"first() is not available (NON_MEMBER_FIRST_LAST_SUB_SPAN=0, or using std::span)" ); #endif } CASE( "first(): Allows to create a sub span of the first n elements (span, function parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) ) int arr[] = { 1, 2, 3, 4, 5, }; span<int> spn( arr ); size_type count = 3; span< int> s = first( spn, count ); span<const int> t = first( spn, count ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] ) ); #else EXPECT( !!"first() is not available (NON_MEMBER_FIRST_LAST_SUB_SPAN=0, or using std::span)" ); #endif } CASE( "first(): Allows to create a sub span of the first n elements (compatible container, template parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) ) #if span_CPP11_120 int arr[] = { 1, 2, 3, 4, 5, }; std::vector<int> v( &arr[0], &arr[0] + DIMENSION_OF(arr) ); const size_type count = 3; span< int, count> s = first<count>( v ); span<const int, count> t = first<count>( v ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] ) ); #else EXPECT( !!"first() is not available (no C++11)" ); #endif #else EXPECT( !!"first() is not available (NON_MEMBER_FIRST_LAST_SUB_CONTAINER=0, or using std::span)" ); #endif } CASE( "first(): Allows to create a sub span of the first n elements (compatible container, function parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) ) #if span_CPP11_120 int arr[] = { 1, 2, 3, 4, 5, }; std::vector<int> v( &arr[0], &arr[0] + DIMENSION_OF(arr) ); size_type count = 3; span< int> s = first( v, count ); span<const int> t = first( v, count ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] ) ); #else EXPECT( !!"first() is not available (no C++11)" ); #endif #else EXPECT( !!"first() is not available (NON_MEMBER_FIRST_LAST_SUB_CONTAINER=0, or using std::span)" ); #endif } CASE( "last(): Allows to create a sub span of the last n elements (span, template parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) ) int arr[] = { 1, 2, 3, 4, 5, }; span<int> spn( arr ); const size_type count = 3; span< int, count> s = last<count>( spn ); span<const int, count> t = last<count>( spn ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + spn.size() - count ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + spn.size() - count ) ); #else EXPECT( !!"last() is not available (NON_MEMBER_FIRST_LAST_SUB_SPAN=0, or using std::span)" ); #endif } CASE( "last(): Allows to create a sub span of the last n elements (span, function parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) ) int arr[] = { 1, 2, 3, 4, 5, }; span<int> spn( arr ); size_type count = 3; span< int> s = last( spn, count ); span<const int> t = last( spn, count ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + spn.size() - count ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + spn.size() - count ) ); #else EXPECT( !!"last() is not available (NON_MEMBER_FIRST_LAST_SUB_SPAN=0, or using std::span)" ); #endif } CASE( "last(): Allows to create a sub span of the last n elements (compatible container, template parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) ) #if span_CPP11_120 int arr[] = { 1, 2, 3, 4, 5, }; std::vector<int> v( &arr[0], &arr[0] + DIMENSION_OF(arr) ); const size_type count = 3; span< int, count> s = last<count>( v ); span<const int, count> t = last<count>( v ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + v.size() - count ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + v.size() - count ) ); #else EXPECT( !!"last() is not available (no C++11)" ); #endif #else EXPECT( !!"last() is not available (NON_MEMBER_FIRST_LAST_SUB_CONTAINER=0, or using std::span)" ); #endif } CASE( "last(): Allows to create a sub span of the last n elements (compatible container, function parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) ) #if span_CPP11_120 int arr[] = { 1, 2, 3, 4, 5, }; std::vector<int> v( &arr[0], &arr[0] + DIMENSION_OF(arr) ); size_type count = 3; span< int> s = last( v, count ); span<const int> t = last( v, count ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + v.size() - count ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + v.size() - count ) ); #else EXPECT( !!"last() is not available (no C++11)" ); #endif #else EXPECT( !!"last() is not available (NON_MEMBER_FIRST_LAST_SUB_CONTAINER=0, or using std::span)" ); #endif } CASE( "subspan(): Allows to create a sub span starting at a given offset (span, template parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) ) int arr[] = { 1, 2, 3, }; span<int> spn( arr ); const size_type offset = 1; const size_type count = DIMENSION_OF(arr) - offset; span< int, count> s = subspan<offset, count>( spn ); span<const int, count> t = subspan<offset, count>( spn ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + offset ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + offset ) ); #else EXPECT( !!"subspan() is not available (NON_MEMBER_FIRST_LAST_SUB_SPAN=0, or using std::span)" ); #endif } CASE( "subspan(): Allows to create a sub span starting at a given offset (span, function parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) ) int arr[] = { 1, 2, 3, }; span<int> spn( arr ); size_type offset = 1; span< int> s = subspan( spn, offset ); span<const int> t = subspan( spn, offset ); EXPECT( s.size() == spn.size() - offset ); EXPECT( t.size() == spn.size() - offset ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + offset ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + offset ) ); #else EXPECT( !!"subspan() is not available (NON_MEMBER_FIRST_LAST_SUB_SPAN=0, or using std::span)" ); #endif } CASE( "subspan(): Allows to create a sub span starting at a given offset (compatible container, template parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) ) #if span_CPP11_120 int arr[] = { 1, 2, 3, }; std::vector<int> v( &arr[0], &arr[0] + DIMENSION_OF(arr) ); const size_type offset = 1; const size_type count = DIMENSION_OF(arr) - offset; span< int, count> s = subspan<offset, count>( v ); span<const int, count> t = subspan<offset, count>( v ); EXPECT( s.size() == count ); EXPECT( t.size() == count ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + offset ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + offset ) ); #else EXPECT( !!"subspan() is not available (no C++11)" ); #endif #else EXPECT( !!"subspan() is not available (NON_MEMBER_FIRST_LAST_SUB_CONTAINER=0, or using std::span)" ); #endif } CASE( "subspan(): Allows to create a sub span starting at a given offset (compatible container, function parameter)" ) { #if span_NONSTD_AND( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) ) #if span_CPP11_120 int arr[] = { 1, 2, 3, }; std::vector<int> v( &arr[0], &arr[0] + DIMENSION_OF(arr) ); size_type offset = 1; span< int> s = subspan( v, offset ); span<const int> t = subspan( v, offset ); EXPECT( s.size() == v.size() - offset ); EXPECT( t.size() == v.size() - offset ); EXPECT( std::equal( s.begin(), s.end(), &arr[0] + offset ) ); EXPECT( std::equal( t.begin(), t.end(), &arr[0] + offset ) ); #else EXPECT( !!"subspan() is not available (no C++11)" ); #endif #else EXPECT( !!"subspan() is not available (NON_MEMBER_FIRST_LAST_SUB_CONTAINER=0, or using std::span)" ); #endif } CASE( "size(): Allows to obtain the number of elements via size()" ) { int a[] = { 1, 2, 3, }; int b[] = { 1, 2, 3, 4, 5, }; span<int> z; span<int> va( a ); span<int> vb( b ); EXPECT( size( va ) == DIMENSION_OF( a ) ); EXPECT( size( vb ) == DIMENSION_OF( b ) ); EXPECT( size( z ) == size_t( 0 ) ); } CASE( "ssize(): Allows to obtain the number of elements via ssize()" ) { int a[] = { 1, 2, 3, }; int b[] = { 1, 2, 3, 4, 5, }; span<int> z; span<int> va( a ); span<int> vb( b ); EXPECT( ssize( va ) == ssize_type( DIMENSION_OF( a ) ) ); EXPECT( ssize( vb ) == ssize_type( DIMENSION_OF( b ) ) ); EXPECT( ssize( z ) == 0 ); } CASE( "tuple_size<>: Allows to obtain the number of elements via std::tuple_size<> (C++11)" ) { #if span_NONSTD_AND( span_HAVE( STRUCT_BINDING ) ) const auto N = 3u; using T = span<int, N>; int a[N] = { 1, 2, 3, }; T v( a ); EXPECT( ssize( v ) == N ); EXPECT( std::tuple_size< T >::value == N ); static_assert( std::tuple_size< T >::value == N, "std::tuple_size< span<> > fails" ); #else EXPECT( !!"std::tuple_size<> is not available (no C++11)" ); #endif } CASE( "tuple_element<>: Allows to obtain an element via std::tuple_element<> (C++11)" ) { #if span_NONSTD_AND( span_HAVE( STRUCT_BINDING ) ) using S = span<int,3>; using T = std::tuple_element<0, S>::type; EXPECT( (std::is_same<T, int>::value) ); static_assert( std::is_same<T, int>::value, "std::tuple_element<0, S>::type fails" ); #else EXPECT( !!"std::tuple_element<> is not available (no C++11)" ); #endif } CASE( "tuple_element<>: Allows to obtain an element via std::tuple_element_t<> (C++11)" ) { #if span_NONSTD_AND( span_HAVE( STRUCT_BINDING ) ) && span_CPP11_140 using S = span<int,3>; using T = std::tuple_element_t<0, S>; EXPECT( (std::is_same<T, int>::value) ); static_assert( std::is_same<T, int>::value, "std::tuple_element_t<0, S> fails" ); #else EXPECT( !!"std::tuple_element<> is not available (no C++11)" ); #endif } CASE( "get<I>(spn): Allows to access an element via std::get<>()" ) { #if span_NONSTD_AND( span_HAVE( STRUCT_BINDING ) ) SETUP("") { const auto N = 3u; using T = span<int, N>; using U = span<const int, N>; int a[N] = { 1, 2, 3, }; const int b[N] = { 1, 2, 3, }; T vna( a ); U vnb( b ); const T vca( a ); const U vcb( b ); SECTION("lvalue") { EXPECT( std::get< 1 >( vna ) == a[1] ); EXPECT( std::get< 1 >( vnb ) == a[1] ); EXPECT( std::get< 1 >( vca ) == a[1] ); EXPECT( std::get< 1 >( vcb ) == a[1] ); std::get< 1 >( vna ) = 7; // std::get< 1 >( vca ) = 7; // read-only EXPECT( std::get< 1 >( vna ) == 7 ); // static_assert( std::get< 1 >( vc ) == 2, "std::tuple_element<I>(spn) fails" ); } SECTION("rvalue") { EXPECT( std::get< 1 >( std::move(vna) ) == 2 ); EXPECT( std::get< 1 >( std::move(vnb) ) == 2 ); EXPECT( std::get< 1 >( std::move(vca) ) == 2 ); EXPECT( std::get< 1 >( std::move(vcb) ) == 2 ); }} #else EXPECT( !!"std::get<>(spn) is not available (no C++11)" ); #endif } // Issues #include <cassert> CASE( "[hide][issue-3: heterogeneous comparison]" ) { #if span_NONSTD_AND( span_FEATURE_TO_STD( MAKE_SPAN ) ) #if span_FEATURE( COMPARISON ) static const int data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; span< const int > spn( data ); EXPECT( !!"(avoid warning)" ); // suppress: unused parameter 'lest_env' [-Wunused-parameter] assert( make_span( data ) == make_span(data) ); // Ok, non-heterogeneous comparison assert( make_span( data ) == spn ); // Compile error: comparing fixed with dynamic extension #else EXPECT( !!"test is unavailable as comparison of span is not provided via span_FEATURE_COMPARISON=1" ); #endif // span_FEATURE( COMPARISON ) #else EXPECT( !!"test is unavailable as make_span() is not provided via span_FEATURE_MAKE_SPAN_TO_STD=99" ); #endif // span_FEATURE_TO_STD( MAKE_SPAN ) } CASE( "[hide][issue-3: same()]" ) { #if span_NONSTD_AND( span_FEATURE_TO_STD( MAKE_SPAN ) ) #if span_FEATURE( SAME ) EXPECT( !!"(avoid warning)" ); // suppress: unused parameter 'lest_env' [-Wunused-parameter] typedef unsigned char uint8_type; static uint8_type const data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; static float const farray[4] = { 0, 1, 2, 3 }; span<float const> fspan1 = make_span( farray ); assert( fspan1.data() == farray ); assert( fspan1.size() == static_cast<size_type>( DIMENSION_OF( farray ) ) ); #if span_STD_OR( span_HAVE( BYTE ) ) span<std::byte const> fspan2 = byte_span( farray[0] ); assert( static_cast<void const *>( fspan1.data() ) == fspan2.data() ); assert( fspan1.size() == fspan2.size() ); assert( ! same( fspan1 , fspan2 ) ); # endif span<uint8_type const> bspan4 = make_span( &data[0], 4 ); assert( bspan4 == fspan1 ); assert( fspan1 == bspan4 ); assert( !same( fspan1 , bspan4 ) ); #if span_STD_OR( span_HAVE( BYTE ) ) assert( as_bytes( fspan1 ) != as_bytes( bspan4 ) ); assert( !same( as_bytes( fspan1 ) , as_bytes( bspan4 ) ) ); #endif union { int i; float f; char c; } u = { 0x12345678 }; span<int > uspan1 = make_span( &u.i, 1 ); span<float> uspan2 = make_span( &u.f, 1 ); span<char > uspan3 = make_span( &u.c, 1 ); assert( static_cast<void const *>( uspan1.data() ) == uspan2.data() ); assert( uspan1.size() == uspan2.size() ); assert( static_cast<void const *>( uspan1.data() ) == uspan3.data() ); assert( uspan1.size() == uspan3.size() ); assert( !same( uspan1, uspan2 ) ); assert( !same( uspan1, uspan3 ) ); assert( !same( uspan2, uspan3 ) ); assert( uspan1 != uspan2 ); assert( uspan1 != uspan3 ); assert( uspan2 != uspan3 ); #if span_STD_OR( span_HAVE( BYTE ) ) assert( same( as_bytes( uspan1 ), as_bytes( uspan2 ) ) ); assert( !same( as_bytes( uspan1 ), as_bytes( uspan3 ) ) ); assert( !same( as_bytes( uspan2 ), as_bytes( uspan3 ) ) ); #endif #else EXPECT( !!"same() is not provided via span_FEATURE_SAME=1" ); #endif // span_FEATURE( SAME ) #else EXPECT( !!"test is unavailable as make_span is not provided via span_FEATURE_MAKE_SPAN_TO_STD=99" ); #endif // span_FEATURE_TO_STD( MAKE_SPAN ) } // issue #64 #if span_HAVE_ITERATOR_CTOR namespace issue64 { void fun(nonstd::span<unsigned>) {} void fun(nonstd::span<nonstd::span<unsigned> >) {} } #endif CASE( "[hide][issue-64: overly permissive constructor]" ) { #if span_HAVE_ITERATOR_CTOR using issue64::fun; unsigned u; fun( {&u, 1u} ); #else EXPECT( !!"construction from iterator is not available (no C++11)" ); #endif } CASE( "[hide][issue-69: constructor from iterators is not properly constrained]" ) { #if span_HAVE_ITERATOR_CTOR static_assert( std::is_constructible<nonstd::span<float>, int*, int*>::value == false, "span<float> should not be constructible from int" ); static_assert( std::is_constructible<nonstd::span<float const>, int*, int*>::value == false, "span<const float> should not be constructible from int" ); #else EXPECT( !!"construction from iterator is not available (no C++11)" ); #endif } CASE( "tweak header: reads tweak header if supported " "[tweak]" ) { #if span_HAVE( TWEAK_HEADER ) EXPECT( SPAN_TWEAK_VALUE == 42 ); #else EXPECT( !!"Tweak header is not available (span_HAVE_TWEAK_HEADER: 0)." ); #endif } // end of file