| 1 |
package encoder |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"math/bits" |
| 6 |
"math/rand" |
| 7 |
"reflect" |
| 8 |
"slices" |
| 9 |
"strconv" |
| 10 |
"strings" |
| 11 |
"testing" |
| 12 |
"unsafe" |
| 13 |
) |
| 14 |
|
| 15 |
// The candidates of the optimizations, which are measured against what is used now on the machine of the CI: |
| 16 |
// amd64 can't be measured on the machine they are developed on. |
| 17 |
|
| 18 |
// escapeMask returns the mask of the bytes of n which may need an escape: a control character, '"', '\\' and |
| 19 |
// a byte which is not ASCII. The most significant bit of such a byte is set. |
| 20 |
// |
| 21 |
// A byte after one which needs an escape may be set too, because of the borrow of the subtraction, |
| 22 |
// so only the first byte of the mask is exact. |
| 23 |
func escapeMask(n uint64) uint64 { |
| 24 |
// `n` is in the mask to check whether the most significant bit of a byte of the input is set |
| 25 |
// ( the byte is outside of ASCII ). |
| 26 |
mask := n | (n - (lsb * 0x20)) | |
| 27 |
((n ^ (lsb * '"')) - lsb) | |
| 28 |
((n ^ (lsb * '\\')) - lsb) |
| 29 |
return mask & msb |
| 30 |
} |
| 31 |
|
| 32 |
// escapeMaskHTML is escapeMask which also has '<', '>' and '&'. |
| 33 |
func escapeMaskHTML(n uint64) uint64 { |
| 34 |
mask := n | (n - (lsb * 0x20)) | |
| 35 |
((n ^ (lsb * '"')) - lsb) | |
| 36 |
((n ^ (lsb * '\\')) - lsb) | |
| 37 |
((n ^ (lsb * '<')) - lsb) | |
| 38 |
((n ^ (lsb * '>')) - lsb) | |
| 39 |
((n ^ (lsb * '&')) - lsb) |
| 40 |
return mask & msb |
| 41 |
} |
| 42 |
|
| 43 |
// shortStringWord returns the bytes of a string of 1 to 7 bytes as a word, without reading out of the string, |
| 44 |
// and the index of the string which each byte of the word is of. The bytes which are not used are 'a'. |
| 45 |
func shortStringWord(p unsafe.Pointer, n int) (uint64, [8]uint8) { |
| 46 |
if n >= 4 { |
| 47 |
// the two halves overlap. |
| 48 |
word := uint64(*(*uint32)(p)) | uint64(*(*uint32)(unsafe.Add(p, n-4)))<<32 |
| 49 |
m := uint8(n - 4) |
| 50 |
return word, [8]uint8{0, 1, 2, 3, m, m + 1, m + 2, m + 3} |
| 51 |
} |
| 52 |
// the first, the middle and the last byte are every byte of 1 to 3 bytes. |
| 53 |
word := uint64(*(*uint8)(p)) | |
| 54 |
uint64(*(*uint8)(unsafe.Add(p, n>>1)))<<8 | |
| 55 |
uint64(*(*uint8)(unsafe.Add(p, n-1)))<<16 | |
| 56 |
0x6161616161000000 |
| 57 |
return word, [8]uint8{0, uint8(n >> 1), uint8(n - 1)} |
| 58 |
} |
| 59 |
|
| 60 |
// firstEscape returns the index of the first byte of s which may need an escape, or len(s) if there is none. |
| 61 |
// The string is always read by words: the last word of a string overlaps the previous one, and a string shorter |
| 62 |
// than a word is gathered into a word. |
| 63 |
func firstEscape(s string) int { |
| 64 |
n := len(s) |
| 65 |
p := unsafe.Pointer(unsafe.StringData(s)) |
| 66 |
if n < 8 { |
| 67 |
if n == 0 { |
| 68 |
return 0 |
| 69 |
} |
| 70 |
word, index := shortStringWord(p, n) |
| 71 |
if mask := escapeMask(word); mask != 0 { |
| 72 |
return int(index[bits.TrailingZeros64(mask)/8]) |
| 73 |
} |
| 74 |
return n |
| 75 |
} |
| 76 |
i := 0 |
| 77 |
for ; i+8 <= n; i += 8 { |
| 78 |
if mask := escapeMask(*(*uint64)(unsafe.Add(p, i))); mask != 0 { |
| 79 |
return i + bits.TrailingZeros64(mask)/8 |
| 80 |
} |
| 81 |
} |
| 82 |
if i < n { |
| 83 |
if mask := escapeMask(*(*uint64)(unsafe.Add(p, n-8))); mask != 0 { |
| 84 |
return n - 8 + bits.TrailingZeros64(mask)/8 |
| 85 |
} |
| 86 |
} |
| 87 |
return n |
| 88 |
} |
| 89 |
|
| 90 |
// firstEscapeHTML is firstEscape which also finds '<', '>' and '&'. |
| 91 |
func firstEscapeHTML(s string) int { |
| 92 |
n := len(s) |
| 93 |
p := unsafe.Pointer(unsafe.StringData(s)) |
| 94 |
if n < 8 { |
| 95 |
if n == 0 { |
| 96 |
return 0 |
| 97 |
} |
| 98 |
word, index := shortStringWord(p, n) |
| 99 |
if mask := escapeMaskHTML(word); mask != 0 { |
| 100 |
return int(index[bits.TrailingZeros64(mask)/8]) |
| 101 |
} |
| 102 |
return n |
| 103 |
} |
| 104 |
i := 0 |
| 105 |
for ; i+8 <= n; i += 8 { |
| 106 |
if mask := escapeMaskHTML(*(*uint64)(unsafe.Add(p, i))); mask != 0 { |
| 107 |
return i + bits.TrailingZeros64(mask)/8 |
| 108 |
} |
| 109 |
} |
| 110 |
if i < n { |
| 111 |
if mask := escapeMaskHTML(*(*uint64)(unsafe.Add(p, n-8))); mask != 0 { |
| 112 |
return n - 8 + bits.TrailingZeros64(mask)/8 |
| 113 |
} |
| 114 |
} |
| 115 |
return n |
| 116 |
} |
| 117 |
|
| 118 |
// appendStringByWords is appendNormalizedHTMLString which scans the string only by words. |
| 119 |
func appendStringByWords(buf []byte, s string) []byte { |
| 120 |
if j := firstEscapeHTML(s); j != len(s) { |
| 121 |
return appendNormalizedHTMLString(buf, s) |
| 122 |
} |
| 123 |
buf = append(buf, '"') |
| 124 |
return append(append(buf, s...), '"') |
| 125 |
} |
| 126 |
|
| 127 |
// appendStringReserved is appendStringByWords which checks the capacity once and writes the quotes directly. |
| 128 |
func appendStringReserved(buf []byte, s string) []byte { |
| 129 |
if j := firstEscapeHTML(s); j != len(s) { |
| 130 |
return appendNormalizedHTMLString(buf, s) |
| 131 |
} |
| 132 |
l := len(buf) |
| 133 |
if cap(buf)-l < len(s)+2 { |
| 134 |
buf = variantReserve(buf, len(s)+2) |
| 135 |
} |
| 136 |
buf = buf[:l+len(s)+2] |
| 137 |
buf[l] = '"' |
| 138 |
copy(buf[l+1:], s) |
| 139 |
buf[l+1+len(s)] = '"' |
| 140 |
return buf |
| 141 |
} |
| 142 |
|
| 143 |
// appendStringShortCopy scans as appendNormalizedHTMLString does ( by bytes under a word ), but it checks the |
| 144 |
// capacity once, writes the quotes directly and copies a string up to 16 bytes without calling memmove. |
| 145 |
func appendStringShortCopy(buf []byte, s string) []byte { |
| 146 |
n := len(s) |
| 147 |
l := len(buf) |
| 148 |
if cap(buf)-l < n+2 { |
| 149 |
buf = variantReserve(buf, n+2) |
| 150 |
} |
| 151 |
src := unsafe.Pointer(unsafe.StringData(s)) |
| 152 |
if n < 8 { |
| 153 |
for i := 0; i < n; i++ { |
| 154 |
if needEscapeHTMLNormalizeUTF8[*(*byte)(unsafe.Add(src, i))] { |
| 155 |
return appendNormalizedHTMLString(buf, s) |
| 156 |
} |
| 157 |
} |
| 158 |
} else { |
| 159 |
i := 0 |
| 160 |
for ; i+8 <= n; i += 8 { |
| 161 |
if escapeMaskHTML(*(*uint64)(unsafe.Add(src, i))) != 0 { |
| 162 |
return appendNormalizedHTMLString(buf, s) |
| 163 |
} |
| 164 |
} |
| 165 |
if i < n && escapeMaskHTML(*(*uint64)(unsafe.Add(src, n-8))) != 0 { |
| 166 |
return appendNormalizedHTMLString(buf, s) |
| 167 |
} |
| 168 |
} |
| 169 |
buf = buf[:l+n+2] |
| 170 |
dst := unsafe.Pointer(unsafe.SliceData(buf[l:])) |
| 171 |
*(*byte)(dst) = '"' |
| 172 |
dst = unsafe.Add(dst, 1) |
| 173 |
switch { |
| 174 |
case n > 16: |
| 175 |
copy(buf[l+1:], s) |
| 176 |
case n >= 8: |
| 177 |
// the two words overlap. |
| 178 |
*(*uint64)(dst) = *(*uint64)(src) |
| 179 |
*(*uint64)(unsafe.Add(dst, n-8)) = *(*uint64)(unsafe.Add(src, n-8)) |
| 180 |
case n >= 4: |
| 181 |
*(*uint32)(dst) = *(*uint32)(src) |
| 182 |
*(*uint32)(unsafe.Add(dst, n-4)) = *(*uint32)(unsafe.Add(src, n-4)) |
| 183 |
case n > 0: |
| 184 |
// the first, the middle and the last byte are every byte of 1 to 3 bytes. |
| 185 |
*(*byte)(dst) = *(*byte)(src) |
| 186 |
*(*byte)(unsafe.Add(dst, n>>1)) = *(*byte)(unsafe.Add(src, n>>1)) |
| 187 |
*(*byte)(unsafe.Add(dst, n-1)) = *(*byte)(unsafe.Add(src, n-1)) |
| 188 |
} |
| 189 |
*(*byte)(unsafe.Add(dst, n)) = '"' |
| 190 |
return buf |
| 191 |
} |
| 192 |
|
| 193 |
//go:noinline |
| 194 |
func variantReserve(b []byte, n int) []byte { |
| 195 |
grown := make([]byte, len(b), 2*cap(b)+n) |
| 196 |
copy(grown, b) |
| 197 |
return grown |
| 198 |
} |
| 199 |
|
| 200 |
const variantKeyChunk = 16 |
| 201 |
|
| 202 |
func variantPaddedKey(key string) string { |
| 203 |
buf := make([]byte, (len(key)/variantKeyChunk+1)*variantKeyChunk) |
| 204 |
copy(buf, key) |
| 205 |
return unsafe.String(unsafe.SliceData(buf), len(key)) |
| 206 |
} |
| 207 |
|
| 208 |
// appendKeyByChunks copies the key, whose memory is padded, by chunks of a fixed size instead of memmove. |
| 209 |
func appendKeyByChunks(b []byte, key string) []byte { |
| 210 |
n := len(b) |
| 211 |
if cap(b)-n < len(key)+variantKeyChunk { |
| 212 |
b = variantReserve(b, len(key)+variantKeyChunk) |
| 213 |
} |
| 214 |
src := unsafe.Pointer(unsafe.StringData(key)) |
| 215 |
dst := unsafe.Pointer(unsafe.SliceData(b[n:cap(b)])) |
| 216 |
for i := 0; i < len(key); i += variantKeyChunk { |
| 217 |
*(*[variantKeyChunk]byte)(unsafe.Add(dst, i)) = *(*[variantKeyChunk]byte)(unsafe.Add(src, i)) |
| 218 |
} |
| 219 |
return b[:n+len(key)] |
| 220 |
} |
| 221 |
|
| 222 |
var ( |
| 223 |
variantStrings = []string{ |
| 224 |
"", "abc", "test42", "active", "127.0.0.1", "user_agent_long", "de305d54-75b4-431b-adb2-eb6b9e546014", |
| 225 |
strings.Repeat("abcdefghij", 10), strings.Repeat("abcdefghij", 100), |
| 226 |
} |
| 227 |
variantKeys = []string{`"a":`, `"sid":`, `"user_agent":`, `"a_key_longer_than_a_chunk":`} |
| 228 |
) |
| 229 |
|
| 230 |
func BenchmarkVariant_String(b *testing.B) { |
| 231 |
for _, s := range variantStrings { |
| 232 |
for _, variant := range []struct { |
| 233 |
name string |
| 234 |
f func([]byte, string) []byte |
| 235 |
}{ |
| 236 |
{"Current", appendNormalizedHTMLString}, |
| 237 |
{"ByWords", appendStringByWords}, |
| 238 |
{"Reserved", appendStringReserved}, |
| 239 |
{"ShortCopy", appendStringShortCopy}, |
| 240 |
} { |
| 241 |
s, f := s, variant.f |
| 242 |
b.Run(variant.name+"/"+strconv.Itoa(len(s)), func(b *testing.B) { |
| 243 |
buf := make([]byte, 0, 4096) |
| 244 |
for i := 0; i < b.N; i++ { |
| 245 |
buf = f(buf[:0], s) |
| 246 |
} |
| 247 |
}) |
| 248 |
} |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
func BenchmarkVariant_Key(b *testing.B) { |
| 253 |
for _, key := range variantKeys { |
| 254 |
padded := variantPaddedKey(key) |
| 255 |
b.Run("Current/"+strconv.Itoa(len(key)), func(b *testing.B) { |
| 256 |
buf := make([]byte, 0, 4096) |
| 257 |
for i := 0; i < b.N; i++ { |
| 258 |
buf = buf[:0] |
| 259 |
for j := 0; j < 8; j++ { |
| 260 |
buf = append(buf, padded...) |
| 261 |
} |
| 262 |
} |
| 263 |
}) |
| 264 |
b.Run("ByChunks/"+strconv.Itoa(len(key)), func(b *testing.B) { |
| 265 |
buf := make([]byte, 0, 4096) |
| 266 |
for i := 0; i < b.N; i++ { |
| 267 |
buf = buf[:0] |
| 268 |
for j := 0; j < 8; j++ { |
| 269 |
buf = appendKeyByChunks(buf, padded) |
| 270 |
} |
| 271 |
} |
| 272 |
}) |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
func TestVariantsEncodeTheSame(t *testing.T) { |
| 277 |
var inputs []string |
| 278 |
for length := 0; length <= 40; length++ { |
| 279 |
inputs = append(inputs, strings.Repeat("a", length)) |
| 280 |
for pos := 0; pos < length; pos++ { |
| 281 |
for _, c := range []byte{'"', '<', 0x01, 0xe3} { |
| 282 |
b := []byte(strings.Repeat("b", length)) |
| 283 |
b[pos] = c |
| 284 |
inputs = append(inputs, string(b)) |
| 285 |
} |
| 286 |
} |
| 287 |
} |
| 288 |
for _, s := range inputs { |
| 289 |
expected := string(appendNormalizedHTMLString([]byte("x"), s)) |
| 290 |
for name, f := range map[string]func([]byte, string) []byte{ |
| 291 |
"ByWords": appendStringByWords, |
| 292 |
"Reserved": appendStringReserved, |
| 293 |
"ShortCopy": appendStringShortCopy, |
| 294 |
} { |
| 295 |
// without and with the capacity. |
| 296 |
for _, buf := range [][]byte{[]byte("x"), append(make([]byte, 0, 128), 'x')} { |
| 297 |
if got := string(f(buf, s)); got != expected { |
| 298 |
t.Fatalf("%s(%q): expected %s but got %s", name, s, expected, got) |
| 299 |
} |
| 300 |
} |
| 301 |
} |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
// the four functions which AppendString chooses by the options must cost the same for a string without an escape. |
| 306 |
func BenchmarkVariant_StringFlags(b *testing.B) { |
| 307 |
for _, s := range []string{"test42", "user_agent_long", "de305d54-75b4-431b-adb2-eb6b9e546014"} { |
| 308 |
for _, variant := range []struct { |
| 309 |
name string |
| 310 |
f func([]byte, string) []byte |
| 311 |
}{ |
| 312 |
{"NormalizedHTML", appendNormalizedHTMLString}, |
| 313 |
{"HTML", appendHTMLString}, |
| 314 |
{"Normalized", appendNormalizedString}, |
| 315 |
{"Plain", appendString}, |
| 316 |
} { |
| 317 |
s, f := s, variant.f |
| 318 |
b.Run(variant.name+"/"+strconv.Itoa(len(s)), func(b *testing.B) { |
| 319 |
buf := make([]byte, 0, 4096) |
| 320 |
for i := 0; i < b.N; i++ { |
| 321 |
buf = f(buf[:0], s) |
| 322 |
} |
| 323 |
}) |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
// where the insertion sort of Mapslice.Sort stops being faster than slices.SortFunc, with keys which are random |
| 329 |
// in their content and in their length. |
| 330 |
func BenchmarkVariant_MapSort(b *testing.B) { |
| 331 |
rnd := rand.New(rand.NewSource(1)) |
| 332 |
for _, n := range []int{2, 4, 8, 12, 16, 24, 32, 48, 64, 128} { |
| 333 |
const sets = 64 |
| 334 |
keys := make([][]MapItem, sets) |
| 335 |
for i := range keys { |
| 336 |
keys[i] = make([]MapItem, n) |
| 337 |
for j := range keys[i] { |
| 338 |
key := make([]byte, 3+rnd.Intn(20)) |
| 339 |
for k := range key { |
| 340 |
key[k] = byte('a' + rnd.Intn(26)) |
| 341 |
} |
| 342 |
keys[i][j].Key = key |
| 343 |
} |
| 344 |
} |
| 345 |
work := make([]MapItem, n) |
| 346 |
b.Run("Insertion/"+strconv.Itoa(n), func(b *testing.B) { |
| 347 |
for i := 0; i < b.N; i++ { |
| 348 |
copy(work, keys[i%sets]) |
| 349 |
insertionSortMapItems(work) |
| 350 |
} |
| 351 |
}) |
| 352 |
b.Run("SortFunc/"+strconv.Itoa(n), func(b *testing.B) { |
| 353 |
for i := 0; i < b.N; i++ { |
| 354 |
copy(work, keys[i%sets]) |
| 355 |
slices.SortFunc(work, func(a, b MapItem) int { return bytes.Compare(a.Key, b.Key) }) |
| 356 |
} |
| 357 |
}) |
| 358 |
} |
| 359 |
} |
| 360 |
|
| 361 |
// the reading of the entries of a map: by a range over the map as a map of the same layout, or by |
| 362 |
// reflect.MapIter, which sets the key and the value to interface values. |
| 363 |
func BenchmarkVariant_MapIter(b *testing.B) { |
| 364 |
for _, n := range []int{1, 5, 20} { |
| 365 |
m := map[string]any{} |
| 366 |
for i := 0; i < n; i++ { |
| 367 |
m["key"+strconv.Itoa(i)] = i |
| 368 |
} |
| 369 |
typ := reflect.TypeOf(m) |
| 370 |
mp := *(*unsafe.Pointer)(unsafe.Pointer(&m)) |
| 371 |
shape := NewMapLayout(typ) |
| 372 |
byReflect := &MapLayout{collect: newReflectCollector(typ), StringKey: true, keySize: 16, valueSize: 16} |
| 373 |
for _, variant := range []struct { |
| 374 |
name string |
| 375 |
layout *MapLayout |
| 376 |
}{{"Shape", shape}, {"Reflect", byReflect}} { |
| 377 |
layout := variant.layout |
| 378 |
b.Run(variant.name+"/"+strconv.Itoa(n), func(b *testing.B) { |
| 379 |
c := &MapContext{} |
| 380 |
var sum int |
| 381 |
for i := 0; i < b.N; i++ { |
| 382 |
layout.Collect(mp, c) |
| 383 |
for j := 0; j < c.Len; j++ { |
| 384 |
sum += len(c.Keys[j]) + int(uintptr(c.ValueAt(j))&1) |
| 385 |
} |
| 386 |
} |
| 387 |
_ = sum |
| 388 |
}) |
| 389 |
} |
| 390 |
} |
| 391 |
} |