add GapBuffer::copy_to()
This commit is contained in:
parent
5de13644de
commit
b9313ad606
@ -99,6 +99,40 @@ public:
|
||||
move_gap(m_size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a range of data from this GapBuffer to another.
|
||||
*
|
||||
* @param source_position
|
||||
* Position in the gap buffer containing the data to copy.
|
||||
* @param length
|
||||
* Length of the data to copy.
|
||||
* @param other
|
||||
* Destination GapBuffer to copy the data into.
|
||||
* @param destination_position
|
||||
* Position in the destination GapBuffer to copy the data to.
|
||||
*/
|
||||
void copy_to(size_t source_position, size_t length, GapBuffer & other, size_t destination_position)
|
||||
{
|
||||
if ((source_position < m_size) &&
|
||||
(length > 0u) &&
|
||||
((source_position + length) <= m_size))
|
||||
{
|
||||
if ((m_gap_position <= source_position) ||
|
||||
(m_gap_position >= (source_position + length)))
|
||||
{
|
||||
/* The gap is before or after the range of data to copy. */
|
||||
other.insert(destination_position, address(source_position), length);
|
||||
}
|
||||
else
|
||||
{
|
||||
/* The gap is in the middle of the range of data to copy. */
|
||||
size_t pre_gap_size = m_gap_position - source_position;
|
||||
other.insert(destination_position, address(source_position), pre_gap_size);
|
||||
other.insert(destination_position + pre_gap_size, address(source_position + pre_gap_size), length - pre_gap_size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
/** Address of the allocated memory buffer. */
|
||||
uint8_t * m_buffer;
|
||||
|
@ -86,3 +86,16 @@ TEST(GapBufferTest, allocates_more_memory_and_copies_buffer_contents_when_needed
|
||||
s += "EFGH";
|
||||
EXPECT_EQ(s, gp.get_string());
|
||||
}
|
||||
|
||||
TEST(GapBufferTest, allows_copying_data_range_from_one_gap_buffer_to_another)
|
||||
{
|
||||
GapBuffer gp1, gp2;
|
||||
gp1.insert(0u, (const uint8_t *)"ABCDEFGH", 8u);
|
||||
gp1.copy_to(0u, 4u, gp2, 0u);
|
||||
EXPECT_EQ("ABCD", gp2.get_string());
|
||||
gp1.insert(0u, (const uint8_t *)"IJKL", 4u);
|
||||
gp1.copy_to(8u, 2u, gp2, 0u);
|
||||
EXPECT_EQ("EFABCD", gp2.get_string());
|
||||
gp1.copy_to(2u, 4u, gp2, 3u);
|
||||
EXPECT_EQ("EFAKLABBCD", gp2.get_string());
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user