This library is a meme. STD invasion, GSL bloat, introduces GSL/Span conflicts, strict templates specifically for std types when such could be reduced to a generic type for further portablity, has generators we shouldn't need or are outright unsafe... Everyone, this is who writes your C++ books.

This commit is contained in:
Reece Wilson 2021-06-02 16:32:29 +01:00 committed by Reece
parent efc6744581
commit 47d09d4dc7
17 changed files with 45 additions and 19014 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,62 +0,0 @@
/*
* Created by Justin R. Wilson on 2/19/2017.
* Copyright 2017 Justin R. Wilson. All rights reserved.
*
* 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)
*/
#ifndef TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED
// Don't #include any Catch headers here - we can assume they are already
// included before this header.
// This is not good practice in general but is necessary in this case so this
// file can be distributed as a single header that works with the main
// Catch single header.
namespace Catch {
struct AutomakeReporter : StreamingReporterBase<AutomakeReporter> {
AutomakeReporter( ReporterConfig const& _config )
: StreamingReporterBase( _config )
{}
~AutomakeReporter() override;
static std::string getDescription() {
return "Reports test results in the format of Automake .trs files";
}
void assertionStarting( AssertionInfo const& ) override {}
bool assertionEnded( AssertionStats const& /*_assertionStats*/ ) override { return true; }
void testCaseEnded( TestCaseStats const& _testCaseStats ) override {
// Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR.
stream << ":test-result: ";
if (_testCaseStats.totals.assertions.allPassed()) {
stream << "PASS";
} else if (_testCaseStats.totals.assertions.allOk()) {
stream << "XFAIL";
} else {
stream << "FAIL";
}
stream << ' ' << _testCaseStats.testInfo.name << '\n';
StreamingReporterBase::testCaseEnded( _testCaseStats );
}
void skipTest( TestCaseInfo const& testInfo ) override {
stream << ":test-result: SKIP " << testInfo.name << '\n';
}
};
#ifdef CATCH_IMPL
AutomakeReporter::~AutomakeReporter() {}
#endif
CATCH_REGISTER_REPORTER( "automake", AutomakeReporter)
} // end namespace Catch
#endif // TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED

View File

@ -1,255 +0,0 @@
/*
* Created by Colton Wolkins on 2015-08-15.
* Copyright 2015 Martin Moene. All rights reserved.
*
* 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)
*/
#ifndef TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED
// Don't #include any Catch headers here - we can assume they are already
// included before this header.
// This is not good practice in general but is necessary in this case so this
// file can be distributed as a single header that works with the main
// Catch single header.
#include <algorithm>
namespace Catch {
struct TAPReporter : StreamingReporterBase<TAPReporter> {
using StreamingReporterBase::StreamingReporterBase;
~TAPReporter() override;
static std::string getDescription() {
return "Reports test results in TAP format, suitable for test harnesses";
}
ReporterPreferences getPreferences() const override {
ReporterPreferences prefs;
prefs.shouldRedirectStdOut = false;
return prefs;
}
void noMatchingTestCases( std::string const& spec ) override {
stream << "# No test cases matched '" << spec << "'" << std::endl;
}
void assertionStarting( AssertionInfo const& ) override {}
bool assertionEnded( AssertionStats const& _assertionStats ) override {
++counter;
AssertionPrinter printer( stream, _assertionStats, counter );
printer.print();
stream << " # " << currentTestCaseInfo->name ;
stream << std::endl;
return true;
}
void testRunEnded( TestRunStats const& _testRunStats ) override {
printTotals( _testRunStats.totals );
stream << "\n" << std::endl;
StreamingReporterBase::testRunEnded( _testRunStats );
}
private:
std::size_t counter = 0;
class AssertionPrinter {
public:
AssertionPrinter& operator= ( AssertionPrinter const& ) = delete;
AssertionPrinter( AssertionPrinter const& ) = delete;
AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter )
: stream( _stream )
, result( _stats.assertionResult )
, messages( _stats.infoMessages )
, itMessage( _stats.infoMessages.begin() )
, printInfoMessages( true )
, counter(_counter)
{}
void print() {
itMessage = messages.begin();
switch( result.getResultType() ) {
case ResultWas::Ok:
printResultType( passedString() );
printOriginalExpression();
printReconstructedExpression();
if ( ! result.hasExpression() )
printRemainingMessages( Colour::None );
else
printRemainingMessages();
break;
case ResultWas::ExpressionFailed:
if (result.isOk()) {
printResultType(passedString());
} else {
printResultType(failedString());
}
printOriginalExpression();
printReconstructedExpression();
if (result.isOk()) {
printIssue(" # TODO");
}
printRemainingMessages();
break;
case ResultWas::ThrewException:
printResultType( failedString() );
printIssue( "unexpected exception with message:" );
printMessage();
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::FatalErrorCondition:
printResultType( failedString() );
printIssue( "fatal error condition with message:" );
printMessage();
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::DidntThrowException:
printResultType( failedString() );
printIssue( "expected exception, got none" );
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::Info:
printResultType( "info" );
printMessage();
printRemainingMessages();
break;
case ResultWas::Warning:
printResultType( "warning" );
printMessage();
printRemainingMessages();
break;
case ResultWas::ExplicitFailure:
printResultType( failedString() );
printIssue( "explicitly" );
printRemainingMessages( Colour::None );
break;
// These cases are here to prevent compiler warnings
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
printResultType( "** internal error **" );
break;
}
}
private:
static Colour::Code dimColour() { return Colour::FileName; }
static const char* failedString() { return "not ok"; }
static const char* passedString() { return "ok"; }
void printSourceInfo() const {
Colour colourGuard( dimColour() );
stream << result.getSourceInfo() << ":";
}
void printResultType( std::string const& passOrFail ) const {
if( !passOrFail.empty() ) {
stream << passOrFail << ' ' << counter << " -";
}
}
void printIssue( std::string const& issue ) const {
stream << " " << issue;
}
void printExpressionWas() {
if( result.hasExpression() ) {
stream << ";";
{
Colour colour( dimColour() );
stream << " expression was:";
}
printOriginalExpression();
}
}
void printOriginalExpression() const {
if( result.hasExpression() ) {
stream << " " << result.getExpression();
}
}
void printReconstructedExpression() const {
if( result.hasExpandedExpression() ) {
{
Colour colour( dimColour() );
stream << " for: ";
}
std::string expr = result.getExpandedExpression();
std::replace( expr.begin(), expr.end(), '\n', ' ');
stream << expr;
}
}
void printMessage() {
if ( itMessage != messages.end() ) {
stream << " '" << itMessage->message << "'";
++itMessage;
}
}
void printRemainingMessages( Colour::Code colour = dimColour() ) {
if (itMessage == messages.end()) {
return;
}
// using messages.end() directly (or auto) yields compilation error:
std::vector<MessageInfo>::const_iterator itEnd = messages.end();
const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
{
Colour colourGuard( colour );
stream << " with " << pluralise( N, "message" ) << ":";
}
for(; itMessage != itEnd; ) {
// If this assertion is a warning ignore any INFO messages
if( printInfoMessages || itMessage->type != ResultWas::Info ) {
stream << " '" << itMessage->message << "'";
if ( ++itMessage != itEnd ) {
Colour colourGuard( dimColour() );
stream << " and";
}
}
}
}
private:
std::ostream& stream;
AssertionResult const& result;
std::vector<MessageInfo> messages;
std::vector<MessageInfo>::const_iterator itMessage;
bool printInfoMessages;
std::size_t counter;
};
void printTotals( const Totals& totals ) const {
if( totals.testCases.total() == 0 ) {
stream << "1..0 # Skipped: No tests ran.";
} else {
stream << "1.." << counter;
}
}
};
#ifdef CATCH_IMPL
TAPReporter::~TAPReporter() {}
#endif
CATCH_REGISTER_REPORTER( "tap", TAPReporter )
} // end namespace Catch
#endif // TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED

View File

@ -1,220 +0,0 @@
/*
* Created by Phil Nash on 19th December 2014
* Copyright 2014 Two Blue Cubes Ltd. All rights reserved.
*
* 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)
*/
#ifndef TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED
// Don't #include any Catch headers here - we can assume they are already
// included before this header.
// This is not good practice in general but is necessary in this case so this
// file can be distributed as a single header that works with the main
// Catch single header.
#include <cstring>
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wpadded"
#endif
namespace Catch {
struct TeamCityReporter : StreamingReporterBase<TeamCityReporter> {
TeamCityReporter( ReporterConfig const& _config )
: StreamingReporterBase( _config )
{
m_reporterPrefs.shouldRedirectStdOut = true;
}
static std::string escape( std::string const& str ) {
std::string escaped = str;
replaceInPlace( escaped, "|", "||" );
replaceInPlace( escaped, "'", "|'" );
replaceInPlace( escaped, "\n", "|n" );
replaceInPlace( escaped, "\r", "|r" );
replaceInPlace( escaped, "[", "|[" );
replaceInPlace( escaped, "]", "|]" );
return escaped;
}
~TeamCityReporter() override;
static std::string getDescription() {
return "Reports test results as TeamCity service messages";
}
void skipTest( TestCaseInfo const& /* testInfo */ ) override {
}
void noMatchingTestCases( std::string const& /* spec */ ) override {}
void testGroupStarting( GroupInfo const& groupInfo ) override {
StreamingReporterBase::testGroupStarting( groupInfo );
stream << "##teamcity[testSuiteStarted name='"
<< escape( groupInfo.name ) << "']\n";
}
void testGroupEnded( TestGroupStats const& testGroupStats ) override {
StreamingReporterBase::testGroupEnded( testGroupStats );
stream << "##teamcity[testSuiteFinished name='"
<< escape( testGroupStats.groupInfo.name ) << "']\n";
}
void assertionStarting( AssertionInfo const& ) override {}
bool assertionEnded( AssertionStats const& assertionStats ) override {
AssertionResult const& result = assertionStats.assertionResult;
if( !result.isOk() ) {
ReusableStringStream msg;
if( !m_headerPrintedForThisSection )
printSectionHeader( msg.get() );
m_headerPrintedForThisSection = true;
msg << result.getSourceInfo() << "\n";
switch( result.getResultType() ) {
case ResultWas::ExpressionFailed:
msg << "expression failed";
break;
case ResultWas::ThrewException:
msg << "unexpected exception";
break;
case ResultWas::FatalErrorCondition:
msg << "fatal error condition";
break;
case ResultWas::DidntThrowException:
msg << "no exception was thrown where one was expected";
break;
case ResultWas::ExplicitFailure:
msg << "explicit failure";
break;
// We shouldn't get here because of the isOk() test
case ResultWas::Ok:
case ResultWas::Info:
case ResultWas::Warning:
throw std::domain_error( "Internal error in TeamCity reporter" );
// These cases are here to prevent compiler warnings
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
throw std::domain_error( "Not implemented" );
}
if( assertionStats.infoMessages.size() == 1 )
msg << " with message:";
if( assertionStats.infoMessages.size() > 1 )
msg << " with messages:";
for( auto const& messageInfo : assertionStats.infoMessages )
msg << "\n \"" << messageInfo.message << "\"";
if( result.hasExpression() ) {
msg <<
"\n " << result.getExpressionInMacro() << "\n"
"with expansion:\n" <<
" " << result.getExpandedExpression() << "\n";
}
if( currentTestCaseInfo->okToFail() ) {
msg << "- failure ignore as test marked as 'ok to fail'\n";
stream << "##teamcity[testIgnored"
<< " name='" << escape( currentTestCaseInfo->name )<< "'"
<< " message='" << escape( msg.str() ) << "'"
<< "]\n";
}
else {
stream << "##teamcity[testFailed"
<< " name='" << escape( currentTestCaseInfo->name )<< "'"
<< " message='" << escape( msg.str() ) << "'"
<< "]\n";
}
}
stream.flush();
return true;
}
void sectionStarting( SectionInfo const& sectionInfo ) override {
m_headerPrintedForThisSection = false;
StreamingReporterBase::sectionStarting( sectionInfo );
}
void testCaseStarting( TestCaseInfo const& testInfo ) override {
m_testTimer.start();
StreamingReporterBase::testCaseStarting( testInfo );
stream << "##teamcity[testStarted name='"
<< escape( testInfo.name ) << "']\n";
stream.flush();
}
void testCaseEnded( TestCaseStats const& testCaseStats ) override {
StreamingReporterBase::testCaseEnded( testCaseStats );
if( !testCaseStats.stdOut.empty() )
stream << "##teamcity[testStdOut name='"
<< escape( testCaseStats.testInfo.name )
<< "' out='" << escape( testCaseStats.stdOut ) << "']\n";
if( !testCaseStats.stdErr.empty() )
stream << "##teamcity[testStdErr name='"
<< escape( testCaseStats.testInfo.name )
<< "' out='" << escape( testCaseStats.stdErr ) << "']\n";
stream << "##teamcity[testFinished name='"
<< escape( testCaseStats.testInfo.name ) << "' duration='"
<< m_testTimer.getElapsedMilliseconds() << "']\n";
stream.flush();
}
private:
void printSectionHeader( std::ostream& os ) {
assert( !m_sectionStack.empty() );
if( m_sectionStack.size() > 1 ) {
os << getLineOfChars<'-'>() << "\n";
std::vector<SectionInfo>::const_iterator
it = m_sectionStack.begin()+1, // Skip first section (test case)
itEnd = m_sectionStack.end();
for( ; it != itEnd; ++it )
printHeaderString( os, it->name );
os << getLineOfChars<'-'>() << "\n";
}
SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;
if( !lineInfo.empty() )
os << lineInfo << "\n";
os << getLineOfChars<'.'>() << "\n\n";
}
// if string has a : in first line will set indent to follow it on
// subsequent lines
static void printHeaderString( std::ostream& os, std::string const& _string, std::size_t indent = 0 ) {
std::size_t i = _string.find( ": " );
if( i != std::string::npos )
i+=2;
else
i = 0;
os << Column( _string )
.indent( indent+i)
.initialIndent( indent ) << "\n";
}
private:
bool m_headerPrintedForThisSection = false;
Timer m_testTimer;
};
#ifdef CATCH_IMPL
TeamCityReporter::~TeamCityReporter() {}
#endif
CATCH_REGISTER_REPORTER( "teamcity", TeamCityReporter )
} // end namespace Catch
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#endif // TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED

View File

@ -1,29 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_GSL_H
#define GSL_GSL_H
#include <gsl/gsl_algorithm> // copy
#include <gsl/gsl_assert> // Ensures/Expects
#include <gsl/gsl_byte> // byte
#include <gsl/gsl_util> // finally()/narrow()/narrow_cast()...
#include <gsl/multi_span> // multi_span, strided_span...
#include <gsl/pointers> // owner, not_null
#include <gsl/span> // span
#include <gsl/string_span> // zstring, string_span, zstring_builder...
#endif // GSL_GSL_H

View File

@ -1,63 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_ALGORITHM_H
#define GSL_ALGORITHM_H
#include <gsl/gsl_assert> // for Expects
#include <gsl/span> // for dynamic_extent, span
#include <algorithm> // for copy_n
#include <cstddef> // for ptrdiff_t
#include <type_traits> // for is_assignable
#ifdef _MSC_VER
#pragma warning(push)
// turn off some warnings that are noisy about our Expects statements
#pragma warning(disable : 4127) // conditional expression is constant
#pragma warning(disable : 4996) // unsafe use of std::copy_n
// blanket turn off warnings from CppCoreCheck for now
// so people aren't annoyed by them when running the tool.
// more targeted suppressions will be added in a future update to the GSL
#pragma warning(disable : 26481 26482 26483 26485 26490 26491 26492 26493 26495)
#endif // _MSC_VER
namespace gsl
{
template <class SrcElementType, std::ptrdiff_t SrcExtent, class DestElementType,
std::ptrdiff_t DestExtent>
void copy(span<SrcElementType, SrcExtent> src, span<DestElementType, DestExtent> dest)
{
static_assert(std::is_assignable<decltype(*dest.data()), decltype(*src.data())>::value,
"Elements of source span can not be assigned to elements of destination span");
static_assert(SrcExtent == dynamic_extent || DestExtent == dynamic_extent ||
(SrcExtent <= DestExtent),
"Source range is longer than target range");
Expects(dest.size() >= src.size());
std::copy_n(src.data(), src.size(), dest.data());
}
} // namespace gsl
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
#endif // GSL_ALGORITHM_H

View File

@ -1,145 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_CONTRACTS_H
#define GSL_CONTRACTS_H
#include <exception>
#include <stdexcept> // for logic_error
//
// Temporary until MSVC STL supports no-exceptions mode.
// Currently terminate is a no-op in this mode, so we add termination behavior back
//
#if defined(_MSC_VER) && defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS
#define GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND
#endif
//
// There are three configuration options for this GSL implementation's behavior
// when pre/post conditions on the GSL types are violated:
//
// 1. GSL_TERMINATE_ON_CONTRACT_VIOLATION: std::terminate will be called (default)
// 2. GSL_THROW_ON_CONTRACT_VIOLATION: a gsl::fail_fast exception will be thrown
// 3. GSL_UNENFORCED_ON_CONTRACT_VIOLATION: nothing happens
//
#if !(defined(GSL_THROW_ON_CONTRACT_VIOLATION) || defined(GSL_TERMINATE_ON_CONTRACT_VIOLATION) || \
defined(GSL_UNENFORCED_ON_CONTRACT_VIOLATION))
#define GSL_TERMINATE_ON_CONTRACT_VIOLATION
#endif
#define GSL_STRINGIFY_DETAIL(x) #x
#define GSL_STRINGIFY(x) GSL_STRINGIFY_DETAIL(x)
#if defined(__clang__) || defined(__GNUC__)
#define GSL_LIKELY(x) __builtin_expect(!!(x), 1)
#define GSL_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define GSL_LIKELY(x) (!!(x))
#define GSL_UNLIKELY(x) (!!(x))
#endif
//
// GSL_ASSUME(cond)
//
// Tell the optimizer that the predicate cond must hold. It is unspecified
// whether or not cond is actually evaluated.
//
#ifdef _MSC_VER
#define GSL_ASSUME(cond) __assume(cond)
#elif defined(__GNUC__)
#define GSL_ASSUME(cond) ((cond) ? static_cast<void>(0) : __builtin_unreachable())
#else
#define GSL_ASSUME(cond) static_cast<void>((cond) ? 0 : 0)
#endif
//
// GSL.assert: assertions
//
namespace gsl
{
struct fail_fast : public std::logic_error
{
explicit fail_fast(char const* const message) : std::logic_error(message) {}
};
namespace details
{
#if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND)
typedef void (__cdecl *terminate_handler)();
inline gsl::details::terminate_handler& get_terminate_handler() noexcept
{
static terminate_handler handler = &abort;
return handler;
}
#endif
[[noreturn]] inline void terminate() noexcept
{
#if defined(GSL_MSVC_USE_STL_NOEXCEPTION_WORKAROUND)
(*gsl::details::get_terminate_handler())();
#else
std::terminate();
#endif
}
#if defined(GSL_TERMINATE_ON_CONTRACT_VIOLATION)
template <typename Exception>
[[noreturn]] void throw_exception(Exception&&)
{
gsl::details::terminate();
}
#else
template <typename Exception>
[[noreturn]] void throw_exception(Exception&& exception)
{
throw std::forward<Exception>(exception);
}
#endif
} // namespace details
} // namespace gsl
#if defined(GSL_THROW_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) \
: gsl::details::throw_exception(gsl::fail_fast( \
"GSL: " type " failure at " __FILE__ ": " GSL_STRINGIFY(__LINE__))))
#elif defined(GSL_TERMINATE_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) : gsl::details::terminate())
#elif defined(GSL_UNENFORCED_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) GSL_ASSUME(cond)
#endif
#define Expects(cond) GSL_CONTRACT_CHECK("Precondition", cond)
#define Ensures(cond) GSL_CONTRACT_CHECK("Postcondition", cond)
#endif // GSL_CONTRACTS_H

View File

@ -1,181 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_BYTE_H
#define GSL_BYTE_H
#include <type_traits>
#ifdef _MSC_VER
#pragma warning(push)
// don't warn about function style casts in byte related operators
#pragma warning(disable : 26493)
#ifndef GSL_USE_STD_BYTE
// this tests if we are under MSVC and the standard lib has std::byte and it is enabled
#if defined(_HAS_STD_BYTE) && _HAS_STD_BYTE
#define GSL_USE_STD_BYTE 1
#else // defined(_HAS_STD_BYTE) && _HAS_STD_BYTE
#define GSL_USE_STD_BYTE 0
#endif // defined(_HAS_STD_BYTE) && _HAS_STD_BYTE
#endif // GSL_USE_STD_BYTE
#else // _MSC_VER
#ifndef GSL_USE_STD_BYTE
// this tests if we are under GCC or Clang with enough -std:c++1z power to get us std::byte
#if defined(__cplusplus) && (__cplusplus >= 201703L)
#define GSL_USE_STD_BYTE 1
#include <cstddef>
#else // defined(__cplusplus) && (__cplusplus >= 201703L)
#define GSL_USE_STD_BYTE 0
#endif //defined(__cplusplus) && (__cplusplus >= 201703L)
#endif // GSL_USE_STD_BYTE
#endif // _MSC_VER
// Use __may_alias__ attribute on gcc and clang
#if defined __clang__ || (__GNUC__ > 5)
#define byte_may_alias __attribute__((__may_alias__))
#else // defined __clang__ || defined __GNUC__
#define byte_may_alias
#endif // defined __clang__ || defined __GNUC__
namespace gsl
{
#if GSL_USE_STD_BYTE
using std::byte;
using std::to_integer;
#else // GSL_USE_STD_BYTE
// This is a simple definition for now that allows
// use of byte within span<> to be standards-compliant
enum class byte_may_alias byte : unsigned char
{
};
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr byte& operator<<=(byte& b, IntegerType shift) noexcept
{
return b = byte(static_cast<unsigned char>(b) << shift);
}
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr byte operator<<(byte b, IntegerType shift) noexcept
{
return byte(static_cast<unsigned char>(b) << shift);
}
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr byte& operator>>=(byte& b, IntegerType shift) noexcept
{
return b = byte(static_cast<unsigned char>(b) >> shift);
}
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr byte operator>>(byte b, IntegerType shift) noexcept
{
return byte(static_cast<unsigned char>(b) >> shift);
}
constexpr byte& operator|=(byte& l, byte r) noexcept
{
return l = byte(static_cast<unsigned char>(l) | static_cast<unsigned char>(r));
}
constexpr byte operator|(byte l, byte r) noexcept
{
return byte(static_cast<unsigned char>(l) | static_cast<unsigned char>(r));
}
constexpr byte& operator&=(byte& l, byte r) noexcept
{
return l = byte(static_cast<unsigned char>(l) & static_cast<unsigned char>(r));
}
constexpr byte operator&(byte l, byte r) noexcept
{
return byte(static_cast<unsigned char>(l) & static_cast<unsigned char>(r));
}
constexpr byte& operator^=(byte& l, byte r) noexcept
{
return l = byte(static_cast<unsigned char>(l) ^ static_cast<unsigned char>(r));
}
constexpr byte operator^(byte l, byte r) noexcept
{
return byte(static_cast<unsigned char>(l) ^ static_cast<unsigned char>(r));
}
constexpr byte operator~(byte b) noexcept { return byte(~static_cast<unsigned char>(b)); }
template <class IntegerType, class = std::enable_if_t<std::is_integral<IntegerType>::value>>
constexpr IntegerType to_integer(byte b) noexcept
{
return static_cast<IntegerType>(b);
}
#endif // GSL_USE_STD_BYTE
template <bool E, typename T>
constexpr byte to_byte_impl(T t) noexcept
{
static_assert(
E, "gsl::to_byte(t) must be provided an unsigned char, otherwise data loss may occur. "
"If you are calling to_byte with an integer contant use: gsl::to_byte<t>() version.");
return static_cast<byte>(t);
}
template <>
constexpr byte to_byte_impl<true, unsigned char>(unsigned char t) noexcept
{
return byte(t);
}
template <typename T>
constexpr byte to_byte(T t) noexcept
{
return to_byte_impl<std::is_same<T, unsigned char>::value, T>(t);
}
template <int I>
constexpr byte to_byte() noexcept
{
static_assert(I >= 0 && I <= 255,
"gsl::byte only has 8 bits of storage, values must be in range 0-255");
return static_cast<byte>(I);
}
} // namespace gsl
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
#endif // GSL_BYTE_H

View File

@ -1,158 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_UTIL_H
#define GSL_UTIL_H
#include <gsl/gsl_assert> // for Expects
#include <array>
#include <cstddef> // for ptrdiff_t, size_t
#include <exception> // for exception
#include <initializer_list> // for initializer_list
#include <type_traits> // for is_signed, integral_constant
#include <utility> // for forward
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4127) // conditional expression is constant
#if _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#endif // _MSC_VER < 1910
#endif // _MSC_VER
namespace gsl
{
//
// GSL.util: utilities
//
// index type for all container indexes/subscripts/sizes
using index = std::ptrdiff_t;
// final_action allows you to ensure something gets run at the end of a scope
template <class F>
class final_action
{
public:
explicit final_action(F f) noexcept : f_(std::move(f)) {}
final_action(final_action&& other) noexcept : f_(std::move(other.f_)), invoke_(other.invoke_)
{
other.invoke_ = false;
}
final_action(const final_action&) = delete;
final_action& operator=(const final_action&) = delete;
final_action& operator=(final_action&&) = delete;
~final_action() noexcept
{
if (invoke_) f_();
}
private:
F f_;
bool invoke_ {true};
};
// finally() - convenience function to generate a final_action
template <class F>
final_action<F> finally(const F& f) noexcept
{
return final_action<F>(f);
}
template <class F>
final_action<F> finally(F&& f) noexcept
{
return final_action<F>(std::forward<F>(f));
}
// narrow_cast(): a searchable way to do narrowing casts of values
template <class T, class U>
constexpr T narrow_cast(U&& u) noexcept
{
return static_cast<T>(std::forward<U>(u));
}
struct narrowing_error : public std::exception
{
};
namespace details
{
template <class T, class U>
struct is_same_signedness
: public std::integral_constant<bool, std::is_signed<T>::value == std::is_signed<U>::value>
{
};
}
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template <class T, class U>
T narrow(U u)
{
T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u) gsl::details::throw_exception(narrowing_error());
if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))
gsl::details::throw_exception(narrowing_error());
return t;
}
//
// at() - Bounds-checked way of accessing builtin arrays, std::array, std::vector
//
template <class T, std::size_t N>
constexpr T& at(T (&arr)[N], const index i)
{
Expects(i >= 0 && i < narrow_cast<index>(N));
return arr[static_cast<std::size_t>(i)];
}
template <class Cont>
constexpr auto at(Cont& cont, const index i) -> decltype(cont[cont.size()])
{
Expects(i >= 0 && i < narrow_cast<index>(cont.size()));
using size_type = decltype(cont.size());
return cont[static_cast<size_type>(i)];
}
template <class T>
constexpr T at(const std::initializer_list<T> cont, const index i)
{
Expects(i >= 0 && i < narrow_cast<index>(cont.size()));
return *(cont.begin() + i);
}
} // namespace gsl
#if defined(_MSC_VER)
#if _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
#endif // _MSC_VER < 1910
#pragma warning(pop)
#endif // _MSC_VER
#endif // GSL_UTIL_H

File diff suppressed because it is too large Load Diff

View File

@ -1,193 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_POINTERS_H
#define GSL_POINTERS_H
#include <gsl/gsl_assert> // for Ensures, Expects
#include <algorithm> // for forward
#include <iosfwd> // for ptrdiff_t, nullptr_t, ostream, size_t
#include <memory> // for shared_ptr, unique_ptr
#include <system_error> // for hash
#include <type_traits> // for enable_if_t, is_convertible, is_assignable
#if defined(_MSC_VER) && _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#endif // defined(_MSC_VER) && _MSC_VER < 1910
namespace gsl
{
//
// GSL.owner: ownership pointers
//
using std::unique_ptr;
using std::shared_ptr;
//
// owner
//
// owner<T> is designed as a bridge for code that must deal directly with owning pointers for some reason
//
// T must be a pointer type
// - disallow construction from any type other than pointer type
//
template <class T, class = std::enable_if_t<std::is_pointer<T>::value>>
using owner = T;
//
// not_null
//
// Restricts a pointer or smart pointer to only hold non-null values.
//
// Has zero size overhead over T.
//
// If T is a pointer (i.e. T == U*) then
// - allow construction from U*
// - disallow construction from nullptr_t
// - disallow default construction
// - ensure construction from null U* fails
// - allow implicit conversion to U*
//
template <class T>
class not_null
{
public:
static_assert(std::is_assignable<T&, std::nullptr_t>::value, "T cannot be assigned nullptr.");
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr explicit not_null(U&& u) : ptr_(std::forward<U>(u))
{
Expects(ptr_ != nullptr);
}
template <typename = std::enable_if_t<!std::is_same<std::nullptr_t, T>::value>>
constexpr explicit not_null(T u) : ptr_(u)
{
Expects(ptr_ != nullptr);
}
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr not_null(const not_null<U>& other) : not_null(other.get())
{
}
not_null(not_null&& other) = default;
not_null(const not_null& other) = default;
not_null& operator=(const not_null& other) = default;
constexpr T get() const
{
Ensures(ptr_ != nullptr);
return ptr_;
}
constexpr operator T() const { return get(); }
constexpr T operator->() const { return get(); }
constexpr decltype(auto) operator*() const { return *get(); }
// prevents compilation when someone attempts to assign a null pointer constant
not_null(std::nullptr_t) = delete;
not_null& operator=(std::nullptr_t) = delete;
// unwanted operators...pointers only point to single objects!
not_null& operator++() = delete;
not_null& operator--() = delete;
not_null operator++(int) = delete;
not_null operator--(int) = delete;
not_null& operator+=(std::ptrdiff_t) = delete;
not_null& operator-=(std::ptrdiff_t) = delete;
void operator[](std::ptrdiff_t) const = delete;
private:
T ptr_;
};
template <class T>
std::ostream& operator<<(std::ostream& os, const not_null<T>& val)
{
os << val.get();
return os;
}
template <class T, class U>
auto operator==(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() == rhs.get())
{
return lhs.get() == rhs.get();
}
template <class T, class U>
auto operator!=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() != rhs.get())
{
return lhs.get() != rhs.get();
}
template <class T, class U>
auto operator<(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() < rhs.get())
{
return lhs.get() < rhs.get();
}
template <class T, class U>
auto operator<=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() <= rhs.get())
{
return lhs.get() <= rhs.get();
}
template <class T, class U>
auto operator>(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() > rhs.get())
{
return lhs.get() > rhs.get();
}
template <class T, class U>
auto operator>=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() >= rhs.get())
{
return lhs.get() >= rhs.get();
}
// more unwanted operators
template <class T, class U>
std::ptrdiff_t operator-(const not_null<T>&, const not_null<U>&) = delete;
template <class T>
not_null<T> operator-(const not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
not_null<T> operator+(const not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
not_null<T> operator+(std::ptrdiff_t, const not_null<T>&) = delete;
} // namespace gsl
namespace std
{
template <class T>
struct hash<gsl::not_null<T>>
{
std::size_t operator()(const gsl::not_null<T>& value) const { return hash<T>{}(value); }
};
} // namespace std
#if defined(_MSC_VER) && _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
#endif // defined(_MSC_VER) && _MSC_VER < 1910
#endif // GSL_POINTERS_H

View File

@ -1,766 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_SPAN_H
#define GSL_SPAN_H
#include <gsl/gsl_assert> // for Expects
#include <gsl/gsl_byte> // for byte
#include <gsl/gsl_util> // for narrow_cast, narrow
#include <algorithm> // for lexicographical_compare
#include <array> // for array
#include <cstddef> // for ptrdiff_t, size_t, nullptr_t
#include <iterator> // for reverse_iterator, distance, random_access_...
#include <limits>
#include <stdexcept>
#include <type_traits> // for enable_if_t, declval, is_convertible, inte...
#include <utility>
#ifdef _MSC_VER
#pragma warning(push)
// turn off some warnings that are noisy about our Expects statements
#pragma warning(disable : 4127) // conditional expression is constant
#pragma warning(disable : 4702) // unreachable code
// blanket turn off warnings from CppCoreCheck for now
// so people aren't annoyed by them when running the tool.
// more targeted suppressions will be added in a future update to the GSL
#pragma warning(disable : 26481 26482 26483 26485 26490 26491 26492 26493 26495)
#if _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#define GSL_USE_STATIC_CONSTEXPR_WORKAROUND
#endif // _MSC_VER < 1910
#else // _MSC_VER
// See if we have enough C++17 power to use a static constexpr data member
// without needing an out-of-line definition
#if !(defined(__cplusplus) && (__cplusplus >= 201703L))
#define GSL_USE_STATIC_CONSTEXPR_WORKAROUND
#endif // !(defined(__cplusplus) && (__cplusplus >= 201703L))
#endif // _MSC_VER
// GCC 7 does not like the signed unsigned missmatch (size_t ptrdiff_t)
// While there is a conversion from signed to unsigned, it happens at
// compiletime, so the compiler wouldn't have to warn indiscriminently, but
// could check if the source value actually doesn't fit into the target type
// and only warn in those cases.
#if __GNUC__ > 6
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
namespace gsl
{
// [views.constants], constants
constexpr const std::ptrdiff_t dynamic_extent = -1;
template <class ElementType, std::ptrdiff_t Extent = dynamic_extent>
class span;
// implementation details
namespace details
{
template <class T>
struct is_span_oracle : std::false_type
{
};
template <class ElementType, std::ptrdiff_t Extent>
struct is_span_oracle<gsl::span<ElementType, Extent>> : std::true_type
{
};
template <class T>
struct is_span : public is_span_oracle<std::remove_cv_t<T>>
{
};
template <class T>
struct is_std_array_oracle : std::false_type
{
};
template <class ElementType, std::size_t Extent>
struct is_std_array_oracle<std::array<ElementType, Extent>> : std::true_type
{
};
template <class T>
struct is_std_array : public is_std_array_oracle<std::remove_cv_t<T>>
{
};
template <std::ptrdiff_t From, std::ptrdiff_t To>
struct is_allowed_extent_conversion
: public std::integral_constant<bool, From == To || From == gsl::dynamic_extent ||
To == gsl::dynamic_extent>
{
};
template <class From, class To>
struct is_allowed_element_type_conversion
: public std::integral_constant<bool, std::is_convertible<From (*)[], To (*)[]>::value>
{
};
template <class Span, bool IsConst>
class span_iterator
{
using element_type_ = typename Span::element_type;
public:
#ifdef _MSC_VER
// Tell Microsoft standard library that span_iterators are checked.
using _Unchecked_type = typename Span::pointer;
#endif
using iterator_category = std::random_access_iterator_tag;
using value_type = std::remove_cv_t<element_type_>;
using difference_type = typename Span::index_type;
using reference = std::conditional_t<IsConst, const element_type_, element_type_>&;
using pointer = std::add_pointer_t<reference>;
span_iterator() = default;
constexpr span_iterator(const Span* span, typename Span::index_type idx) noexcept
: span_(span), index_(idx)
{}
friend span_iterator<Span, true>;
template<bool B, std::enable_if_t<!B && IsConst>* = nullptr>
constexpr span_iterator(const span_iterator<Span, B>& other) noexcept
: span_iterator(other.span_, other.index_)
{
}
constexpr reference operator*() const
{
Expects(index_ != span_->size());
return *(span_->data() + index_);
}
constexpr pointer operator->() const
{
Expects(index_ != span_->size());
return span_->data() + index_;
}
constexpr span_iterator& operator++()
{
Expects(0 <= index_ && index_ != span_->size());
++index_;
return *this;
}
constexpr span_iterator operator++(int)
{
auto ret = *this;
++(*this);
return ret;
}
constexpr span_iterator& operator--()
{
Expects(index_ != 0 && index_ <= span_->size());
--index_;
return *this;
}
constexpr span_iterator operator--(int)
{
auto ret = *this;
--(*this);
return ret;
}
constexpr span_iterator operator+(difference_type n) const
{
auto ret = *this;
return ret += n;
}
friend constexpr span_iterator operator+(difference_type n, span_iterator const& rhs)
{
return rhs + n;
}
constexpr span_iterator& operator+=(difference_type n)
{
Expects((index_ + n) >= 0 && (index_ + n) <= span_->size());
index_ += n;
return *this;
}
constexpr span_iterator operator-(difference_type n) const
{
auto ret = *this;
return ret -= n;
}
constexpr span_iterator& operator-=(difference_type n) { return *this += -n; }
constexpr difference_type operator-(span_iterator rhs) const
{
Expects(span_ == rhs.span_);
return index_ - rhs.index_;
}
constexpr reference operator[](difference_type n) const
{
return *(*this + n);
}
constexpr friend bool operator==(span_iterator lhs,
span_iterator rhs) noexcept
{
return lhs.span_ == rhs.span_ && lhs.index_ == rhs.index_;
}
constexpr friend bool operator!=(span_iterator lhs,
span_iterator rhs) noexcept
{
return !(lhs == rhs);
}
constexpr friend bool operator<(span_iterator lhs,
span_iterator rhs) noexcept
{
return lhs.index_ < rhs.index_;
}
constexpr friend bool operator<=(span_iterator lhs,
span_iterator rhs) noexcept
{
return !(rhs < lhs);
}
constexpr friend bool operator>(span_iterator lhs,
span_iterator rhs) noexcept
{
return rhs < lhs;
}
constexpr friend bool operator>=(span_iterator lhs,
span_iterator rhs) noexcept
{
return !(rhs > lhs);
}
#ifdef _MSC_VER
// MSVC++ iterator debugging support; allows STL algorithms in 15.8+
// to unwrap span_iterator to a pointer type after a range check in STL
// algorithm calls
friend constexpr void _Verify_range(span_iterator lhs,
span_iterator rhs) noexcept
{ // test that [lhs, rhs) forms a valid range inside an STL algorithm
Expects(lhs.span_ == rhs.span_ // range spans have to match
&& lhs.index_ <= rhs.index_); // range must not be transposed
}
constexpr void _Verify_offset(const difference_type n) const noexcept
{ // test that the iterator *this + n is a valid range in an STL
// algorithm call
Expects((index_ + n) >= 0 && (index_ + n) <= span_->size());
}
constexpr pointer _Unwrapped() const noexcept
{ // after seeking *this to a high water mark, or using one of the
// _Verify_xxx functions above, unwrap this span_iterator to a raw
// pointer
return span_->data() + index_;
}
// Tell the STL that span_iterator should not be unwrapped if it can't
// validate in advance, even in release / optimized builds:
#if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND)
static constexpr const bool _Unwrap_when_unverified = false;
#else
static constexpr bool _Unwrap_when_unverified = false;
#endif
constexpr void _Seek_to(const pointer p) noexcept
{ // adjust the position of *this to previously verified location p
// after _Unwrapped
index_ = p - span_->data();
}
#endif
protected:
const Span* span_ = nullptr;
std::ptrdiff_t index_ = 0;
};
template <std::ptrdiff_t Ext>
class extent_type
{
public:
using index_type = std::ptrdiff_t;
static_assert(Ext >= 0, "A fixed-size span must be >= 0 in size.");
constexpr extent_type() noexcept {}
template <index_type Other>
constexpr extent_type(extent_type<Other> ext)
{
static_assert(Other == Ext || Other == dynamic_extent,
"Mismatch between fixed-size extent and size of initializing data.");
Expects(ext.size() == Ext);
}
constexpr extent_type(index_type size) { Expects(size == Ext); }
constexpr index_type size() const noexcept { return Ext; }
};
template <>
class extent_type<dynamic_extent>
{
public:
using index_type = std::ptrdiff_t;
template <index_type Other>
explicit constexpr extent_type(extent_type<Other> ext) : size_(ext.size())
{
}
explicit constexpr extent_type(index_type size) : size_(size) { Expects(size >= 0); }
constexpr index_type size() const noexcept { return size_; }
private:
index_type size_;
};
template <class ElementType, std::ptrdiff_t Extent, std::ptrdiff_t Offset, std::ptrdiff_t Count>
struct calculate_subspan_type
{
using type = span<ElementType, Count != dynamic_extent ? Count : (Extent != dynamic_extent ? Extent - Offset : Extent)>;
};
} // namespace details
// [span], class template span
template <class ElementType, std::ptrdiff_t Extent>
class span
{
public:
// constants and types
using element_type = ElementType;
using value_type = std::remove_cv_t<ElementType>;
using index_type = std::ptrdiff_t;
using pointer = element_type*;
using reference = element_type&;
using iterator = details::span_iterator<span<ElementType, Extent>, false>;
using const_iterator = details::span_iterator<span<ElementType, Extent>, true>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using size_type = index_type;
#if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND)
static constexpr const index_type extent { Extent };
#else
static constexpr index_type extent { Extent };
#endif
// [span.cons], span constructors, copy, assignment, and destructor
template <bool Dependent = false,
// "Dependent" is needed to make "std::enable_if_t<Dependent || Extent <= 0>" SFINAE,
// since "std::enable_if_t<Extent <= 0>" is ill-formed when Extent is greater than 0.
class = std::enable_if_t<(Dependent || Extent <= 0)>>
constexpr span() noexcept : storage_(nullptr, details::extent_type<0>())
{
}
constexpr span(pointer ptr, index_type count) : storage_(ptr, count) {}
constexpr span(pointer firstElem, pointer lastElem)
: storage_(firstElem, std::distance(firstElem, lastElem))
{
}
template <std::size_t N>
constexpr span(element_type (&arr)[N]) noexcept
: storage_(KnownNotNull{&arr[0]}, details::extent_type<N>())
{
}
template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>>
constexpr span(std::array<ArrayElementType, N>& arr) noexcept
: storage_(&arr[0], details::extent_type<N>())
{
}
template <std::size_t N>
constexpr span(const std::array<std::remove_const_t<element_type>, N>& arr) noexcept
: storage_(&arr[0], details::extent_type<N>())
{
}
// NB: the SFINAE here uses .data() as a incomplete/imperfect proxy for the requirement
// on Container to be a contiguous sequence container.
template <class Container,
class = std::enable_if_t<
!details::is_span<Container>::value && !details::is_std_array<Container>::value &&
std::is_convertible<typename Container::pointer, pointer>::value &&
std::is_convertible<typename Container::pointer,
decltype(std::declval<Container>().data())>::value>>
constexpr span(Container& cont) : span(cont.data(), narrow<index_type>(cont.size()))
{
}
template <class Container,
class = std::enable_if_t<
std::is_const<element_type>::value && !details::is_span<Container>::value &&
std::is_convertible<typename Container::pointer, pointer>::value &&
std::is_convertible<typename Container::pointer,
decltype(std::declval<Container>().data())>::value>>
constexpr span(const Container& cont) : span(cont.data(), narrow<index_type>(cont.size()))
{
}
constexpr span(const span& other) noexcept = default;
template <
class OtherElementType, std::ptrdiff_t OtherExtent,
class = std::enable_if_t<
details::is_allowed_extent_conversion<OtherExtent, Extent>::value &&
details::is_allowed_element_type_conversion<OtherElementType, element_type>::value>>
constexpr span(const span<OtherElementType, OtherExtent>& other)
: storage_(other.data(), details::extent_type<OtherExtent>(other.size()))
{
}
~span() noexcept = default;
constexpr span& operator=(const span& other) noexcept = default;
// [span.sub], span subviews
template <std::ptrdiff_t Count>
constexpr span<element_type, Count> first() const
{
Expects(Count >= 0 && Count <= size());
return {data(), Count};
}
template <std::ptrdiff_t Count>
constexpr span<element_type, Count> last() const
{
Expects(Count >= 0 && size() - Count >= 0);
return {data() + (size() - Count), Count};
}
template <std::ptrdiff_t Offset, std::ptrdiff_t Count = dynamic_extent>
constexpr auto subspan() const -> typename details::calculate_subspan_type<ElementType, Extent, Offset, Count>::type
{
Expects((Offset >= 0 && size() - Offset >= 0) &&
(Count == dynamic_extent || (Count >= 0 && Offset + Count <= size())));
return {data() + Offset, Count == dynamic_extent ? size() - Offset : Count};
}
constexpr span<element_type, dynamic_extent> first(index_type count) const
{
Expects(count >= 0 && count <= size());
return {data(), count};
}
constexpr span<element_type, dynamic_extent> last(index_type count) const
{
return make_subspan(size() - count, dynamic_extent, subspan_selector<Extent>{});
}
constexpr span<element_type, dynamic_extent> subspan(index_type offset,
index_type count = dynamic_extent) const
{
return make_subspan(offset, count, subspan_selector<Extent>{});
}
// [span.obs], span observers
constexpr index_type size() const noexcept { return storage_.size(); }
constexpr index_type size_bytes() const noexcept
{
return size() * narrow_cast<index_type>(sizeof(element_type));
}
constexpr bool empty() const noexcept { return size() == 0; }
// [span.elem], span element access
constexpr reference operator[](index_type idx) const
{
Expects(idx >= 0 && idx < storage_.size());
return data()[idx];
}
constexpr reference at(index_type idx) const { return this->operator[](idx); }
constexpr reference operator()(index_type idx) const { return this->operator[](idx); }
constexpr pointer data() const noexcept { return storage_.data(); }
// [span.iter], span iterator support
constexpr iterator begin() const noexcept { return {this, 0}; }
constexpr iterator end() const noexcept { return {this, size()}; }
constexpr const_iterator cbegin() const noexcept { return {this, 0}; }
constexpr const_iterator cend() const noexcept { return {this, size()}; }
constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; }
constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; }
constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator{cend()}; }
constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator{cbegin()}; }
#ifdef _MSC_VER
// Tell MSVC how to unwrap spans in range-based-for
constexpr pointer _Unchecked_begin() const noexcept { return data(); }
constexpr pointer _Unchecked_end() const noexcept { return data() + size(); }
#endif // _MSC_VER
private:
// Needed to remove unnecessary null check in subspans
struct KnownNotNull
{
pointer p;
};
// this implementation detail class lets us take advantage of the
// empty base class optimization to pay for only storage of a single
// pointer in the case of fixed-size spans
template <class ExtentType>
class storage_type : public ExtentType
{
public:
// KnownNotNull parameter is needed to remove unnecessary null check
// in subspans and constructors from arrays
template <class OtherExtentType>
constexpr storage_type(KnownNotNull data, OtherExtentType ext) : ExtentType(ext), data_(data.p)
{
Expects(ExtentType::size() >= 0);
}
template <class OtherExtentType>
constexpr storage_type(pointer data, OtherExtentType ext) : ExtentType(ext), data_(data)
{
Expects(ExtentType::size() >= 0);
Expects(data || ExtentType::size() == 0);
}
constexpr pointer data() const noexcept { return data_; }
private:
pointer data_;
};
storage_type<details::extent_type<Extent>> storage_;
// The rest is needed to remove unnecessary null check
// in subspans and constructors from arrays
constexpr span(KnownNotNull ptr, index_type count) : storage_(ptr, count) {}
template <std::ptrdiff_t CallerExtent>
class subspan_selector {};
template <std::ptrdiff_t CallerExtent>
span<element_type, dynamic_extent> make_subspan(index_type offset,
index_type count,
subspan_selector<CallerExtent>) const
{
span<element_type, dynamic_extent> tmp(*this);
return tmp.subspan(offset, count);
}
span<element_type, dynamic_extent> make_subspan(index_type offset,
index_type count,
subspan_selector<dynamic_extent>) const
{
Expects(offset >= 0 && size() - offset >= 0);
if (count == dynamic_extent)
{
return { KnownNotNull{ data() + offset }, size() - offset };
}
Expects(count >= 0 && size() - offset >= count);
return { KnownNotNull{ data() + offset }, count };
}
};
#if defined(GSL_USE_STATIC_CONSTEXPR_WORKAROUND)
template <class ElementType, std::ptrdiff_t Extent>
constexpr const typename span<ElementType, Extent>::index_type span<ElementType, Extent>::extent;
#endif
// [span.comparison], span comparison operators
template <class ElementType, std::ptrdiff_t FirstExtent, std::ptrdiff_t SecondExtent>
constexpr bool operator==(span<ElementType, FirstExtent> l,
span<ElementType, SecondExtent> r)
{
return std::equal(l.begin(), l.end(), r.begin(), r.end());
}
template <class ElementType, std::ptrdiff_t Extent>
constexpr bool operator!=(span<ElementType, Extent> l,
span<ElementType, Extent> r)
{
return !(l == r);
}
template <class ElementType, std::ptrdiff_t Extent>
constexpr bool operator<(span<ElementType, Extent> l,
span<ElementType, Extent> r)
{
return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
}
template <class ElementType, std::ptrdiff_t Extent>
constexpr bool operator<=(span<ElementType, Extent> l,
span<ElementType, Extent> r)
{
return !(l > r);
}
template <class ElementType, std::ptrdiff_t Extent>
constexpr bool operator>(span<ElementType, Extent> l,
span<ElementType, Extent> r)
{
return r < l;
}
template <class ElementType, std::ptrdiff_t Extent>
constexpr bool operator>=(span<ElementType, Extent> l,
span<ElementType, Extent> r)
{
return !(l < r);
}
namespace details
{
// if we only supported compilers with good constexpr support then
// this pair of classes could collapse down to a constexpr function
// we should use a narrow_cast<> to go to std::size_t, but older compilers may not see it as
// constexpr
// and so will fail compilation of the template
template <class ElementType, std::ptrdiff_t Extent>
struct calculate_byte_size
: std::integral_constant<std::ptrdiff_t,
static_cast<std::ptrdiff_t>(sizeof(ElementType) *
static_cast<std::size_t>(Extent))>
{
};
template <class ElementType>
struct calculate_byte_size<ElementType, dynamic_extent>
: std::integral_constant<std::ptrdiff_t, dynamic_extent>
{
};
}
// [span.objectrep], views of object representation
template <class ElementType, std::ptrdiff_t Extent>
span<const byte, details::calculate_byte_size<ElementType, Extent>::value>
as_bytes(span<ElementType, Extent> s) noexcept
{
return {reinterpret_cast<const byte*>(s.data()), s.size_bytes()};
}
template <class ElementType, std::ptrdiff_t Extent,
class = std::enable_if_t<!std::is_const<ElementType>::value>>
span<byte, details::calculate_byte_size<ElementType, Extent>::value>
as_writeable_bytes(span<ElementType, Extent> s) noexcept
{
return {reinterpret_cast<byte*>(s.data()), s.size_bytes()};
}
//
// make_span() - Utility functions for creating spans
//
template <class ElementType>
constexpr span<ElementType> make_span(ElementType* ptr, typename span<ElementType>::index_type count)
{
return span<ElementType>(ptr, count);
}
template <class ElementType>
constexpr span<ElementType> make_span(ElementType* firstElem, ElementType* lastElem)
{
return span<ElementType>(firstElem, lastElem);
}
template <class ElementType, std::size_t N>
constexpr span<ElementType, N> make_span(ElementType (&arr)[N]) noexcept
{
return span<ElementType, N>(arr);
}
template <class Container>
constexpr span<typename Container::value_type> make_span(Container& cont)
{
return span<typename Container::value_type>(cont);
}
template <class Container>
constexpr span<const typename Container::value_type> make_span(const Container& cont)
{
return span<const typename Container::value_type>(cont);
}
template <class Ptr>
constexpr span<typename Ptr::element_type> make_span(Ptr& cont, std::ptrdiff_t count)
{
return span<typename Ptr::element_type>(cont, count);
}
template <class Ptr>
constexpr span<typename Ptr::element_type> make_span(Ptr& cont)
{
return span<typename Ptr::element_type>(cont);
}
// Specialization of gsl::at for span
template <class ElementType, std::ptrdiff_t Extent>
constexpr ElementType& at(span<ElementType, Extent> s, index i)
{
// No bounds checking here because it is done in span::operator[] called below
return s[i];
}
} // namespace gsl
#ifdef _MSC_VER
#if _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
#endif // _MSC_VER < 1910
#pragma warning(pop)
#endif // _MSC_VER
#if __GNUC__ > 6
#pragma GCC diagnostic pop
#endif // __GNUC__ > 6
#endif // GSL_SPAN_H

View File

@ -1,730 +0,0 @@
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_STRING_SPAN_H
#define GSL_STRING_SPAN_H
#include <gsl/gsl_assert> // for Ensures, Expects
#include <gsl/gsl_util> // for narrow_cast
#include <gsl/span> // for operator!=, operator==, dynamic_extent
#include <algorithm> // for equal, lexicographical_compare
#include <array> // for array
#include <cstddef> // for ptrdiff_t, size_t, nullptr_t
#include <cstdint> // for PTRDIFF_MAX
#include <cstring>
#include <string> // for basic_string, allocator, char_traits
#include <type_traits> // for declval, is_convertible, enable_if_t, add_...
#ifdef _MSC_VER
#pragma warning(push)
// blanket turn off warnings from CppCoreCheck for now
// so people aren't annoyed by them when running the tool.
// more targeted suppressions will be added in a future update to the GSL
#pragma warning(disable : 26481 26482 26483 26485 26490 26491 26492 26493 26495)
#if _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#endif // _MSC_VER < 1910
#endif // _MSC_VER
// In order to test the library, we need it to throw exceptions that we can catch
#ifdef GSL_THROW_ON_CONTRACT_VIOLATION
#define GSL_NOEXCEPT /*noexcept*/
#else
#define GSL_NOEXCEPT noexcept
#endif // GSL_THROW_ON_CONTRACT_VIOLATION
namespace gsl
{
//
// czstring and wzstring
//
// These are "tag" typedefs for C-style strings (i.e. null-terminated character arrays)
// that allow static analysis to help find bugs.
//
// There are no additional features/semantics that we can find a way to add inside the
// type system for these types that will not either incur significant runtime costs or
// (sometimes needlessly) break existing programs when introduced.
//
template <typename CharT, std::ptrdiff_t Extent = dynamic_extent>
using basic_zstring = CharT*;
template <std::ptrdiff_t Extent = dynamic_extent>
using czstring = basic_zstring<const char, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cwzstring = basic_zstring<const wchar_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cu16zstring = basic_zstring<const char16_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cu32zstring = basic_zstring<const char32_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using zstring = basic_zstring<char, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using wzstring = basic_zstring<wchar_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using u16zstring = basic_zstring<char16_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using u32zstring = basic_zstring<char32_t, Extent>;
namespace details
{
template <class CharT>
std::ptrdiff_t string_length(const CharT* str, std::ptrdiff_t n)
{
if (str == nullptr || n <= 0) return 0;
const span<const CharT> str_span{str, n};
std::ptrdiff_t len = 0;
while (len < n && str_span[len]) len++;
return len;
}
}
//
// ensure_sentinel()
//
// Provides a way to obtain an span from a contiguous sequence
// that ends with a (non-inclusive) sentinel value.
//
// Will fail-fast if sentinel cannot be found before max elements are examined.
//
template <typename T, const T Sentinel>
span<T, dynamic_extent> ensure_sentinel(T* seq, std::ptrdiff_t max = PTRDIFF_MAX)
{
auto cur = seq;
while ((cur - seq) < max && *cur != Sentinel) ++cur;
Ensures(*cur == Sentinel);
return {seq, cur - seq};
}
//
// ensure_z - creates a span for a zero terminated strings.
// Will fail fast if a null-terminator cannot be found before
// the limit of size_type.
//
template <typename CharT>
span<CharT, dynamic_extent> ensure_z(CharT* const& sz, std::ptrdiff_t max = PTRDIFF_MAX)
{
return ensure_sentinel<CharT, CharT(0)>(sz, max);
}
template <typename CharT, std::size_t N>
span<CharT, dynamic_extent> ensure_z(CharT (&sz)[N])
{
return ensure_z(&sz[0], static_cast<std::ptrdiff_t>(N));
}
template <class Cont>
span<typename std::remove_pointer<typename Cont::pointer>::type, dynamic_extent>
ensure_z(Cont& cont)
{
return ensure_z(cont.data(), static_cast<std::ptrdiff_t>(cont.size()));
}
template <typename CharT, std::ptrdiff_t>
class basic_string_span;
namespace details
{
template <typename T>
struct is_basic_string_span_oracle : std::false_type
{
};
template <typename CharT, std::ptrdiff_t Extent>
struct is_basic_string_span_oracle<basic_string_span<CharT, Extent>> : std::true_type
{
};
template <typename T>
struct is_basic_string_span : is_basic_string_span_oracle<std::remove_cv_t<T>>
{
};
}
//
// string_span and relatives
//
template <typename CharT, std::ptrdiff_t Extent = dynamic_extent>
class basic_string_span
{
public:
using element_type = CharT;
using pointer = std::add_pointer_t<element_type>;
using reference = std::add_lvalue_reference_t<element_type>;
using const_reference = std::add_lvalue_reference_t<std::add_const_t<element_type>>;
using impl_type = span<element_type, Extent>;
using index_type = typename impl_type::index_type;
using iterator = typename impl_type::iterator;
using const_iterator = typename impl_type::const_iterator;
using reverse_iterator = typename impl_type::reverse_iterator;
using const_reverse_iterator = typename impl_type::const_reverse_iterator;
// default (empty)
constexpr basic_string_span() GSL_NOEXCEPT = default;
// copy
constexpr basic_string_span(const basic_string_span& other) GSL_NOEXCEPT = default;
// assign
constexpr basic_string_span& operator=(const basic_string_span& other) GSL_NOEXCEPT = default;
constexpr basic_string_span(pointer ptr, index_type length) : span_(ptr, length) {}
constexpr basic_string_span(pointer firstElem, pointer lastElem) : span_(firstElem, lastElem) {}
// From static arrays - if 0-terminated, remove 0 from the view
// All other containers allow 0s within the length, so we do not remove them
template <std::size_t N>
constexpr basic_string_span(element_type (&arr)[N]) : span_(remove_z(arr))
{
}
template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>>
constexpr basic_string_span(std::array<ArrayElementType, N>& arr) GSL_NOEXCEPT : span_(arr)
{
}
template <std::size_t N, class ArrayElementType = std::remove_const_t<element_type>>
constexpr basic_string_span(const std::array<ArrayElementType, N>& arr) GSL_NOEXCEPT
: span_(arr)
{
}
// Container signature should work for basic_string after C++17 version exists
template <class Traits, class Allocator>
constexpr basic_string_span(std::basic_string<element_type, Traits, Allocator>& str)
: span_(&str[0], narrow_cast<std::ptrdiff_t>(str.length()))
{
}
template <class Traits, class Allocator>
constexpr basic_string_span(const std::basic_string<element_type, Traits, Allocator>& str)
: span_(&str[0], str.length())
{
}
// from containers. Containers must have a pointer type and data() function signatures
template <class Container,
class = std::enable_if_t<
!details::is_basic_string_span<Container>::value &&
std::is_convertible<typename Container::pointer, pointer>::value &&
std::is_convertible<typename Container::pointer,
decltype(std::declval<Container>().data())>::value>>
constexpr basic_string_span(Container& cont) : span_(cont)
{
}
template <class Container,
class = std::enable_if_t<
!details::is_basic_string_span<Container>::value &&
std::is_convertible<typename Container::pointer, pointer>::value &&
std::is_convertible<typename Container::pointer,
decltype(std::declval<Container>().data())>::value>>
constexpr basic_string_span(const Container& cont) : span_(cont)
{
}
// from string_span
template <
class OtherValueType, std::ptrdiff_t OtherExtent,
class = std::enable_if_t<std::is_convertible<
typename basic_string_span<OtherValueType, OtherExtent>::impl_type, impl_type>::value>>
constexpr basic_string_span(basic_string_span<OtherValueType, OtherExtent> other)
: span_(other.data(), other.length())
{
}
template <index_type Count>
constexpr basic_string_span<element_type, Count> first() const
{
return {span_.template first<Count>()};
}
constexpr basic_string_span<element_type, dynamic_extent> first(index_type count) const
{
return {span_.first(count)};
}
template <index_type Count>
constexpr basic_string_span<element_type, Count> last() const
{
return {span_.template last<Count>()};
}
constexpr basic_string_span<element_type, dynamic_extent> last(index_type count) const
{
return {span_.last(count)};
}
template <index_type Offset, index_type Count>
constexpr basic_string_span<element_type, Count> subspan() const
{
return {span_.template subspan<Offset, Count>()};
}
constexpr basic_string_span<element_type, dynamic_extent>
subspan(index_type offset, index_type count = dynamic_extent) const
{
return {span_.subspan(offset, count)};
}
constexpr reference operator[](index_type idx) const { return span_[idx]; }
constexpr reference operator()(index_type idx) const { return span_[idx]; }
constexpr pointer data() const { return span_.data(); }
constexpr index_type length() const GSL_NOEXCEPT { return span_.size(); }
constexpr index_type size() const GSL_NOEXCEPT { return span_.size(); }
constexpr index_type size_bytes() const GSL_NOEXCEPT { return span_.size_bytes(); }
constexpr index_type length_bytes() const GSL_NOEXCEPT { return span_.length_bytes(); }
constexpr bool empty() const GSL_NOEXCEPT { return size() == 0; }
constexpr iterator begin() const GSL_NOEXCEPT { return span_.begin(); }
constexpr iterator end() const GSL_NOEXCEPT { return span_.end(); }
constexpr const_iterator cbegin() const GSL_NOEXCEPT { return span_.cbegin(); }
constexpr const_iterator cend() const GSL_NOEXCEPT { return span_.cend(); }
constexpr reverse_iterator rbegin() const GSL_NOEXCEPT { return span_.rbegin(); }
constexpr reverse_iterator rend() const GSL_NOEXCEPT { return span_.rend(); }
constexpr const_reverse_iterator crbegin() const GSL_NOEXCEPT { return span_.crbegin(); }
constexpr const_reverse_iterator crend() const GSL_NOEXCEPT { return span_.crend(); }
private:
static impl_type remove_z(pointer const& sz, std::ptrdiff_t max)
{
return {sz, details::string_length(sz, max)};
}
template <std::size_t N>
static impl_type remove_z(element_type (&sz)[N])
{
return remove_z(&sz[0], narrow_cast<std::ptrdiff_t>(N));
}
impl_type span_;
};
template <std::ptrdiff_t Extent = dynamic_extent>
using string_span = basic_string_span<char, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cstring_span = basic_string_span<const char, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using wstring_span = basic_string_span<wchar_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cwstring_span = basic_string_span<const wchar_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using u16string_span = basic_string_span<char16_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cu16string_span = basic_string_span<const char16_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using u32string_span = basic_string_span<char32_t, Extent>;
template <std::ptrdiff_t Extent = dynamic_extent>
using cu32string_span = basic_string_span<const char32_t, Extent>;
//
// to_string() allow (explicit) conversions from string_span to string
//
template <typename CharT, std::ptrdiff_t Extent>
std::basic_string<typename std::remove_const<CharT>::type>
to_string(basic_string_span<CharT, Extent> view)
{
return {view.data(), static_cast<std::size_t>(view.length())};
}
template <typename CharT, typename Traits = typename std::char_traits<CharT>,
typename Allocator = std::allocator<CharT>, typename gCharT, std::ptrdiff_t Extent>
std::basic_string<CharT, Traits, Allocator> to_basic_string(basic_string_span<gCharT, Extent> view)
{
return {view.data(), static_cast<std::size_t>(view.length())};
}
template <class ElementType, std::ptrdiff_t Extent>
basic_string_span<const byte, details::calculate_byte_size<ElementType, Extent>::value>
as_bytes(basic_string_span<ElementType, Extent> s) noexcept
{
return { reinterpret_cast<const byte*>(s.data()), s.size_bytes() };
}
template <class ElementType, std::ptrdiff_t Extent,
class = std::enable_if_t<!std::is_const<ElementType>::value>>
basic_string_span<byte, details::calculate_byte_size<ElementType, Extent>::value>
as_writeable_bytes(basic_string_span<ElementType, Extent> s) noexcept
{
return {reinterpret_cast<byte*>(s.data()), s.size_bytes()};
}
// zero-terminated string span, used to convert
// zero-terminated spans to legacy strings
template <typename CharT, std::ptrdiff_t Extent = dynamic_extent>
class basic_zstring_span
{
public:
using value_type = CharT;
using const_value_type = std::add_const_t<CharT>;
using pointer = std::add_pointer_t<value_type>;
using const_pointer = std::add_pointer_t<const_value_type>;
using zstring_type = basic_zstring<value_type, Extent>;
using const_zstring_type = basic_zstring<const_value_type, Extent>;
using impl_type = span<value_type, Extent>;
using string_span_type = basic_string_span<value_type, Extent>;
constexpr basic_zstring_span(impl_type s) GSL_NOEXCEPT : span_(s)
{
// expects a zero-terminated span
Expects(s[s.size() - 1] == '\0');
}
// copy
constexpr basic_zstring_span(const basic_zstring_span& other) = default;
// move
constexpr basic_zstring_span(basic_zstring_span&& other) = default;
// assign
constexpr basic_zstring_span& operator=(const basic_zstring_span& other) = default;
// move assign
constexpr basic_zstring_span& operator=(basic_zstring_span&& other) = default;
constexpr bool empty() const GSL_NOEXCEPT { return span_.size() == 0; }
constexpr string_span_type as_string_span() const GSL_NOEXCEPT
{
auto sz = span_.size();
return { span_.data(), sz > 1 ? sz - 1 : 0 };
}
constexpr string_span_type ensure_z() const GSL_NOEXCEPT { return gsl::ensure_z(span_); }
constexpr const_zstring_type assume_z() const GSL_NOEXCEPT { return span_.data(); }
private:
impl_type span_;
};
template <std::ptrdiff_t Max = dynamic_extent>
using zstring_span = basic_zstring_span<char, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using wzstring_span = basic_zstring_span<wchar_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using u16zstring_span = basic_zstring_span<char16_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using u32zstring_span = basic_zstring_span<char32_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using czstring_span = basic_zstring_span<const char, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using cwzstring_span = basic_zstring_span<const wchar_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using cu16zstring_span = basic_zstring_span<const char16_t, Max>;
template <std::ptrdiff_t Max = dynamic_extent>
using cu32zstring_span = basic_zstring_span<const char32_t, Max>;
// operator ==
template <class CharT, std::ptrdiff_t Extent, class T,
class = std::enable_if_t<
details::is_basic_string_span<T>::value ||
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>>>::value>>
bool operator==(const gsl::basic_string_span<CharT, Extent>& one, const T& other) GSL_NOEXCEPT
{
const gsl::basic_string_span<std::add_const_t<CharT>> tmp(other);
return std::equal(one.begin(), one.end(), tmp.begin(), tmp.end());
}
template <class CharT, std::ptrdiff_t Extent, class T,
class = std::enable_if_t<
!details::is_basic_string_span<T>::value &&
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>>>::value>>
bool operator==(const T& one, const gsl::basic_string_span<CharT, Extent>& other) GSL_NOEXCEPT
{
gsl::basic_string_span<std::add_const_t<CharT>> tmp(one);
return std::equal(tmp.begin(), tmp.end(), other.begin(), other.end());
}
// operator !=
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator!=(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
return !(one == other);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator!=(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
return !(one == other);
}
// operator<
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator<(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
const gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(other);
return std::lexicographical_compare(one.begin(), one.end(), tmp.begin(), tmp.end());
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator<(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(one);
return std::lexicographical_compare(tmp.begin(), tmp.end(), other.begin(), other.end());
}
#ifndef _MSC_VER
// VS treats temp and const containers as convertible to basic_string_span,
// so the cases below are already covered by the previous operators
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator<(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(other);
return std::lexicographical_compare(one.begin(), one.end(), tmp.begin(), tmp.end());
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator<(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
gsl::basic_string_span<std::add_const_t<CharT>, Extent> tmp(one);
return std::lexicographical_compare(tmp.begin(), tmp.end(), other.begin(), other.end());
}
#endif
// operator <=
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator<=(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
return !(other < one);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator<=(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
return !(other < one);
}
#ifndef _MSC_VER
// VS treats temp and const containers as convertible to basic_string_span,
// so the cases below are already covered by the previous operators
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator<=(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
return !(other < one);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator<=(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
return !(other < one);
}
#endif
// operator>
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator>(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
return other < one;
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator>(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
return other < one;
}
#ifndef _MSC_VER
// VS treats temp and const containers as convertible to basic_string_span,
// so the cases below are already covered by the previous operators
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator>(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
return other < one;
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator>(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
return other < one;
}
#endif
// operator >=
template <typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<std::is_convertible<
T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value>>
bool operator>=(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
return !(one < other);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename = std::enable_if_t<
std::is_convertible<T, gsl::basic_string_span<std::add_const_t<CharT>, Extent>>::value &&
!gsl::details::is_basic_string_span<T>::value>>
bool operator>=(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
return !(one < other);
}
#ifndef _MSC_VER
// VS treats temp and const containers as convertible to basic_string_span,
// so the cases below are already covered by the previous operators
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator>=(gsl::basic_string_span<CharT, Extent> one, const T& other) GSL_NOEXCEPT
{
return !(one < other);
}
template <
typename CharT, std::ptrdiff_t Extent = gsl::dynamic_extent, typename T,
typename DataType = typename T::value_type,
typename = std::enable_if_t<
!gsl::details::is_span<T>::value && !gsl::details::is_basic_string_span<T>::value &&
std::is_convertible<DataType*, CharT*>::value &&
std::is_same<std::decay_t<decltype(std::declval<T>().size(), *std::declval<T>().data())>,
DataType>::value>>
bool operator>=(const T& one, gsl::basic_string_span<CharT, Extent> other) GSL_NOEXCEPT
{
return !(one < other);
}
#endif
} // namespace gsl
#undef GSL_NOEXCEPT
#ifdef _MSC_VER
#pragma warning(pop)
#if _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
#endif // _MSC_VER < 1910
#endif // _MSC_VER
#endif // GSL_STRING_SPAN_H

View File

@ -5,7 +5,6 @@
#include <sstream>
#include <iomanip>
#include <array>
#include <string_view>
#include <iterator>
#include <random>
#include <memory>
@ -15,7 +14,6 @@
#include <chrono>
#include <numeric>
#include <atomic>
#include <gsl/span>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
@ -342,19 +340,19 @@ namespace uuids
constexpr uuid() noexcept : data({}) {};
uuid(value_type(&arr)[16]) noexcept
{
std::copy(std::cbegin(arr), std::cend(arr), std::begin(data));
}
//uuid(value_type(&arr)[16]) noexcept
//{
// std::copy(std::cbegin(arr), std::cend(arr), std::begin(data));
//}
uuid(std::array<value_type, 16> const & arr) noexcept
{
std::copy(std::cbegin(arr), std::cend(arr), std::begin(data));
}
explicit uuid(gsl::span<value_type, 16> bytes)
explicit uuid(value_type * bytes)
{
std::copy(std::cbegin(bytes), std::cend(bytes), std::begin(data));
std::copy(bytes, bytes + 16, std::begin(data));
}
template<typename ForwardIterator>
@ -403,9 +401,14 @@ namespace uuids
data.swap(other.data);
}
inline gsl::span<std::byte const, 16> as_bytes() const
inline const std::array<value_type, 16> & as_array() const
{
return gsl::span<std::byte const, 16>(reinterpret_cast<std::byte const*>(data.data()), 16);
return data;
}
inline const std::uint8_t * as_data() const
{
return reinterpret_cast<const std::uint8_t*>(data.data());
}
template<class CharT = char>
@ -758,9 +761,12 @@ namespace uuids
class uuid_name_generator
{
public:
explicit uuid_name_generator(uuid const& namespace_uuid) noexcept
: nsuuid(namespace_uuid)
{}
explicit uuid_name_generator(uuid const& namespace_uuid) noexcept
: nsuuid(namespace_uuid)
{}
explicit uuid_name_generator()
: nsuuid()
{}
template<class CharT = char>
uuid operator()(CharT const * name)
@ -789,24 +795,21 @@ namespace uuids
private:
void reset()
{
hasher.reset();
std::byte bytes[16];
auto nsbytes = nsuuid.as_bytes();
std::copy(std::cbegin(nsbytes), std::cend(nsbytes), bytes);
hasher.process_bytes(bytes, 16);
hasher.reset();
if (nsuuid.has_value())
{
auto nsbytes = nsuuid.value().as_array();
hasher.process_bytes(nsbytes.data(), 16);
}
}
template <typename char_type,
typename = std::enable_if_t<std::is_integral<char_type>::value>>
void process_characters(char_type const * const characters, size_t const count)
{
for (size_t i = 0; i < count; i++)
for (size_t i = 0; i < count * sizeof(char_type); i++)
{
uint32_t c = characters[i];
hasher.process_byte(static_cast<unsigned char>((c >> 0) & 0xFF));
hasher.process_byte(static_cast<unsigned char>((c >> 8) & 0xFF));
hasher.process_byte(static_cast<unsigned char>((c >> 16) & 0xFF));
hasher.process_byte(static_cast<unsigned char>((c >> 24) & 0xFF));
hasher.process_byte(reinterpret_cast<const std::uint8_t *>(characters)[i]);
}
}
@ -832,105 +835,29 @@ namespace uuids
}
private:
uuid nsuuid;
detail::sha1 hasher;
std::optional<uuid> nsuuid;
};
// !!! DO NOT USE THIS IN PRODUCTION
// this implementation is unreliable for good uuids
class uuid_time_generator
static uuid gen_string(const std::string& in)
{
using mac_address = std::array<unsigned char, 6>;
std::optional<mac_address> device_address;
bool get_mac_address()
{
if (device_address.has_value())
{
return true;
}
#ifdef _WIN32
DWORD len = 0;
auto ret = GetAdaptersInfo(nullptr, &len);
if (ret != ERROR_BUFFER_OVERFLOW) return false;
std::vector<unsigned char> buf(len);
auto pips = reinterpret_cast<PIP_ADAPTER_INFO>(&buf.front());
ret = GetAdaptersInfo(pips, &len);
if (ret != ERROR_SUCCESS) return false;
mac_address addr;
std::copy(pips->Address, pips->Address + 6, std::begin(addr));
device_address = addr;
#endif
return device_address.has_value();
}
long long get_time_intervals()
{
auto start = std::chrono::system_clock::from_time_t(time_t(-12219292800));
auto diff = std::chrono::system_clock::now() - start;
auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(diff).count();
return ns / 100;
}
public:
uuid_time_generator()
{
}
uuid operator()()
{
if (get_mac_address())
{
std::array<uuids::uuid::value_type, 16> data;
auto tm = get_time_intervals();
short clock_seq = detail::clock_sequence++;
clock_seq &= 0x3FFF;
auto ptm = reinterpret_cast<uuids::uuid::value_type*>(&tm);
ptm[0] &= 0x0F;
memcpy(&data[0], ptm + 4, 4);
memcpy(&data[4], ptm + 2, 2);
memcpy(&data[6], ptm, 2);
memcpy(&data[8], reinterpret_cast<uuids::uuid::value_type*>(&clock_seq), 2);
// variant must be 0b10xxxxxx
data[8] &= 0xBF;
data[8] |= 0x80;
// version must be 0b0001xxxx
data[6] &= 0x5F;
data[6] |= 0x10;
memcpy(&data[10], &device_address.value()[0], 6);
return uuids::uuid{std::cbegin(data), std::cend(data)};
}
return {};
}
};
}
uuids::uuid_name_generator re;
return re(in);
}
};
namespace std
{
template <>
struct hash<uuids::uuid>
{
using argument_type = uuids::uuid;
using result_type = std::size_t;
template <>
struct hash<uuids::uuid>
{
using argument_type = uuids::uuid;
using result_type = std::size_t;
result_type operator()(argument_type const &uuid) const
{
std::hash<std::string> hasher;
return static_cast<result_type>(hasher(uuids::to_string(uuid)));
}
};
}
result_type operator()(argument_type const& uuid) const
{
std::hash<std::string> hasher;
return static_cast<result_type>(hasher(uuids::to_string(uuid)));
}
};
}

View File

@ -1,3 +0,0 @@
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

View File

@ -1,279 +0,0 @@
#include "uuid.h"
#include "catch.hpp"
#include <set>
#include <unordered_set>
#include <random>
#include <vector>
using namespace uuids;
TEST_CASE("Test multiple default generators", "[gen][rand]")
{
uuid id1;
uuid id2;
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
id1 = uuids::uuid_random_generator{ generator }();
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
}
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
id2 = uuids::uuid_random_generator{ generator }();
REQUIRE(!id2.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
}
REQUIRE(id1 != id2);
}
TEST_CASE("Test default generator", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
uuid const guid = uuids::uuid_random_generator{generator}();
REQUIRE(!guid.is_nil());
REQUIRE(guid.version() == uuids::uuid_version::random_number_based);
REQUIRE(guid.variant() == uuids::uuid_variant::rfc);
}
TEST_CASE("Test random generator (conversion ctor w/ smart ptr)", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
uuids::uuid_random_generator dgen(&generator);
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test random generator (conversion ctor w/ ptr)", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
auto generator = std::make_unique<std::mt19937>(seq);
uuids::uuid_random_generator dgen(generator.get());
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test random generator (conversion ctor w/ ref)", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
uuids::uuid_random_generator dgen(generator);
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test basic random generator (conversion ctor w/ ptr) w/ ranlux48_base", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, 6> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::ranlux48_base generator(seq);
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(&generator);
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test basic random generator (conversion ctor w/ smart ptr) w/ ranlux48_base", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, 6> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
auto generator = std::make_unique<std::ranlux48_base>(seq);
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(generator.get());
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test basic random generator (conversion ctor w/ ref) w/ ranlux48_base", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, 6> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::ranlux48_base generator(seq);
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(generator);
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test namespaces", "[gen][name]")
{
REQUIRE(uuid_namespace_dns == uuids::uuid::from_string("6ba7b810-9dad-11d1-80b4-00c04fd430c8"));
REQUIRE(uuid_namespace_url == uuids::uuid::from_string("6ba7b811-9dad-11d1-80b4-00c04fd430c8"));
REQUIRE(uuid_namespace_oid == uuids::uuid::from_string("6ba7b812-9dad-11d1-80b4-00c04fd430c8"));
REQUIRE(uuid_namespace_x500 == uuids::uuid::from_string("6ba7b814-9dad-11d1-80b4-00c04fd430c8"));
}
TEST_CASE("Test name generator (char*)", "[gen][name]")
{
uuids::uuid_name_generator dgen(uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e43").value());
auto id1 = dgen("john");
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen("jane");
REQUIRE(!id2.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
auto id3 = dgen("jane");
REQUIRE(!id3.is_nil());
REQUIRE(id3.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id3.variant() == uuids::uuid_variant::rfc);
auto id4 = dgen(L"jane");
REQUIRE(!id4.is_nil());
REQUIRE(id4.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id4.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
REQUIRE(id2 == id3);
REQUIRE(id3 != id4);
}
TEST_CASE("Test name generator (std::string)", "[gen][name]")
{
using namespace std::string_literals;
uuids::uuid_name_generator dgen(uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e43").value());
auto id1 = dgen("john"s);
REQUIRE(!id1.is_nil());
REQUIRE(id1.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen("jane"s);
REQUIRE(!id2.is_nil());
REQUIRE(id2.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
auto id3 = dgen("jane"s);
REQUIRE(!id3.is_nil());
REQUIRE(id3.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id3.variant() == uuids::uuid_variant::rfc);
auto id4 = dgen(L"jane"s);
REQUIRE(!id4.is_nil());
REQUIRE(id4.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id4.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
REQUIRE(id2 == id3);
REQUIRE(id3 != id4);
}
#ifdef _WIN32
TEST_CASE("Test time generator", "[gen][time]")
{
uuid_time_generator gen;
auto id1 = gen();
auto id2 = gen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1.version() == uuids::uuid_version::time_based);
REQUIRE(!id2.is_nil());
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id2.version() == uuids::uuid_version::time_based);
REQUIRE(id1 != id2);
std::set<uuids::uuid> ids;
for (int i = 0; i < 100; ++i)
ids.insert(gen());
REQUIRE(ids.size() == 100);
}
#endif

View File

@ -1,520 +0,0 @@
#include "uuid.h"
#include "catch.hpp"
#include <cstring>
#include <set>
#include <unordered_set>
#include <vector>
#include <iostream>
using namespace uuids;
namespace
{
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0205r0.html
template <typename EngineT, std::size_t StateSize = EngineT::state_size>
void seed_rng(EngineT& engine)
{
using engine_type = typename EngineT::result_type;
using device_type = std::random_device::result_type;
using seedseq_type = std::seed_seq::result_type;
constexpr auto bytes_needed = StateSize * sizeof(engine_type);
constexpr auto numbers_needed = (sizeof(device_type) < sizeof(seedseq_type))
? (bytes_needed / sizeof(device_type))
: (bytes_needed / sizeof(seedseq_type));
std::array<device_type, numbers_needed> numbers{};
std::random_device rnddev{};
std::generate(std::begin(numbers), std::end(numbers), std::ref(rnddev));
std::seed_seq seedseq(std::cbegin(numbers), std::cend(numbers));
engine.seed(seedseq);
}
}
TEST_CASE("Test default constructor", "[ctors]")
{
uuid empty;
REQUIRE(empty.is_nil());
}
TEST_CASE("Test string conversion", "[ops]")
{
uuid empty;
REQUIRE(uuids::to_string(empty) == "00000000-0000-0000-0000-000000000000");
REQUIRE(uuids::to_string<wchar_t>(empty) == L"00000000-0000-0000-0000-000000000000");
}
TEST_CASE("Test is_valid_uuid(char*)", "[parse]")
{
REQUIRE(uuids::uuid::is_valid_uuid("47183823-2574-4bfd-b411-99ed177d3e43"));
REQUIRE(uuids::uuid::is_valid_uuid("{47183823-2574-4bfd-b411-99ed177d3e43}"));
REQUIRE(uuids::uuid::is_valid_uuid(L"47183823-2574-4bfd-b411-99ed177d3e43"));
REQUIRE(uuids::uuid::is_valid_uuid(L"{47183823-2574-4bfd-b411-99ed177d3e43}"));
REQUIRE(uuids::uuid::is_valid_uuid("00000000-0000-0000-0000-000000000000"));
REQUIRE(uuids::uuid::is_valid_uuid("{00000000-0000-0000-0000-000000000000}"));
REQUIRE(uuids::uuid::is_valid_uuid(L"00000000-0000-0000-0000-000000000000"));
REQUIRE(uuids::uuid::is_valid_uuid(L"{00000000-0000-0000-0000-000000000000}"));
}
TEST_CASE("Test is_valid_uuid(basic_string)", "[parse]")
{
using namespace std::string_literals;
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s;
REQUIRE(uuids::uuid::is_valid_uuid(str));
}
{
auto str = "{47183823-2574-4bfd-b411-99ed177d3e43}"s;
REQUIRE(uuids::uuid::is_valid_uuid(str));
}
{
auto str = L"47183823-2574-4bfd-b411-99ed177d3e43"s;
REQUIRE(uuids::uuid::is_valid_uuid(str));
}
{
auto str = L"{47183823-2574-4bfd-b411-99ed177d3e43}"s;
REQUIRE(uuids::uuid::is_valid_uuid(str));
}
{
auto str = "00000000-0000-0000-0000-000000000000"s;
REQUIRE(uuids::uuid::is_valid_uuid(str));
}
{
auto str = "{00000000-0000-0000-0000-000000000000}"s;
REQUIRE(uuids::uuid::is_valid_uuid(str));
}
{
auto str = L"00000000-0000-0000-0000-000000000000"s;
REQUIRE(uuids::uuid::is_valid_uuid(str));
}
{
auto str = L"{00000000-0000-0000-0000-000000000000}"s;
REQUIRE(uuids::uuid::is_valid_uuid(str));
}
}
TEST_CASE("Test is_valid_uuid(char*) invalid format", "[parse]")
{
REQUIRE(!uuids::uuid::is_valid_uuid(""));
REQUIRE(!uuids::uuid::is_valid_uuid("{}"));
REQUIRE(!uuids::uuid::is_valid_uuid("47183823-2574-4bfd-b411-99ed177d3e4"));
REQUIRE(!uuids::uuid::is_valid_uuid("47183823-2574-4bfd-b411-99ed177d3e430"));
REQUIRE(!uuids::uuid::is_valid_uuid("{47183823-2574-4bfd-b411-99ed177d3e43"));
REQUIRE(!uuids::uuid::is_valid_uuid("47183823-2574-4bfd-b411-99ed177d3e43}"));
}
TEST_CASE("Test is_valid_uuid(basic_string) invalid format", "[parse]")
{
using namespace std::string_literals;
{
auto str = ""s;
REQUIRE(!uuids::uuid::is_valid_uuid(str));
}
{
auto str = "{}"s;
REQUIRE(!uuids::uuid::is_valid_uuid(str));
}
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e4"s;
REQUIRE(!uuids::uuid::is_valid_uuid(str));
}
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e430"s;
REQUIRE(!uuids::uuid::is_valid_uuid(str));
}
{
auto str = "{47183823-2574-4bfd-b411-99ed177d3e43"s;
REQUIRE(!uuids::uuid::is_valid_uuid(str));
}
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e43}"s;
REQUIRE(!uuids::uuid::is_valid_uuid(str));
}
}
TEST_CASE("Test from_string(char*)", "[parse]")
{
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e43";
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(uuids::to_string(guid) == str);
}
{
auto str = "{47183823-2574-4bfd-b411-99ed177d3e43}";
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
}
{
auto guid = uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e43").value();
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
REQUIRE(uuids::to_string<wchar_t>(guid) == L"47183823-2574-4bfd-b411-99ed177d3e43");
}
{
auto str = L"47183823-2574-4bfd-b411-99ed177d3e43";
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(uuids::to_string<wchar_t>(guid) == str);
}
{
auto str = "4718382325744bfdb41199ed177d3e43";
REQUIRE_NOTHROW(uuids::uuid::from_string(str));
REQUIRE(uuids::uuid::from_string(str).has_value());
}
{
auto str = "00000000-0000-0000-0000-000000000000";
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(guid.is_nil());
}
{
auto str = "{00000000-0000-0000-0000-000000000000}";
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(guid.is_nil());
}
{
auto str = L"00000000-0000-0000-0000-000000000000";
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(guid.is_nil());
}
{
auto str = L"{00000000-0000-0000-0000-000000000000}";
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(guid.is_nil());
}
}
TEST_CASE("Test from_string(basic_string)", "[parse]")
{
using namespace std::string_literals;
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s;
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(uuids::to_string(guid) == str);
}
{
auto str = "{47183823-2574-4bfd-b411-99ed177d3e43}"s;
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
}
{
auto guid = uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e43").value();
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
REQUIRE(uuids::to_string<wchar_t>(guid) == L"47183823-2574-4bfd-b411-99ed177d3e43");
}
{
auto str = L"47183823-2574-4bfd-b411-99ed177d3e43"s;
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(uuids::to_string<wchar_t>(guid) == str);
}
{
auto str = "4718382325744bfdb41199ed177d3e43"s;
REQUIRE_NOTHROW(uuids::uuid::from_string(str));
REQUIRE(uuids::uuid::from_string(str).has_value());
}
{
auto str = "00000000-0000-0000-0000-000000000000"s;
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(guid.is_nil());
}
{
auto str = "{00000000-0000-0000-0000-000000000000}"s;
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(guid.is_nil());
}
{
auto str = L"00000000-0000-0000-0000-000000000000"s;
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(guid.is_nil());
}
{
auto str = L"{00000000-0000-0000-0000-000000000000}"s;
auto guid = uuids::uuid::from_string(str).value();
REQUIRE(guid.is_nil());
}
}
TEST_CASE("Test from_string(char*) invalid format", "[parse]")
{
REQUIRE(!uuids::uuid::from_string("").has_value());
REQUIRE(!uuids::uuid::from_string("{}").has_value());
REQUIRE(!uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e4").has_value());
REQUIRE(!uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e430").has_value());
REQUIRE(!uuids::uuid::from_string("{47183823-2574-4bfd-b411-99ed177d3e43").has_value());
REQUIRE(!uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e43}").has_value());
}
TEST_CASE("Test from_string(basic_string) invalid format", "[parse]")
{
using namespace std::string_literals;
{
auto str = ""s;
REQUIRE(!uuids::uuid::from_string(str).has_value());
}
{
auto str = "{}"s;
REQUIRE(!uuids::uuid::from_string(str).has_value());
}
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e4"s;
REQUIRE(!uuids::uuid::from_string(str).has_value());
}
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e430"s;
REQUIRE(!uuids::uuid::from_string(str).has_value());
}
{
auto str = "{47183823-2574-4bfd-b411-99ed177d3e43"s;
REQUIRE(!uuids::uuid::from_string(str).has_value());
}
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e43}"s;
REQUIRE(!uuids::uuid::from_string(str).has_value());
}
}
TEST_CASE("Test iterators constructor", "[ctors]")
{
using namespace std::string_literals;
{
std::array<uuids::uuid::value_type, 16> arr{ {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 } };
uuid guid(std::begin(arr), std::end(arr));
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
{
uuids::uuid::value_type arr[16] = {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 };
uuid guid(std::begin(arr), std::end(arr));
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
}
TEST_CASE("Test array constructors", "[ctors]")
{
using namespace std::string_literals;
{
uuids::uuid guid{
{0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 } };
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
{
std::array<uuids::uuid::value_type, 16> arr{ {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 } };
uuid guid(arr);
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
{
uuids::uuid::value_type arr[16] {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 };
uuid guid(arr);
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
}
TEST_CASE("Test equality", "[operators]")
{
uuid empty;
auto engine = uuids::uuid_random_generator::engine_type{};
seed_rng(engine);
uuid guid = uuids::uuid_random_generator{engine}();
REQUIRE(empty == empty);
REQUIRE(guid == guid);
REQUIRE(empty != guid);
}
TEST_CASE("Test comparison", "[operators]")
{
auto empty = uuid{};
auto engine = uuids::uuid_random_generator::engine_type{};
seed_rng(engine);
uuids::uuid_random_generator gen{ engine };
auto id = gen();
REQUIRE(empty < id);
std::set<uuids::uuid> ids{
uuid{},
gen(),
gen(),
gen(),
gen()
};
REQUIRE(ids.size() == 5);
REQUIRE(ids.find(uuid{}) != ids.end());
}
TEST_CASE("Test hashing", "[ops]")
{
using namespace std::string_literals;
auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s;
auto guid = uuids::uuid::from_string(str).value();
auto h1 = std::hash<std::string>{};
auto h2 = std::hash<uuid>{};
REQUIRE(h1(str) == h2(guid));
auto engine = uuids::uuid_random_generator::engine_type{};
seed_rng(engine);
uuids::uuid_random_generator gen{ engine };
std::unordered_set<uuids::uuid> ids{
uuid{},
gen(),
gen(),
gen(),
gen()
};
REQUIRE(ids.size() == 5);
REQUIRE(ids.find(uuid{}) != ids.end());
}
TEST_CASE("Test swap", "[ops]")
{
uuid empty;
auto engine = uuids::uuid_random_generator::engine_type{};
seed_rng(engine);
uuid guid = uuids::uuid_random_generator{engine}();
REQUIRE(empty.is_nil());
REQUIRE(!guid.is_nil());
std::swap(empty, guid);
REQUIRE(!empty.is_nil());
REQUIRE(guid.is_nil());
empty.swap(guid);
REQUIRE(empty.is_nil());
REQUIRE(!guid.is_nil());
}
TEST_CASE("Test constexpr", "[const]")
{
constexpr uuid empty;
[[maybe_unused]] constexpr bool isnil = empty.is_nil();
[[maybe_unused]] constexpr uuids::uuid_variant variant = empty.variant();
[[maybe_unused]] constexpr uuid_version version = empty.version();
}
TEST_CASE("Test size", "[operators]")
{
REQUIRE(sizeof(uuid) == 16);
}
TEST_CASE("Test assignment", "[ops]")
{
auto id1 = uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e43").value();
auto id2 = id1;
REQUIRE(id1 == id2);
id1 = uuids::uuid::from_string("{fea43102-064f-4444-adc2-02cec42623f8}").value();
REQUIRE(id1 != id2);
auto id3 = std::move(id2);
REQUIRE(uuids::to_string(id3) == "47183823-2574-4bfd-b411-99ed177d3e43");
}
TEST_CASE("Test trivial", "[trivial]")
{
REQUIRE(std::is_trivially_copyable_v<uuids::uuid>);
}
TEST_CASE("Test as_bytes", "[ops]")
{
std::array<uuids::uuid::value_type, 16> arr{ {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43
} };
{
uuids::uuid id{ arr };
REQUIRE(!id.is_nil());
auto view = id.as_bytes();
REQUIRE(memcmp(view.data(), arr.data(), arr.size()) == 0);
}
{
const uuids::uuid id{ arr };
REQUIRE(!id.is_nil());
auto view = id.as_bytes();
REQUIRE(memcmp(view.data(), arr.data(), arr.size()) == 0);
}
}