-
Notifications
You must be signed in to change notification settings - Fork 0
/
v1.go
84 lines (69 loc) · 1.62 KB
/
v1.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
82
83
84
package ropeExperiment
import (
"bytes"
"fmt"
"io"
"strings"
"unicode/utf8"
)
// V1 is a simple string
type V1 struct {
value string
}
func CreateV1(initial string) Rope {
return &V1{initial}
}
func (r *V1) Alter(start, end int, value string) error {
var buf bytes.Buffer
byteStart := r.findByteOffsets(start)
byteEnd := r.findByteOffsets(end)
buf.Grow(len(r.value) + len(value) - byteEnd + byteStart)
buf.WriteString(r.value[:byteStart])
buf.WriteString(value)
buf.WriteString(r.value[byteEnd:])
r.value = buf.String()
return nil
}
func (r *V1) ByteLength() int {
return len(r.value)
}
func (r *V1) GoString() string {
return fmt.Sprintf("[%d, %d]", r.Length(), r.ByteLength())
}
func (r *V1) Insert(start int, value string) error {
var buf bytes.Buffer
offset := r.findByteOffsets(start)
buf.Grow(len(r.value) + len(value))
buf.WriteString(r.value[:offset])
buf.WriteString(value)
buf.WriteString(r.value[offset:])
r.value = buf.String()
return nil
}
func (r *V1) Length() int {
return utf8.RuneCountInString(r.value)
}
func (r *V1) NewReader() io.Reader {
return strings.NewReader(r.value)
}
func (r *V1) Remove(start, end int) error {
var buf bytes.Buffer
byteStart := r.findByteOffsets(start)
byteEnd := r.findByteOffsets(end)
buf.Grow(len(r.value) - byteEnd + byteStart)
buf.WriteString(r.value[:byteStart])
buf.WriteString(r.value[byteEnd:])
r.value = buf.String()
return nil
}
func (r *V1) String() string {
return r.value
}
func (r *V1) findByteOffsets(position int) int {
rs := []rune(r.value)
offset := 0
for i := 0; i < position; i++ {
offset += utf8.RuneLen(rs[i])
}
return offset
}