1#![deny(missing_docs)]
2use std::{
7 convert::Infallible,
8 fmt::{Display, Formatter},
9 ops::Range,
10 str::FromStr,
11};
12
13#[derive(Clone, Default)]
15pub struct TextLine {
16 text: String,
17 indices: Vec<usize>,
18}
19
20impl TextLine {
21 #[must_use]
32 pub fn new() -> Self {
33 Self::default()
34 }
35
36 fn enable_indices(&mut self) {
37 let mut index = 0;
38 for c in self.text.chars() {
39 index += c.len_utf8() - 1;
40 self.indices.push(index);
41 }
42 }
43
44 fn refresh_indices(&mut self) {
45 if !self.text.is_ascii() {
46 self.enable_indices();
47 }
48 }
49
50 fn index_insert(&mut self, pos: usize, extra: usize) {
53 let base = if pos > 0 { self.indices[pos - 1] } else { 0 };
54 self.indices.insert(pos, base + extra);
55 if extra > 0 {
56 for v in &mut self.indices[pos + 1..] {
57 *v += extra;
58 }
59 }
60 }
61
62 fn index_remove(&mut self, pos: usize, extra: usize) {
65 self.indices.remove(pos);
66 if extra > 0 {
67 for v in &mut self.indices[pos..] {
68 *v -= extra;
69 }
70 }
71 }
72
73 #[must_use]
84 pub fn from_string(text: String) -> Self {
85 let mut result = Self {
86 text,
87 ..Self::default()
88 };
89 result.refresh_indices();
90 result
91 }
92
93 pub fn clear(&mut self) {
105 self.text.clear();
106 self.indices.clear();
107 }
108
109 #[must_use]
120 pub const fn is_empty(&self) -> bool {
121 self.text.is_empty()
122 }
123
124 #[must_use]
135 pub const fn len(&self) -> usize {
136 if self.indices.is_empty() {
137 self.text.len()
138 } else {
139 self.indices.len()
140 }
141 }
142
143 #[must_use]
154 pub fn as_str(&self) -> &str {
155 &self.text
156 }
157
158 #[must_use]
169 pub fn string_index(&self, index: usize) -> usize {
170 if !self.indices.is_empty() && index > 0 {
171 self.indices[index - 1] + index
172 } else {
173 index
174 }
175 }
176
177 #[must_use]
194 pub fn char_index(&self, byte_index: usize) -> usize {
195 assert!(
196 self.text.is_char_boundary(byte_index),
197 "byte index {byte_index} is not a char boundary",
198 );
199 if self.indices.is_empty() {
200 return byte_index;
201 }
202 let mut low = 0;
203 let mut high = self.len();
204 while low < high {
205 let middle = low + (high - low) / 2;
206 if self.string_index(middle) < byte_index {
207 low = middle + 1;
208 } else {
209 high = middle;
210 }
211 }
212 low
213 }
214
215 #[must_use]
230 pub fn slice(&self, range: Range<usize>) -> &str {
231 &self.text[self.string_index(range.start)..self.string_index(range.end)]
232 }
233
234 #[must_use]
246 pub fn char_at_checked(&self, at: usize) -> Option<char> {
247 if at >= self.len() {
248 return None;
249 }
250 self.text[self.string_index(at)..].chars().next()
251 }
252
253 #[must_use]
269 pub fn char_at(&self, at: usize) -> char {
270 self.char_at_checked(at).unwrap()
271 }
272
273 pub fn insert(&mut self, index: usize, c: char) {
289 self.text.insert(self.string_index(index), c);
290 let extra = c.len_utf8() - 1;
291 if !self.indices.is_empty() {
292 self.index_insert(index, extra);
293 } else if extra > 0 {
294 self.enable_indices();
295 }
296 }
297
298 pub fn remove(&mut self, index: usize) -> char {
314 let result = self.text.remove(self.string_index(index));
315 if !self.indices.is_empty() {
316 self.index_remove(index, result.len_utf8() - 1);
317 }
318 result
319 }
320
321 pub fn remove_range(&mut self, range: Range<usize>) {
337 self.text.replace_range(
338 self.string_index(range.start)..self.string_index(range.end),
339 "",
340 );
341 if !self.indices.is_empty() && !range.is_empty() {
342 let before = if range.start > 0 {
343 self.indices[range.start - 1]
344 } else {
345 0
346 };
347 let total_extra = self.indices[range.end - 1] - before;
348 let start = range.start;
349 self.indices.drain(range);
350 if total_extra > 0 {
351 for v in &mut self.indices[start..] {
352 *v -= total_extra;
353 }
354 }
355 }
356 }
357
358 pub fn replace_range(&mut self, range: Range<usize>, text: &str) {
374 let mut cursor = range.start;
375 self.remove_range(range);
376 self.insert_str(&mut cursor, text);
377 }
378
379 #[must_use]
392 pub fn split(&mut self, index: usize) -> Self {
393 let text = self.text.split_off(self.string_index(index));
394 let result_indices = if self.indices.is_empty() {
395 Vec::new()
396 } else {
397 let before = if index > 0 {
398 self.indices[index - 1]
399 } else {
400 0
401 };
402 let tail: Vec<usize> = self.indices[index..].iter().map(|&v| v - before).collect();
403 self.indices.truncate(index);
404 tail
405 };
406 Self {
407 text,
408 indices: result_indices,
409 }
410 }
411
412 pub fn join(&mut self, other: &Self) {
425 self.text.push_str(&other.text);
426 if !self.indices.is_empty() {
427 let mut running = *self.indices.last().unwrap_or(&0);
428 for c in other.text.chars() {
429 running += c.len_utf8() - 1;
430 self.indices.push(running);
431 }
432 } else if !other.text.is_ascii() {
433 self.enable_indices();
434 }
435 }
436}
437
438impl FromStr for TextLine {
439 type Err = Infallible;
440
441 fn from_str(text: &str) -> Result<Self, Infallible> {
442 Ok(Self::from_string(text.into()))
443 }
444}
445
446impl Display for TextLine {
447 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
448 f.write_str(self.as_str())
449 }
450}
451
452impl From<String> for TextLine {
453 fn from(text: String) -> Self {
454 Self::from_string(text)
455 }
456}
457
458impl From<&str> for TextLine {
459 fn from(text: &str) -> Self {
460 Self::from_string(text.into())
461 }
462}
463
464impl From<TextLine> for String {
465 fn from(text_line: TextLine) -> Self {
466 text_line.text
467 }
468}
469
470mod cursor;
471mod editing;
472mod selection;
473
474pub use cursor::Direction;
475
476#[cfg(test)]
477mod tests {
478 use super::TextLine;
479
480 fn expected_offsets(line: &TextLine) -> Vec<usize> {
482 let mut offsets = vec![0];
483 let mut last = 0;
484 for c in line.as_str().chars() {
485 last += c.len_utf8();
486 offsets.push(last);
487 }
488 offsets
489 }
490
491 fn check(line: &TextLine) {
493 let expected = expected_offsets(line);
494 assert_eq!(line.len() + 1, expected.len());
495 for (i, &offset) in expected.iter().enumerate() {
496 assert_eq!(
497 line.string_index(i),
498 offset,
499 "string_index({i}) wrong for {:?}",
500 line.as_str(),
501 );
502 }
503 for (i, c) in line.as_str().chars().enumerate() {
504 assert_eq!(
505 line.char_at(i),
506 c,
507 "char_at({i}) wrong for {:?}",
508 line.as_str(),
509 );
510 }
511 }
512
513 #[test]
514 fn ascii_stays_cacheless() {
515 let mut line = TextLine::from_string("hello".into());
516 line.insert(5, ' ');
517 line.insert(6, 'w');
518 check(&line);
519 line.remove(0);
520 check(&line);
521 }
522
523 #[test]
524 fn insert_non_ascii_activates() {
525 let mut line = TextLine::from_string("ab".into());
526 line.insert(1, 'π');
527 check(&line);
528 assert_eq!(line.as_str(), "aπb");
529 }
530
531 #[test]
532 fn insert_ascii_into_non_ascii() {
533 let mut line = TextLine::from_string("aπb".into());
534 check(&line);
535 line.insert(2, 'X');
536 check(&line);
537 line.insert(0, 'Y');
538 check(&line);
539 line.insert(line.len(), 'Z');
540 check(&line);
541 assert_eq!(line.as_str(), "YaπXbZ");
542 }
543
544 #[test]
545 fn remove_non_ascii() {
546 let mut line = TextLine::from_string("aπb".into());
547 assert_eq!(line.remove(1), 'π');
548 check(&line);
549 assert_eq!(line.as_str(), "ab");
550 }
551
552 #[test]
553 fn remove_range_spanning_non_ascii() {
554 let mut line = TextLine::from_string("xπyπz".into());
555 line.remove_range(1..3);
556 check(&line);
557 assert_eq!(line.as_str(), "xπz");
558 line.remove_range(0..line.len());
559 check(&line);
560 assert!(line.is_empty());
561 }
562
563 #[test]
564 fn insert_str_non_ascii() {
565 let mut line = TextLine::from_string("aπb".into());
566 let mut cursor = 2;
567 line.insert_str(&mut cursor, "xπ¦y");
568 check(&line);
569 assert_eq!(cursor, 5);
570 assert_eq!(line.as_str(), "aπxπ¦yb");
571 }
572
573 #[test]
574 fn split_non_ascii() {
575 let mut line = TextLine::from_string("aπbπ¦c".into());
576 let second = line.split(3);
577 check(&line);
578 check(&second);
579 assert_eq!(line.as_str(), "aπb");
580 assert_eq!(second.as_str(), "π¦c");
581 }
582
583 #[test]
584 fn join_non_ascii() {
585 let mut line = TextLine::from_string("aπ".into());
586 line.join(&TextLine::from_string("bπ¦".into()));
587 check(&line);
588 assert_eq!(line.as_str(), "aπbπ¦");
589 }
590
591 #[test]
592 fn char_index_inverts_string_index() {
593 for text in ["", "hello", "aπbπ¦c", "π", "Àâü"] {
594 let line = TextLine::from(text);
595 for position in 0..=line.len() {
596 assert_eq!(line.char_index(line.string_index(position)), position);
597 }
598 }
599 }
600
601 #[test]
602 #[should_panic(expected = "not a char boundary")]
603 fn char_index_rejects_mid_char_offset() {
604 let _ = TextLine::from("aπb").char_index(2);
605 }
606
607 #[test]
608 fn slice_matches_chars() {
609 let line = TextLine::from("aπbπ¦c");
610 let chars: Vec<char> = line.as_str().chars().collect();
611 for start in 0..=chars.len() {
612 for end in start..=chars.len() {
613 let expected: String = chars[start..end].iter().collect();
614 assert_eq!(line.slice(start..end), expected);
615 }
616 }
617 }
618
619 #[test]
620 fn replace_range_keeps_cache_consistent() {
621 let mut line = TextLine::from("aπbπ¦c");
622 line.replace_range(1..4, "xy");
623 check(&line);
624 assert_eq!(line.as_str(), "axyc");
625 line.replace_range(1..3, "ππ¦π");
626 check(&line);
627 assert_eq!(line.as_str(), "aππ¦πc");
628 line.replace_range(0..line.len(), "");
629 check(&line);
630 assert!(line.is_empty());
631 line.replace_range(0..0, "Γ©");
632 check(&line);
633 }
634
635 #[test]
636 fn mixed_mutation_sequence() {
637 let mut line = TextLine::new();
638 for (i, c) in ['h', 'i', 'π', '!', 'π¦'].into_iter().enumerate() {
639 line.insert(i, c);
640 check(&line);
641 }
642 assert_eq!(line.remove(2), 'π');
643 check(&line);
644 assert_eq!(line.as_str(), "hi!π¦");
645 let mut cursor = line.len();
646 line.insert_str(&mut cursor, "π¦ end");
647 check(&line);
648 line.remove_range(1..4);
649 check(&line);
650 }
651}