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
//! simple_json_formatter は JSON を整形するライブラリです。
//!
//! 依存はなく、std だけで書いています。
//! JSON を読んで値の木を作り、それを Options に従って書き出します。
//! 数値は元の書き方のまま持ち、オブジェクトのキーは出てきた順に並べます。
mod format;
mod parse;
mod value;
use std::fmt;
/// 整形のしかた。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Options {
pub indent: Indent,
/// この桁数に収まる配列とオブジェクトは 1 行にまとめる。0 ならまとめない
pub max_width: usize,
/// オブジェクトのキーを辞書順に並べ替える。入れ子の中まで効く
pub sort_keys: bool,
/// ASCII 以外の文字を \uXXXX にする。BMP の外はサロゲートペアにする
pub ensure_ascii: bool,
}
impl Default for Options {
fn default() -> Self {
Options {
indent: Indent::Spaces(2),
max_width: 0,
sort_keys: false,
ensure_ascii: false,
}
}
}
/// インデントの種類。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Indent {
/// 空白 n 個。n が大きいほど出力も大きくなるので、信用できない値をそのまま渡さないこと
Spaces(usize),
/// タブ 1 個。max_width の計算では 4 桁として数える
Tab,
/// 改行もインデントもしない
Compact,
}
/// 読めなかった理由と、その位置。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
/// 1 から数える行
pub line: usize,
/// 1 から数える列。バイトではなく文字の数で数える
pub column: usize,
pub message: String,
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{} 行 {} 列: {}", self.line, self.column, self.message)
}
}
impl std::error::Error for Error {}
/// JSON を整形する。
///
/// 先頭に BOM があれば取り除く。末尾に改行は付けない。
pub fn format(source: &str, options: &Options) -> Result<String, Error> {
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
let value = parse::parse(source)?;
Ok(format::write(value, options, source.len()))
}