Permalink
Browse files

add string view substr function

  • Loading branch information...
mrwonko committed May 8, 2016
1 parent 8916e7d commit 1ee49ccc6281ae4a773941aa13fb041a9997a87b
Showing with 23 additions and 0 deletions.
  1. +11 −0 shared/qcommon/safe/string.cpp
  2. +3 −0 shared/qcommon/safe/string.h
  3. +9 −0 tests/safe/string.cpp
@@ -39,6 +39,17 @@ namespace Q
return Ordering::LT;
}
gsl::cstring_view substr( const gsl::cstring_view& lhs, const std::string::size_type pos, const std::string::size_type count )
{
if( pos > lhs.size() )
{
throw std::out_of_range( "Q::substr called with out-of-bounds pos parameter!" );
}
auto start = lhs.begin() + pos;
auto end = count == std::string::npos ? lhs.end() : std::min( start + count, lhs.end() );
return{ start, end };
}
int svtoi( const gsl::cstring_view& view )
{
int result = 0;
@@ -6,6 +6,7 @@
#include <cassert>
#include <iostream>
#include <string>
namespace Q
{
@@ -25,6 +26,8 @@ namespace Q
}
};
gsl::cstring_view substr( const gsl::cstring_view& lhs, const std::string::size_type pos = 0, const std::string::size_type count = std::string::npos );
int svtoi( const gsl::cstring_view& view );
float svtof( const gsl::cstring_view& view );
}
View
@@ -35,6 +35,15 @@ BOOST_AUTO_TEST_CASE( stricmp )
BOOST_CHECK_EQUAL( Q::stricmp( CSTRING_VIEW( "a" ), CSTRING_VIEW( "" ) ), Q::Ordering::GT );
}
BOOST_AUTO_TEST_CASE( substr )
{
BOOST_CHECK_EQUAL( Q::substr( CSTRING_VIEW( "Hello World" ), 6 ), CSTRING_VIEW( "World" ) );
BOOST_CHECK_EQUAL( Q::substr( CSTRING_VIEW( "Hello World" ), 6, 100 ), CSTRING_VIEW( "World" ) );
BOOST_CHECK_EQUAL( Q::substr( CSTRING_VIEW( "Hello World" ), 0, 5 ), CSTRING_VIEW( "Hello" ) );
BOOST_CHECK_EQUAL( Q::substr( CSTRING_VIEW( "Hello my World!" ), 6, 2 ), CSTRING_VIEW( "my" ) );
BOOST_CHECK_THROW( Q::substr( CSTRING_VIEW( "Hello" ), 20 ), std::out_of_range );
}
BOOST_AUTO_TEST_CASE( svtoi )
{
BOOST_CHECK_EQUAL( Q::svtoi( CSTRING_VIEW( "" ) ), 0 );

0 comments on commit 1ee49cc

Please sign in to comment.