-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransformer_numbers.go
88 lines (79 loc) · 2.19 KB
/
transformer_numbers.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
85
86
87
88
package sinoname
import (
"context"
"strconv"
)
// NumbersPrefix adds a integer to the beginning of the string.
// It obtains the integer by:
// 1. From the context via NumberFromContext .
// 2. Collects all the numbers from the string.
//
// Foo1 Bar2 Buz3 -> 123Foo Bar Buz .
var NumbersPrefix = func(sep string) func(cfg *Config) (Transformer, bool) {
return func(cfg *Config) (Transformer, bool) {
return &numbersTransformer{
where: prefix,
cfg: cfg,
sep: sep,
}, false
}
}
// NumbersSuffix adds a integer to the end of the string.
// It obtains the integer by:
// 1. From the context via NumberFromContext .
// 2. Collects all the numbers from the string.
//
// Foo1 Bar2 Buz3 -> Foo Bar Buz123
var NumbersSuffix = func(sep string) func(cfg *Config) (Transformer, bool) {
return func(cfg *Config) (Transformer, bool) {
return &numbersTransformer{
where: suffix,
cfg: cfg,
sep: sep,
}, false
}
}
// NumbersCircumfix adds a integer to the end and beinning of the string.
// It obtains the integer by:
// 1. From the context via NumberFromContext .
// 2. Collects all the numbers from the string.
//
// Foo1 Bar2 Buz3 -> 123Foo Bar Buz123
var NumbersCircumfix = func(sep string) func(cfg *Config) (Transformer, bool) {
return func(cfg *Config) (Transformer, bool) {
return &numbersTransformer{
where: circumfix,
cfg: cfg,
sep: sep,
}, false
}
}
type numbersTransformer struct {
where affix
cfg *Config
sep string
}
func (t *numbersTransformer) Transform(ctx context.Context, in MessagePacket) (MessagePacket, error) {
if len(in.Message)+len(t.sep) > t.cfg.MaxBytes {
return in, nil
}
if v, ok := NumberFromContext(ctx); ok {
num := strconv.Itoa(v)
out, ok := applyAffix(t.cfg, t.where, in.Message, t.sep, num)
if ok {
unique, err := t.cfg.Source.Valid(ctx, out)
if err != nil || unique {
in.setAndIncrement(out)
return in, err
}
}
}
stripped, num := t.cfg.StripNumbers(in.Message)
// no point in checking the ok value since len(stripped) + len(num) == len(in.Message)
out, _ := applyAffix(t.cfg, t.where, stripped, t.sep, num)
ok, err := t.cfg.Source.Valid(ctx, out)
if ok {
in.setAndIncrement(out)
}
return in, err
}