reader.go 1.7 KB

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