blob: b026f6a10e1f5e2baf08957c0a12903f1828c9a4 (
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>
#define PAGE_SIZE 4096
struct page {
uint8_t buffer[PAGE_SIZE];
uint8_t *gap_start;
uint8_t *gap_end;
struct page *next;
struct page *prev;
};
struct page *new_page() {
struct page *result = malloc(sizeof(struct page));
result->gap_start = result->buffer;
result->gap_end = result->buffer + PAGE_SIZE - 1;
result->next = 0;
result->prev = 0;
return result;
}
static inline void set_half_page_gap(struct page *page) {
page->gap_start = page->buffer + PAGE_SIZE / 2;
page->gap_end = page->buffer + PAGE_SIZE - 1;
}
void split_page(struct page *first_half) {
struct page *second_half = new_page();
memcpy(second_half->buffer, first_half->buffer + PAGE_SIZE / 2, PAGE_SIZE / 2 - 1);
set_half_page_gap(first_half);
set_half_page_gap(second_half);
if (first_half->next) {
first_half->next->prev = second_half;
}
second_half->next = first_half->next;
second_half->prev = first_half;
first_half->next = second_half;
}
void delete_page(struct page *page) {
if (page->next) {
page->next->prev = page->prev;
}
if (page->prev) {
page->prev->next = page->next;
}
free(page);
}
void move_gap(struct page *page, int target) {
while(target) {
if (target > 0) {
page->gap_end++;
*(page->gap_start) = *(page->gap_end);
page->gap_start++;
target--;
} else {
page->gap_start--;
*(page->gap_end) = *(page->gap_start);
page->gap_end--;
target++;
}
}
}
void insert_into_page(struct page *page, uint8_t c) {
if (page->gap_start != page->gap_end) {
*(page->gap_start) = c;
page->gap_start++;
}
}
void delete_from_page(struct page *page) {
if (page->gap_start != page->buffer) {
page->gap_start--;
}
}
|