pub struct StructSerializer { /* private fields */ }Expand description
Builder for serializing structured data with fluent interface
This struct provides a fluent interface for building complex serializable structures without requiring trait imports. It maintains type safety while allowing for future extensibility with field attributes and customization options.
The serializer supports both JSON and binary formats, with automatic type detection
through the ToFieldValue trait. Fields are stored in insertion order to maintain
consistent serialization output.
§Fields
fields- Vector of field name-value pairs preserving insertion order
§Examples
The serializer provides a fluent interface for building structured data with automatic type detection and support for both JSON and binary formats.
§Thread Safety
This type is not thread-safe. Each thread should create its own instance for concurrent serialization operations.
Implementations§
Source§impl StructSerializer
impl StructSerializer
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new empty struct serializer
Returns a new StructSerializer with an empty field collection.
Use this constructor when you don’t know the final number of fields
in advance.
§Returns
A new StructSerializer instance ready for field registration
§Examples
Creates a new empty serializer ready for field registration.
Examples found in repository?
48 fn to_serializer(&self) -> StructSerializer {
49 StructSerializer::new()
50 .field("version", &self.version)
51 .field("name", &self.name)
52 .field("value", &self.value)
53 .field("optional_field", &self.optional_field)
54 .field("new_field", &self.new_field)
55 }
56
57 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
58 let version = deserializer.field("version")?;
59 let name = deserializer.field("name")?;
60 let value = deserializer.field("value")?;
61
62 // Handle optional fields gracefully for schema evolution
63 let optional_field = deserializer.field_optional("optional_field")?;
64 let new_field = deserializer.field_optional("new_field")?;
65
66 // Validate version compatibility
67 if version > 3 {
68 return Err(SerializationError::ValidationFailed {
69 field: "version".to_string(),
70 message: format!("Unsupported version: {}. Maximum supported: 3", version),
71 });
72 }
73
74 Ok(VersionedData {
75 version,
76 name,
77 value,
78 optional_field,
79 new_field,
80 })
81 }
82}
83
84impl ToFieldValue for VersionedData {
85 fn to_field_value(&self) -> FieldValue {
86 match self.to_json() {
87 Ok(json_str) => FieldValue::from_json_object(json_str),
88 Err(_) => FieldValue::from_string("serialization_error".to_string()),
89 }
90 }
91}
92
93impl FromFieldValue for VersionedData {
94 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
95 // Try JSON object first
96 if let Ok(json_data) = value.as_json_object() {
97 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
98 field: field_name.to_string(),
99 message: format!("Failed to deserialize VersionedData from JSON: {}", e),
100 });
101 }
102
103 // Try binary object
104 if let Ok(binary_data) = value.as_binary_object() {
105 return Self::from_binary(binary_data).map_err(|e| {
106 SerializationError::ValidationFailed {
107 field: field_name.to_string(),
108 message: format!("Failed to deserialize VersionedData from binary: {}", e),
109 }
110 });
111 }
112
113 Err(SerializationError::ValidationFailed {
114 field: field_name.to_string(),
115 message: format!(
116 "Expected JsonObject or BinaryObject for VersionedData, found {}",
117 value.type_name()
118 ),
119 })
120 }
121}
122
123/// Validated user input with constraints
124#[derive(Debug, Clone, PartialEq)]
125pub struct ValidatedUserInput {
126 pub username: String,
127 pub email: String,
128 pub age: u16,
129 pub preferences: HashMap<String, String>,
130}
131
132impl StructSerializable for ValidatedUserInput {
133 fn to_serializer(&self) -> StructSerializer {
134 StructSerializer::new()
135 .field("username", &self.username)
136 .field("email", &self.email)
137 .field("age", &self.age)
138 .field("preferences", &self.preferences)
139 }
140
141 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
142 let username: String = deserializer.field("username")?;
143 let email: String = deserializer.field("email")?;
144 let age: u16 = deserializer.field("age")?;
145 let preferences: HashMap<String, String> = deserializer.field("preferences")?;
146
147 // Validate username
148 if username.is_empty() || username.len() > 50 {
149 return Err(SerializationError::ValidationFailed {
150 field: "username".to_string(),
151 message: "Username must be 1-50 characters long".to_string(),
152 });
153 }
154
155 if !username
156 .chars()
157 .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
158 {
159 return Err(SerializationError::ValidationFailed {
160 field: "username".to_string(),
161 message:
162 "Username can only contain alphanumeric characters, underscores, and hyphens"
163 .to_string(),
164 });
165 }
166
167 // Validate email (basic check)
168 if !email.contains('@') || !email.contains('.') || email.len() < 5 {
169 return Err(SerializationError::ValidationFailed {
170 field: "email".to_string(),
171 message: "Invalid email format".to_string(),
172 });
173 }
174
175 // Validate age
176 if !(13..=120).contains(&age) {
177 return Err(SerializationError::ValidationFailed {
178 field: "age".to_string(),
179 message: "Age must be between 13 and 120".to_string(),
180 });
181 }
182
183 // Validate preferences
184 if preferences.len() > 20 {
185 return Err(SerializationError::ValidationFailed {
186 field: "preferences".to_string(),
187 message: "Too many preferences (maximum 20)".to_string(),
188 });
189 }
190
191 for (key, value) in &preferences {
192 if key.len() > 50 || value.len() > 200 {
193 return Err(SerializationError::ValidationFailed {
194 field: "preferences".to_string(),
195 message: format!("Preference key/value too long: {}", key),
196 });
197 }
198 }
199
200 Ok(ValidatedUserInput {
201 username,
202 email,
203 age,
204 preferences,
205 })
206 }
207}
208
209impl ToFieldValue for ValidatedUserInput {
210 fn to_field_value(&self) -> FieldValue {
211 match self.to_json() {
212 Ok(json_str) => FieldValue::from_json_object(json_str),
213 Err(_) => FieldValue::from_string("serialization_error".to_string()),
214 }
215 }
216}
217
218impl FromFieldValue for ValidatedUserInput {
219 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
220 // Try JSON object first
221 if let Ok(json_data) = value.as_json_object() {
222 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
223 field: field_name.to_string(),
224 message: format!("Failed to deserialize ValidatedUserInput from JSON: {}", e),
225 });
226 }
227
228 // Try binary object
229 if let Ok(binary_data) = value.as_binary_object() {
230 return Self::from_binary(binary_data).map_err(|e| {
231 SerializationError::ValidationFailed {
232 field: field_name.to_string(),
233 message: format!(
234 "Failed to deserialize ValidatedUserInput from binary: {}",
235 e
236 ),
237 }
238 });
239 }
240
241 Err(SerializationError::ValidationFailed {
242 field: field_name.to_string(),
243 message: format!(
244 "Expected JsonObject or BinaryObject for ValidatedUserInput, found {}",
245 value.type_name()
246 ),
247 })
248 }
249}
250
251/// Recovery helper for handling partial data
252#[derive(Debug, Clone, PartialEq)]
253pub struct RecoverableData {
254 pub critical_field: String,
255 pub important_field: Option<String>,
256 pub optional_field: Option<String>,
257 pub metadata: HashMap<String, String>,
258}
259
260impl StructSerializable for RecoverableData {
261 fn to_serializer(&self) -> StructSerializer {
262 StructSerializer::new()
263 .field("critical_field", &self.critical_field)
264 .field("important_field", &self.important_field)
265 .field("optional_field", &self.optional_field)
266 .field("metadata", &self.metadata)
267 }More examples
47 fn to_serializer(&self) -> StructSerializer {
48 StructSerializer::new()
49 .field("email", &self.email)
50 .field("phone", &self.phone)
51 .field("address_city", &self.address_city)
52 .field("address_state", &self.address_state)
53 .field("social_media", &self.social_media)
54 }
55
56 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
57 let email = deserializer.field("email")?;
58 let phone = deserializer.field("phone")?;
59 let address_city = deserializer.field("address_city")?;
60 let address_state = deserializer.field("address_state")?;
61 let social_media = deserializer.field("social_media")?;
62
63 Ok(ContactInfo {
64 email,
65 phone,
66 address_city,
67 address_state,
68 social_media,
69 })
70 }
71}
72
73impl ToFieldValue for ContactInfo {
74 fn to_field_value(&self) -> FieldValue {
75 match self.to_json() {
76 Ok(json_str) => FieldValue::from_json_object(json_str),
77 Err(_) => FieldValue::from_string("serialization_error".to_string()),
78 }
79 }
80}
81
82impl FromFieldValue for ContactInfo {
83 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
84 // Try JSON object first
85 if let Ok(json_data) = value.as_json_object() {
86 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
87 field: field_name.to_string(),
88 message: format!("Failed to deserialize ContactInfo from JSON: {}", e),
89 });
90 }
91
92 // Try binary object
93 if let Ok(binary_data) = value.as_binary_object() {
94 return Self::from_binary(binary_data).map_err(|e| {
95 SerializationError::ValidationFailed {
96 field: field_name.to_string(),
97 message: format!("Failed to deserialize ContactInfo from binary: {}", e),
98 }
99 });
100 }
101
102 Err(SerializationError::ValidationFailed {
103 field: field_name.to_string(),
104 message: format!(
105 "Expected JsonObject or BinaryObject for ContactInfo, found {}",
106 value.type_name()
107 ),
108 })
109 }
110}
111
112/// Address struct
113#[derive(Debug, Clone, PartialEq)]
114pub struct Address {
115 pub street: String,
116 pub city: String,
117 pub state: String,
118 pub postal_code: String,
119 pub country: String,
120}
121
122impl StructSerializable for Address {
123 fn to_serializer(&self) -> StructSerializer {
124 StructSerializer::new()
125 .field("street", &self.street)
126 .field("city", &self.city)
127 .field("state", &self.state)
128 .field("postal_code", &self.postal_code)
129 .field("country", &self.country)
130 }
131
132 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
133 let street = deserializer.field("street")?;
134 let city = deserializer.field("city")?;
135 let state = deserializer.field("state")?;
136 let postal_code = deserializer.field("postal_code")?;
137 let country = deserializer.field("country")?;
138
139 Ok(Address {
140 street,
141 city,
142 state,
143 postal_code,
144 country,
145 })
146 }
147}
148
149impl ToFieldValue for Address {
150 fn to_field_value(&self) -> FieldValue {
151 match self.to_json() {
152 Ok(json_str) => FieldValue::from_json_object(json_str),
153 Err(_) => FieldValue::from_string("serialization_error".to_string()),
154 }
155 }
156}
157
158impl FromFieldValue for Address {
159 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
160 // Try JSON object first
161 if let Ok(json_data) = value.as_json_object() {
162 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
163 field: field_name.to_string(),
164 message: format!("Failed to deserialize Address from JSON: {}", e),
165 });
166 }
167
168 // Try binary object
169 if let Ok(binary_data) = value.as_binary_object() {
170 return Self::from_binary(binary_data).map_err(|e| {
171 SerializationError::ValidationFailed {
172 field: field_name.to_string(),
173 message: format!("Failed to deserialize Address from binary: {}", e),
174 }
175 });
176 }
177
178 Err(SerializationError::ValidationFailed {
179 field: field_name.to_string(),
180 message: format!(
181 "Expected JsonObject or BinaryObject for Address, found {}",
182 value.type_name()
183 ),
184 })
185 }
186}
187
188/// Project information struct
189#[derive(Debug, Clone, PartialEq)]
190pub struct Project {
191 pub name: String,
192 pub description: String,
193 pub status: ProjectStatus,
194 pub budget: f64,
195 pub team_members: Vec<String>,
196 pub milestones: Vec<Milestone>,
197 pub metadata: HashMap<String, String>,
198}
199
200impl StructSerializable for Project {
201 fn to_serializer(&self) -> StructSerializer {
202 StructSerializer::new()
203 .field("name", &self.name)
204 .field("description", &self.description)
205 .field("status", &self.status)
206 .field("budget", &self.budget)
207 .field("team_members", &self.team_members)
208 .field("milestones", &self.milestones)
209 .field("metadata", &self.metadata)
210 }
211
212 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
213 let name = deserializer.field("name")?;
214 let description = deserializer.field("description")?;
215 let status = deserializer.field("status")?;
216 let budget = deserializer.field("budget")?;
217 let team_members = deserializer.field("team_members")?;
218 let milestones = deserializer.field("milestones")?;
219 let metadata = deserializer.field("metadata")?;
220
221 Ok(Project {
222 name,
223 description,
224 status,
225 budget,
226 team_members,
227 milestones,
228 metadata,
229 })
230 }
231}
232
233impl ToFieldValue for Project {
234 fn to_field_value(&self) -> FieldValue {
235 match self.to_json() {
236 Ok(json_str) => FieldValue::from_json_object(json_str),
237 Err(_) => FieldValue::from_string("serialization_error".to_string()),
238 }
239 }
240}
241
242impl FromFieldValue for Project {
243 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
244 // Try JSON object first
245 if let Ok(json_data) = value.as_json_object() {
246 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
247 field: field_name.to_string(),
248 message: format!("Failed to deserialize Project from JSON: {}", e),
249 });
250 }
251
252 // Try binary object
253 if let Ok(binary_data) = value.as_binary_object() {
254 return Self::from_binary(binary_data).map_err(|e| {
255 SerializationError::ValidationFailed {
256 field: field_name.to_string(),
257 message: format!("Failed to deserialize Project from binary: {}", e),
258 }
259 });
260 }
261
262 Err(SerializationError::ValidationFailed {
263 field: field_name.to_string(),
264 message: format!(
265 "Expected JsonObject or BinaryObject for Project, found {}",
266 value.type_name()
267 ),
268 })
269 }
270}
271
272/// Project status enumeration
273#[derive(Debug, Clone, PartialEq)]
274pub enum ProjectStatus {
275 Planning,
276 InProgress,
277 OnHold,
278 Completed,
279 Cancelled,
280}
281
282impl ToFieldValue for ProjectStatus {
283 fn to_field_value(&self) -> FieldValue {
284 let status_str = match self {
285 ProjectStatus::Planning => "planning",
286 ProjectStatus::InProgress => "in_progress",
287 ProjectStatus::OnHold => "on_hold",
288 ProjectStatus::Completed => "completed",
289 ProjectStatus::Cancelled => "cancelled",
290 };
291 FieldValue::from_string(status_str.to_string())
292 }
293}
294
295impl FromFieldValue for ProjectStatus {
296 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
297 match value {
298 FieldValue::String(s) => match s.as_str() {
299 "planning" => Ok(ProjectStatus::Planning),
300 "in_progress" => Ok(ProjectStatus::InProgress),
301 "on_hold" => Ok(ProjectStatus::OnHold),
302 "completed" => Ok(ProjectStatus::Completed),
303 "cancelled" => Ok(ProjectStatus::Cancelled),
304 _ => Err(SerializationError::ValidationFailed {
305 field: field_name.to_string(),
306 message: format!("Unknown project status: {}", s),
307 }),
308 },
309 _ => Err(SerializationError::ValidationFailed {
310 field: field_name.to_string(),
311 message: format!(
312 "Expected String for ProjectStatus, found {}",
313 value.type_name()
314 ),
315 }),
316 }
317 }
318}
319
320/// Project milestone struct
321#[derive(Debug, Clone, PartialEq)]
322pub struct Milestone {
323 pub name: String,
324 pub description: String,
325 pub due_date: String, // Simplified as string for this example
326 pub is_completed: bool,
327 pub progress_percentage: f32,
328 pub dependencies: Vec<String>,
329}
330
331impl StructSerializable for Milestone {
332 fn to_serializer(&self) -> StructSerializer {
333 StructSerializer::new()
334 .field("name", &self.name)
335 .field("description", &self.description)
336 .field("due_date", &self.due_date)
337 .field("is_completed", &self.is_completed)
338 .field("progress_percentage", &self.progress_percentage)
339 .field("dependencies", &self.dependencies)
340 }
341
342 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
343 let name = deserializer.field("name")?;
344 let description = deserializer.field("description")?;
345 let due_date = deserializer.field("due_date")?;
346 let is_completed = deserializer.field("is_completed")?;
347 let progress_percentage = deserializer.field("progress_percentage")?;
348 let dependencies = deserializer.field("dependencies")?;
349
350 Ok(Milestone {
351 name,
352 description,
353 due_date,
354 is_completed,
355 progress_percentage,
356 dependencies,
357 })
358 }
359}
360
361impl ToFieldValue for Milestone {
362 fn to_field_value(&self) -> FieldValue {
363 match self.to_json() {
364 Ok(json_str) => FieldValue::from_json_object(json_str),
365 Err(_) => FieldValue::from_string("serialization_error".to_string()),
366 }
367 }
368}
369
370impl FromFieldValue for Milestone {
371 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
372 // Try JSON object first
373 if let Ok(json_data) = value.as_json_object() {
374 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
375 field: field_name.to_string(),
376 message: format!("Failed to deserialize Milestone from JSON: {}", e),
377 });
378 }
379
380 // Try binary object
381 if let Ok(binary_data) = value.as_binary_object() {
382 return Self::from_binary(binary_data).map_err(|e| {
383 SerializationError::ValidationFailed {
384 field: field_name.to_string(),
385 message: format!("Failed to deserialize Milestone from binary: {}", e),
386 }
387 });
388 }
389
390 Err(SerializationError::ValidationFailed {
391 field: field_name.to_string(),
392 message: format!(
393 "Expected JsonObject or BinaryObject for Milestone, found {}",
394 value.type_name()
395 ),
396 })
397 }
398}
399
400/// Company struct with basic collections and nesting
401#[derive(Debug, Clone, PartialEq)]
402pub struct Company {
403 pub name: String,
404 pub founded_year: i32,
405 pub headquarters_city: String,
406 pub headquarters_state: String,
407 pub employee_count: usize,
408 pub department_names: Vec<String>,
409 pub active_project_names: Vec<String>,
410 pub company_metadata: HashMap<String, String>,
411}
412
413impl StructSerializable for Company {
414 fn to_serializer(&self) -> StructSerializer {
415 StructSerializer::new()
416 .field("name", &self.name)
417 .field("founded_year", &self.founded_year)
418 .field("headquarters_city", &self.headquarters_city)
419 .field("headquarters_state", &self.headquarters_state)
420 .field("employee_count", &self.employee_count)
421 .field("department_names", &self.department_names)
422 .field("active_project_names", &self.active_project_names)
423 .field("company_metadata", &self.company_metadata)
424 }
425
426 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
427 let name = deserializer.field("name")?;
428 let founded_year = deserializer.field("founded_year")?;
429 let headquarters_city = deserializer.field("headquarters_city")?;
430 let headquarters_state = deserializer.field("headquarters_state")?;
431 let employee_count = deserializer.field("employee_count")?;
432 let department_names = deserializer.field("department_names")?;
433 let active_project_names = deserializer.field("active_project_names")?;
434 let company_metadata = deserializer.field("company_metadata")?;
435
436 Ok(Company {
437 name,
438 founded_year,
439 headquarters_city,
440 headquarters_state,
441 employee_count,
442 department_names,
443 active_project_names,
444 company_metadata,
445 })
446 }
447}
448
449impl ToFieldValue for Company {
450 fn to_field_value(&self) -> FieldValue {
451 match self.to_json() {
452 Ok(json_str) => FieldValue::from_json_object(json_str),
453 Err(_) => FieldValue::from_string("serialization_error".to_string()),
454 }
455 }
456}
457
458impl FromFieldValue for Company {
459 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
460 // Try JSON object first
461 if let Ok(json_data) = value.as_json_object() {
462 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
463 field: field_name.to_string(),
464 message: format!("Failed to deserialize Company from JSON: {}", e),
465 });
466 }
467
468 // Try binary object
469 if let Ok(binary_data) = value.as_binary_object() {
470 return Self::from_binary(binary_data).map_err(|e| {
471 SerializationError::ValidationFailed {
472 field: field_name.to_string(),
473 message: format!("Failed to deserialize Company from binary: {}", e),
474 }
475 });
476 }
477
478 Err(SerializationError::ValidationFailed {
479 field: field_name.to_string(),
480 message: format!(
481 "Expected JsonObject or BinaryObject for Company, found {}",
482 value.type_name()
483 ),
484 })
485 }
486}
487
488/// Department struct
489#[derive(Debug, Clone, PartialEq)]
490pub struct Department {
491 pub name: String,
492 pub manager: String,
493 pub employee_count: u32,
494 pub budget: f64,
495 pub office_locations: Vec<Address>,
496}
497
498impl StructSerializable for Department {
499 fn to_serializer(&self) -> StructSerializer {
500 StructSerializer::new()
501 .field("name", &self.name)
502 .field("manager", &self.manager)
503 .field("employee_count", &self.employee_count)
504 .field("budget", &self.budget)
505 .field("office_locations", &self.office_locations)
506 }48 fn to_serializer(&self) -> StructSerializer {
49 StructSerializer::new()
50 .field("id", &self.id)
51 .field("username", &self.username)
52 .field("email", &self.email)
53 .field("age", &self.age)
54 .field("is_active", &self.is_active)
55 .field("score", &self.score)
56 }
57
58 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
59 let id = deserializer.field("id")?;
60 let username = deserializer.field("username")?;
61 let email = deserializer.field("email")?;
62 let age = deserializer.field("age")?;
63 let is_active = deserializer.field("is_active")?;
64 let score = deserializer.field("score")?;
65
66 Ok(UserProfile {
67 id,
68 username,
69 email,
70 age,
71 is_active,
72 score,
73 })
74 }
75}
76
77impl ToFieldValue for UserProfile {
78 fn to_field_value(&self) -> FieldValue {
79 // Convert to JSON and then parse as FieldValue for nested object handling
80 match self.to_json() {
81 Ok(json_str) => {
82 // For examples, we'll serialize as JSON string for simplicity
83 FieldValue::from_json_object(json_str)
84 }
85 Err(_) => FieldValue::from_string("serialization_error".to_string()),
86 }
87 }
88}
89
90impl FromFieldValue for UserProfile {
91 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
92 // Try JSON object first
93 if let Ok(json_data) = value.as_json_object() {
94 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
95 field: field_name.to_string(),
96 message: format!("Failed to deserialize UserProfile from JSON: {}", e),
97 });
98 }
99
100 // Try binary object
101 if let Ok(binary_data) = value.as_binary_object() {
102 return Self::from_binary(binary_data).map_err(|e| {
103 SerializationError::ValidationFailed {
104 field: field_name.to_string(),
105 message: format!("Failed to deserialize UserProfile from binary: {}", e),
106 }
107 });
108 }
109
110 Err(SerializationError::ValidationFailed {
111 field: field_name.to_string(),
112 message: format!(
113 "Expected JsonObject or BinaryObject for UserProfile, found {}",
114 value.type_name()
115 ),
116 })
117 }
118}
119
120/// Application settings struct with optional fields and collections
121#[derive(Debug, Clone, PartialEq)]
122pub struct AppSettings {
123 pub app_name: String,
124 pub version: String,
125 pub debug_mode: bool,
126 pub max_connections: u32,
127 pub timeout_seconds: f32,
128 pub features: Vec<String>,
129 pub environment_vars: HashMap<String, String>,
130 pub optional_database_url: Option<String>,
131}
132
133impl StructSerializable for AppSettings {
134 fn to_serializer(&self) -> StructSerializer {
135 StructSerializer::new()
136 .field("app_name", &self.app_name)
137 .field("version", &self.version)
138 .field("debug_mode", &self.debug_mode)
139 .field("max_connections", &self.max_connections)
140 .field("timeout_seconds", &self.timeout_seconds)
141 .field("features", &self.features)
142 .field("environment_vars", &self.environment_vars)
143 .field("optional_database_url", &self.optional_database_url)
144 }48 fn to_serializer(&self) -> StructSerializer {
49 StructSerializer::new()
50 .field("operation", &self.operation)
51 .field("duration_micros", &self.duration_micros)
52 .field("memory_usage_bytes", &self.memory_usage_bytes)
53 .field("cpu_usage_percent", &self.cpu_usage_percent)
54 .field("throughput_ops_per_sec", &self.throughput_ops_per_sec)
55 .field("metadata", &self.metadata)
56 }
57
58 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
59 let operation = deserializer.field("operation")?;
60 let duration_micros = deserializer.field("duration_micros")?;
61 let memory_usage_bytes = deserializer.field("memory_usage_bytes")?;
62 let cpu_usage_percent = deserializer.field("cpu_usage_percent")?;
63 let throughput_ops_per_sec = deserializer.field("throughput_ops_per_sec")?;
64 let metadata = deserializer.field("metadata")?;
65
66 Ok(PerformanceMetrics {
67 operation,
68 duration_micros,
69 memory_usage_bytes,
70 cpu_usage_percent,
71 throughput_ops_per_sec,
72 metadata,
73 })
74 }
75}
76
77impl ToFieldValue for PerformanceMetrics {
78 fn to_field_value(&self) -> FieldValue {
79 match self.to_json() {
80 Ok(json_str) => FieldValue::from_json_object(json_str),
81 Err(_) => FieldValue::from_string("serialization_error".to_string()),
82 }
83 }
84}
85
86impl FromFieldValue for PerformanceMetrics {
87 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
88 // Try JSON object first
89 if let Ok(json_data) = value.as_json_object() {
90 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
91 field: field_name.to_string(),
92 message: format!("Failed to deserialize PerformanceMetrics from JSON: {}", e),
93 });
94 }
95
96 // Try binary object
97 if let Ok(binary_data) = value.as_binary_object() {
98 return Self::from_binary(binary_data).map_err(|e| {
99 SerializationError::ValidationFailed {
100 field: field_name.to_string(),
101 message: format!(
102 "Failed to deserialize PerformanceMetrics from binary: {}",
103 e
104 ),
105 }
106 });
107 }
108
109 Err(SerializationError::ValidationFailed {
110 field: field_name.to_string(),
111 message: format!(
112 "Expected JsonObject or BinaryObject for PerformanceMetrics, found {}",
113 value.type_name()
114 ),
115 })
116 }
117}
118
119/// Large dataset for performance testing
120#[derive(Debug, Clone, PartialEq)]
121pub struct LargeDataset {
122 pub name: String,
123 pub values: Vec<f32>, // Changed from f64 to f32 (supported)
124 pub labels: Vec<String>,
125 pub feature_count: usize, // Simplified from Vec<Vec<f32>> to just a count
126 pub feature_dimension: usize, // Store dimensions separately
127 pub metadata: HashMap<String, String>,
128 pub timestamp_count: usize, // Simplified from Vec<u64> to just count
129}
130
131impl StructSerializable for LargeDataset {
132 fn to_serializer(&self) -> StructSerializer {
133 StructSerializer::new()
134 .field("name", &self.name)
135 .field("values", &self.values)
136 .field("labels", &self.labels)
137 .field("feature_count", &self.feature_count)
138 .field("feature_dimension", &self.feature_dimension)
139 .field("metadata", &self.metadata)
140 .field("timestamp_count", &self.timestamp_count)
141 }
142
143 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
144 let name = deserializer.field("name")?;
145 let values = deserializer.field("values")?;
146 let labels = deserializer.field("labels")?;
147 let feature_count = deserializer.field("feature_count")?;
148 let feature_dimension = deserializer.field("feature_dimension")?;
149 let metadata = deserializer.field("metadata")?;
150 let timestamp_count = deserializer.field("timestamp_count")?;
151
152 Ok(LargeDataset {
153 name,
154 values,
155 labels,
156 feature_count,
157 feature_dimension,
158 metadata,
159 timestamp_count,
160 })
161 }
162}
163
164impl ToFieldValue for LargeDataset {
165 fn to_field_value(&self) -> FieldValue {
166 match self.to_json() {
167 Ok(json_str) => FieldValue::from_json_object(json_str),
168 Err(_) => FieldValue::from_string("serialization_error".to_string()),
169 }
170 }
171}
172
173impl FromFieldValue for LargeDataset {
174 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
175 // Try JSON object first
176 if let Ok(json_data) = value.as_json_object() {
177 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
178 field: field_name.to_string(),
179 message: format!("Failed to deserialize LargeDataset from JSON: {}", e),
180 });
181 }
182
183 // Try binary object
184 if let Ok(binary_data) = value.as_binary_object() {
185 return Self::from_binary(binary_data).map_err(|e| {
186 SerializationError::ValidationFailed {
187 field: field_name.to_string(),
188 message: format!("Failed to deserialize LargeDataset from binary: {}", e),
189 }
190 });
191 }
192
193 Err(SerializationError::ValidationFailed {
194 field: field_name.to_string(),
195 message: format!(
196 "Expected JsonObject or BinaryObject for LargeDataset, found {}",
197 value.type_name()
198 ),
199 })
200 }
201}
202
203/// Configuration data (typical JSON use case)
204#[derive(Debug, Clone, PartialEq)]
205pub struct Configuration {
206 pub version: String,
207 pub debug_enabled: bool,
208 pub log_level: String,
209 pub database_settings: HashMap<String, String>,
210 pub feature_flags_enabled: bool, // Simplified from HashMap<String, bool>
211 pub max_connections: f32, // Simplified from HashMap<String, f64>
212 pub timeout_seconds: f32,
213}
214
215impl StructSerializable for Configuration {
216 fn to_serializer(&self) -> StructSerializer {
217 StructSerializer::new()
218 .field("version", &self.version)
219 .field("debug_enabled", &self.debug_enabled)
220 .field("log_level", &self.log_level)
221 .field("database_settings", &self.database_settings)
222 .field("feature_flags_enabled", &self.feature_flags_enabled)
223 .field("max_connections", &self.max_connections)
224 .field("timeout_seconds", &self.timeout_seconds)
225 }Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Creates a new struct serializer with pre-allocated capacity
Returns a new StructSerializer with enough capacity to hold the specified
number of fields without reallocating. This is useful for performance-critical
applications where you know the number of fields in advance.
§Arguments
capacity- Number of fields the serializer should be able to hold without reallocating
§Returns
A new StructSerializer instance with pre-allocated capacity
§Examples
Creates a serializer with pre-allocated capacity for performance optimization.
Sourcepub fn field<T>(self, name: &str, value: &T) -> Selfwhere
T: ToFieldValue,
pub fn field<T>(self, name: &str, value: &T) -> Selfwhere
T: ToFieldValue,
Registers a field with automatic type detection
Adds a field to the serializer with automatic type conversion through the
ToFieldValue trait. The field name is preserved as a string, and the value
is converted to a FieldValue for serialization.
This method consumes self and returns a new StructSerializer with the
field added, enabling fluent method chaining.
§Arguments
name- Field name as a string slicevalue- Field value that implementsToFieldValue
§Returns
A new StructSerializer with the field added
§Examples
Adds a field with automatic type conversion and enables fluent method chaining.
Examples found in repository?
48 fn to_serializer(&self) -> StructSerializer {
49 StructSerializer::new()
50 .field("version", &self.version)
51 .field("name", &self.name)
52 .field("value", &self.value)
53 .field("optional_field", &self.optional_field)
54 .field("new_field", &self.new_field)
55 }
56
57 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
58 let version = deserializer.field("version")?;
59 let name = deserializer.field("name")?;
60 let value = deserializer.field("value")?;
61
62 // Handle optional fields gracefully for schema evolution
63 let optional_field = deserializer.field_optional("optional_field")?;
64 let new_field = deserializer.field_optional("new_field")?;
65
66 // Validate version compatibility
67 if version > 3 {
68 return Err(SerializationError::ValidationFailed {
69 field: "version".to_string(),
70 message: format!("Unsupported version: {}. Maximum supported: 3", version),
71 });
72 }
73
74 Ok(VersionedData {
75 version,
76 name,
77 value,
78 optional_field,
79 new_field,
80 })
81 }
82}
83
84impl ToFieldValue for VersionedData {
85 fn to_field_value(&self) -> FieldValue {
86 match self.to_json() {
87 Ok(json_str) => FieldValue::from_json_object(json_str),
88 Err(_) => FieldValue::from_string("serialization_error".to_string()),
89 }
90 }
91}
92
93impl FromFieldValue for VersionedData {
94 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
95 // Try JSON object first
96 if let Ok(json_data) = value.as_json_object() {
97 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
98 field: field_name.to_string(),
99 message: format!("Failed to deserialize VersionedData from JSON: {}", e),
100 });
101 }
102
103 // Try binary object
104 if let Ok(binary_data) = value.as_binary_object() {
105 return Self::from_binary(binary_data).map_err(|e| {
106 SerializationError::ValidationFailed {
107 field: field_name.to_string(),
108 message: format!("Failed to deserialize VersionedData from binary: {}", e),
109 }
110 });
111 }
112
113 Err(SerializationError::ValidationFailed {
114 field: field_name.to_string(),
115 message: format!(
116 "Expected JsonObject or BinaryObject for VersionedData, found {}",
117 value.type_name()
118 ),
119 })
120 }
121}
122
123/// Validated user input with constraints
124#[derive(Debug, Clone, PartialEq)]
125pub struct ValidatedUserInput {
126 pub username: String,
127 pub email: String,
128 pub age: u16,
129 pub preferences: HashMap<String, String>,
130}
131
132impl StructSerializable for ValidatedUserInput {
133 fn to_serializer(&self) -> StructSerializer {
134 StructSerializer::new()
135 .field("username", &self.username)
136 .field("email", &self.email)
137 .field("age", &self.age)
138 .field("preferences", &self.preferences)
139 }
140
141 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
142 let username: String = deserializer.field("username")?;
143 let email: String = deserializer.field("email")?;
144 let age: u16 = deserializer.field("age")?;
145 let preferences: HashMap<String, String> = deserializer.field("preferences")?;
146
147 // Validate username
148 if username.is_empty() || username.len() > 50 {
149 return Err(SerializationError::ValidationFailed {
150 field: "username".to_string(),
151 message: "Username must be 1-50 characters long".to_string(),
152 });
153 }
154
155 if !username
156 .chars()
157 .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
158 {
159 return Err(SerializationError::ValidationFailed {
160 field: "username".to_string(),
161 message:
162 "Username can only contain alphanumeric characters, underscores, and hyphens"
163 .to_string(),
164 });
165 }
166
167 // Validate email (basic check)
168 if !email.contains('@') || !email.contains('.') || email.len() < 5 {
169 return Err(SerializationError::ValidationFailed {
170 field: "email".to_string(),
171 message: "Invalid email format".to_string(),
172 });
173 }
174
175 // Validate age
176 if !(13..=120).contains(&age) {
177 return Err(SerializationError::ValidationFailed {
178 field: "age".to_string(),
179 message: "Age must be between 13 and 120".to_string(),
180 });
181 }
182
183 // Validate preferences
184 if preferences.len() > 20 {
185 return Err(SerializationError::ValidationFailed {
186 field: "preferences".to_string(),
187 message: "Too many preferences (maximum 20)".to_string(),
188 });
189 }
190
191 for (key, value) in &preferences {
192 if key.len() > 50 || value.len() > 200 {
193 return Err(SerializationError::ValidationFailed {
194 field: "preferences".to_string(),
195 message: format!("Preference key/value too long: {}", key),
196 });
197 }
198 }
199
200 Ok(ValidatedUserInput {
201 username,
202 email,
203 age,
204 preferences,
205 })
206 }
207}
208
209impl ToFieldValue for ValidatedUserInput {
210 fn to_field_value(&self) -> FieldValue {
211 match self.to_json() {
212 Ok(json_str) => FieldValue::from_json_object(json_str),
213 Err(_) => FieldValue::from_string("serialization_error".to_string()),
214 }
215 }
216}
217
218impl FromFieldValue for ValidatedUserInput {
219 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
220 // Try JSON object first
221 if let Ok(json_data) = value.as_json_object() {
222 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
223 field: field_name.to_string(),
224 message: format!("Failed to deserialize ValidatedUserInput from JSON: {}", e),
225 });
226 }
227
228 // Try binary object
229 if let Ok(binary_data) = value.as_binary_object() {
230 return Self::from_binary(binary_data).map_err(|e| {
231 SerializationError::ValidationFailed {
232 field: field_name.to_string(),
233 message: format!(
234 "Failed to deserialize ValidatedUserInput from binary: {}",
235 e
236 ),
237 }
238 });
239 }
240
241 Err(SerializationError::ValidationFailed {
242 field: field_name.to_string(),
243 message: format!(
244 "Expected JsonObject or BinaryObject for ValidatedUserInput, found {}",
245 value.type_name()
246 ),
247 })
248 }
249}
250
251/// Recovery helper for handling partial data
252#[derive(Debug, Clone, PartialEq)]
253pub struct RecoverableData {
254 pub critical_field: String,
255 pub important_field: Option<String>,
256 pub optional_field: Option<String>,
257 pub metadata: HashMap<String, String>,
258}
259
260impl StructSerializable for RecoverableData {
261 fn to_serializer(&self) -> StructSerializer {
262 StructSerializer::new()
263 .field("critical_field", &self.critical_field)
264 .field("important_field", &self.important_field)
265 .field("optional_field", &self.optional_field)
266 .field("metadata", &self.metadata)
267 }More examples
47 fn to_serializer(&self) -> StructSerializer {
48 StructSerializer::new()
49 .field("email", &self.email)
50 .field("phone", &self.phone)
51 .field("address_city", &self.address_city)
52 .field("address_state", &self.address_state)
53 .field("social_media", &self.social_media)
54 }
55
56 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
57 let email = deserializer.field("email")?;
58 let phone = deserializer.field("phone")?;
59 let address_city = deserializer.field("address_city")?;
60 let address_state = deserializer.field("address_state")?;
61 let social_media = deserializer.field("social_media")?;
62
63 Ok(ContactInfo {
64 email,
65 phone,
66 address_city,
67 address_state,
68 social_media,
69 })
70 }
71}
72
73impl ToFieldValue for ContactInfo {
74 fn to_field_value(&self) -> FieldValue {
75 match self.to_json() {
76 Ok(json_str) => FieldValue::from_json_object(json_str),
77 Err(_) => FieldValue::from_string("serialization_error".to_string()),
78 }
79 }
80}
81
82impl FromFieldValue for ContactInfo {
83 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
84 // Try JSON object first
85 if let Ok(json_data) = value.as_json_object() {
86 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
87 field: field_name.to_string(),
88 message: format!("Failed to deserialize ContactInfo from JSON: {}", e),
89 });
90 }
91
92 // Try binary object
93 if let Ok(binary_data) = value.as_binary_object() {
94 return Self::from_binary(binary_data).map_err(|e| {
95 SerializationError::ValidationFailed {
96 field: field_name.to_string(),
97 message: format!("Failed to deserialize ContactInfo from binary: {}", e),
98 }
99 });
100 }
101
102 Err(SerializationError::ValidationFailed {
103 field: field_name.to_string(),
104 message: format!(
105 "Expected JsonObject or BinaryObject for ContactInfo, found {}",
106 value.type_name()
107 ),
108 })
109 }
110}
111
112/// Address struct
113#[derive(Debug, Clone, PartialEq)]
114pub struct Address {
115 pub street: String,
116 pub city: String,
117 pub state: String,
118 pub postal_code: String,
119 pub country: String,
120}
121
122impl StructSerializable for Address {
123 fn to_serializer(&self) -> StructSerializer {
124 StructSerializer::new()
125 .field("street", &self.street)
126 .field("city", &self.city)
127 .field("state", &self.state)
128 .field("postal_code", &self.postal_code)
129 .field("country", &self.country)
130 }
131
132 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
133 let street = deserializer.field("street")?;
134 let city = deserializer.field("city")?;
135 let state = deserializer.field("state")?;
136 let postal_code = deserializer.field("postal_code")?;
137 let country = deserializer.field("country")?;
138
139 Ok(Address {
140 street,
141 city,
142 state,
143 postal_code,
144 country,
145 })
146 }
147}
148
149impl ToFieldValue for Address {
150 fn to_field_value(&self) -> FieldValue {
151 match self.to_json() {
152 Ok(json_str) => FieldValue::from_json_object(json_str),
153 Err(_) => FieldValue::from_string("serialization_error".to_string()),
154 }
155 }
156}
157
158impl FromFieldValue for Address {
159 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
160 // Try JSON object first
161 if let Ok(json_data) = value.as_json_object() {
162 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
163 field: field_name.to_string(),
164 message: format!("Failed to deserialize Address from JSON: {}", e),
165 });
166 }
167
168 // Try binary object
169 if let Ok(binary_data) = value.as_binary_object() {
170 return Self::from_binary(binary_data).map_err(|e| {
171 SerializationError::ValidationFailed {
172 field: field_name.to_string(),
173 message: format!("Failed to deserialize Address from binary: {}", e),
174 }
175 });
176 }
177
178 Err(SerializationError::ValidationFailed {
179 field: field_name.to_string(),
180 message: format!(
181 "Expected JsonObject or BinaryObject for Address, found {}",
182 value.type_name()
183 ),
184 })
185 }
186}
187
188/// Project information struct
189#[derive(Debug, Clone, PartialEq)]
190pub struct Project {
191 pub name: String,
192 pub description: String,
193 pub status: ProjectStatus,
194 pub budget: f64,
195 pub team_members: Vec<String>,
196 pub milestones: Vec<Milestone>,
197 pub metadata: HashMap<String, String>,
198}
199
200impl StructSerializable for Project {
201 fn to_serializer(&self) -> StructSerializer {
202 StructSerializer::new()
203 .field("name", &self.name)
204 .field("description", &self.description)
205 .field("status", &self.status)
206 .field("budget", &self.budget)
207 .field("team_members", &self.team_members)
208 .field("milestones", &self.milestones)
209 .field("metadata", &self.metadata)
210 }
211
212 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
213 let name = deserializer.field("name")?;
214 let description = deserializer.field("description")?;
215 let status = deserializer.field("status")?;
216 let budget = deserializer.field("budget")?;
217 let team_members = deserializer.field("team_members")?;
218 let milestones = deserializer.field("milestones")?;
219 let metadata = deserializer.field("metadata")?;
220
221 Ok(Project {
222 name,
223 description,
224 status,
225 budget,
226 team_members,
227 milestones,
228 metadata,
229 })
230 }
231}
232
233impl ToFieldValue for Project {
234 fn to_field_value(&self) -> FieldValue {
235 match self.to_json() {
236 Ok(json_str) => FieldValue::from_json_object(json_str),
237 Err(_) => FieldValue::from_string("serialization_error".to_string()),
238 }
239 }
240}
241
242impl FromFieldValue for Project {
243 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
244 // Try JSON object first
245 if let Ok(json_data) = value.as_json_object() {
246 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
247 field: field_name.to_string(),
248 message: format!("Failed to deserialize Project from JSON: {}", e),
249 });
250 }
251
252 // Try binary object
253 if let Ok(binary_data) = value.as_binary_object() {
254 return Self::from_binary(binary_data).map_err(|e| {
255 SerializationError::ValidationFailed {
256 field: field_name.to_string(),
257 message: format!("Failed to deserialize Project from binary: {}", e),
258 }
259 });
260 }
261
262 Err(SerializationError::ValidationFailed {
263 field: field_name.to_string(),
264 message: format!(
265 "Expected JsonObject or BinaryObject for Project, found {}",
266 value.type_name()
267 ),
268 })
269 }
270}
271
272/// Project status enumeration
273#[derive(Debug, Clone, PartialEq)]
274pub enum ProjectStatus {
275 Planning,
276 InProgress,
277 OnHold,
278 Completed,
279 Cancelled,
280}
281
282impl ToFieldValue for ProjectStatus {
283 fn to_field_value(&self) -> FieldValue {
284 let status_str = match self {
285 ProjectStatus::Planning => "planning",
286 ProjectStatus::InProgress => "in_progress",
287 ProjectStatus::OnHold => "on_hold",
288 ProjectStatus::Completed => "completed",
289 ProjectStatus::Cancelled => "cancelled",
290 };
291 FieldValue::from_string(status_str.to_string())
292 }
293}
294
295impl FromFieldValue for ProjectStatus {
296 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
297 match value {
298 FieldValue::String(s) => match s.as_str() {
299 "planning" => Ok(ProjectStatus::Planning),
300 "in_progress" => Ok(ProjectStatus::InProgress),
301 "on_hold" => Ok(ProjectStatus::OnHold),
302 "completed" => Ok(ProjectStatus::Completed),
303 "cancelled" => Ok(ProjectStatus::Cancelled),
304 _ => Err(SerializationError::ValidationFailed {
305 field: field_name.to_string(),
306 message: format!("Unknown project status: {}", s),
307 }),
308 },
309 _ => Err(SerializationError::ValidationFailed {
310 field: field_name.to_string(),
311 message: format!(
312 "Expected String for ProjectStatus, found {}",
313 value.type_name()
314 ),
315 }),
316 }
317 }
318}
319
320/// Project milestone struct
321#[derive(Debug, Clone, PartialEq)]
322pub struct Milestone {
323 pub name: String,
324 pub description: String,
325 pub due_date: String, // Simplified as string for this example
326 pub is_completed: bool,
327 pub progress_percentage: f32,
328 pub dependencies: Vec<String>,
329}
330
331impl StructSerializable for Milestone {
332 fn to_serializer(&self) -> StructSerializer {
333 StructSerializer::new()
334 .field("name", &self.name)
335 .field("description", &self.description)
336 .field("due_date", &self.due_date)
337 .field("is_completed", &self.is_completed)
338 .field("progress_percentage", &self.progress_percentage)
339 .field("dependencies", &self.dependencies)
340 }
341
342 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
343 let name = deserializer.field("name")?;
344 let description = deserializer.field("description")?;
345 let due_date = deserializer.field("due_date")?;
346 let is_completed = deserializer.field("is_completed")?;
347 let progress_percentage = deserializer.field("progress_percentage")?;
348 let dependencies = deserializer.field("dependencies")?;
349
350 Ok(Milestone {
351 name,
352 description,
353 due_date,
354 is_completed,
355 progress_percentage,
356 dependencies,
357 })
358 }
359}
360
361impl ToFieldValue for Milestone {
362 fn to_field_value(&self) -> FieldValue {
363 match self.to_json() {
364 Ok(json_str) => FieldValue::from_json_object(json_str),
365 Err(_) => FieldValue::from_string("serialization_error".to_string()),
366 }
367 }
368}
369
370impl FromFieldValue for Milestone {
371 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
372 // Try JSON object first
373 if let Ok(json_data) = value.as_json_object() {
374 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
375 field: field_name.to_string(),
376 message: format!("Failed to deserialize Milestone from JSON: {}", e),
377 });
378 }
379
380 // Try binary object
381 if let Ok(binary_data) = value.as_binary_object() {
382 return Self::from_binary(binary_data).map_err(|e| {
383 SerializationError::ValidationFailed {
384 field: field_name.to_string(),
385 message: format!("Failed to deserialize Milestone from binary: {}", e),
386 }
387 });
388 }
389
390 Err(SerializationError::ValidationFailed {
391 field: field_name.to_string(),
392 message: format!(
393 "Expected JsonObject or BinaryObject for Milestone, found {}",
394 value.type_name()
395 ),
396 })
397 }
398}
399
400/// Company struct with basic collections and nesting
401#[derive(Debug, Clone, PartialEq)]
402pub struct Company {
403 pub name: String,
404 pub founded_year: i32,
405 pub headquarters_city: String,
406 pub headquarters_state: String,
407 pub employee_count: usize,
408 pub department_names: Vec<String>,
409 pub active_project_names: Vec<String>,
410 pub company_metadata: HashMap<String, String>,
411}
412
413impl StructSerializable for Company {
414 fn to_serializer(&self) -> StructSerializer {
415 StructSerializer::new()
416 .field("name", &self.name)
417 .field("founded_year", &self.founded_year)
418 .field("headquarters_city", &self.headquarters_city)
419 .field("headquarters_state", &self.headquarters_state)
420 .field("employee_count", &self.employee_count)
421 .field("department_names", &self.department_names)
422 .field("active_project_names", &self.active_project_names)
423 .field("company_metadata", &self.company_metadata)
424 }
425
426 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
427 let name = deserializer.field("name")?;
428 let founded_year = deserializer.field("founded_year")?;
429 let headquarters_city = deserializer.field("headquarters_city")?;
430 let headquarters_state = deserializer.field("headquarters_state")?;
431 let employee_count = deserializer.field("employee_count")?;
432 let department_names = deserializer.field("department_names")?;
433 let active_project_names = deserializer.field("active_project_names")?;
434 let company_metadata = deserializer.field("company_metadata")?;
435
436 Ok(Company {
437 name,
438 founded_year,
439 headquarters_city,
440 headquarters_state,
441 employee_count,
442 department_names,
443 active_project_names,
444 company_metadata,
445 })
446 }
447}
448
449impl ToFieldValue for Company {
450 fn to_field_value(&self) -> FieldValue {
451 match self.to_json() {
452 Ok(json_str) => FieldValue::from_json_object(json_str),
453 Err(_) => FieldValue::from_string("serialization_error".to_string()),
454 }
455 }
456}
457
458impl FromFieldValue for Company {
459 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
460 // Try JSON object first
461 if let Ok(json_data) = value.as_json_object() {
462 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
463 field: field_name.to_string(),
464 message: format!("Failed to deserialize Company from JSON: {}", e),
465 });
466 }
467
468 // Try binary object
469 if let Ok(binary_data) = value.as_binary_object() {
470 return Self::from_binary(binary_data).map_err(|e| {
471 SerializationError::ValidationFailed {
472 field: field_name.to_string(),
473 message: format!("Failed to deserialize Company from binary: {}", e),
474 }
475 });
476 }
477
478 Err(SerializationError::ValidationFailed {
479 field: field_name.to_string(),
480 message: format!(
481 "Expected JsonObject or BinaryObject for Company, found {}",
482 value.type_name()
483 ),
484 })
485 }
486}
487
488/// Department struct
489#[derive(Debug, Clone, PartialEq)]
490pub struct Department {
491 pub name: String,
492 pub manager: String,
493 pub employee_count: u32,
494 pub budget: f64,
495 pub office_locations: Vec<Address>,
496}
497
498impl StructSerializable for Department {
499 fn to_serializer(&self) -> StructSerializer {
500 StructSerializer::new()
501 .field("name", &self.name)
502 .field("manager", &self.manager)
503 .field("employee_count", &self.employee_count)
504 .field("budget", &self.budget)
505 .field("office_locations", &self.office_locations)
506 }48 fn to_serializer(&self) -> StructSerializer {
49 StructSerializer::new()
50 .field("id", &self.id)
51 .field("username", &self.username)
52 .field("email", &self.email)
53 .field("age", &self.age)
54 .field("is_active", &self.is_active)
55 .field("score", &self.score)
56 }
57
58 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
59 let id = deserializer.field("id")?;
60 let username = deserializer.field("username")?;
61 let email = deserializer.field("email")?;
62 let age = deserializer.field("age")?;
63 let is_active = deserializer.field("is_active")?;
64 let score = deserializer.field("score")?;
65
66 Ok(UserProfile {
67 id,
68 username,
69 email,
70 age,
71 is_active,
72 score,
73 })
74 }
75}
76
77impl ToFieldValue for UserProfile {
78 fn to_field_value(&self) -> FieldValue {
79 // Convert to JSON and then parse as FieldValue for nested object handling
80 match self.to_json() {
81 Ok(json_str) => {
82 // For examples, we'll serialize as JSON string for simplicity
83 FieldValue::from_json_object(json_str)
84 }
85 Err(_) => FieldValue::from_string("serialization_error".to_string()),
86 }
87 }
88}
89
90impl FromFieldValue for UserProfile {
91 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
92 // Try JSON object first
93 if let Ok(json_data) = value.as_json_object() {
94 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
95 field: field_name.to_string(),
96 message: format!("Failed to deserialize UserProfile from JSON: {}", e),
97 });
98 }
99
100 // Try binary object
101 if let Ok(binary_data) = value.as_binary_object() {
102 return Self::from_binary(binary_data).map_err(|e| {
103 SerializationError::ValidationFailed {
104 field: field_name.to_string(),
105 message: format!("Failed to deserialize UserProfile from binary: {}", e),
106 }
107 });
108 }
109
110 Err(SerializationError::ValidationFailed {
111 field: field_name.to_string(),
112 message: format!(
113 "Expected JsonObject or BinaryObject for UserProfile, found {}",
114 value.type_name()
115 ),
116 })
117 }
118}
119
120/// Application settings struct with optional fields and collections
121#[derive(Debug, Clone, PartialEq)]
122pub struct AppSettings {
123 pub app_name: String,
124 pub version: String,
125 pub debug_mode: bool,
126 pub max_connections: u32,
127 pub timeout_seconds: f32,
128 pub features: Vec<String>,
129 pub environment_vars: HashMap<String, String>,
130 pub optional_database_url: Option<String>,
131}
132
133impl StructSerializable for AppSettings {
134 fn to_serializer(&self) -> StructSerializer {
135 StructSerializer::new()
136 .field("app_name", &self.app_name)
137 .field("version", &self.version)
138 .field("debug_mode", &self.debug_mode)
139 .field("max_connections", &self.max_connections)
140 .field("timeout_seconds", &self.timeout_seconds)
141 .field("features", &self.features)
142 .field("environment_vars", &self.environment_vars)
143 .field("optional_database_url", &self.optional_database_url)
144 }48 fn to_serializer(&self) -> StructSerializer {
49 StructSerializer::new()
50 .field("operation", &self.operation)
51 .field("duration_micros", &self.duration_micros)
52 .field("memory_usage_bytes", &self.memory_usage_bytes)
53 .field("cpu_usage_percent", &self.cpu_usage_percent)
54 .field("throughput_ops_per_sec", &self.throughput_ops_per_sec)
55 .field("metadata", &self.metadata)
56 }
57
58 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
59 let operation = deserializer.field("operation")?;
60 let duration_micros = deserializer.field("duration_micros")?;
61 let memory_usage_bytes = deserializer.field("memory_usage_bytes")?;
62 let cpu_usage_percent = deserializer.field("cpu_usage_percent")?;
63 let throughput_ops_per_sec = deserializer.field("throughput_ops_per_sec")?;
64 let metadata = deserializer.field("metadata")?;
65
66 Ok(PerformanceMetrics {
67 operation,
68 duration_micros,
69 memory_usage_bytes,
70 cpu_usage_percent,
71 throughput_ops_per_sec,
72 metadata,
73 })
74 }
75}
76
77impl ToFieldValue for PerformanceMetrics {
78 fn to_field_value(&self) -> FieldValue {
79 match self.to_json() {
80 Ok(json_str) => FieldValue::from_json_object(json_str),
81 Err(_) => FieldValue::from_string("serialization_error".to_string()),
82 }
83 }
84}
85
86impl FromFieldValue for PerformanceMetrics {
87 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
88 // Try JSON object first
89 if let Ok(json_data) = value.as_json_object() {
90 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
91 field: field_name.to_string(),
92 message: format!("Failed to deserialize PerformanceMetrics from JSON: {}", e),
93 });
94 }
95
96 // Try binary object
97 if let Ok(binary_data) = value.as_binary_object() {
98 return Self::from_binary(binary_data).map_err(|e| {
99 SerializationError::ValidationFailed {
100 field: field_name.to_string(),
101 message: format!(
102 "Failed to deserialize PerformanceMetrics from binary: {}",
103 e
104 ),
105 }
106 });
107 }
108
109 Err(SerializationError::ValidationFailed {
110 field: field_name.to_string(),
111 message: format!(
112 "Expected JsonObject or BinaryObject for PerformanceMetrics, found {}",
113 value.type_name()
114 ),
115 })
116 }
117}
118
119/// Large dataset for performance testing
120#[derive(Debug, Clone, PartialEq)]
121pub struct LargeDataset {
122 pub name: String,
123 pub values: Vec<f32>, // Changed from f64 to f32 (supported)
124 pub labels: Vec<String>,
125 pub feature_count: usize, // Simplified from Vec<Vec<f32>> to just a count
126 pub feature_dimension: usize, // Store dimensions separately
127 pub metadata: HashMap<String, String>,
128 pub timestamp_count: usize, // Simplified from Vec<u64> to just count
129}
130
131impl StructSerializable for LargeDataset {
132 fn to_serializer(&self) -> StructSerializer {
133 StructSerializer::new()
134 .field("name", &self.name)
135 .field("values", &self.values)
136 .field("labels", &self.labels)
137 .field("feature_count", &self.feature_count)
138 .field("feature_dimension", &self.feature_dimension)
139 .field("metadata", &self.metadata)
140 .field("timestamp_count", &self.timestamp_count)
141 }
142
143 fn from_deserializer(deserializer: &mut StructDeserializer) -> SerializationResult<Self> {
144 let name = deserializer.field("name")?;
145 let values = deserializer.field("values")?;
146 let labels = deserializer.field("labels")?;
147 let feature_count = deserializer.field("feature_count")?;
148 let feature_dimension = deserializer.field("feature_dimension")?;
149 let metadata = deserializer.field("metadata")?;
150 let timestamp_count = deserializer.field("timestamp_count")?;
151
152 Ok(LargeDataset {
153 name,
154 values,
155 labels,
156 feature_count,
157 feature_dimension,
158 metadata,
159 timestamp_count,
160 })
161 }
162}
163
164impl ToFieldValue for LargeDataset {
165 fn to_field_value(&self) -> FieldValue {
166 match self.to_json() {
167 Ok(json_str) => FieldValue::from_json_object(json_str),
168 Err(_) => FieldValue::from_string("serialization_error".to_string()),
169 }
170 }
171}
172
173impl FromFieldValue for LargeDataset {
174 fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
175 // Try JSON object first
176 if let Ok(json_data) = value.as_json_object() {
177 return Self::from_json(json_data).map_err(|e| SerializationError::ValidationFailed {
178 field: field_name.to_string(),
179 message: format!("Failed to deserialize LargeDataset from JSON: {}", e),
180 });
181 }
182
183 // Try binary object
184 if let Ok(binary_data) = value.as_binary_object() {
185 return Self::from_binary(binary_data).map_err(|e| {
186 SerializationError::ValidationFailed {
187 field: field_name.to_string(),
188 message: format!("Failed to deserialize LargeDataset from binary: {}", e),
189 }
190 });
191 }
192
193 Err(SerializationError::ValidationFailed {
194 field: field_name.to_string(),
195 message: format!(
196 "Expected JsonObject or BinaryObject for LargeDataset, found {}",
197 value.type_name()
198 ),
199 })
200 }
201}
202
203/// Configuration data (typical JSON use case)
204#[derive(Debug, Clone, PartialEq)]
205pub struct Configuration {
206 pub version: String,
207 pub debug_enabled: bool,
208 pub log_level: String,
209 pub database_settings: HashMap<String, String>,
210 pub feature_flags_enabled: bool, // Simplified from HashMap<String, bool>
211 pub max_connections: f32, // Simplified from HashMap<String, f64>
212 pub timeout_seconds: f32,
213}
214
215impl StructSerializable for Configuration {
216 fn to_serializer(&self) -> StructSerializer {
217 StructSerializer::new()
218 .field("version", &self.version)
219 .field("debug_enabled", &self.debug_enabled)
220 .field("log_level", &self.log_level)
221 .field("database_settings", &self.database_settings)
222 .field("feature_flags_enabled", &self.feature_flags_enabled)
223 .field("max_connections", &self.max_connections)
224 .field("timeout_seconds", &self.timeout_seconds)
225 }Sourcepub fn to_json(self) -> SerializationResult<String>
pub fn to_json(self) -> SerializationResult<String>
Converts the struct to a JSON string
Serializes all registered fields to a JSON string format. The JSON output is human-readable and maintains field order and type information.
This method consumes the serializer, preventing further field additions.
§Returns
Ok(String) containing the JSON representation on success
Err(SerializationError) if serialization fails
§Examples
Serializes all fields to human-readable JSON format with proper escaping.
Sourcepub fn to_binary(self) -> SerializationResult<Vec<u8>>
pub fn to_binary(self) -> SerializationResult<Vec<u8>>
Converts the struct to binary data
Serializes all registered fields to a compact binary format. The binary output is platform-independent and optimized for fast serialization and deserialization.
This method consumes the serializer, preventing further field additions.
§Returns
Ok(Vec<u8>) containing the binary representation on success
Err(SerializationError) if serialization fails
§Examples
Serializes all fields to compact binary format for efficient storage.
Sourcepub fn save_json<P: AsRef<Path>>(self, path: P) -> SerializationResult<()>
pub fn save_json<P: AsRef<Path>>(self, path: P) -> SerializationResult<()>
Saves the struct to a JSON file
Serializes all registered fields to JSON format and writes the result to the specified file path. The file is created if it doesn’t exist, or truncated if it already exists.
This method consumes the serializer, preventing further field additions.
§Arguments
path- File path where the JSON data should be written
§Returns
Ok(()) on successful file write
Err(SerializationError) if serialization or file I/O fails
§Examples
Saves serialized data to a JSON file with proper file I/O handling.
Sourcepub fn save_binary<P: AsRef<Path>>(self, path: P) -> SerializationResult<()>
pub fn save_binary<P: AsRef<Path>>(self, path: P) -> SerializationResult<()>
Saves the struct to a binary file
Serializes all registered fields to binary format and writes the result to the specified file path. The file is created if it doesn’t exist, or truncated if it already exists.
This method consumes the serializer, preventing further field additions.
§Arguments
path- File path where the binary data should be written
§Returns
Ok(()) on successful file write
Err(SerializationError) if serialization or file I/O fails
§Examples
Saves serialized data to a binary file with proper file I/O handling.