From 86a3fe34b4d0361ff1deb307f211d7bbdb1f14fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Wed, 29 Nov 2017 09:24:51 +0100 Subject: [PATCH] String builder - truncate() method --- include/ebcl/Strings.hh | 1 + include/ebcl/inline/Strings.hh | 10 ++++++++++ tests/strings-builder.cc | 25 +++++++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/include/ebcl/Strings.hh b/include/ebcl/Strings.hh index a8e47da..0c6ddc7 100644 --- a/include/ebcl/Strings.hh +++ b/include/ebcl/Strings.hh @@ -391,6 +391,7 @@ class T_StringBuilder T_StringBuilder& ensureCapacity( uint32_t minCap ); T_StringBuilder& clear( ); T_StringBuilder& free( ); + T_StringBuilder& truncate( uint32_t maxLength ) noexcept; // --------------------------------------------------------------------- diff --git a/include/ebcl/inline/Strings.hh b/include/ebcl/inline/Strings.hh index 7780c8b..99712c7 100644 --- a/include/ebcl/inline/Strings.hh +++ b/include/ebcl/inline/Strings.hh @@ -458,6 +458,16 @@ inline T_StringBuilder& T_StringBuilder::clear( ) return *this; } +inline T_StringBuilder& T_StringBuilder::truncate( + const uint32_t maxLength ) noexcept +{ + if ( maxLength < length_ ) { + size_ = UTF8GetMemoryOffset( data_ , maxLength ); + length_ = maxLength; + } + return *this; +} + /*----------------------------------------------------------------------------*/ inline bool T_StringBuilder::operator== ( T_StringBuilder const& other ) const diff --git a/tests/strings-builder.cc b/tests/strings-builder.cc index 586b322..4b9d374 100644 --- a/tests/strings-builder.cc +++ b/tests/strings-builder.cc @@ -29,6 +29,9 @@ class StringsBuilderTest : public CppUnit::TestFixture CPPUNIT_TEST( testClear ); CPPUNIT_TEST( testFree ); + CPPUNIT_TEST( testTruncate ); + CPPUNIT_TEST( testTruncateLonger ); + CPPUNIT_TEST( testAppendOther ); CPPUNIT_TEST( testAppendSwap ); CPPUNIT_TEST( testAppendStr ); @@ -121,6 +124,9 @@ public: void testClear( ); void testFree( ); + void testTruncate( ); + void testTruncateLonger( ); + void testAppendOther( ); void testAppendSwap( ); void testAppendStr( ); @@ -425,6 +431,25 @@ void StringsBuilderTest::testFree( ) /*----------------------------------------------------------------------------*/ +void StringsBuilderTest::testTruncate( ) +{ + T_StringBuilder sb( "this is\uf1bb a test" ); + sb.truncate( 8 ); + CPPUNIT_ASSERT_EQUAL( uint32_t( 8 ) , sb.length( ) ); + CPPUNIT_ASSERT_EQUAL( uint32_t( 10 ) , sb.size( ) ); +} + +void StringsBuilderTest::testTruncateLonger( ) +{ + T_StringBuilder sb( "this is\uf1bb a test" ); + sb.truncate( 20 ); + printf( "%d\n" , sb.size( ) ); + CPPUNIT_ASSERT_EQUAL( uint32_t( 15 ) , sb.length( ) ); + CPPUNIT_ASSERT_EQUAL( uint32_t( 17 ) , sb.size( ) ); +} + +/*----------------------------------------------------------------------------*/ + void StringsBuilderTest::testAppendOther( ) { T_StringBuilder sb1( "this is " ) , sb2( "a test!" );