From 18246e131fd2e19dd8db1f99ea82577e0ece1648 Mon Sep 17 00:00:00 2001 From: Myles Busig Date: Thu, 7 Mar 2024 16:07:21 -0700 Subject: [PATCH] Implement istring::insert with given index and count --- src/string.cpp | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/string.cpp b/src/string.cpp index b633142..15c5610 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -205,7 +205,7 @@ istring& istring::insert(size_t index, const istring& str) { // only copy the string if there is room size_t num_to_copy = std::min(str.m_size, space); - mtl::memmove(substr, str.m_str, num_to_copy); + mtl::memcpy(substr, str.m_str, num_to_copy); m_size += num_to_copy; m_str[m_size] = '\0'; @@ -213,6 +213,32 @@ istring& istring::insert(size_t index, const istring& str) { return *this; } +istring& istring::insert(size_t index, const istring& str, size_t str_index, size_t count) { + if (count == npos) { + count = str.m_size - str_index; + } + + char* substr = m_str + index; + size_t space = m_capacity - index; + + if (space > count) { + size_t space_to_move = space - count; + size_t items_to_move = m_size - index; + // only move items if there is room, and they exist + size_t num_to_move = std::min(items_to_move, space_to_move); + mtl::memmove(substr + count, substr, num_to_move); + } + + // only copy the string if there is room + size_t num_to_copy = std::min(count, space); + mtl::memcpy(substr, str.m_str + str_index, num_to_copy); + + m_size += num_to_copy; + m_str[m_size] = '\0'; + + return *this; +} + size_t istring::copy(char* dest, size_t count, size_t pos) const { mtl_hybridcpy(dest, m_str + pos, count); return count;