-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.go
52 lines (39 loc) · 1014 Bytes
/
translate.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
package zyt
import (
"errors"
"fmt"
"strings"
)
var errIncompleteTranslation = errors.New("translation incomplete")
// Apply mappers to text without overlapping in the order they're given. An
// error is returned if not all mappers find a piece of text to replace.
func translate(text string, mappers mapperSlice) (string, error) {
var buf strings.Builder
buf.Grow(len(text))
textPos := 0
mapperPos := 0
for textPos < len(text) {
if mapperPos >= len(mappers) {
break
}
m := mappers[mapperPos]
if repl, skipCount := m.replacePrefix(text[textPos:]); skipCount > 0 {
buf.WriteString(repl)
textPos += skipCount
mapperPos++
continue
}
buf.WriteByte(text[textPos])
textPos++
}
if textPos < len(text) {
buf.WriteString(text[textPos:])
}
var err error
if mapperPos < len(mappers) {
err = fmt.Errorf("%w: used only %d of %d mappers for %q with result %q",
errIncompleteTranslation,
mapperPos, len(mappers), text, buf.String())
}
return buf.String(), err
}