| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
package canonicaljson |
| 22 |
|
| 23 |
import ( |
| 24 |
"bytes" |
| 25 |
"encoding" |
| 26 |
"encoding/base64" |
| 27 |
"encoding/json" |
| 28 |
"fmt" |
| 29 |
"math" |
| 30 |
"reflect" |
| 31 |
"regexp" |
| 32 |
"runtime" |
| 33 |
"sort" |
| 34 |
"strconv" |
| 35 |
"strings" |
| 36 |
"sync" |
| 37 |
"unicode" |
| 38 |
"unicode/utf8" |
| 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 |
ld |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
func Marshal(v interface{}) ([]byte, error) { |
| 166 |
e := &encodeState{} |
| 167 |
err := e.marshal(v) |
| 168 |
if err != nil { |
| 169 |
return nil, err |
| 170 |
} |
| 171 |
return e.Bytes(), nil |
| 172 |
} |
| 173 |
|
| 174 |
|
| 175 |
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { |
| 176 |
b, err := Marshal(v) |
| 177 |
if err != nil { |
| 178 |
return nil, err |
| 179 |
} |
| 180 |
var buf bytes.Buffer |
| 181 |
err = addIndentation(&buf, b, prefix, indent) |
| 182 |
if err != nil { |
| 183 |
return nil, err |
| 184 |
} |
| 185 |
return buf.Bytes(), nil |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
type Marshaler interface { |
| 191 |
MarshalJSON() ([]byte, error) |
| 192 |
} |
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
type UnsupportedTypeError struct { |
| 197 |
Type reflect.Type |
| 198 |
} |
| 199 |
|
| 200 |
func (e *UnsupportedTypeError) Error() string { |
| 201 |
return "canonicaljson: unsupported type: " + e.Type.String() |
| 202 |
} |
| 203 |
|
| 204 |
type UnsupportedValueError struct { |
| 205 |
Value reflect.Value |
| 206 |
Str string |
| 207 |
} |
| 208 |
|
| 209 |
func (e *UnsupportedValueError) Error() string { |
| 210 |
return "canonicaljson: unsupported value: " + e.Str |
| 211 |
} |
| 212 |
|
| 213 |
type MarshalerError struct { |
| 214 |
Type reflect.Type |
| 215 |
Err error |
| 216 |
} |
| 217 |
|
| 218 |
func (e *MarshalerError) Error() string { |
| 219 |
return "canonicaljson: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error() |
| 220 |
} |
| 221 |
|
| 222 |
var hex = "0123456789ABCDEF" |
| 223 |
var jsonNumberType = reflect.TypeOf(json.Number("")) |
| 224 |
|
| 225 |
|
| 226 |
type encodeState struct { |
| 227 |
bytes.Buffer |
| 228 |
scratch [64]byte |
| 229 |
} |
| 230 |
|
| 231 |
var encodeStatePool sync.Pool |
| 232 |
|
| 233 |
func newEncodeState() *encodeState { |
| 234 |
if v := encodeStatePool.Get(); v != nil { |
| 235 |
e := v.(*encodeState) |
| 236 |
e.Reset() |
| 237 |
return e |
| 238 |
} |
| 239 |
return new(encodeState) |
| 240 |
} |
| 241 |
|
| 242 |
func (e *encodeState) marshal(v interface{}) (err error) { |
| 243 |
defer func() { |
| 244 |
if r := recover(); r != nil { |
| 245 |
if _, ok := r.(runtime.Error); ok { |
| 246 |
panic(r) |
| 247 |
} |
| 248 |
if s, ok := r.(string); ok { |
| 249 |
panic(s) |
| 250 |
} |
| 251 |
err = r.(error) |
| 252 |
} |
| 253 |
}() |
| 254 |
e.reflectValue(reflect.ValueOf(v)) |
| 255 |
return nil |
| 256 |
} |
| 257 |
|
| 258 |
func (e *encodeState) error(err error) { |
| 259 |
panic(err) |
| 260 |
} |
| 261 |
|
| 262 |
func isEmptyValue(v reflect.Value) bool { |
| 263 |
switch v.Kind() { |
| 264 |
case reflect.Array, reflect.Map, reflect.Slice, reflect.String: |
| 265 |
return v.Len() == 0 |
| 266 |
case reflect.Bool: |
| 267 |
return !v.Bool() |
| 268 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 269 |
return v.Int() == 0 |
| 270 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 271 |
return v.Uint() == 0 |
| 272 |
case reflect.Float32, reflect.Float64: |
| 273 |
return v.Float() == 0 |
| 274 |
case reflect.Interface, reflect.Ptr: |
| 275 |
return v.IsNil() |
| 276 |
} |
| 277 |
return false |
| 278 |
} |
| 279 |
|
| 280 |
func (e *encodeState) reflectValue(v reflect.Value) { |
| 281 |
valueEncoder(v)(e, v, false) |
| 282 |
} |
| 283 |
|
| 284 |
type encoderFunc func(e *encodeState, v reflect.Value, quoted bool) |
| 285 |
|
| 286 |
var encoderCache struct { |
| 287 |
sync.RWMutex |
| 288 |
m map[reflect.Type]encoderFunc |
| 289 |
} |
| 290 |
|
| 291 |
func valueEncoder(v reflect.Value) encoderFunc { |
| 292 |
if !v.IsValid() { |
| 293 |
return invalidValueEncoder |
| 294 |
} |
| 295 |
return typeEncoder(v.Type()) |
| 296 |
} |
| 297 |
|
| 298 |
func typeEncoder(t reflect.Type) encoderFunc { |
| 299 |
encoderCache.RLock() |
| 300 |
f := encoderCache.m[t] |
| 301 |
encoderCache.RUnlock() |
| 302 |
if f != nil { |
| 303 |
return f |
| 304 |
} |
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
encoderCache.Lock() |
| 311 |
if encoderCache.m == nil { |
| 312 |
encoderCache.m = make(map[reflect.Type]encoderFunc) |
| 313 |
} |
| 314 |
var wg sync.WaitGroup |
| 315 |
wg.Add(1) |
| 316 |
encoderCache.m[t] = func(e *encodeState, v reflect.Value, quoted bool) { |
| 317 |
wg.Wait() |
| 318 |
f(e, v, quoted) |
| 319 |
} |
| 320 |
encoderCache.Unlock() |
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
f = newTypeEncoder(t, true) |
| 325 |
wg.Done() |
| 326 |
encoderCache.Lock() |
| 327 |
encoderCache.m[t] = f |
| 328 |
encoderCache.Unlock() |
| 329 |
return f |
| 330 |
} |
| 331 |
|
| 332 |
var ( |
| 333 |
marshalerType = reflect.TypeOf(new(json.Marshaler)).Elem() |
| 334 |
textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem() |
| 335 |
) |
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc { |
| 340 |
if t.Implements(marshalerType) { |
| 341 |
return marshalerEncoder |
| 342 |
} |
| 343 |
if t.Kind() != reflect.Ptr && allowAddr { |
| 344 |
if reflect.PtrTo(t).Implements(marshalerType) { |
| 345 |
return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false)) |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
if t.Implements(textMarshalerType) { |
| 350 |
return textMarshalerEncoder |
| 351 |
} |
| 352 |
if t.Kind() != reflect.Ptr && allowAddr { |
| 353 |
if reflect.PtrTo(t).Implements(textMarshalerType) { |
| 354 |
return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false)) |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
switch t.Kind() { |
| 359 |
case reflect.Bool: |
| 360 |
return boolEncoder |
| 361 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 362 |
return intEncoder |
| 363 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: |
| 364 |
return uintEncoder |
| 365 |
case reflect.Float32: |
| 366 |
return float32Encoder |
| 367 |
case reflect.Float64: |
| 368 |
return float64Encoder |
| 369 |
case reflect.String: |
| 370 |
return stringEncoder |
| 371 |
case reflect.Interface: |
| 372 |
return interfaceEncoder |
| 373 |
case reflect.Struct: |
| 374 |
return newStructEncoder(t) |
| 375 |
case reflect.Map: |
| 376 |
return newMapEncoder(t) |
| 377 |
case reflect.Slice: |
| 378 |
return newSliceEncoder(t) |
| 379 |
case reflect.Array: |
| 380 |
return newArrayEncoder(t) |
| 381 |
case reflect.Ptr: |
| 382 |
return newPtrEncoder(t) |
| 383 |
default: |
| 384 |
return unsupportedTypeEncoder |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
func invalidValueEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 389 |
e.WriteString("null") |
| 390 |
} |
| 391 |
|
| 392 |
func marshalerEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 393 |
if v.Kind() == reflect.Ptr && v.IsNil() { |
| 394 |
e.WriteString("null") |
| 395 |
return |
| 396 |
} |
| 397 |
m := v.Interface().(json.Marshaler) |
| 398 |
b, err := m.MarshalJSON() |
| 399 |
|
| 400 |
|
| 401 |
var data interface{} |
| 402 |
var jsonBlob []byte |
| 403 |
if err == nil { |
| 404 |
err = Unmarshal(b, &data) |
| 405 |
} |
| 406 |
if err == nil { |
| 407 |
jsonBlob, err = Marshal(data) |
| 408 |
} |
| 409 |
if err == nil { |
| 410 |
e.Buffer.Write(jsonBlob) |
| 411 |
} |
| 412 |
if err != nil { |
| 413 |
e.error(&MarshalerError{v.Type(), err}) |
| 414 |
} |
| 415 |
} |
| 416 |
|
| 417 |
func addrMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 418 |
va := v.Addr() |
| 419 |
if va.IsNil() { |
| 420 |
e.WriteString("null") |
| 421 |
return |
| 422 |
} |
| 423 |
m := va.Interface().(json.Marshaler) |
| 424 |
b, err := m.MarshalJSON() |
| 425 |
|
| 426 |
|
| 427 |
var data interface{} |
| 428 |
var jsonBlob []byte |
| 429 |
if err == nil { |
| 430 |
err = Unmarshal(b, &data) |
| 431 |
} |
| 432 |
if err == nil { |
| 433 |
jsonBlob, err = Marshal(data) |
| 434 |
} |
| 435 |
if err == nil { |
| 436 |
e.Buffer.Write(jsonBlob) |
| 437 |
} |
| 438 |
if err != nil { |
| 439 |
e.error(&MarshalerError{v.Type(), err}) |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
func textMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 444 |
if v.Kind() == reflect.Ptr && v.IsNil() { |
| 445 |
e.WriteString("null") |
| 446 |
return |
| 447 |
} |
| 448 |
m := v.Interface().(encoding.TextMarshaler) |
| 449 |
b, err := m.MarshalText() |
| 450 |
if err != nil { |
| 451 |
e.error(&MarshalerError{v.Type(), err}) |
| 452 |
} |
| 453 |
e.stringBytes(b) |
| 454 |
} |
| 455 |
|
| 456 |
func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 457 |
va := v.Addr() |
| 458 |
if va.IsNil() { |
| 459 |
e.WriteString("null") |
| 460 |
return |
| 461 |
} |
| 462 |
m := va.Interface().(encoding.TextMarshaler) |
| 463 |
b, err := m.MarshalText() |
| 464 |
if err != nil { |
| 465 |
e.error(&MarshalerError{v.Type(), err}) |
| 466 |
} |
| 467 |
e.stringBytes(b) |
| 468 |
} |
| 469 |
|
| 470 |
func boolEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 471 |
if quoted { |
| 472 |
e.WriteByte('"') |
| 473 |
} |
| 474 |
if v.Bool() { |
| 475 |
e.WriteString("true") |
| 476 |
} else { |
| 477 |
e.WriteString("false") |
| 478 |
} |
| 479 |
if quoted { |
| 480 |
e.WriteByte('"') |
| 481 |
} |
| 482 |
} |
| 483 |
|
| 484 |
func intEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 485 |
b := strconv.AppendInt(e.scratch[:0], v.Int(), 10) |
| 486 |
if quoted { |
| 487 |
e.WriteByte('"') |
| 488 |
e.Write(b) |
| 489 |
e.WriteByte('"') |
| 490 |
} else { |
| 491 |
e.Write(b) |
| 492 |
} |
| 493 |
} |
| 494 |
|
| 495 |
func uintEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 496 |
b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10) |
| 497 |
if quoted { |
| 498 |
e.WriteByte('"') |
| 499 |
e.Write(b) |
| 500 |
e.WriteByte('"') |
| 501 |
} else { |
| 502 |
e.Write(b) |
| 503 |
} |
| 504 |
} |
| 505 |
|
| 506 |
|
| 507 |
var expNormalizer = regexp.MustCompile("(?:E(?:[+]0*|(-|)0+)|e(?:[+]|(-|))0*)([0-9])") |
| 508 |
var expNormalizerReplacement = "E$1$2$3" |
| 509 |
|
| 510 |
|
| 511 |
var significantDigits = regexp.MustCompile(`^(?:0(?:\.0*|)|)([0-9.]+?)(?:0*\.?0*|)(?:E|$)`) |
| 512 |
|
| 513 |
|
| 514 |
func normalizeNumber(e *encodeState, stringBytes []byte) { |
| 515 |
s := expNormalizer.ReplaceAllString(string(stringBytes), expNormalizerReplacement) |
| 516 |
|
| 517 |
|
| 518 |
negative := s[0] == '-' |
| 519 |
if negative { |
| 520 |
s = s[1:] |
| 521 |
} |
| 522 |
|
| 523 |
|
| 524 |
exp := 0 |
| 525 |
expPos := strings.LastIndexByte(s, 'E') |
| 526 |
if expPos == -1 { |
| 527 |
expPos = len(s) |
| 528 |
} else { |
| 529 |
var err error |
| 530 |
exp, err = strconv.Atoi(s[expPos+1:]) |
| 531 |
if err != nil { |
| 532 |
e.error(err) |
| 533 |
} |
| 534 |
} |
| 535 |
|
| 536 |
|
| 537 |
significantRange := significantDigits.FindStringSubmatchIndex(s) |
| 538 |
if significantRange == nil { |
| 539 |
e.error(fmt.Errorf("canonicaljson: no significand in %q", s)) |
| 540 |
} |
| 541 |
significantRange = significantRange[2:4] |
| 542 |
if s[significantRange[0]] == '0' { |
| 543 |
e.WriteByte('0') |
| 544 |
return |
| 545 |
} |
| 546 |
pointPos := strings.IndexByte(s, '.') |
| 547 |
effectivePointPos := pointPos |
| 548 |
if effectivePointPos == -1 { |
| 549 |
effectivePointPos = expPos |
| 550 |
} |
| 551 |
var significand string |
| 552 |
if pointPos > significantRange[0] && pointPos < significantRange[1] { |
| 553 |
significand = s[significantRange[0]:pointPos] + s[pointPos+1:significantRange[1]] |
| 554 |
} else { |
| 555 |
significand = s[significantRange[0]:significantRange[1]] |
| 556 |
} |
| 557 |
|
| 558 |
|
| 559 |
isInt := (exp <= 0 && (effectivePointPos+exp) >= significantRange[1]) || |
| 560 |
(exp > 0 && (effectivePointPos+exp+1) >= significantRange[1]) |
| 561 |
|
| 562 |
|
| 563 |
if effectivePointPos > 1 { |
| 564 |
exp += effectivePointPos - 1 |
| 565 |
} else if significantRange[0] > 0 { |
| 566 |
exp -= significantRange[0] - 1 |
| 567 |
} |
| 568 |
|
| 569 |
|
| 570 |
if negative { |
| 571 |
e.WriteByte('-') |
| 572 |
} |
| 573 |
if isInt { |
| 574 |
|
| 575 |
e.WriteString(significand) |
| 576 |
if len(significand) < exp+1 { |
| 577 |
e.WriteString(strings.Repeat("0", exp+1-len(significand))) |
| 578 |
} |
| 579 |
} else { |
| 580 |
|
| 581 |
if len(significand) == 1 { |
| 582 |
significand += "0" |
| 583 |
} |
| 584 |
e.WriteString(significand[:1] + "." + significand[1:] + "E" + strconv.Itoa(exp)) |
| 585 |
} |
| 586 |
} |
| 587 |
|
| 588 |
type floatEncoder int |
| 589 |
|
| 590 |
func (bits floatEncoder) encode(e *encodeState, v reflect.Value, quoted bool) { |
| 591 |
|
| 592 |
f := v.Float() + 0 |
| 593 |
if math.IsInf(f, 0) || math.IsNaN(f) { |
| 594 |
e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))}) |
| 595 |
} |
| 596 |
b := strconv.AppendFloat(e.scratch[:0], f, 'E', -1, int(bits)) |
| 597 |
if quoted { |
| 598 |
e.WriteByte('"') |
| 599 |
e.Write(b) |
| 600 |
e.WriteByte('"') |
| 601 |
} else { |
| 602 |
normalizeNumber(e, b) |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
var ( |
| 607 |
float32Encoder = (floatEncoder(32)).encode |
| 608 |
float64Encoder = (floatEncoder(64)).encode |
| 609 |
) |
| 610 |
|
| 611 |
func stringEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 612 |
if t := v.Type(); t == numberType || t == jsonNumberType { |
| 613 |
numStr := v.String() |
| 614 |
if !isValidNumber(numStr) { |
| 615 |
e.error(fmt.Errorf("canonicaljson: invalid number literal %q", numStr)) |
| 616 |
} |
| 617 |
normalizeNumber(e, []byte(numStr)) |
| 618 |
return |
| 619 |
} |
| 620 |
if quoted { |
| 621 |
sb, err := Marshal(v.String()) |
| 622 |
if err != nil { |
| 623 |
e.error(err) |
| 624 |
} |
| 625 |
e.string(string(sb)) |
| 626 |
} else { |
| 627 |
e.string(v.String()) |
| 628 |
} |
| 629 |
} |
| 630 |
|
| 631 |
func interfaceEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 632 |
if v.IsNil() { |
| 633 |
e.WriteString("null") |
| 634 |
return |
| 635 |
} |
| 636 |
e.reflectValue(v.Elem()) |
| 637 |
} |
| 638 |
|
| 639 |
func unsupportedTypeEncoder(e *encodeState, v reflect.Value, quoted bool) { |
| 640 |
e.error(&UnsupportedTypeError{v.Type()}) |
| 641 |
} |
| 642 |
|
| 643 |
type structEncoder struct { |
| 644 |
fields []field |
| 645 |
fieldEncs []encoderFunc |
| 646 |
} |
| 647 |
|
| 648 |
func (se *structEncoder) encode(e *encodeState, v reflect.Value, quoted bool) { |
| 649 |
e.WriteByte('{') |
| 650 |
first := true |
| 651 |
for i, f := range se.fields { |
| 652 |
fv := fieldByIndex(v, f.index) |
| 653 |
if !fv.IsValid() || f.omitEmpty && isEmptyValue(fv) { |
| 654 |
continue |
| 655 |
} |
| 656 |
if first { |
| 657 |
first = false |
| 658 |
} else { |
| 659 |
e.WriteByte(',') |
| 660 |
} |
| 661 |
e.string(f.name) |
| 662 |
e.WriteByte(':') |
| 663 |
se.fieldEncs[i](e, fv, f.quoted) |
| 664 |
} |
| 665 |
e.WriteByte('}') |
| 666 |
} |
| 667 |
|
| 668 |
func newStructEncoder(t reflect.Type) encoderFunc { |
| 669 |
fields := cachedTypeFields(t) |
| 670 |
se := &structEncoder{ |
| 671 |
fields: fields, |
| 672 |
fieldEncs: make([]encoderFunc, len(fields)), |
| 673 |
} |
| 674 |
for i, f := range fields { |
| 675 |
se.fieldEncs[i] = typeEncoder(typeByIndex(t, f.index)) |
| 676 |
} |
| 677 |
return se.encode |
| 678 |
} |
| 679 |
|
| 680 |
type mapEncoder struct { |
| 681 |
elemEnc encoderFunc |
| 682 |
} |
| 683 |
|
| 684 |
func (me *mapEncoder) encode(e *encodeState, v reflect.Value, _ bool) { |
| 685 |
if v.IsNil() { |
| 686 |
e.WriteString("null") |
| 687 |
return |
| 688 |
} |
| 689 |
e.WriteByte('{') |
| 690 |
var sv stringValues = v.MapKeys() |
| 691 |
sort.Sort(sv) |
| 692 |
for i, k := range sv { |
| 693 |
if i > 0 { |
| 694 |
e.WriteByte(',') |
| 695 |
} |
| 696 |
e.string(k.String()) |
| 697 |
e.WriteByte(':') |
| 698 |
me.elemEnc(e, v.MapIndex(k), false) |
| 699 |
} |
| 700 |
e.WriteByte('}') |
| 701 |
} |
| 702 |
|
| 703 |
func newMapEncoder(t reflect.Type) encoderFunc { |
| 704 |
if t.Key().Kind() != reflect.String { |
| 705 |
return unsupportedTypeEncoder |
| 706 |
} |
| 707 |
me := &mapEncoder{typeEncoder(t.Elem())} |
| 708 |
return me.encode |
| 709 |
} |
| 710 |
|
| 711 |
func encodeByteSlice(e *encodeState, v reflect.Value, _ bool) { |
| 712 |
if v.IsNil() { |
| 713 |
e.WriteString("null") |
| 714 |
return |
| 715 |
} |
| 716 |
s := v.Bytes() |
| 717 |
e.WriteByte('"') |
| 718 |
if len(s) < 1024 { |
| 719 |
|
| 720 |
dst := make([]byte, base64.StdEncoding.EncodedLen(len(s))) |
| 721 |
base64.StdEncoding.Encode(dst, s) |
| 722 |
e.Write(dst) |
| 723 |
} else { |
| 724 |
|
| 725 |
|
| 726 |
enc := base64.NewEncoder(base64.StdEncoding, e) |
| 727 |
enc.Write(s) |
| 728 |
enc.Close() |
| 729 |
} |
| 730 |
e.WriteByte('"') |
| 731 |
} |
| 732 |
|
| 733 |
|
| 734 |
type sliceEncoder struct { |
| 735 |
arrayEnc encoderFunc |
| 736 |
} |
| 737 |
|
| 738 |
func (se *sliceEncoder) encode(e *encodeState, v reflect.Value, _ bool) { |
| 739 |
if v.IsNil() { |
| 740 |
e.WriteString("null") |
| 741 |
return |
| 742 |
} |
| 743 |
se.arrayEnc(e, v, false) |
| 744 |
} |
| 745 |
|
| 746 |
func newSliceEncoder(t reflect.Type) encoderFunc { |
| 747 |
|
| 748 |
if t.Elem().Kind() == reflect.Uint8 { |
| 749 |
return encodeByteSlice |
| 750 |
} |
| 751 |
enc := &sliceEncoder{newArrayEncoder(t)} |
| 752 |
return enc.encode |
| 753 |
} |
| 754 |
|
| 755 |
type arrayEncoder struct { |
| 756 |
elemEnc encoderFunc |
| 757 |
} |
| 758 |
|
| 759 |
func (ae *arrayEncoder) encode(e *encodeState, v reflect.Value, _ bool) { |
| 760 |
e.WriteByte('[') |
| 761 |
n := v.Len() |
| 762 |
for i := 0; i < n; i++ { |
| 763 |
if i > 0 { |
| 764 |
e.WriteByte(',') |
| 765 |
} |
| 766 |
ae.elemEnc(e, v.Index(i), false) |
| 767 |
} |
| 768 |
e.WriteByte(']') |
| 769 |
} |
| 770 |
|
| 771 |
func newArrayEncoder(t reflect.Type) encoderFunc { |
| 772 |
enc := &arrayEncoder{typeEncoder(t.Elem())} |
| 773 |
return enc.encode |
| 774 |
} |
| 775 |
|
| 776 |
type ptrEncoder struct { |
| 777 |
elemEnc encoderFunc |
| 778 |
} |
| 779 |
|
| 780 |
func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) { |
| 781 |
if v.IsNil() { |
| 782 |
e.WriteString("null") |
| 783 |
return |
| 784 |
} |
| 785 |
pe.elemEnc(e, v.Elem(), quoted) |
| 786 |
} |
| 787 |
|
| 788 |
func newPtrEncoder(t reflect.Type) encoderFunc { |
| 789 |
enc := &ptrEncoder{typeEncoder(t.Elem())} |
| 790 |
return enc.encode |
| 791 |
} |
| 792 |
|
| 793 |
type condAddrEncoder struct { |
| 794 |
canAddrEnc, elseEnc encoderFunc |
| 795 |
} |
| 796 |
|
| 797 |
func (ce *condAddrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) { |
| 798 |
if v.CanAddr() { |
| 799 |
ce.canAddrEnc(e, v, quoted) |
| 800 |
} else { |
| 801 |
ce.elseEnc(e, v, quoted) |
| 802 |
} |
| 803 |
} |
| 804 |
|
| 805 |
|
| 806 |
|
| 807 |
func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc { |
| 808 |
enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc} |
| 809 |
return enc.encode |
| 810 |
} |
| 811 |
|
| 812 |
func isValidTag(s string) bool { |
| 813 |
if s == "" { |
| 814 |
return false |
| 815 |
} |
| 816 |
for _, c := range s { |
| 817 |
switch { |
| 818 |
case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): |
| 819 |
|
| 820 |
|
| 821 |
|
| 822 |
default: |
| 823 |
if !unicode.IsLetter(c) && !unicode.IsDigit(c) { |
| 824 |
return false |
| 825 |
} |
| 826 |
} |
| 827 |
} |
| 828 |
return true |
| 829 |
} |
| 830 |
|
| 831 |
func fieldByIndex(v reflect.Value, index []int) reflect.Value { |
| 832 |
for _, i := range index { |
| 833 |
if v.Kind() == reflect.Ptr { |
| 834 |
if v.IsNil() { |
| 835 |
return reflect.Value{} |
| 836 |
} |
| 837 |
v = v.Elem() |
| 838 |
} |
| 839 |
v = v.Field(i) |
| 840 |
} |
| 841 |
return v |
| 842 |
} |
| 843 |
|
| 844 |
func typeByIndex(t reflect.Type, index []int) reflect.Type { |
| 845 |
for _, i := range index { |
| 846 |
if t.Kind() == reflect.Ptr { |
| 847 |
t = t.Elem() |
| 848 |
} |
| 849 |
t = t.Field(i).Type |
| 850 |
} |
| 851 |
return t |
| 852 |
} |
| 853 |
|
| 854 |
|
| 855 |
|
| 856 |
type stringValues []reflect.Value |
| 857 |
|
| 858 |
func (sv stringValues) Len() int { return len(sv) } |
| 859 |
func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } |
| 860 |
func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) } |
| 861 |
func (sv stringValues) get(i int) string { return sv[i].String() } |
| 862 |
|
| 863 |
func (e *encodeState) string(s string) int { |
| 864 |
return e.stringBytes([]byte(s)) |
| 865 |
} |
| 866 |
|
| 867 |
func (e *encodeState) stringBytes(s []byte) int { |
| 868 |
len0 := e.Len() |
| 869 |
e.WriteByte('"') |
| 870 |
start := 0 |
| 871 |
rejectLowSurrogateAt := -1 |
| 872 |
for i := 0; i < len(s); { |
| 873 |
if b := s[i]; b < utf8.RuneSelf { |
| 874 |
if 0x20 <= b && b != '\\' && b != '"' { |
| 875 |
i++ |
| 876 |
continue |
| 877 |
} |
| 878 |
if start < i { |
| 879 |
e.Write(s[start:i]) |
| 880 |
} |
| 881 |
e.WriteByte('\\') |
| 882 |
switch b { |
| 883 |
case '\\', '"': |
| 884 |
e.WriteByte(b) |
| 885 |
case '\n': |
| 886 |
e.WriteByte('n') |
| 887 |
case '\r': |
| 888 |
e.WriteByte('r') |
| 889 |
case '\t': |
| 890 |
e.WriteByte('t') |
| 891 |
case '\x08': |
| 892 |
e.WriteByte('b') |
| 893 |
case '\x0c': |
| 894 |
e.WriteByte('f') |
| 895 |
default: |
| 896 |
|
| 897 |
e.WriteString("u00") |
| 898 |
e.WriteByte(hex[b>>4]) |
| 899 |
e.WriteByte(hex[b&0xF]) |
| 900 |
} |
| 901 |
i++ |
| 902 |
start = i |
| 903 |
continue |
| 904 |
} |
| 905 |
c, size := utf8.DecodeRune(s[i:]) |
| 906 |
if c == utf8.RuneError && size == 1 { |
| 907 |
if start < i { |
| 908 |
e.Write(s[start:i]) |
| 909 |
} |
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
if s[i] == 0xED && i+2 < len(s) { |
| 915 |
c2 := s[i+1] |
| 916 |
c3 := s[i+2] |
| 917 |
if c2 >= 0xA0 && c2 <= 0xBF && (c3&0xC0) == 0x80 { |
| 918 |
|
| 919 |
if isHigh := (c2 & 0x10) == 0; isHigh || i != rejectLowSurrogateAt { |
| 920 |
if isHigh { |
| 921 |
rejectLowSurrogateAt = i + 3 |
| 922 |
} |
| 923 |
e.WriteString(`\u`) |
| 924 |
e.WriteByte(hex[0xD]) |
| 925 |
e.WriteByte(hex[(c2>>2)&0x0F]) |
| 926 |
e.WriteByte(hex[((c2<<2)&0x0C)|((c3>>4)&0x03)]) |
| 927 |
e.WriteByte(hex[c3&0x0F]) |
| 928 |
i += 3 |
| 929 |
start = i |
| 930 |
continue |
| 931 |
} |
| 932 |
} |
| 933 |
} |
| 934 |
|
| 935 |
e.error(&UnsupportedValueError{reflect.ValueOf(s), fmt.Sprintf("%q", string(s))}) |
| 936 |
} |
| 937 |
i += size |
| 938 |
} |
| 939 |
if start < len(s) { |
| 940 |
e.Write(s[start:]) |
| 941 |
} |
| 942 |
e.WriteByte('"') |
| 943 |
return e.Len() - len0 |
| 944 |
} |
| 945 |
|
| 946 |
|
| 947 |
type field struct { |
| 948 |
name string |
| 949 |
nameBytes []byte |
| 950 |
equalFold func(s, t []byte) bool |
| 951 |
|
| 952 |
tag bool |
| 953 |
index []int |
| 954 |
typ reflect.Type |
| 955 |
omitEmpty bool |
| 956 |
quoted bool |
| 957 |
} |
| 958 |
|
| 959 |
func fillField(f field) field { |
| 960 |
f.nameBytes = []byte(f.name) |
| 961 |
f.equalFold = foldFunc(f.nameBytes) |
| 962 |
return f |
| 963 |
} |
| 964 |
|
| 965 |
|
| 966 |
|
| 967 |
|
| 968 |
type byName []field |
| 969 |
|
| 970 |
func (x byName) Len() int { return len(x) } |
| 971 |
|
| 972 |
func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } |
| 973 |
|
| 974 |
func (x byName) Less(i, j int) bool { |
| 975 |
if x[i].name != x[j].name { |
| 976 |
return x[i].name < x[j].name |
| 977 |
} |
| 978 |
if len(x[i].index) != len(x[j].index) { |
| 979 |
return len(x[i].index) < len(x[j].index) |
| 980 |
} |
| 981 |
if x[i].tag != x[j].tag { |
| 982 |
return x[i].tag |
| 983 |
} |
| 984 |
return byIndex(x).Less(i, j) |
| 985 |
} |
| 986 |
|
| 987 |
|
| 988 |
type byIndex []field |
| 989 |
|
| 990 |
func (x byIndex) Len() int { return len(x) } |
| 991 |
|
| 992 |
func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } |
| 993 |
|
| 994 |
func (x byIndex) Less(i, j int) bool { |
| 995 |
for k, xik := range x[i].index { |
| 996 |
if k >= len(x[j].index) { |
| 997 |
return false |
| 998 |
} |
| 999 |
if xik != x[j].index[k] { |
| 1000 |
return xik < x[j].index[k] |
| 1001 |
} |
| 1002 |
} |
| 1003 |
return len(x[i].index) < len(x[j].index) |
| 1004 |
} |
| 1005 |
|
| 1006 |
|
| 1007 |
|
| 1008 |
|
| 1009 |
func typeFields(t reflect.Type) []field { |
| 1010 |
|
| 1011 |
current := []field{} |
| 1012 |
next := []field{{typ: t}} |
| 1013 |
|
| 1014 |
|
| 1015 |
count := map[reflect.Type]int{} |
| 1016 |
nextCount := map[reflect.Type]int{} |
| 1017 |
|
| 1018 |
|
| 1019 |
visited := map[reflect.Type]bool{} |
| 1020 |
|
| 1021 |
|
| 1022 |
var fields []field |
| 1023 |
|
| 1024 |
for len(next) > 0 { |
| 1025 |
current, next = next, current[:0] |
| 1026 |
count, nextCount = nextCount, map[reflect.Type]int{} |
| 1027 |
|
| 1028 |
for _, f := range current { |
| 1029 |
if visited[f.typ] { |
| 1030 |
continue |
| 1031 |
} |
| 1032 |
visited[f.typ] = true |
| 1033 |
|
| 1034 |
|
| 1035 |
for i := 0; i < f.typ.NumField(); i++ { |
| 1036 |
sf := f.typ.Field(i) |
| 1037 |
if sf.PkgPath != "" && !sf.Anonymous { |
| 1038 |
continue |
| 1039 |
} |
| 1040 |
tag := sf.Tag.Get("json") |
| 1041 |
if tag == "-" { |
| 1042 |
continue |
| 1043 |
} |
| 1044 |
name, opts := parseTag(tag) |
| 1045 |
if !isValidTag(name) { |
| 1046 |
name = "" |
| 1047 |
} |
| 1048 |
index := make([]int, len(f.index)+1) |
| 1049 |
copy(index, f.index) |
| 1050 |
index[len(f.index)] = i |
| 1051 |
|
| 1052 |
ft := sf.Type |
| 1053 |
if ft.Name() == "" && ft.Kind() == reflect.Ptr { |
| 1054 |
|
| 1055 |
ft = ft.Elem() |
| 1056 |
} |
| 1057 |
|
| 1058 |
|
| 1059 |
quoted := false |
| 1060 |
if opts.Contains("string") { |
| 1061 |
switch ft.Kind() { |
| 1062 |
case reflect.Bool, |
| 1063 |
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, |
| 1064 |
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, |
| 1065 |
reflect.Float32, reflect.Float64, |
| 1066 |
reflect.String: |
| 1067 |
quoted = true |
| 1068 |
} |
| 1069 |
} |
| 1070 |
|
| 1071 |
|
| 1072 |
if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { |
| 1073 |
tagged := name != "" |
| 1074 |
if name == "" { |
| 1075 |
name = sf.Name |
| 1076 |
} |
| 1077 |
fields = append(fields, fillField(field{ |
| 1078 |
name: name, |
| 1079 |
tag: tagged, |
| 1080 |
index: index, |
| 1081 |
typ: ft, |
| 1082 |
omitEmpty: opts.Contains("omitempty"), |
| 1083 |
quoted: quoted, |
| 1084 |
})) |
| 1085 |
if count[f.typ] > 1 { |
| 1086 |
|
| 1087 |
|
| 1088 |
|
| 1089 |
|
| 1090 |
fields = append(fields, fields[len(fields)-1]) |
| 1091 |
} |
| 1092 |
continue |
| 1093 |
} |
| 1094 |
|
| 1095 |
|
| 1096 |
nextCount[ft]++ |
| 1097 |
if nextCount[ft] == 1 { |
| 1098 |
next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) |
| 1099 |
} |
| 1100 |
} |
| 1101 |
} |
| 1102 |
} |
| 1103 |
|
| 1104 |
sort.Sort(byName(fields)) |
| 1105 |
|
| 1106 |
|
| 1107 |
|
| 1108 |
|
| 1109 |
|
| 1110 |
|
| 1111 |
|
| 1112 |
out := fields[:0] |
| 1113 |
for advance, i := 0, 0; i < len(fields); i += advance { |
| 1114 |
|
| 1115 |
|
| 1116 |
fi := fields[i] |
| 1117 |
name := fi.name |
| 1118 |
for advance = 1; i+advance < len(fields); advance++ { |
| 1119 |
fj := fields[i+advance] |
| 1120 |
if fj.name != name { |
| 1121 |
break |
| 1122 |
} |
| 1123 |
} |
| 1124 |
if advance == 1 { |
| 1125 |
out = append(out, fi) |
| 1126 |
continue |
| 1127 |
} |
| 1128 |
dominant, ok := dominantField(fields[i : i+advance]) |
| 1129 |
if ok { |
| 1130 |
out = append(out, dominant) |
| 1131 |
} |
| 1132 |
} |
| 1133 |
|
| 1134 |
return out |
| 1135 |
} |
| 1136 |
|
| 1137 |
|
| 1138 |
|
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
func dominantField(fields []field) (field, bool) { |
| 1144 |
|
| 1145 |
|
| 1146 |
|
| 1147 |
length := len(fields[0].index) |
| 1148 |
tagged := -1 |
| 1149 |
for i, f := range fields { |
| 1150 |
if len(f.index) > length { |
| 1151 |
fields = fields[:i] |
| 1152 |
break |
| 1153 |
} |
| 1154 |
if f.tag { |
| 1155 |
if tagged >= 0 { |
| 1156 |
|
| 1157 |
|
| 1158 |
return field{}, false |
| 1159 |
} |
| 1160 |
tagged = i |
| 1161 |
} |
| 1162 |
} |
| 1163 |
if tagged >= 0 { |
| 1164 |
return fields[tagged], true |
| 1165 |
} |
| 1166 |
|
| 1167 |
|
| 1168 |
|
| 1169 |
if len(fields) > 1 { |
| 1170 |
return field{}, false |
| 1171 |
} |
| 1172 |
return fields[0], true |
| 1173 |
} |
| 1174 |
|
| 1175 |
var fieldCache struct { |
| 1176 |
sync.RWMutex |
| 1177 |
m map[reflect.Type][]field |
| 1178 |
} |
| 1179 |
|
| 1180 |
|
| 1181 |
func cachedTypeFields(t reflect.Type) []field { |
| 1182 |
fieldCache.RLock() |
| 1183 |
f := fieldCache.m[t] |
| 1184 |
fieldCache.RUnlock() |
| 1185 |
if f != nil { |
| 1186 |
return f |
| 1187 |
} |
| 1188 |
|
| 1189 |
|
| 1190 |
|
| 1191 |
f = typeFields(t) |
| 1192 |
if f == nil { |
| 1193 |
f = []field{} |
| 1194 |
} |
| 1195 |
|
| 1196 |
fieldCache.Lock() |
| 1197 |
if fieldCache.m == nil { |
| 1198 |
fieldCache.m = map[reflect.Type][]field{} |
| 1199 |
} |
| 1200 |
fieldCache.m[t] = f |
| 1201 |
fieldCache.Unlock() |
| 1202 |
return f |
| 1203 |
} |