lexer_string_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package jsoniter
  2. import (
  3. "testing"
  4. "bytes"
  5. "encoding/json"
  6. )
  7. func Test_string_empty(t *testing.T) {
  8. lexer := NewLexer(bytes.NewBufferString(`""`), 4096)
  9. val, err := lexer.LexString()
  10. if err != nil {
  11. t.Fatal(err)
  12. }
  13. if val != "" {
  14. t.Fatal(val)
  15. }
  16. }
  17. func Test_string_hello(t *testing.T) {
  18. lexer := NewLexer(bytes.NewBufferString(`"hello"`), 4096)
  19. val, err := lexer.LexString()
  20. if err != nil {
  21. t.Fatal(err)
  22. }
  23. if val != "hello" {
  24. t.Fatal(val)
  25. }
  26. }
  27. func Test_string_escape_quote(t *testing.T) {
  28. lexer := NewLexer(bytes.NewBufferString(`"hel\"lo"`), 4096)
  29. val, err := lexer.LexString()
  30. if err != nil {
  31. t.Fatal(err)
  32. }
  33. if val != `hel"lo` {
  34. t.Fatal(val)
  35. }
  36. }
  37. func Test_string_escape_newline(t *testing.T) {
  38. lexer := NewLexer(bytes.NewBufferString(`"hel\nlo"`), 4096)
  39. val, err := lexer.LexString()
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. if val != "hel\nlo" {
  44. t.Fatal(val)
  45. }
  46. }
  47. func Test_string_escape_unicode(t *testing.T) {
  48. lexer := NewLexer(bytes.NewBufferString(`"\u4e2d\u6587"`), 4096)
  49. val, err := lexer.LexString()
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. if val != "中文" {
  54. t.Fatal(val)
  55. }
  56. }
  57. func Test_string_escape_unicode_with_surrogate(t *testing.T) {
  58. lexer := NewLexer(bytes.NewBufferString(`"\ud83d\udc4a"`), 4096)
  59. val, err := lexer.LexString()
  60. if err != nil {
  61. t.Fatal(err)
  62. }
  63. if val != "\xf0\x9f\x91\x8a" {
  64. t.Fatal(val)
  65. }
  66. }
  67. func Benchmark_jsoniter_unicode(b *testing.B) {
  68. for n := 0; n < b.N; n++ {
  69. lexer := NewLexerWithArray([]byte(`"\ud83d\udc4a"`))
  70. lexer.LexString()
  71. }
  72. }
  73. func Benchmark_jsoniter_ascii(b *testing.B) {
  74. for n := 0; n < b.N; n++ {
  75. lexer := NewLexerWithArray([]byte(`"hello"`))
  76. lexer.LexString()
  77. }
  78. }
  79. func Benchmark_json_unicode(b *testing.B) {
  80. for n := 0; n < b.N; n++ {
  81. result := ""
  82. json.Unmarshal([]byte(`"\ud83d\udc4a"`), &result)
  83. }
  84. }
  85. func Benchmark_json_ascii(b *testing.B) {
  86. for n := 0; n < b.N; n++ {
  87. result := ""
  88. json.Unmarshal([]byte(`"hello"`), &result)
  89. }
  90. }