forked from digitalcrab/browscap_go
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhelpers.go
70 lines (64 loc) · 1.38 KB
/
helpers.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
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package browscap_go
import (
"sync"
"unicode/utf8"
)
var (
bytesPool = &sync.Pool{}
minCap = 128
)
func getBytes(size int) []byte {
if b := bytesPool.Get(); b != nil {
bs := b.([]byte)
if cap(bs) >= size {
return bs[:size]
}
}
c := size
if c < minCap {
c = minCap
}
return make([]byte, size, c)
}
func mapToBytes(mapping func(rune) rune, s string) []byte {
// In the worst case, the string can grow when mapped, making
// things unpleasant. But it's so rare we barge in assuming it's
// fine. It could also shrink but that falls out naturally.
maxbytes := len(s) // length of b
nbytes := 0 // number of bytes encoded in b
// The output buffer b is initialized on demand, the first
// time a character differs.
var b []byte
for i, c := range s {
r := mapping(c)
if b == nil {
if r == c {
continue
}
b = getBytes(maxbytes)
nbytes = copy(b, s[:i])
}
if r >= 0 {
wid := 1
if r >= utf8.RuneSelf {
wid = utf8.RuneLen(r)
}
if nbytes+wid > maxbytes {
// Grow the buffer.
maxbytes = maxbytes*2 + utf8.UTFMax
nb := getBytes(maxbytes)
copy(nb, b[0:nbytes])
b = nb
}
nbytes += utf8.EncodeRune(b[nbytes:maxbytes], r)
}
}
if b == nil {
b = getBytes(maxbytes)
copy(b, s)
return b
}
return b[0:nbytes]
}