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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
|
use std::fs::File;
use std::io::{ErrorKind, Read, Write};
use std::path::Path;
use std::error::Error;
use std::rc::Rc;
// Set to a small value to help identify bugs in the implementation.
const MAX_NODE_SIZE: usize = 4;
#[derive(Debug, Clone)]
struct Leaf {
buf: Rc<[u8]>,
start: u8,
end: u8,
}
impl Leaf {
fn bytes(&self) -> &[u8] {
return &self.buf[usize::from(self.start)..usize::from(self.end)];
}
}
#[derive(Debug, Clone)]
struct Branch {
left: Rc<Rope>,
right: Rc<Rope>,
len: usize,
// Number of newline characters under this branch.
lines: usize,
}
#[derive(Debug, Clone)]
enum Node {
Leaf(Leaf),
Branch(Branch),
}
#[derive(Debug, Clone)]
pub struct Rope(Node);
impl Rope {
fn leaf(buf: Vec<u8>) -> Rope {
let len = buf.len();
return Rope(Node::Leaf(Leaf{
buf: Rc::from(buf),
start: 0,
end: u8::try_from(len).expect("buffer too long"),
}));
}
pub fn lines(&self) -> usize {
match self {
Rope(Node::Leaf(l)) => {
let mut count = 0;
for &c in l.bytes().iter() {
if c == b'\n' {
count += 1;
}
}
return count;
}
Rope(Node::Branch(b)) => {
return b.lines;
}
}
}
pub fn len(&self) -> usize {
match self {
Rope(Node::Leaf(l)) => {
return usize::from(l.end - l.start);
}
Rope(Node::Branch(b)) => {
return b.len;
}
}
}
pub fn print(&self, out: &mut dyn Write) -> Result<(), std::io::Error> {
if self.len() == 0 {
return Ok(());
}
// TODO: escape unprintable characters
match self {
Rope(Node::Leaf(l)) => {
out.write_all(l.bytes())?;
return Ok(());
}
Rope(Node::Branch(b)) => {
b.left.print(out)?;
b.right.print(out)?;
return Ok(());
}
}
}
pub fn line_idx(&self, n: usize) -> usize {
if n > self.lines() {
panic!("Index {} out of range 0..{}", n, self.lines()+1);
}
if n == 0 {
return 0;
}
match self {
Rope(Node::Leaf(l)) => {
let mut nl_count = 0;
for (i, &c) in l.bytes().iter().enumerate() {
if c != b'\n' {
continue;
}
nl_count += 1;
if nl_count == n {
return i + 1;
}
}
panic!("unreachable");
}
Rope(Node::Branch(b)) => {
let left_lines = b.left.lines();
if n <= left_lines {
return b.left.line_idx(n);
}
return b.left.len() + b.right.line_idx(n - left_lines);
}
}
}
fn concat(&self, other: &Rope) -> Rope {
if self.len() == 0 {
return other.clone();
}
if other.len() == 0 {
return self.clone();
}
let len = self.len() + other.len();
let lines = self.lines() + other.lines();
return Rope(Node::Branch(Branch {
left: Rc::new(self.clone()),
right: Rc::new(other.clone()),
len: len,
lines: lines,
}));
}
pub fn insert(&self, pos: usize, c: u8) -> Rope {
match self {
Rope(Node::Leaf(l)) => {
if self.len() < MAX_NODE_SIZE {
let mut new_buf = vec![0; self.len() + 1];
new_buf[..pos].copy_from_slice(&l.bytes()[..pos]);
new_buf[pos] = c;
new_buf[pos + 1..].copy_from_slice(&l.bytes()[pos..]);
return Rope::leaf(new_buf);
}
let mut buf_left = vec![0; pos + 1];
buf_left[..pos].copy_from_slice(&l.bytes()[..pos]);
buf_left[pos] = c;
let mut buf_right = Vec::new();
buf_right.extend_from_slice(&l.bytes()[pos..]);
return Rope::leaf(buf_left).concat(&Rope::leaf(buf_right));
}
Rope(Node::Branch(b)) => {
if pos < b.left.len() {
return b.left.insert(pos, c).concat(&b.right);
}
return b.left.concat(&b.right.insert(pos - b.left.len(), c));
}
}
}
pub fn open(path: &Path) -> Result<Rope, Box<dyn Error>> {
let mut f = File::open(path).map_err(|err| format!("open file {}: {}", path.display(), err))?;
let mut rope = Rope::leaf(Vec::new());
loop {
let mut buf = vec![0; MAX_NODE_SIZE];
let n = match f.read(&mut buf) {
Ok(n) => n,
Err(err) => {
if err.kind() == ErrorKind::Interrupted {
continue;
}
return Err(Box::from(format!("read file {}: {}", path.display(), err)));
}
};
if n == 0 {
break;
}
buf.truncate(n);
rope = rope.concat(&Rope::leaf(buf));
}
// TODO: rebalance
return Ok(rope);
}
pub fn save(&self, path: &Path) -> Result<(), Box<dyn Error>> {
let mut f = File::create(path).map_err(|err| format!("save: create file {}: {}", path.display(), err))?;
self.print(&mut f).map_err(|err| format!("save: write file {}: {}", path.display(), err))?;
f.sync_all().map_err(|err| format!("save: write file {}: {}", path.display(), err))?;
return Ok(());
}
pub fn slice(&self, start: usize, end: usize) -> Rope {
if start > self.len() {
panic!("Index {} out of range 0..{}", start, self.len()+1);
}
if end > self.len() {
panic!("Index {} out of range 0..{}", end, self.len());
}
if start > end {
panic!("Slice start index {} is greater than end index {}", start, end);
}
match self {
Rope(Node::Leaf(l)) => {
return Rope(Node::Leaf(Leaf{
buf: l.buf.clone(),
start: l.start + u8::try_from(start).expect("buffer too long"),
end: l.start + u8::try_from(end).expect("buffer too long"),
}));
}
Rope(Node::Branch(b)) => {
let mut left = Rope::leaf(Vec::new());
if start < b.left.len() {
left = b.left.slice(start, std::cmp::min(end, b.left.len()));
}
let mut right = Rope::leaf(Vec::new());
if end > b.left.len() {
let mut right_start = 0;
if start > b.left.len() {
right_start = start - b.left.len();
}
right = b.right.slice(right_start, end - b.left.len());
}
return left.concat(&right);
}
}
}
pub fn line(&self, n: usize) -> Rope {
if n > self.lines() {
panic!("Index {} out of range 0..{}", n, self.lines()+1);
}
let start = self.line_idx(n);
let mut end = self.len();
if n < self.lines() {
end = self.line_idx(n+1)-1;
}
return self.slice(start, end);
}
fn is_char_boundary(&self, index: usize) -> bool {
match self {
Rope(Node::Leaf(l)) => {
return l.bytes()[index] & 0xc0 != 0x80;
}
Rope(Node::Branch(b)) => {
if index < b.left.len() {
return b.left.is_char_boundary(index);
}
return b.right.is_char_boundary(index - b.left.len());
}
}
}
pub fn floor_char_boundary(&self, index: usize) -> usize {
for i in (0..index+1).rev() {
if self.is_char_boundary(i) {
return i;
}
}
panic!("I'm not valid UTF-8: {:?}", self);
}
pub fn ceil_char_boundary(&self, index: usize) -> usize {
for i in index..self.len() {
if self.is_char_boundary(i) {
return i;
}
}
return self.len();
}
pub fn char(&self, index: usize) -> usize {
if index == 0 {
return 0;
}
let mut count = 1;
for i in 1..self.len() {
if !self.is_char_boundary(i) {
continue;
}
if count == index {
return i;
}
count += 1;
}
return self.len();
}
}
|