Implement istring replace, append, erase

This commit is contained in:
Myles Busig 2024-03-10 20:50:09 -06:00
parent 72a6bbe584
commit a8c30df08e

View File

@ -195,6 +195,89 @@ istring& istring::insert(size_t index, const string_view& str, size_t str_index,
return *this; return *this;
} }
istring& istring::erase(size_t index, size_t count) {
size_t num_after_index = m_size - index;
if (count > num_after_index) {
count = num_after_index;
}
size_t num_to_move = num_after_index - count;
if (num_to_move) {
mtl::memmove(m_str + index, m_str + index + count, num_to_move);
}
m_size -= count;
m_str[m_size] = '\0';
return *this;
}
istring& istring::append(const string_view& str) {
size_t space = m_capacity - m_size;
size_t count = str.m_size > space ? space : str.m_size;
mtl::memcpy(m_str + m_size, str.m_str, count);
m_size += count;
m_str[m_size] = '\0';
return *this;
}
istring& istring::append(const string_view& str, size_t str_index, size_t count) {
size_t space = m_capacity - m_size;
if (count > space) { count = space; }
mtl::memcpy(m_str + m_size, str.m_str + str_index, count);
m_size += count;
m_str[m_size] = '\0';
return *this;
}
istring& istring::append(size_t count, char ch) {
size_t space = m_capacity - m_size;
if (count > space) { count = space; }
std::memset(m_str + m_size, ch, count);
m_size += count;
m_str[m_size] = '\0';
return *this;
}
istring& istring::operator+=(const string_view& str) {
return append(str);
}
istring& istring::operator+=(char ch) {
return append(1, ch);
}
istring& istring::replace(size_t pos, size_t count, const string_view& str) {
size_t space = m_capacity - pos;
char* substr = m_str + pos;
if (str.m_size - count) {
size_t space_to_move = space - str.m_size;
size_t items_to_move = m_size - count - pos;
size_t num_to_move = std::min(items_to_move, space_to_move);
std::memmove(substr + str.m_size, substr + count, num_to_move);
}
mtl::memcpy(substr, str.m_str, str.m_size);
m_size += str.m_size - count;
m_str[m_size] = '\0';
return *this;
}
void istring::resize(size_t count) { void istring::resize(size_t count) {
if (count > m_capacity) { count = m_capacity; } if (count > m_capacity) { count = m_capacity; }
@ -213,6 +296,8 @@ void istring::resize(size_t count, char ch) {
m_str[m_size] = '\0'; m_str[m_size] = '\0';
} }
// ===== search =====
size_t istring::find(const string_view& str, size_t pos) const { size_t istring::find(const string_view& str, size_t pos) const {
if (str.m_size > m_size) { return npos; } if (str.m_size > m_size) { return npos; }