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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! Jsonxf is a JSON transformer, providing fast pretty-printing and
//! minimizing of JSON-encoded data.
//!
//! Jsonxf is built for speed, and does not attempt to perform any
//! input validation whatsoever.  Invalid input may produce strange
//! output.
//!
//! Installing this project via `cargo install` will also install the
//! `jsonxf` command-line tool.  Run `jsonxf -h` to see configuration
//! options.
//!
//! GitHub:
//! <a href="https://github.com/gamache/jsonxf" target="_blank">gamache/jsonxf</a>
//!

use std::io::prelude::*;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Error;


/// Pretty-prints a stream of JSON-encoded data.
///
/// Valid inputs produce valid outputs.  However, this function does
/// *not* perform JSON validation, and is not guaranteed to either
/// reject or accept invalid input.
///
/// The `indent` parameter sets the string used to indent pretty-printed
/// output; e.g., `"  "` or `"\t"`.
///
/// `pretty_print_stream` uses `std::io::BufReader` and `std::io:BufWriter`
/// to provide IO buffering; no external buffering should be necessary.
///
/// # Example
///
/// ```no_run
/// match jsonxf::pretty_print_stream(&mut std::io::stdin(), &mut std::io::stdout(), "\t") {
///   Ok(_) => { },
///   Err(e) => { panic!(e.to_string()) }
/// };
/// ```
///
pub fn pretty_print_stream(input: &mut Read, output: &mut Write, indent: &str) -> Result<(), Error> {
  /*
    Strategy: pass bytes from `input` to `output`, taking notice of when the
    current byte is:

    * Part of a JSON string (and if so, whether it follows a backslash)

    * One of `{`, `}`, `[`, or `]`, which affect indent level and usually
      emit whitespace

    * `,`, which does not affect indent level but always emits whitespace

    Empty JSON structures `{}` and `[]` are treated as special cases and
    rendered as such.
  */

  let reader = BufReader::new(input);
  let mut writer = BufWriter::new(output);

  let mut depth = 0;

  // string special cases
  let mut in_string = false;
  let mut in_backslash = false;

  // whitespace special cases, after { or [
  let mut whitespace_buffer = String::from("");
  let mut current_structure_is_empty = false;

  for byte in reader.bytes() {
    let b = byte?;
    let c = b as char;

    if in_string {
      writer.write(&[b])?;
      if in_backslash { in_backslash = false; }
      else if c == '"' { in_string = false; }
      else if c == '\\' { in_backslash = true; }
    }
    else {
      match c {
        ' ' | '\t' | '\n' | '\r' => {
          // skip whitespace
        },

        '{' | '[' => {
          writer.write(&[b])?;
          depth += 1;
          // don't write trailing whitespace immediately, in case this
          // is an empty structure
          current_structure_is_empty = true;
          whitespace_buffer = String::from("\n");
          for _ in 0..depth {
            whitespace_buffer.push_str(indent);
          }
        },

        '}' | ']' => {
          depth -= 1;
          if current_structure_is_empty {
            writer.write(&[b])?;
            current_structure_is_empty = false;
          }
          else {
            writer.write(&['\n' as u8])?;
            for _ in 0..depth {
              writer.write(indent.as_bytes())?;
            }
            writer.write(&[b])?;
          }
          if depth == 0 {
            writer.write(&['\n' as u8])?;
          }
        },

        ',' => {
          writer.write(&[b, '\n' as u8])?;
          for _ in 0..depth {
            writer.write(indent.as_bytes())?;
          }
        },

        ':' => {
          writer.write(&[':' as u8, ' ' as u8])?;
        },

        c => {
          if current_structure_is_empty {
            writer.write(whitespace_buffer.as_bytes())?;
            current_structure_is_empty = false;
          }
          if c == '"' {
            in_string = true;
          }
          writer.write(&[b])?;
        },
      }
    }
  }
  return Ok(());
}


/// Pretty-prints a string of JSON-encoded data.
///
/// Valid inputs produce valid outputs.  However, this function does
/// *not* perform JSON validation, and is not guaranteed to either
/// reject or accept invalid input.
///
/// The `indent` parameter sets the string used to indent pretty-printed
/// output; e.g., `"  "` or `"\t"`.
///
/// # Examples:
///
/// ```
/// assert_eq!(
///   jsonxf::pretty_print("{\"a\":1,\"b\":2}", "  ").unwrap(),
///   "{\n  \"a\": 1,\n  \"b\": 2\n}\n"
/// );
/// assert_eq!(
///   jsonxf::pretty_print("{\"empty\":{},\n\n\n\n\n\"one\":[1]}", "\t").unwrap(),
///   "{\n\t\"empty\": {},\n\t\"one\": [\n\t\t1\n\t]\n}\n"
/// );
/// ```
///
pub fn pretty_print(json_string: &str, indent: &str) -> Result<String, String> {
  let mut input = json_string.as_bytes();
  let mut output: Vec<u8> = vec![];
  match pretty_print_stream(&mut input, &mut output, indent) {
    Ok(_) => {},
    Err(f) => { return Err(f.to_string()); },
  };
  let output_string = match String::from_utf8(output) {
    Ok(s) => { s },
    Err(f) => { return Err(f.to_string()); },
  };
  return Ok(output_string);
}



/// Minimizes a stream of JSON-encoded data.
///
/// Valid inputs produce valid outputs.  However, this function does
/// *not* perform JSON validation, and is not guaranteed to either
/// reject or accept invalid input.
///
/// `minimize_stream` uses `std::io::BufReader` and `std::io:BufWriter`
/// to provide IO buffering; no external buffering should be necessary.
///
/// # Example
///
/// ```no_run
/// match jsonxf::minimize_stream(&mut std::io::stdin(), &mut std::io::stdout()) {
///   Ok(_) => { },
///   Err(e) => { panic!(e.to_string()) }
/// };
/// ```
///
pub fn minimize_stream(input: &mut Read, output: &mut Write) -> Result<(), Error> {
  // Strategy is similar to `pretty_print`, with much less whitespace mgmt.
  // Care is taken not to emit a newline at the end of the stream.

  let reader = BufReader::new(input);
  let mut writer = BufWriter::new(output);

  let mut in_string = false;
  let mut in_backslash = false;
  let mut depth = 0;
  let mut print_newline = false;

  for byte in reader.bytes() {
    let b = byte?;
    let c = b as char;

    if in_string {
      writer.write(&[b])?;
      if in_backslash { in_backslash = false; }
      else if c == '"' { in_string = false; }
      else if c == '\\' { in_backslash = true; }
    }
    else {
      match c {
        ' ' | '\t' | '\n' | '\r' => {
          // skip whitespace
        },

        '{' | '[' => {
          if depth == 0 {
            if print_newline {
              writer.write(&['\n' as u8])?;
            }
            print_newline = true;
          }
          writer.write(&[b])?;
          depth += 1;
        },

        '}' | ']' => {
          writer.write(&[b])?;
          depth -= 1;
        },

        c => {
          if c == '"' {
            in_string = true;
          }
          writer.write(&[b])?;
        },
      }
    }
  }
  return Ok(());
}


/// Minimizes a string of JSON-encoded data.
///
/// Valid inputs produce valid outputs.  However, this function does
/// *not* perform JSON validation, and is not guaranteed to either
/// reject or accept invalid input.
///
/// # Examples:
///
/// ```
/// assert_eq!(
///   jsonxf::minimize("{ \"a\": \"b\", \"c\": 0 } ").unwrap(),
///   "{\"a\":\"b\",\"c\":0}"
/// );
/// assert_eq!(
///   jsonxf::minimize("\r\n\tnull\r\n").unwrap(),
///   "null"
/// );
/// ```
///
pub fn minimize(json_string: &str) -> Result<String, String> {
  let mut input = json_string.as_bytes();
  let mut output: Vec<u8> = vec![];
  match minimize_stream(&mut input, &mut output) {
    Ok(_) => {},
    Err(f) => { return Err(f.to_string()); },
  };
  let output_string = match String::from_utf8(output) {
    Ok(s) => { s },
    Err(f) => { return Err(f.to_string()); },
  };
  return Ok(output_string);
}