-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared_runes.go
81 lines (73 loc) · 1.47 KB
/
shared_runes.go
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
package regexer
import "iter"
// The same as [Match] but for runes.
//
// Because the compiler can't infer the core type of [text] if we extend it
// with a slice of runes.
type RMatch struct {
// The full match text.
Content []rune
// The range of the match in the original text.
Span Span
// Matches for sub-patterns.
Subs RSubs
}
// Matches for sub-patterns.
type RSubs struct {
content []rune
shift int
rawSpans []int
}
func (s RSubs) Len() int {
return len(s.rawSpans)/2 - 1
}
func (s RSubs) At(i int) RSub {
start := s.rawSpans[i*2]
end := s.rawSpans[i*2+1]
return RSub{
Content: s.content[start:end],
Span: Span{
Start: s.shift + start,
End: s.shift + end,
},
}
}
func (s RSubs) Slice() []RSub {
spans := s.rawSpans
nSubs := len(spans)/2 - 1
subs := make([]RSub, 0, nSubs)
for i := 2; i < len(spans); i += 2 {
subStart := spans[i]
subEnd := spans[i+1]
sub := RSub{
Content: s.content[subStart:subEnd],
Span: Span{
Start: s.shift + subStart,
End: s.shift + subEnd,
},
}
subs = append(subs, sub)
}
return subs
}
func (s RSubs) Iter() iter.Seq[RSub] {
return func(yield func(RSub) bool) {
spans := s.rawSpans
for i := 2; i < len(spans); i += 2 {
subStart := spans[i]
subEnd := spans[i+1]
sub := RSub{
Content: s.content[subStart:subEnd],
Span: Span{
Start: s.shift + subStart,
End: s.shift + subEnd,
},
}
more := yield(sub)
if !more {
return
}
}
}
}
type RSub = Sub[[]rune]