Removes trailing commas that appear immediately before `}` or `]` (with optional whitespace/newlines in between).
(input: &str)
| 1087 | /// Removes trailing commas that appear immediately before `}` or `]` (with |
| 1088 | /// optional whitespace/newlines in between). |
| 1089 | fn remove_trailing_commas(input: &str) -> String { |
| 1090 | // We scan for comma, optional whitespace, then `}` or `]`. |
| 1091 | let bytes = input.as_bytes(); |
| 1092 | let len = bytes.len(); |
| 1093 | let mut out = Vec::with_capacity(len); |
| 1094 | let mut i = 0; |
| 1095 | |
| 1096 | while i < len { |
| 1097 | if bytes[i] == b',' { |
| 1098 | // Peek ahead past whitespace. |
| 1099 | let mut j = i + 1; |
| 1100 | while j < len |
| 1101 | && (bytes[j] == b' ' || bytes[j] == b'\t' || bytes[j] == b'\n' || bytes[j] == b'\r') |
| 1102 | { |
| 1103 | j += 1; |
| 1104 | } |
| 1105 | if j < len && (bytes[j] == b'}' || bytes[j] == b']') { |
| 1106 | // Skip the comma; whitespace will be included normally. |
| 1107 | i += 1; |
| 1108 | continue; |
| 1109 | } |
| 1110 | } |
| 1111 | out.push(bytes[i]); |
| 1112 | i += 1; |
| 1113 | } |
| 1114 | |
| 1115 | String::from_utf8(out).unwrap_or_else(|_| input.to_string()) |
| 1116 | } |
| 1117 | |
| 1118 | /// Read a file and parse it as JSONC. Falls back to `json!({})` if the file |
| 1119 | /// is missing, unreadable, or unparseable. |
no test coverage detected