1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 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
 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
use std::io::{self, Read, Result, ErrorKind};
use std::fmt;

#[derive(Eq, PartialEq, Copy, Clone, Debug)]
enum State {
    Top,
    InString,
    StringEscape,
    InComment,
    InBlockComment,
    MaybeCommentEnd,
    InLineComment,
}

use State::*;

/// A [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html)
/// that strips out comments from JSON-like text. See [`strip_comments`](fn.strip_comments.html).
pub struct StripComments<T: Read> {
    inner: T,
    state: State,
}

/// Transform a `input` so that it changes all comments to spaces so that a downstream json parser
/// (such as json-serde) doesn't choke on them.
///
/// The supported comments are:
///   - C style block comments (`/* ... */`)
///   - C style line comments (`// ...`)
///   - Shell style line comments (`# ...`)
///
/// ## Example
/// ```
/// use json_comments::strip_comments;
/// use std::io::Read;
///
/// let input = r#"{
/// // c line comment
/// "a": "comment in string /* a */",
/// ## shell line comment
/// } /** end */"#;
///
/// let mut stripped = String::new();
/// strip_comments(input.as_bytes()).read_to_string(&mut stripped).unwrap();
///
/// assert_eq!(stripped, "{
///                  \n\"a\": \"comment in string /* a */\",
///                     \n}           ");
///
/// ```
pub fn strip_comments<T: Read>(input: T) -> StripComments<T> {
    StripComments {
        inner: input,
        state: State::Top,
    }
}

/// Errors specific to removing comments.
///
/// Note that due to the signature of [`Read::read`], this will actually be wrapped inside a
/// [`std::io::Error`].
#[derive(Debug, Eq, PartialEq)]
pub enum Error {
    /// Error if the stream ends with a string that was never terminated.
    IncompleteString,
    /// Error if the stream ends with a block comment that was never terminated.
    IncompleteComment,
    /// Error if there is a forward slash at the top level that isn't immediately followed by a "*"
    /// or "/" to start a comment.
    UnexpectedForwardSlash,
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Invalid state for json with comments ({:?})", self)
    }
}

impl std::error::Error for Error {
}

impl<T> Read for StripComments<T> where T: Read{
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        let count = self.inner.read(buf)?;
        if count > 0 {
            let mut iter = buf[..count].iter_mut();
            while let Some(c) = iter.next() {
                self.state = match self.state {
                    Top => top(c),
                    InString => in_string(*c),
                    StringEscape => InString,
                    InComment => in_comment(c)?,
                    InBlockComment => in_block_comment(c),
                    MaybeCommentEnd => maybe_comment_end(c),
                    InLineComment => in_line_comment(c),
                }
            }
        } else {
            match self.state {
                InString | StringEscape => return Err(data_error(Error::IncompleteString)),
                InComment | InBlockComment | MaybeCommentEnd => return Err(data_error(Error::IncompleteComment)),
                _ => {}
            }
        }
        Ok(count)
    }
}

fn top(c: &mut u8) -> State {
    match *c {
        b'"' => InString,
        b'/' => {
            *c = b' ';
            InComment
        },
        b'#' => {
            *c = b' ';
            InLineComment
        }
        _ => Top,
    }
}

fn in_string(c: u8) -> State {
    match c {
        b'"' => Top,
        b'\\' => StringEscape,
        _ => InString
    }
}

fn in_comment(c: &mut u8) -> Result<State> {
    let new_state = match c {
        b'*' => InBlockComment,
        b'/' => InLineComment,
        _ => return Err(data_error(Error::UnexpectedForwardSlash)),
   };
    *c = b' ';
    Ok(new_state)
}

fn in_block_comment(c: &mut u8) -> State {
    let old = *c;
    *c = b' ';
    if old == b'*' {
        MaybeCommentEnd
    } else {
        InBlockComment
    }
}

fn maybe_comment_end(c: &mut u8) -> State {
    if *c == b'/' {
        *c = b' ';
        Top
    } else {
        InBlockComment
    }
}

fn in_line_comment(c: &mut u8) -> State {
    if *c == b'\n' {
        Top
    } else {
        *c = b' ';
        InLineComment
    }
}



fn data_error(err: Error) -> io::Error {
    io::Error::new(ErrorKind::InvalidData, err)
}

#[cfg(test)]
mod tests {
     use super::strip_comments;
     use std::io::{Read, ErrorKind};

     fn strip_string(input: &str) -> String {
         let mut out = String::new();
         let count = strip_comments(input.as_bytes()).read_to_string(&mut out).unwrap();
         assert_eq!(count, input.len());
         out
     }

    #[test]
    fn block_comments() {
        let json = r#"{/* Comment */"hi": /** abc */ "bye"}"#;
        let stripped = strip_string(json);
        assert_eq!(stripped, r#"{             "hi":            "bye"}"#);
    }

    #[test]
    fn line_comments() {
        let json = r#"{
            // line comment
            "a": 4,
            # another
        }"#;

        let expected = "{
                           \n            \"a\": 4,
                     \n        }";

        assert_eq!(strip_string(json), expected);
    }

    #[test]
    fn incomplete_string() {
        let json = r#""foo"#;
        let mut stripped = String::new();

        let err = strip_comments(json.as_bytes()).read_to_string(&mut stripped).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);
    }

    #[test]
    fn incomplete_comment() {
        let json = r#"/* foo "#;
        let mut stripped = String::new();

        let err = strip_comments(json.as_bytes()).read_to_string(&mut stripped).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);
    }

    #[test]
    fn incomplete_comment2() {
        let json = r#"/* foo *"#;
        let mut stripped = String::new();

        let err = strip_comments(json.as_bytes()).read_to_string(&mut stripped).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData);
    }
}