summaryrefslogtreecommitdiff
path: root/page.c
blob: e08470512c3150d69eb542807813a189f90c3644 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif

struct page {
	uint8_t *elements;
	struct page *next;
	struct page *prev;
	uint16_t gap_start;
	uint16_t gap_end;
	uint16_t element_count;
};

struct page *new_page() {
	struct page *result = malloc(sizeof(struct page));
	result->elements = malloc(PAGE_SIZE);
	result->gap_start = 0;
	result->gap_end = PAGE_SIZE;
	result->next = 0;
	result->prev = 0;
	return result;
}

void split_page(struct page *back) {
	struct page *front = new_page();

	memcpy(front->elements, back->elements + PAGE_SIZE / 2, PAGE_SIZE / 2);

	front->gap_start = PAGE_SIZE / 2;
	front->gap_end = PAGE_SIZE;
	front->element_count = PAGE_SIZE / 2;

	back->gap_start = PAGE_SIZE / 2;
	back->gap_end = PAGE_SIZE;
	back->element_count = PAGE_SIZE / 2;

	if (back->next) {
		back->next->prev = front;
	}
	front->next = back->next;
	front->prev = back;
	back->next = front;
}

void free_page(struct page *page) {
	if (page->prev) {
		page->prev->next = page->next;
	}
	if (page->next) {
		page->next->prev = page->prev;
	}
	free(page);
}

void move_gap_forward(struct page *page) {
	page->elements[page->gap_start] = page->elements[page->gap_end];
	page->gap_start++;
	page->gap_end++;
}

void move_gap_backward(struct page *page) {
	page->gap_end--;
	page->gap_start--;
	page->elements[page->gap_end] = page->elements[page->gap_start];
}

void insert_at_gap(struct page *page, uint8_t c) {
	page->elements[page->gap_start] = c;
	page->gap_start++;
	page->element_count++;
}

void delete_at_gap(struct page *page) {
	if (page->gap_start) {
		page->gap_start--;
		page->element_count--;
	}
}