LEFT | RIGHT |
1 // Copyright 2011 The Go Authors. All rights reserved. | 1 // Copyright 2011 The Go Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style | 2 // Use of this source code is governed by a BSD-style |
3 // license that can be found in the LICENSE file. | 3 // license that can be found in the LICENSE file. |
4 | 4 |
5 package json | 5 package json |
6 | 6 |
7 import ( | 7 import ( |
8 "bytes" | 8 "bytes" |
9 "math" | 9 "math" |
10 "reflect" | 10 "reflect" |
11 "testing" | 11 "testing" |
| 12 "unicode" |
12 ) | 13 ) |
13 | 14 |
14 type Optionals struct { | 15 type Optionals struct { |
15 Sr string `json:"sr"` | 16 Sr string `json:"sr"` |
16 So string `json:"so,omitempty"` | 17 So string `json:"so,omitempty"` |
17 Sw string `json:"-"` | 18 Sw string `json:"-"` |
18 | 19 |
19 Ir int `json:"omitempty"` // actually named omitempty, not an option | 20 Ir int `json:"omitempty"` // actually named omitempty, not an option |
20 Io int `json:"io,omitempty"` | 21 Io int `json:"io,omitempty"` |
21 | 22 |
(...skipping 325 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
347 b, err := Marshal(v) | 348 b, err := Marshal(v) |
348 if err != nil { | 349 if err != nil { |
349 t.Fatal("Marshal:", err) | 350 t.Fatal("Marshal:", err) |
350 } | 351 } |
351 want := `{}` | 352 want := `{}` |
352 got := string(b) | 353 got := string(b) |
353 if got != want { | 354 if got != want { |
354 t.Fatalf("Marshal: got %s want %s", got, want) | 355 t.Fatalf("Marshal: got %s want %s", got, want) |
355 } | 356 } |
356 } | 357 } |
| 358 |
| 359 func TestStringBytes(t *testing.T) { |
| 360 // Test that encodeState.stringBytes and encodeState.string use the same
encoding. |
| 361 es := &encodeState{} |
| 362 var r []rune |
| 363 for i := '\u0000'; i <= unicode.MaxRune; i++ { |
| 364 r = append(r, i) |
| 365 } |
| 366 s := string(r) + "\xff\xff\xffhello" // some invalid UTF-8 too |
| 367 _, err := es.string(s) |
| 368 if err != nil { |
| 369 t.Fatal(err) |
| 370 } |
| 371 |
| 372 esBytes := &encodeState{} |
| 373 _, err = esBytes.stringBytes([]byte(s)) |
| 374 if err != nil { |
| 375 t.Fatal(err) |
| 376 } |
| 377 |
| 378 enc := es.Buffer.String() |
| 379 encBytes := esBytes.Buffer.String() |
| 380 if enc != encBytes { |
| 381 i := 0 |
| 382 for i < len(enc) && i < len(encBytes) && enc[i] == encBytes[i] { |
| 383 i++ |
| 384 } |
| 385 enc = enc[i:] |
| 386 encBytes = encBytes[i:] |
| 387 i = 0 |
| 388 for i < len(enc) && i < len(encBytes) && enc[len(enc)-i-1] == en
cBytes[len(encBytes)-i-1] { |
| 389 i++ |
| 390 } |
| 391 enc = enc[:len(enc)-i] |
| 392 encBytes = encBytes[:len(encBytes)-i] |
| 393 |
| 394 if len(enc) > 20 { |
| 395 enc = enc[:20] + "..." |
| 396 } |
| 397 if len(encBytes) > 20 { |
| 398 encBytes = encBytes[:20] + "..." |
| 399 } |
| 400 |
| 401 t.Errorf("encodings differ at %#q vs %#q", enc, encBytes) |
| 402 } |
| 403 } |
LEFT | RIGHT |