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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use ;
use ;
use fs;
use ;
/// Streaming serialization for files and network I/O.
///
/// This module provides streaming serialization capabilities for efficient
/// handling of large data structures and network protocols. Supports both
/// synchronous file I/O and asynchronous operations with futures.
///
/// ## Features
///
/// - **Streaming I/O**: Direct serialization to/from readers and writers
/// - **Async Support**: Non-blocking file operations with async/await
/// - **Memory Efficient**: Process large data without loading everything into memory
/// - **Network Ready**: Compatible with TCP streams and other I/O sources
/// - **Error Propagation**: Comprehensive error handling for I/O operations
/// - **Pretty Printing**: Formatted JSON output for configuration files
///
/// ## Examples
///
/// ### File-Based Configuration
/// ```rust,no_run
/// use trash_utilities::serde::{serialize_pretty_to_writer, deserialize_from_reader};
/// use serde::{Serialize, Deserialize};
/// use std::fs::File;
///
/// #[derive(Serialize, Deserialize, Debug)]
/// struct AppConfig {
/// database_url: String,
/// max_connections: u32,
/// features: Vec<String>,
/// }
///
/// let config = AppConfig {
/// database_url: "postgres://localhost/app".to_string(),
/// max_connections: 50,
/// features: vec!["logging".to_string(), "metrics".to_string()],
/// };
///
/// // Write pretty-printed config to file
/// let mut file = File::create("config.json").unwrap();
/// serialize_pretty_to_writer(&mut file, &config).unwrap();
///
/// // Read config back
/// let file = File::open("config.json").unwrap();
/// let loaded: AppConfig = deserialize_from_reader(file).unwrap();
/// assert_eq!(config.database_url, loaded.database_url);
/// ```
///
/// ### Async File Operations
/// ```rust,no_run
/// use trash_utilities::serde::{serialize_to_file_async, deserialize_from_file_async};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, Debug, PartialEq)]
/// struct UserData {
/// id: u64,
/// preferences: std::collections::HashMap<String, String>,
/// }
///
/// async fn save_and_load_user() -> Result<(), Box<dyn std::error::Error>> {
/// let user = UserData {
/// id: 12345,
/// preferences: [("theme".to_string(), "dark".to_string())].into(),
/// };
///
/// // Save asynchronously
/// serialize_to_file_async(&user, "user.json").await?;
///
/// // Load asynchronously
/// let loaded: UserData = deserialize_from_file_async("user.json").await?;
/// assert_eq!(user, loaded);
///
/// Ok(())
/// }
/// ```
///
/// ### Network Protocol Streaming
/// ```rust,no_run
/// use trash_utilities::serde::serialize_to_writer;
/// use serde::Serialize;
/// use std::net::TcpStream;
///
/// #[derive(Serialize)]
/// struct ApiRequest {
/// method: String,
/// path: String,
/// headers: std::collections::HashMap<String, String>,
/// }
///
/// fn send_request(stream: &mut TcpStream) -> Result<(), Box<dyn std::error::Error>> {
/// let request = ApiRequest {
/// method: "POST".to_string(),
/// path: "/api/data".to_string(),
/// headers: [("content-type".to_string(), "application/json".to_string())].into(),
/// };
///
/// // Stream JSON directly to network
/// serialize_to_writer(stream, &request)?;
/// Ok(())
/// }
/// ```
///
/// ### Large Data Processing
/// ```rust,no_run
/// use trash_utilities::serde::deserialize_from_reader;
/// use serde::Deserialize;
/// use std::fs::File;
/// use std::io::BufReader;
///
/// #[derive(Deserialize)]
/// struct LargeDataset {
/// records: Vec<Record>,
/// }
///
/// #[derive(Deserialize)]
/// struct Record {
/// id: u64,
/// data: Vec<f64>,
/// }
///
/// fn process_large_file() -> Result<(), Box<dyn std::error::Error>> {
/// // Use buffered reader for efficiency
/// let file = File::open("large_dataset.json")?;
/// let reader = BufReader::new(file);
///
/// // Stream deserialize without loading entire file into memory
/// let dataset: LargeDataset = deserialize_from_reader(reader)?;
///
/// println!("Processed {} records", dataset.records.len());
/// Ok(())
/// }
/// ```
/// Serialize a value to JSON and write it to a writer.
///
/// This function serializes a value to JSON and writes it directly to any type
/// that implements `Write`. Useful for streaming JSON to files or network sockets.
///
/// # Type Parameters
/// - `T`: The type to serialize, must implement `Serialize`.
/// - `W`: The writer type, must implement `Write`.
///
/// # Parameters
/// - `writer`: The writer to output the JSON to.
/// - `value`: The value to serialize.
///
/// # Returns
/// - `Ok(())` if serialization and writing succeed.
/// - `Err(serde_json::Error)` if serialization fails.
/// - `Err(std::io::Error)` if writing fails.
///
/// # Errors
/// Returns `serde_json::Error` if the value cannot be serialized to JSON, or `std::io::Error` if writing to the writer fails.
///
/// # Examples
/// ```rust,no_run
/// use trash_analyzer::serde::serialize_to_writer;
/// use serde::Serialize;
/// use std::fs::File;
///
/// #[derive(Serialize)]
/// struct Person { name: String, age: u32 }
///
/// let person = Person { name: "Alice".to_string(), age: 30 };
/// let mut file = File::create("person.json").unwrap();
/// serialize_to_writer(&mut file, &person).unwrap();
/// ```
/// Deserialize a value from JSON read from a reader.
///
/// This function reads JSON from any type that implements `Read` and deserializes
/// it into a struct. Useful for streaming JSON from files or network sockets.
///
/// # Type Parameters
/// - `R`: The reader type, must implement `Read`.
/// - `T`: The type to deserialize into, must implement `DeserializeOwned`.
///
/// # Parameters
/// - `reader`: The reader to read JSON from.
///
/// # Returns
/// - `Ok(T)` containing the deserialized value.
/// - `Err(serde_json::Error)` if deserialization fails.
/// - `Err(std::io::Error)` if reading fails.
///
/// # Errors
/// Returns `serde_json::Error` if the JSON is malformed or doesn't match the expected type, or `std::io::Error` if reading from the reader fails.
///
/// # Examples
/// ```rust,no_run
/// use trash_analyzer::serde::deserialize_from_reader;
/// use serde::Deserialize;
/// use std::fs::File;
///
/// #[derive(Deserialize, Debug)]
/// struct Person { name: String, age: u32 }
///
/// let file = File::open("person.json").unwrap();
/// let person: Person = deserialize_from_reader(file).unwrap();
/// println!("{:?}", person);
/// ```
/// Serialize a value to pretty-printed JSON and write it to a writer.
///
/// Similar to `serialize_to_writer` but produces formatted JSON with indentation.
/// Useful for creating human-readable configuration files or debug output.
///
/// # Type Parameters
/// - `T`: The type to serialize, must implement `Serialize`.
/// - `W`: The writer type, must implement `Write`.
///
/// # Parameters
/// - `writer`: The writer to output the JSON to.
/// - `value`: The value to serialize.
///
/// # Returns
/// - `Ok(())` if serialization and writing succeed.
/// - `Err(serde_json::Error)` if serialization fails.
/// - `Err(std::io::Error)` if writing fails.
///
/// # Errors
/// Returns `serde_json::Error` if the value cannot be serialized to JSON, or `std::io::Error` if writing to the writer fails.
///
/// # Examples
/// ```rust,no_run
/// use trash_analyzer::serde::serialize_pretty_to_writer;
/// use serde::Serialize;
/// use std::fs::File;
///
/// #[derive(Serialize)]
/// struct Config { settings: Vec<String>, debug: bool }
///
/// let config = Config {
/// settings: vec!["option1".to_string()],
/// debug: true,
/// };
/// let mut file = File::create("config.json").unwrap();
/// serialize_pretty_to_writer(&mut file, &config).unwrap();
/// ```
/// Asynchronously serialize a value to JSON and write to a file.
///
/// This function uses async I/O for efficient file operations.
/// Useful for non-blocking serialization to disk.
///
/// # Type Parameters
/// - `T`: The type to serialize, must implement `Serialize`.
///
/// # Parameters
/// - `value`: The value to serialize.
/// - `path`: The file path to write to.
///
/// # Returns
/// - `Ok(())` if serialization and writing succeed.
/// - `Err(Box<dyn std::error::Error>)` if serialization or I/O fails.
///
/// # Errors
/// Returns an error if the value cannot be serialized to JSON or if file I/O operations fail.
///
/// # Examples
/// ```rust,no_run
/// use trash_analyzer::serde::serialize_to_file_async;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Config { debug: bool, level: String }
///
/// let config = Config { debug: true, level: "info".to_string() };
/// serialize_to_file_async(&config, "config.json").await.unwrap();
/// ```
pub async
/// Asynchronously deserialize from a file.
///
/// This function uses async I/O to read and deserialize JSON from a file.
/// Useful for non-blocking file operations.
///
/// # Type Parameters
/// - `T`: The type to deserialize into, must implement `DeserializeOwned`.
///
/// # Parameters
/// - `path`: The file path to read from.
///
/// # Returns
/// - `Ok(T)` containing the deserialized value.
/// - `Err(Box<dyn std::error::Error>)` if I/O or deserialization fails.
///
/// # Errors
/// Returns an error if the file cannot be read or if the JSON content cannot be deserialized into the target type.
///
/// # Examples
/// ```rust,no_run
/// use trash_analyzer::serde::deserialize_from_file_async;
/// use serde::Deserialize;
///
/// #[derive(Deserialize, Debug)]
/// struct Config { debug: bool, level: String }
///
/// let config: Config = deserialize_from_file_async("config.json").await.unwrap();
/// println!("Loaded config: {:?}", config);
/// ```
pub async