summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Makefile3
-rw-r--r--src/piece-table.c33
-rw-r--r--src/piece-table.h2
-rw-r--r--tests/piece-table-insert.c10
4 files changed, 40 insertions, 8 deletions
diff --git a/Makefile b/Makefile
index a805d05..0bdfd44 100644
--- a/Makefile
+++ b/Makefile
@@ -10,7 +10,8 @@ HEADERS = $(wildcard src/*.h)
TEST := buffer\
piece-table-print\
- piece-table-delete
+ piece-table-delete\
+ piece-table-insert
TEST_FILES = $(addprefix tests/, $(TEST))
TEST_SOURCES = $(addsuffix .c, $(addprefix tests/, $(TEST)))
diff --git a/src/piece-table.c b/src/piece-table.c
index 6db05d7..2e7f0a2 100644
--- a/src/piece-table.c
+++ b/src/piece-table.c
@@ -138,16 +138,37 @@ static piece *split_piece(piece *p, size_t pos) {
return p;
}
-void insert_piece_table(piece_table *pt, char val, size_t pos) {
- /* At the moment inserts only one char */
- // piece *cur;
- assert(pos <= pt->length );
+void insert_piece_table(piece_table *pt, size_t pos, char *in, size_t in_len) {
+ /* TODO: Make sure it doesn't screw up the cache */
+ piece *start, *end, *new;
- append_growable_buffer(&pt->add, &val, 1);
- // TODO
+ assert( pos <= pt->length );
+
+ append_growable_buffer(&pt->add, in, in_len);
+
+ if ( pos == 0 ) {
+ start = pt->sentinel;
+ } else if ( pos == pt->length ) {
+ start = pt->sentinel->prev;
+ } else {
+ find_piece_by_pos(pt, pos);
+ start = split_piece(pt->cached, pos - pt->cached_offset);
+ }
+ end = start->next;
+
+ new = make_piece();
+ new->start = pt->add.content + pt->add.used - in_len;
+ new->length = in_len;
+
+ start->next = new;
+ new->prev = start;
+ new->next = end;
+ end->prev = new;
+ pt->length += in_len;
}
void delete_piece_table(piece_table *pt, size_t pos, size_t len) {
+ /* TODO: Make sure it doesn't screw up the cache */
piece *cur, *next, *start, *end;
assert( pos + len <= pt->length );
diff --git a/src/piece-table.h b/src/piece-table.h
index 8a13ae3..b65da15 100644
--- a/src/piece-table.h
+++ b/src/piece-table.h
@@ -26,7 +26,7 @@ void init_piece_table(piece_table *pt, char *orig);
void free_piece_table(piece_table *pt);
char index_piece_table(piece_table *pt, size_t pos);
-void insert_piece_table(piece_table *pt, char val, size_t pos);
+void insert_piece_table(piece_table *pt, size_t pos, char *val, size_t len);
void delete_piece_table(piece_table *pt, size_t pos, size_t len);
void print_piece_table(piece_table *pt);
diff --git a/tests/piece-table-insert.c b/tests/piece-table-insert.c
new file mode 100644
index 0000000..bed55bc
--- /dev/null
+++ b/tests/piece-table-insert.c
@@ -0,0 +1,10 @@
+#include "../src/piece-table.h"
+
+int main() {
+ piece_table pt;
+ init_piece_table(&pt, "1234567890");
+ insert_piece_table(&pt, 4, "abcdefgh", 8);
+ print_piece_table(&pt);
+ free_piece_table(&pt);
+ return 0;
+}