reader.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package json
  2. import (
  3. "io"
  4. )
  5. // State is the internal state of parser.
  6. type State byte
  7. const (
  8. StateContent State = iota
  9. StateEscape
  10. StateDoubleQuote
  11. StateDoubleQuoteEscape
  12. StateSingleQuote
  13. StateSingleQuoteEscape
  14. StateComment
  15. StateSlash
  16. StateMultilineComment
  17. StateMultilineCommentStar
  18. )
  19. type Reader struct {
  20. io.Reader
  21. state State
  22. }
  23. func (v *Reader) Read(b []byte) (int, error) {
  24. n, err := v.Reader.Read(b)
  25. if err != nil {
  26. return n, err
  27. }
  28. p := b[:0]
  29. for _, x := range b[:n] {
  30. switch v.state {
  31. case StateContent:
  32. switch x {
  33. case '"':
  34. v.state = StateDoubleQuote
  35. p = append(p, x)
  36. case '\'':
  37. v.state = StateSingleQuote
  38. p = append(p, x)
  39. case '\\':
  40. v.state = StateEscape
  41. case '#':
  42. v.state = StateComment
  43. case '/':
  44. v.state = StateSlash
  45. default:
  46. p = append(p, x)
  47. }
  48. case StateEscape:
  49. p = append(p, '\\', x)
  50. v.state = StateContent
  51. case StateDoubleQuote:
  52. switch x {
  53. case '"':
  54. v.state = StateContent
  55. p = append(p, x)
  56. case '\\':
  57. v.state = StateDoubleQuoteEscape
  58. default:
  59. p = append(p, x)
  60. }
  61. case StateDoubleQuoteEscape:
  62. p = append(p, '\\', x)
  63. v.state = StateDoubleQuote
  64. case StateSingleQuote:
  65. switch x {
  66. case '\'':
  67. v.state = StateContent
  68. p = append(p, x)
  69. case '\\':
  70. v.state = StateSingleQuoteEscape
  71. default:
  72. p = append(p, x)
  73. }
  74. case StateSingleQuoteEscape:
  75. p = append(p, '\\', x)
  76. v.state = StateSingleQuote
  77. case StateComment:
  78. if x == '\n' {
  79. v.state = StateContent
  80. }
  81. case StateSlash:
  82. switch x {
  83. case '/':
  84. v.state = StateComment
  85. case '*':
  86. v.state = StateMultilineComment
  87. default:
  88. p = append(p, '/', x)
  89. }
  90. case StateMultilineComment:
  91. if x == '*' {
  92. v.state = StateMultilineCommentStar
  93. }
  94. case StateMultilineCommentStar:
  95. switch x {
  96. case '/':
  97. v.state = StateContent
  98. case '*':
  99. // Stay
  100. default:
  101. v.state = StateMultilineComment
  102. }
  103. default:
  104. panic("Unknown state.")
  105. }
  106. }
  107. return len(p), nil
  108. }