Skip to content

Commit

Permalink
add string view substr function
Browse files Browse the repository at this point in the history
  • Loading branch information
mrwonko committed May 8, 2016
1 parent 8916e7d commit 1ee49cc
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
11 changes: 11 additions & 0 deletions shared/qcommon/safe/string.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions shared/qcommon/safe/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

#include <cassert>
#include <iostream>
#include <string>

namespace Q
{
Expand All @@ -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 );
}
Expand Down
9 changes: 9 additions & 0 deletions tests/safe/string.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down

0 comments on commit 1ee49cc

Please sign in to comment.