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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use AHasher;
use ;
use memchr;
use ;
use Hasher;
/// Utility functions for advanced JSON processing and metadata handling.
///
/// This module provides specialized utilities for JSON operations including
/// fast hashing, timestamping, logging, and efficient key/value extraction.
/// Designed for high-performance applications requiring additional metadata
/// and debugging capabilities.
///
/// ## Features
///
/// - **Fast Hashing**: Non-cryptographic hashing using ahash for performance
/// - **Timestamp Metadata**: Automatic timestamping for audit trails
/// - **Operation Logging**: Debug logging for serialization operations
/// - **Key Extraction**: Efficient JSON key searching and value extraction
/// - **Memory Efficient**: Optimized string operations using memchr
/// - **Type Safe**: Full compile-time type checking with serde
///
/// ## Examples
///
/// ### Fast Content Hashing
/// ```rust
/// use trash_utilities::serde::hash_json_ahash;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Document {
/// id: u64,
/// title: String,
/// content: String,
/// }
///
/// let doc = Document {
/// id: 123,
/// title: "Important Document".to_string(),
/// content: "This is the document content...".to_string(),
/// };
///
/// let hash = hash_json_ahash(&doc).unwrap();
/// println!("Document hash: {}", hash);
/// // Use hash for caching, deduplication, or change detection
/// ```
///
/// ### Timestamped Operations
/// ```rust
/// use trash_utilities::serde::{serialize_with_timestamp, deserialize_with_timestamp};
/// use serde::Serialize;
/// use chrono::{DateTime, Utc};
///
/// #[derive(Serialize, serde::Deserialize, Debug)]
/// struct UserAction {
/// user_id: u64,
/// action: String,
/// }
///
/// let action = UserAction {
/// user_id: 456,
/// action: "login".to_string(),
/// };
///
/// // Serialize with automatic timestamp
/// let json = serialize_with_timestamp(&action, "user_action").unwrap();
/// println!("{}", json);
/// // {"timestamp":"2025-10-19T...","operation":"user_action","data":{...}}
///
/// // Deserialize with metadata
/// let (data, timestamp, operation): (UserAction, DateTime<Utc>, String) =
/// deserialize_with_timestamp(&json).unwrap();
/// ```
///
/// ### JSON Key Operations
/// ```rust
/// use trash_utilities::serde::{json_contains_key, extract_json_value};
///
/// let user_json = r#"{
/// "id": 123,
/// "name": "Alice",
/// "email": "alice@example.com",
/// "active": true
/// }"#;
///
/// // Fast key existence check
/// assert!(json_contains_key(user_json, "name"));
/// assert!(!json_contains_key(user_json, "phone"));
///
/// // Extract specific values
/// assert_eq!(extract_json_value(user_json, "name"), Some(r#""Alice""#.to_string()));
/// assert_eq!(extract_json_value(user_json, "id"), Some("123".to_string()));
/// assert_eq!(extract_json_value(user_json, "phone"), None);
/// ```
///
/// ### Debug Logging
/// ```rust
/// use trash_utilities::serde::serialize_with_logging;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct ApiRequest {
/// endpoint: String,
/// params: std::collections::HashMap<String, String>,
/// }
///
/// let request = ApiRequest {
/// endpoint: "/api/users".to_string(),
/// params: [("limit".to_string(), "10".to_string())].into(),
/// };
///
/// // Serialize with debug logging
/// let json = serialize_with_logging(&request, "api_request").unwrap();
/// // Output: Serializing with context: api_request
/// ```
/// Compute a fast non-cryptographic hash of serialized JSON.
///
/// This function uses ahash for fast hashing, suitable for hash tables
/// and checksums where cryptographic security is not required.
///
/// # Type Parameters
/// - `T`: The type to serialize and hash, must implement `Serialize`.
///
/// # Parameters
/// - `value`: The value to hash.
///
/// # Returns
/// - `Ok(u64)` containing the hash value.
/// - `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::hash_json_ahash;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Data { id: u32, name: String }
///
/// let data = Data { id: 123, name: "test".to_string() };
/// let hash = hash_json_ahash(&data).unwrap();
/// println!("Fast hash: {}", hash);
/// ```
/// Serialize a value to JSON with logging.
///
/// This function serializes a value to JSON and logs the operation,
/// useful for debugging serialization performance.
///
/// # Type Parameters
/// - `T`: The type to serialize, must implement `Serialize`.
///
/// # Parameters
/// - `value`: The value to serialize.
/// - `context`: A context string for logging.
///
/// # 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.
/// Serialize with timestamp metadata.
///
/// This function wraps the data with timestamp information, useful for
/// versioning or audit trails.
///
/// # Type Parameters
/// - `T`: The type to serialize, must implement `Serialize`.
///
/// # Parameters
/// - `value`: The value to serialize.
/// - `operation`: A string describing the operation (e.g., "create", "update").
///
/// # Returns
/// - `Ok(String)` containing JSON with timestamp metadata.
/// - `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_with_timestamp;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Config { settings: Vec<String> }
///
/// let config = Config { settings: vec!["debug".to_string()] };
/// let json = serialize_with_timestamp(&config, "save_config").unwrap();
/// println!("{}", json);
/// // Output: {"timestamp":"2025-10-19T...","operation":"save_config","data":{...}}
/// ```
/// Deserialize timestamped data.
///
/// This function deserializes data that was serialized with `serialize_with_timestamp`.
///
/// # Type Parameters
/// - `T`: The type to deserialize into, must implement `DeserializeOwned`.
///
/// # Parameters
/// - `json`: The JSON string containing timestamped data.
///
/// # Returns
/// - `Ok((T, DateTime<Utc>, String))` containing the data, timestamp, and operation.
/// - `Err(serde_json::Error)` if deserialization fails.
///
/// # Errors
/// Returns `serde_json::Error` if the JSON is malformed or doesn't match the expected timestamped data structure.
///
/// # Examples
/// ```rust
/// use trash_analyzer::serde::{serialize_with_timestamp, deserialize_with_timestamp};
/// use serde::Serialize;
/// use chrono::{DateTime, Utc};
///
/// #[derive(Serialize, serde::Deserialize, Debug)]
/// struct Config { settings: Vec<String> }
///
/// let config = Config { settings: vec!["debug".to_string()] };
/// let json = serialize_with_timestamp(&config, "save").unwrap();
/// let (data, timestamp, operation): (Config, DateTime<Utc>, String) =
/// deserialize_with_timestamp(&json).unwrap();
/// println!("Operation '{}' at {}", operation, timestamp);
/// ```
/// Efficiently search for a key in JSON string using memchr.
///
/// This function uses optimized string searching to quickly find JSON keys.
/// Much faster than regex for simple key lookups.
///
/// # Parameters
/// - `json`: The JSON string to search.
/// - `key`: The key to find (without quotes).
///
/// # Returns
/// `true` if the key exists in the JSON, `false` otherwise.
///
/// # Examples
/// ```rust
/// use trash_analyzer::serde::json_contains_key;
///
/// let json = r#"{"name":"Alice","age":30,"active":true}"#;
/// assert!(json_contains_key(json, "name"));
/// assert!(json_contains_key(json, "age"));
/// assert!(!json_contains_key(json, "email"));
/// ```
/// Extract a JSON value by key path using efficient searching.
///
/// This function finds a top-level key in JSON and extracts its value.
/// Uses memchr for efficient string operations.
///
/// # Parameters
/// - `json`: The JSON string to search.
/// - `key`: The key to extract.
///
/// # Returns
/// - `Some(String)` containing the JSON value if found.
/// - `None` if the key is not found or parsing fails.
///
/// # Examples
/// ```rust
/// use trash_analyzer::serde::extract_json_value;
///
/// let json = r#"{"name":"Alice","age":30,"active":true}"#;
/// assert_eq!(extract_json_value(json, "name"), Some(r#""Alice""#.to_string()));
/// assert_eq!(extract_json_value(json, "age"), Some("30".to_string()));
/// assert_eq!(extract_json_value(json, "email"), None);
/// ```