Skip to content

Commit

Permalink
Merge pull request scummvm#342 from RichieSams/addDeleteRangeStringMe…
Browse files Browse the repository at this point in the history
…thod

COMMON: Add erase method to String class
  • Loading branch information
lordhoto committed Jul 1, 2013
2 parents 1b7681e + e1ff60d commit a00c3e7
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions common/str.cpp
Expand Up @@ -361,6 +361,25 @@ void String::deleteChar(uint32 p) {
_size--;
}

void String::erase(uint32 p, uint32 len) {
assert(p < _size);

makeUnique();
// If len == npos or p + len is over the end, remove all the way to the end
if (len == npos || p + len >= _size) {
// Delete char at p as well. So _size = (p - 1) + 1
_size = p;
// Null terminate
_str[_size] = 0;
return;
}

for ( ; p + len <= _size; p++) {
_str[p] = _str[p + len];
}
_size -= len;
}

void String::clear() {
decRefCount(_extern._refCount);

Expand Down
5 changes: 5 additions & 0 deletions common/str.h
Expand Up @@ -43,6 +43,8 @@ namespace Common {
* behavior in some operations.
*/
class String {
public:
static const uint32 npos = 0xFFFFFFFF;
protected:
/**
* The size of the internal storage. Increasing this means less heap
Expand Down Expand Up @@ -191,6 +193,9 @@ class String {
/** Remove the character at position p from the string. */
void deleteChar(uint32 p);

/** Remove all characters from position p to the p + len. If len = String::npos, removes all characters to the end */
void erase(uint32 p, uint32 len = npos);

/** Set character c at position p, replacing the previous character there. */
void setChar(char c, uint32 p);

Expand Down
8 changes: 8 additions & 0 deletions test/common/str.h
Expand Up @@ -243,6 +243,14 @@ class StringTestSuite : public CxxTest::TestSuite
TS_ASSERT_EQUALS(str, "012345678923456789012345678901");
}

void test_erase() {
Common::String str("01234567890123456789012345678901");
str.erase(18);
TS_ASSERT_EQUALS(str, "012345678901234567");
str.erase(7, 5);
TS_ASSERT_EQUALS(str, "0123456234567");
}

void test_sharing() {
Common::String str("01234567890123456789012345678901");
Common::String str2(str);
Expand Down

0 comments on commit a00c3e7

Please sign in to comment.