Skip to content

Commit

Permalink
Make find() constexpr in C++11 - recursion ifdef __OPTIMIZE__ (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
martinmoene committed Feb 13, 2022
1 parent bc1b45e commit 22fc549
Showing 1 changed file with 31 additions and 15 deletions.
46 changes: 31 additions & 15 deletions include/nonstd/string_view.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,17 @@ nssv_DISABLE_MSVC_WARNINGS( 4455 26481 26472 )

namespace nonstd { namespace sv_lite {

//
// basic_string_view declaration:
//

template
<
class CharT,
class Traits = std::char_traits<CharT>
>
class basic_string_view;

namespace detail {

// support constexpr comparison in C++14;
Expand Down Expand Up @@ -538,28 +549,33 @@ inline nssv_constexpr14 std::size_t length( CharT * s )

#endif // OPTIMIZE

} // namespace detail
#if nssv_CPP11_OR_GREATER && ! nssv_CPP17_OR_GREATER
#if defined(__OPTIMIZE__)

template
<
class CharT,
class Traits = std::char_traits<CharT>
>
class basic_string_view;
// gcc, clang provide __OPTIMIZE__
// Expect tail call optimization to make search() non-recursive:

#if nssv_CPP11_OR_GREATER && ! nssv_CPP17_OR_GREATER
namespace detail {
template< class CharT, class Traits = std::char_traits<CharT> >
constexpr const CharT* search( basic_string_view<CharT, Traits> haystack, basic_string_view<CharT, Traits> needle )
{
return haystack.starts_with( needle ) ? haystack.begin() :
haystack.empty() ? haystack.end() : search( haystack.substr(1), needle );
}

template <class CharT, class Traits = std::char_traits<CharT> >
constexpr const CharT* search(basic_string_view<CharT, Traits> haystack, basic_string_view<CharT, Traits> needle)
#else // OPTIMIZE

// non-recursive:

template< class CharT, class Traits = std::char_traits<CharT> >
constexpr const CharT* search( basic_string_view<CharT, Traits> haystack, basic_string_view<CharT, Traits> needle )
{
return haystack.starts_with(needle) ? haystack.begin() :
haystack.empty() ? haystack.end() :
search(haystack.substr(1), needle);
return std::search( haystack.begin(), haystack.end(), needle.begin(), needle.end() );
}

#endif // OPTIMIZE
#endif // nssv_CPP11_OR_GREATER && ! nssv_CPP17_OR_GREATER

} // namespace detail
#endif

//
// basic_string_view:
Expand Down

0 comments on commit 22fc549

Please sign in to comment.