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
use unic_segment::{Graphemes, WordBounds};
pub fn len(s: &str) -> usize {
Graphemes::new(s).count()
}
pub fn to_byte_offset(s: &'_ str, grapheme_offset: usize) -> usize {
let mut byte_offset = 0;
for item in Graphemes::new(s).take(grapheme_offset) {
byte_offset += item.len();
}
byte_offset
}
pub fn split_at(s: &str, grapheme_offset: usize) -> (&str, &str) {
let mut byte_offset = 0;
for item in Graphemes::new(s).take(grapheme_offset) {
byte_offset += item.len();
}
(&s[0..byte_offset], &s[byte_offset..])
}
pub fn prev_word_grapheme(s: &str, current_offset: usize) -> usize {
let mut grapheme_offset = 0;
for word in WordBounds::new(s) {
let next = grapheme_offset + len(word);
if next >= current_offset {
break;
}
grapheme_offset = next;
}
grapheme_offset
}
pub fn next_word_grapheme(s: &str, current_offset: usize) -> usize {
let mut grapheme_offset = 0;
for word in WordBounds::new(s) {
let next = grapheme_offset + len(word);
grapheme_offset = next;
if next > current_offset {
break;
}
}
grapheme_offset
}