-
-
Notifications
You must be signed in to change notification settings - Fork 117
/
format.go
80 lines (67 loc) · 1.79 KB
/
format.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
package entity
import (
"strings"
"github.com/gotd/td/tg"
)
type utf8entity struct {
offset int
length int
}
// Builder builds message string and text entities.
type Builder struct {
entities []tg.MessageEntityClass
// lengths stores offset/length of entities too, but in UTF-8 codepoints.
lengths []utf8entity
// We store index of first entity added at last Format call.
// It needed to trim space in all entities of last text block.
lastFormatIndex int
// utf16length stores length in UTF-16 codepoints.
utf16length int
// message is message string builder.
message strings.Builder
}
// GrowText grows internal buffer capacity.
func (b *Builder) GrowText(n int) {
b.message.Grow(n)
}
// GrowEntities grows internal buffer capacity.
func (b *Builder) GrowEntities(n int) {
if n < 0 {
panic("entity.Builder.GrowEntities: negative count")
}
buf := make([]tg.MessageEntityClass, len(b.entities), 2*cap(b.entities)+n)
copy(buf, b.entities)
b.entities = buf
}
// Reset resets the Builder to be empty.
func (b *Builder) Reset() {
b.message.Reset()
b.entities = nil
b.utf16length = 0
}
// UTF8Len returns length of text in bytes.
func (b *Builder) UTF8Len() int {
return b.message.Len()
}
// UTF16Len returns length of text in UTF-16 codepoints.
func (b *Builder) UTF16Len() int {
return b.utf16length
}
// EntitiesLen return length of added entities.
func (b *Builder) EntitiesLen() int {
return len(b.entities)
}
// TextRange returns message text of given byte (UTF-8) range.
//
// If range is invalid, it will panic.
func (b *Builder) TextRange(from, to int) string {
return b.message.String()[from:to]
}
// LastEntity returns last entity if any.
func (b *Builder) LastEntity() (tg.MessageEntityClass, bool) {
l := b.EntitiesLen()
if l < 1 {
return nil, false
}
return b.entities[l-1], true
}