Created
November 4, 2019 20:35
-
-
Save thomcc/a860b2c10f30bb7e36e8897f2b5766f5 to your computer and use it in GitHub Desktop.
strip-json-comments rust (untested, kept here so i can find it later)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn strip_json_comments(s: &str) -> String { | |
let mut result = String::with_capacity(s.len()); | |
let mut iter = s.chars(); | |
while let Some(c) = iter.next() { | |
if c == '"' { | |
// It's a string, skip to end without touching any comments inside. | |
result.push(c); | |
while let Some(c) = iter.next() { | |
result.push(c); | |
// Skip escape sequence. | |
if c == '\\' { | |
result.extend(iter.next()); | |
continue; | |
} | |
if c == '"' { | |
break; | |
} | |
} | |
} else if c == '/' { | |
// A comment. Skip past it, and replace it's non-whitespace | |
// characters with spaces. This preserves line/column numbering | |
// in the case that serde complains about something. | |
#[inline] | |
fn as_whitespace(c: char) -> char { | |
if c.is_whitespace() { | |
c | |
} else { | |
' ' | |
} | |
} | |
match iter.next() { | |
Some('/') => { | |
result.push(' '); // first '/' | |
result.push(' '); // second '/' | |
while let Some(c) = iter.next() { | |
result.push(as_whitespace(c)); | |
if c == '\n' { | |
break; | |
} | |
} | |
} | |
Some('*') => { | |
// Multiline comment. Don't allow nesting, since it's easier not | |
// to and e.g. JS doesn't anyway. | |
result.push(' '); // replace '/' | |
result.push(' '); // replace '*' | |
while let Some(c) = iter.next() { | |
result.push(as_whitespace(c)); | |
if c == '*' { | |
let c2 = iter.next(); | |
result.extend(c2.map(as_whitespace)); | |
if let Some('/') = c2 { | |
result.push(' '); | |
break; | |
} | |
} | |
} | |
} | |
Some(c2) => { | |
// Regular charac | |
result.extend([c, c2].iter().copied()); | |
} | |
None => {} | |
} | |
} else { | |
result.push(c); | |
} | |
} | |
result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment