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
use ;
/// JSON serialization and deserialization utilities.
///
/// This module provides comprehensive JSON handling with both compact and
/// pretty-printed output, validation, and efficient parsing. Built on `serde_json`
/// for maximum performance and compatibility.
///
/// ## Features
///
/// - **Compact Serialization**: Minified JSON for network efficiency
/// - **Pretty Printing**: Human-readable formatted JSON for debugging
/// - **Type Validation**: Runtime JSON structure validation
/// - **Flexible Parsing**: Support for owned and borrowed data
/// - **Error Handling**: Detailed error reporting with context
/// - **Performance Optimized**: Zero-copy operations where possible
///
/// ## Examples
///
/// ### Basic Serialization
/// ```rust
/// use trash_utilities::serde::{serialize_to_json, deserialize_from_json};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, Debug, PartialEq)]
/// struct User {
/// id: u32,
/// name: String,
/// email: String,
/// }
///
/// let user = User {
/// id: 123,
/// name: "Alice Johnson".to_string(),
/// email: "alice@example.com".to_string(),
/// };
///
/// // Serialize to compact JSON
/// let json = serialize_to_json(&user).unwrap();
/// assert_eq!(json, r#"{"id":123,"name":"Alice Johnson","email":"alice@example.com"}"#);
///
/// // Deserialize back
/// let recovered: User = deserialize_from_json(&json).unwrap();
/// assert_eq!(user, recovered);
/// ```
///
/// ### Pretty Printing for Configuration
/// ```rust
/// use trash_utilities::serde::pretty_json;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Config {
/// database_url: String,
/// max_connections: u32,
/// features: Vec<String>,
/// }
///
/// let config = Config {
/// database_url: "postgres://localhost/mydb".to_string(),
/// max_connections: 100,
/// features: vec!["ssl".to_string(), "compression".to_string()],
/// };
///
/// let pretty = pretty_json(&config).unwrap();
/// println!("{}", pretty);
/// // Output:
/// // {
/// // "database_url": "postgres://localhost/mydb",
/// // "max_connections": 100,
/// // "features": [
/// // "ssl",
/// // "compression"
/// // ]
/// // }
/// ```
///
/// ### JSON Validation
/// ```rust
/// use trash_utilities::serde::validate_json;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, Debug)]
/// struct ApiResponse {
/// status: String,
/// data: Vec<String>,
/// }
///
/// let json = r#"{
/// "status": "success",
/// "data": ["item1", "item2"]
/// }"#;
///
/// // Validate and parse
/// let response: ApiResponse = validate_json(json).unwrap();
/// assert_eq!(response.status, "success");
/// assert_eq!(response.data.len(), 2);
/// ```
///
/// ### Error Handling
/// ```rust
/// use trash_utilities::serde::deserialize_from_json;
///
/// #[derive(serde::Deserialize, Debug)]
/// struct Person { name: String, age: u32 }
///
/// // Invalid JSON
/// let result: Result<Person, _> = deserialize_from_json(r#"{"name": "Alice", "age": "thirty"}"#);
/// assert!(result.is_err()); // Age should be a number
///
/// // Missing required field
/// let result2: Result<Person, _> = deserialize_from_json(r#"{"name": "Bob"}"#);
/// assert!(result2.is_err()); // Missing age field
/// ```
/// Serialize a struct to a compact JSON string.
///
/// This function converts any serializable type into a minified JSON string.
/// It's suitable for network transmission or storage where size matters.
///
/// # Type Parameters
/// - `T`: The type to serialize, must implement `Serialize`.
///
/// # Parameters
/// - `value`: The value to serialize.
///
/// # Returns
/// - `Ok(String)` containing the JSON representation.
/// - `Err(serde_json::Error)` if serialization fails.
///
/// # Errors
/// Returns `serde_json::Error` if the value cannot be serialized to JSON.
///
/// # Examples
/// ```rust
/// use trash_analyzer::serde::serialize_to_json;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Person { name: String, age: u32 }
///
/// let person = Person { name: "Alice".to_string(), age: 30 };
/// let json = serialize_to_json(&person).unwrap();
/// assert_eq!(json, r#"{"name":"Alice","age":30}"#);
/// ```
/// Deserialize a JSON string into a struct.
///
/// This function parses a JSON string into any deserializable type.
/// The lifetime parameter ensures the returned value doesn't outlive the input string.
///
/// # Type Parameters
/// - `T`: The type to deserialize into, must implement `Deserialize<'a>`.
///
/// # Parameters
/// - `json`: The JSON string to parse.
///
/// # Returns
/// - `Ok(T)` containing the deserialized value.
/// - `Err(serde_json::Error)` if deserialization fails.
///
/// # Errors
/// Returns a `serde_json::Error` if the JSON is malformed or doesn't match the expected type.
///
/// # Examples
/// ```rust
/// use trash_analyzer::serde::deserialize_from_json;
/// use serde::Deserialize;
///
/// #[derive(Deserialize, Debug, PartialEq)]
/// struct Person { name: String, age: u32 }
///
/// let json = r#"{"name":"Alice","age":30}"#;
/// let person: Person = deserialize_from_json(json).unwrap();
/// assert_eq!(person, Person { name: "Alice".to_string(), age: 30 });
/// ```
/// Parse a JSON value from a string.
///
/// This is a convenience function for deserializing JSON.
///
/// # Type Parameters
/// - `T`: The type to deserialize into.
///
/// # Parameters
/// - `s`: The JSON string.
///
/// # Returns
/// - `Ok(T)` on success.
/// - `Err(serde_json::Error)` on failure.
///
/// # Errors
/// Returns a `serde_json::Error` if the JSON is malformed or doesn't match the expected type.
/// Pretty-print a struct as formatted JSON.
///
/// This function produces human-readable JSON with proper indentation and spacing.
/// Useful for configuration files, debugging, or user-facing output.
///
/// # Type Parameters
/// - `T`: The type to serialize, must implement `Serialize`.
///
/// # Parameters
/// - `value`: The value to serialize.
///
/// # Returns
/// - `Ok(String)` containing the pretty-printed JSON.
/// - `Err(serde_json::Error)` if serialization fails.
///
/// # Errors
/// Returns a `serde_json::Error` if the value cannot be serialized to JSON.
///
/// # Examples
/// ```rust
/// use trash_analyzer::serde::pretty_json;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Person { name: String, age: u32 }
///
/// let person = Person { name: "Alice".to_string(), age: 30 };
/// let json = pretty_json(&person).unwrap();
/// println!("{}", json);
/// // Output:
/// // {
/// // "name": "Alice",
/// // "age": 30
/// // }
/// ```
/// Validate JSON structure against a schema at runtime.
///
/// This function attempts to deserialize and re-serialize to validate
/// the JSON structure. More comprehensive validation would require
/// a JSON Schema library.
///
/// # Type Parameters
/// - `T`: The type to validate against, must implement `Serialize + DeserializeOwned`.
///
/// # Parameters
/// - `json`: The JSON string to validate.
///
/// # Returns
/// - `Ok(T)` if the JSON is valid for the type.
/// - `Err(serde_json::Error)` if validation fails.
///
/// # Errors
/// Returns `serde_json::Error` if the JSON is malformed or doesn't match the expected type.
///
/// # Examples
/// ```rust
/// use trash_analyzer::serde::validate_json;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, Debug)]
/// struct Person { name: String, age: u32 }
///
/// let json = r#"{"name":"Alice","age":30}"#;
/// let person: Person = validate_json(json).unwrap();
/// println!("Valid person: {:?}", person);
/// ```