catch_stringref.cpp
1 2 // Copyright Catch2 Authors 3 // Distributed under the Boost Software License, Version 1.0. 4 // (See accompanying file LICENSE.txt or copy at 5 // https://www.boost.org/LICENSE_1_0.txt) 6 7 // SPDX-License-Identifier: BSL-1.0 8 #include <catch2/internal/catch_stringref.hpp> 9 10 #include <algorithm> 11 #include <ostream> 12 #include <cstring> 13 #include <cstdint> 14 15 namespace Catch { 16 StringRef::StringRef( char const* rawChars ) noexcept 17 : StringRef( rawChars, std::strlen(rawChars) ) 18 {} 19 20 21 bool StringRef::operator<(StringRef rhs) const noexcept { 22 if (m_size < rhs.m_size) { 23 return strncmp(m_start, rhs.m_start, m_size) <= 0; 24 } 25 return strncmp(m_start, rhs.m_start, rhs.m_size) < 0; 26 } 27 28 int StringRef::compare( StringRef rhs ) const { 29 auto cmpResult = 30 strncmp( m_start, rhs.m_start, std::min( m_size, rhs.m_size ) ); 31 32 // This means that strncmp found a difference before the strings 33 // ended, and we can return it directly 34 if ( cmpResult != 0 ) { 35 return cmpResult; 36 } 37 38 // If strings are equal up to length, then their comparison results on 39 // their size 40 if ( m_size < rhs.m_size ) { 41 return -1; 42 } else if ( m_size > rhs.m_size ) { 43 return 1; 44 } else { 45 return 0; 46 } 47 } 48 49 auto operator << ( std::ostream& os, StringRef str ) -> std::ostream& { 50 return os.write(str.data(), static_cast<std::streamsize>(str.size())); 51 } 52 53 std::string operator+(StringRef lhs, StringRef rhs) { 54 std::string ret; 55 ret.reserve(lhs.size() + rhs.size()); 56 ret += lhs; 57 ret += rhs; 58 return ret; 59 } 60 61 auto operator+=( std::string& lhs, StringRef rhs ) -> std::string& { 62 lhs.append(rhs.data(), rhs.size()); 63 return lhs; 64 } 65 66 } // namespace Catch