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
pub mod access;
pub mod formatter;
use serde::ser;
use std::{fs::File, io, path::Path};
use crate::Value;
use self::access::jsonc::JsoncSerializer;
/// Serialize struct `S` as minified JSON with comments text.
/// If you want to serialize as pretty formatted JSONC text, use [`to_string_pretty`] instead.
///
/// # Examples
/// ```
/// use serde::Serialize;
/// #[derive(Serialize)]
/// struct Country {
/// name: String,
/// code: u32,
/// regions: Vec<String>,
/// }
/// let japan = Country {
/// name: "Japan".to_string(),
/// code: 81,
/// regions: vec!["Hokkaido".to_string(), "Kanto".to_string(), "Kyushu-Okinawa".to_string()],
/// };
/// let jp = json_with_comments::to_string(japan).unwrap();
/// assert_eq!(jp, r#"{"name":"Japan","code":81,"regions":["Hokkaido","Kanto","Kyushu-Okinawa"]}"#);
/// ```
pub fn to_string<S>(value: S) -> crate::Result<String>
where
S: ser::Serialize,
{
let mut write = Vec::new();
to_write(value, &mut write, formatter::minify::MinifyFormatter)?;
Ok(unsafe { String::from_utf8_unchecked(write) }) // TODO maybe safe
}
/// Serialize struct `S` as pretty formatted JSON with comments text.
/// If you want to serialize as minified JSONC text, use [`to_string`] instead.
///
/// # Examples
/// ```
/// use serde::Serialize;
/// #[derive(Serialize)]
/// struct Country<'a> {
/// name: &'a str,
/// code: u32,
/// regions: Vec<&'a str>,
/// }
/// let japan = Country {
/// name: "Japan",
/// code: 81,
/// regions: vec!["Hokkaido", "Kanto", "Kyushu-Okinawa"],
/// };
/// let jp = json_with_comments::to_string_pretty(japan).unwrap();
/// let pretty = r#"{
/// "name": "Japan",
/// "code": 81,
/// "regions": [
/// "Hokkaido",
/// "Kanto",
/// "Kyushu-Okinawa",
/// ],
/// }"#;
/// assert_eq!(jp, pretty);
/// ```
pub fn to_string_pretty<S>(value: S) -> crate::Result<String>
where
S: ser::Serialize,
{
let mut write = Vec::new();
to_write(value, &mut write, formatter::pretty::PrettyFormatter::new())?;
Ok(unsafe { String::from_utf8_unchecked(write) }) // TODO maybe safe
}
/// Serialize struct `S` as a minified JSON with comments text of the given path.
/// If you want to serialize as pretty formatted JSONC text, use [`to_path_pretty`] instead.
///
/// # Examples
/// ```
/// use serde::Serialize;
/// #[derive(Serialize)]
/// struct Product {
/// name: String,
/// price: u32,
/// }
///
/// // {"name":"candy","price":100}
/// let path = std::path::Path::new("tests/data/product_minify.jsonc");
/// let before = std::fs::read_to_string(path).unwrap();
///
/// if path.exists() {
/// std::fs::remove_file(path).unwrap();
/// }
///
/// let product = Product {
/// name: "candy".to_string(),
/// price: 100,
/// };
/// json_with_comments::to_path(product, path).unwrap();
/// let after = std::fs::read_to_string(path).unwrap();
/// assert_eq!(before, after);
/// ```
pub fn to_path<S>(value: S, path: &Path) -> crate::Result<()>
where
S: ser::Serialize,
{
let mut file = File::create(path)?;
to_file(value, &mut file)
}
/// Serialize struct `S` as a pretty formatted JSON with comments text of the given path.
/// If you want to serialize as minified JSONC text, use [`to_path`] instead.
///
/// # Examples
/// ```
/// use serde::Serialize;
/// #[derive(Serialize)]
/// struct Product {
/// name: String,
/// price: u32,
/// }
///
/// // {
/// // "name": "candy",
/// // "price": 100,
/// // }
/// let path = std::path::Path::new("tests/data/product_pretty.jsonc");
/// let before = std::fs::read_to_string(path).unwrap();
///
/// if path.exists() {
/// std::fs::remove_file(path).unwrap();
/// }
///
/// let product = Product {
/// name: "candy".to_string(),
/// price: 100,
/// };
/// json_with_comments::to_path_pretty(product, path).unwrap();
/// let after = std::fs::read_to_string(path).unwrap();
/// assert_eq!(before, after);
/// ```
pub fn to_path_pretty<S>(value: S, path: &Path) -> crate::Result<()>
where
S: ser::Serialize,
{
let mut file = File::create(path)?;
to_file_pretty(value, &mut file)
}
/// Serialize struct `S` as a minified JSON with comments text of the given file.
/// If you want to serialize as pretty formatted JSONC text, use [`to_file_pretty`] instead.
///
/// # Examples
/// ```
/// use serde::Serialize;
/// #[derive(Serialize)]
/// struct Product {
/// name: String,
/// price: u32,
/// }
/// let path = std::path::Path::new("tests/data/product_minify.jsonc");
/// if path.exists() {
/// std::fs::remove_file(path).unwrap();
/// }
/// let mut file = std::fs::File::create(path).unwrap();
/// let product = Product { name: "candy".to_string(), price: 100 };
/// json_with_comments::to_file(product, &mut file).unwrap();
/// assert_eq!(std::fs::read_to_string(path).unwrap(), r#"{"name":"candy","price":100}"#);
/// ```
pub fn to_file<S>(value: S, file: &mut File) -> crate::Result<()>
where
S: ser::Serialize,
{
to_write(value, file, formatter::minify::MinifyFormatter)
}
/// Serialize struct `S` as a pretty formatted JSON with comments text of the given file.
/// If you want to serialize as minified JSONC text, use [`to_file`] instead.
///
/// # Examples
/// ```
/// use serde::Serialize;
/// #[derive(Serialize)]
/// struct Product {
/// name: String,
/// price: u32,
/// }
/// let path = std::path::Path::new("tests/data/product_pretty.jsonc");
/// if path.exists() {
/// std::fs::remove_file(path).unwrap();
/// }
/// let mut file = std::fs::File::create(path).unwrap();
/// let product = Product { name: "candy".to_string(), price: 100 };
/// json_with_comments::to_file_pretty(product, &mut file).unwrap();
/// let pretty = r#"{
/// "name": "candy",
/// "price": 100,
/// }"#;
/// assert_eq!(std::fs::read_to_string(path).unwrap(), pretty);
/// ```
pub fn to_file_pretty(value: impl ser::Serialize, file: &mut File) -> crate::Result<()> {
to_write(value, file, formatter::pretty::PrettyFormatter::new())
}
/// Serialize struct `S` as a JSON with comments text of the given writer.
///
/// # Examples
/// ```
/// use serde::Serialize;
/// #[derive(Serialize)]
/// struct Product {
/// name: String,
/// price: u32,
/// }
/// let mut write = Vec::new();
/// let product = Product { name: "candy".to_string(), price: 100 };
/// json_with_comments::to_write(product, &mut write, json_with_comments::ser::formatter::minify::MinifyFormatter).unwrap();
/// assert_eq!(String::from_utf8(write).unwrap(), r#"{"name":"candy","price":100}"#);
/// ```
pub fn to_write<W, F, S>(value: S, write: W, formatter: F) -> crate::Result<()>
where
W: io::Write,
F: formatter::JsoncFormatter,
S: ser::Serialize,
{
let mut ser = JsoncSerializer::new(write, formatter);
value.serialize(&mut ser)
}
/// Serialize `T` to [`crate::value::JsoncValue`]
///
/// # Examples
/// ```
/// use serde::Serialize;
/// #[derive(Serialize)]
/// struct Product {
/// name: String,
/// price: u32,
/// }
/// let target = Product { name: "candy".to_string(), price: 100 };
/// let product = json_with_comments::to_value(target).unwrap();
/// assert_eq!(product, json_with_comments::jsonc!({ "name": "candy", "price": 100 }));
/// ```
pub fn to_value<T>(value: T) -> crate::Result<Value>
where
T: ser::Serialize,
{
Value::from_serialize(value)
}