train_station/serialization/core/
impls.rs

1//! Core serialization trait implementations for standard Rust types
2//!
3//! This module provides comprehensive implementations of `ToFieldValue` and `FromFieldValue` traits
4//! for all standard Rust types and common collections. These implementations enable seamless
5//! serialization and deserialization of structured data through the core serialization framework.
6//!
7//! # Purpose
8//!
9//! The implementations module serves as the foundation for type-safe serialization by providing:
10//! - Automatic conversion between Rust types and `FieldValue` representations
11//! - Support for primitive types, collections, and custom serializable types
12//! - JSON-compatible serialization formats for human-readable data
13//! - Binary-compatible formats for efficient storage and transmission
14//! - Error handling with detailed validation messages
15//!
16//! # Supported Types
17//!
18//! ## Primitive Types
19//! - **Integers**: `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64`, `usize`
20//! - **Floating Point**: `f32`, `f64`
21//! - **Boolean**: `bool`
22//! - **String Types**: `String`, `&str`, `str`
23//!
24//! ## Collections
25//! - **Vectors**: `Vec<T>` for all supported types
26//! - **Arrays**: Fixed-size arrays for common types
27//! - **HashMaps**: `HashMap<String, String>` for key-value data
28//! - **Options**: `Option<T>` for optional values
29//!
30//! ## Custom Types
31//! - **Serializable Objects**: Types implementing `Serializable` trait
32//! - **Struct Types**: Types implementing `StructSerializable` trait
33//!
34//! # Serialization Strategy
35//!
36//! ## JSON Compatibility
37//! - Numeric vectors are serialized as human-readable arrays
38//! - String data maintains UTF-8 encoding
39//! - Boolean values are preserved as true/false
40//! - Collections maintain their structure and relationships
41//!
42//! ## Binary Efficiency
43//! - Raw byte arrays use compact binary representation
44//! - Numeric data uses native endianness
45//! - String data includes length prefixes for efficient parsing
46//! - Collections use optimized storage formats
47//!
48//! ## Error Handling
49//! - Detailed validation error messages with field names
50//! - Type mismatch detection with clear error descriptions
51//! - Array element validation with indexed error reporting
52//! - Backward compatibility for legacy data formats
53//!
54//! # Usage Patterns
55//!
56//! The trait implementations are automatically used when:
57//! - Serializing structs with `StructSerializer`
58//! - Deserializing data with `StructDeserializer`
59//! - Converting between `FieldValue` and concrete types
60//! - Handling nested serializable objects
61//!
62//! # Thread Safety
63//!
64//! All implementations are thread-safe and can be used concurrently across multiple threads.
65//! No shared state is maintained between serialization operations.
66
67use super::error::{SerializationError, SerializationResult};
68use super::traits::{FromFieldValue, StructSerializable, ToFieldValue};
69use super::types::FieldValue;
70use std::collections::HashMap;
71
72// ===== ToFieldValue implementations =====
73
74/// Converts boolean values to FieldValue representation
75///
76/// Boolean values are stored as native boolean types in both JSON and binary formats,
77/// maintaining their logical meaning across serialization boundaries.
78impl ToFieldValue for bool {
79    fn to_field_value(&self) -> FieldValue {
80        FieldValue::from_bool(*self)
81    }
82}
83
84/// Converts 8-bit signed integers to FieldValue representation
85///
86/// Small integers are stored efficiently in both JSON and binary formats,
87/// with proper range validation during deserialization.
88impl ToFieldValue for i8 {
89    fn to_field_value(&self) -> FieldValue {
90        FieldValue::from_i8(*self)
91    }
92}
93
94/// Converts 16-bit signed integers to FieldValue representation
95///
96/// Medium-sized integers provide a balance between range and storage efficiency
97/// for most common use cases.
98impl ToFieldValue for i16 {
99    fn to_field_value(&self) -> FieldValue {
100        FieldValue::from_i16(*self)
101    }
102}
103
104/// Converts 32-bit signed integers to FieldValue representation
105///
106/// Standard integer type used for most numeric data, providing sufficient range
107/// for typical application needs.
108impl ToFieldValue for i32 {
109    fn to_field_value(&self) -> FieldValue {
110        FieldValue::from_i32(*self)
111    }
112}
113
114/// Converts 64-bit signed integers to FieldValue representation
115///
116/// Large integer type for values requiring extended range, such as timestamps,
117/// file sizes, or large counts.
118impl ToFieldValue for i64 {
119    fn to_field_value(&self) -> FieldValue {
120        FieldValue::from_i64(*self)
121    }
122}
123
124/// Converts 8-bit unsigned integers to FieldValue representation
125///
126/// Small unsigned integers for values that are always non-negative,
127/// such as array indices or small counts.
128impl ToFieldValue for u8 {
129    fn to_field_value(&self) -> FieldValue {
130        FieldValue::from_u8(*self)
131    }
132}
133
134/// Converts 16-bit unsigned integers to FieldValue representation
135///
136/// Medium-sized unsigned integers for values requiring positive range
137/// with moderate storage efficiency.
138impl ToFieldValue for u16 {
139    fn to_field_value(&self) -> FieldValue {
140        FieldValue::from_u16(*self)
141    }
142}
143
144/// Converts 32-bit unsigned integers to FieldValue representation
145///
146/// Standard unsigned integer type for large positive values,
147/// commonly used for sizes, counts, and identifiers.
148impl ToFieldValue for u32 {
149    fn to_field_value(&self) -> FieldValue {
150        FieldValue::from_u32(*self)
151    }
152}
153
154/// Converts 64-bit unsigned integers to FieldValue representation
155///
156/// Large unsigned integer type for very large positive values,
157/// such as memory addresses or large file sizes.
158impl ToFieldValue for u64 {
159    fn to_field_value(&self) -> FieldValue {
160        FieldValue::from_u64(*self)
161    }
162}
163
164/// Converts platform-specific size integers to FieldValue representation
165///
166/// Size type that adapts to the platform's pointer size, commonly used
167/// for array lengths, memory sizes, and indexing operations.
168impl ToFieldValue for usize {
169    fn to_field_value(&self) -> FieldValue {
170        FieldValue::from_usize(*self)
171    }
172}
173
174/// Converts 32-bit floating point numbers to FieldValue representation
175///
176/// Single-precision floating point for values requiring decimal precision
177/// with moderate storage requirements.
178impl ToFieldValue for f32 {
179    fn to_field_value(&self) -> FieldValue {
180        FieldValue::from_f32(*self)
181    }
182}
183
184/// Converts 64-bit floating point numbers to FieldValue representation
185///
186/// Double-precision floating point for values requiring high decimal precision,
187/// commonly used for scientific calculations and financial data.
188impl ToFieldValue for f64 {
189    fn to_field_value(&self) -> FieldValue {
190        FieldValue::from_f64(*self)
191    }
192}
193
194/// Converts string slices to FieldValue representation
195///
196/// String slices are converted to owned strings for serialization,
197/// maintaining UTF-8 encoding and preserving all character data.
198impl ToFieldValue for str {
199    fn to_field_value(&self) -> FieldValue {
200        FieldValue::from_string_slice(self)
201    }
202}
203
204/// Converts string references to FieldValue representation
205///
206/// String references are converted to owned strings for serialization,
207/// ensuring data ownership and thread safety.
208impl ToFieldValue for &str {
209    fn to_field_value(&self) -> FieldValue {
210        FieldValue::from_string_slice(self)
211    }
212}
213
214/// Converts owned strings to FieldValue representation
215///
216/// Owned strings are cloned for serialization to maintain data ownership
217/// while preserving the original string for further use.
218impl ToFieldValue for String {
219    fn to_field_value(&self) -> FieldValue {
220        FieldValue::from_string(self.clone())
221    }
222}
223
224/// Converts byte slices to FieldValue representation
225///
226/// Byte slices are converted to owned byte vectors for serialization,
227/// preserving raw binary data without encoding assumptions.
228impl ToFieldValue for [u8] {
229    fn to_field_value(&self) -> FieldValue {
230        FieldValue::from_bytes(self.to_vec())
231    }
232}
233
234/// Converts byte vectors to FieldValue representation
235///
236/// Byte vectors are cloned for serialization to maintain data ownership
237/// while preserving the original vector for further use.
238impl ToFieldValue for Vec<u8> {
239    fn to_field_value(&self) -> FieldValue {
240        FieldValue::from_bytes(self.clone())
241    }
242}
243
244/// Converts integer vectors to FieldValue representation
245///
246/// Integer vectors are serialized as JSON-compatible arrays for human readability,
247/// while maintaining efficient binary storage for performance-critical applications.
248impl ToFieldValue for Vec<i32> {
249    fn to_field_value(&self) -> FieldValue {
250        // Use Array format for JSON compatibility (human-readable numbers)
251        let mut values = Vec::new();
252        for &val in self {
253            values.push(FieldValue::from_i32(val));
254        }
255        FieldValue::from_array(values)
256    }
257}
258
259/// Converts size vectors to FieldValue representation
260///
261/// Size vectors are serialized as JSON-compatible arrays, adapting to the platform's
262/// pointer size while maintaining cross-platform compatibility.
263impl ToFieldValue for Vec<usize> {
264    fn to_field_value(&self) -> FieldValue {
265        // Use Array format for JSON compatibility (human-readable numbers)
266        let mut values = Vec::new();
267        for &val in self {
268            values.push(FieldValue::from_usize(val));
269        }
270        FieldValue::from_array(values)
271    }
272}
273
274/// Converts single-precision float vectors to FieldValue representation
275///
276/// Float vectors are serialized as JSON-compatible arrays to maintain human readability
277/// while preserving numerical precision for scientific and engineering applications.
278impl ToFieldValue for Vec<f32> {
279    fn to_field_value(&self) -> FieldValue {
280        // CRITICAL: JSON must remain human-readable as number arrays
281        // Use Array format for JSON compatibility (not bytes)
282        let mut values = Vec::new();
283        for &val in self {
284            values.push(FieldValue::from_f32(val));
285        }
286        FieldValue::from_array(values)
287    }
288}
289
290/// Converts double-precision float vectors to FieldValue representation
291///
292/// Double-precision float vectors maintain high numerical accuracy for scientific
293/// calculations while providing JSON-compatible serialization for data exchange.
294impl ToFieldValue for Vec<f64> {
295    fn to_field_value(&self) -> FieldValue {
296        // Use Array format for JSON compatibility (human-readable numbers)
297        let mut values = Vec::new();
298        for &val in self {
299            values.push(FieldValue::from_f64(val));
300        }
301        FieldValue::from_array(values)
302    }
303}
304
305/// Converts boolean vectors to FieldValue representation
306///
307/// Boolean vectors are serialized as JSON-compatible arrays, maintaining logical
308/// relationships and providing clear true/false representation.
309impl ToFieldValue for Vec<bool> {
310    fn to_field_value(&self) -> FieldValue {
311        let mut values = Vec::new();
312        for &val in self {
313            values.push(FieldValue::from_bool(val));
314        }
315        FieldValue::from_array(values)
316    }
317}
318
319/// Converts string vectors to FieldValue representation
320///
321/// String vectors are serialized as JSON-compatible arrays, preserving UTF-8 encoding
322/// and maintaining string relationships for text processing applications.
323impl ToFieldValue for Vec<String> {
324    fn to_field_value(&self) -> FieldValue {
325        let mut values = Vec::new();
326        for val in self {
327            values.push(FieldValue::from_string(val.clone()));
328        }
329        FieldValue::from_array(values)
330    }
331}
332
333/// Converts string hash maps to FieldValue representation
334///
335/// String hash maps are serialized as JSON objects, maintaining key-value relationships
336/// for configuration data, metadata, and structured text storage.
337impl ToFieldValue for HashMap<String, String> {
338    fn to_field_value(&self) -> FieldValue {
339        let mut object = HashMap::new();
340        for (key, value) in self {
341            object.insert(key.clone(), FieldValue::from_string(value.clone()));
342        }
343        FieldValue::from_object(object)
344    }
345}
346
347/// Converts fixed-size byte arrays to FieldValue representation
348///
349/// Fixed-size byte arrays are converted to vectors for serialization,
350/// maintaining the original data while providing flexible storage.
351impl<const N: usize> ToFieldValue for [u8; N] {
352    fn to_field_value(&self) -> FieldValue {
353        FieldValue::from_bytes(self.to_vec())
354    }
355}
356
357/// Converts fixed-size integer arrays to FieldValue representation
358///
359/// Fixed-size integer arrays are serialized as JSON-compatible arrays,
360/// maintaining the original structure while providing human-readable format.
361impl<const N: usize> ToFieldValue for [i32; N] {
362    fn to_field_value(&self) -> FieldValue {
363        let mut values = Vec::new();
364        for &val in self {
365            values.push(FieldValue::from_i32(val));
366        }
367        FieldValue::from_array(values)
368    }
369}
370
371/// Converts optional values to FieldValue representation
372///
373/// Optional values are serialized with explicit None/Some representation,
374/// maintaining the optional nature of the data across serialization boundaries.
375impl<T> ToFieldValue for Option<T>
376where
377    T: ToFieldValue,
378{
379    fn to_field_value(&self) -> FieldValue {
380        match self {
381            Some(value) => FieldValue::from_optional(Some(value.to_field_value())),
382            None => FieldValue::from_optional(None),
383        }
384    }
385}
386
387/// Converts serializable struct vectors to FieldValue representation
388///
389/// Struct vectors are serialized as arrays of objects, maintaining the structure
390/// and relationships of complex data while providing JSON-compatible format.
391impl<T> ToFieldValue for Vec<T>
392where
393    T: StructSerializable,
394{
395    fn to_field_value(&self) -> FieldValue {
396        let field_values: Vec<FieldValue> = self
397            .iter()
398            .map(|item| {
399                // Convert struct to field-value map and then to Object
400                let serializer = item.to_serializer();
401                let mut object = HashMap::new();
402                for (field_name, field_value) in serializer.fields {
403                    object.insert(field_name, field_value);
404                }
405                FieldValue::from_object(object)
406            })
407            .collect();
408        FieldValue::from_array(field_values)
409    }
410}
411
412/// Converts serializable objects to FieldValue representation
413///
414/// Serializable objects are converted using their JSON representation,
415/// providing format-aware serialization for complex data structures.
416impl<T> ToFieldValue for T
417where
418    T: crate::serialization::Serializable,
419{
420    fn to_field_value(&self) -> FieldValue {
421        // This will be handled by format-aware serialization
422        // For now, default to JSON serialization
423        match self.to_json() {
424            Ok(json_str) => FieldValue::from_json_object(json_str),
425            Err(_) => FieldValue::from_string("ERROR: Failed to serialize object".to_string()),
426        }
427    }
428}
429
430// ===== FromFieldValue implementations =====
431
432/// Converts FieldValue representation back to boolean values
433///
434/// Validates that the FieldValue contains a boolean type and returns
435/// the corresponding boolean value with detailed error reporting.
436impl FromFieldValue for bool {
437    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
438        value
439            .as_bool()
440            .map_err(|_| SerializationError::ValidationFailed {
441                field: field_name.to_string(),
442                message: format!("Expected bool, found {:?}", value),
443            })
444    }
445}
446
447/// Converts FieldValue representation back to 8-bit signed integers
448///
449/// Validates that the FieldValue contains an i8 type and returns
450/// the corresponding integer value with range validation.
451impl FromFieldValue for i8 {
452    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
453        value
454            .as_i8()
455            .map_err(|_| SerializationError::ValidationFailed {
456                field: field_name.to_string(),
457                message: format!("Expected i8, found {:?}", value),
458            })
459    }
460}
461
462/// Converts FieldValue representation back to 16-bit signed integers
463///
464/// Validates that the FieldValue contains an i16 type and returns
465/// the corresponding integer value with range validation.
466impl FromFieldValue for i16 {
467    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
468        value
469            .as_i16()
470            .map_err(|_| SerializationError::ValidationFailed {
471                field: field_name.to_string(),
472                message: format!("Expected i16, found {:?}", value),
473            })
474    }
475}
476
477/// Converts FieldValue representation back to 32-bit signed integers
478///
479/// Validates that the FieldValue contains an i32 type and returns
480/// the corresponding integer value with range validation.
481impl FromFieldValue for i32 {
482    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
483        value
484            .as_i32()
485            .map_err(|_| SerializationError::ValidationFailed {
486                field: field_name.to_string(),
487                message: format!("Expected i32, found {:?}", value),
488            })
489    }
490}
491
492/// Converts FieldValue representation back to 64-bit signed integers
493///
494/// Validates that the FieldValue contains an i64 type and returns
495/// the corresponding integer value with range validation.
496impl FromFieldValue for i64 {
497    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
498        value
499            .as_i64()
500            .map_err(|_| SerializationError::ValidationFailed {
501                field: field_name.to_string(),
502                message: format!("Expected i64, found {:?}", value),
503            })
504    }
505}
506
507/// Converts FieldValue representation back to 8-bit unsigned integers
508///
509/// Validates that the FieldValue contains a u8 type and returns
510/// the corresponding integer value with range validation.
511impl FromFieldValue for u8 {
512    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
513        value
514            .as_u8()
515            .map_err(|_| SerializationError::ValidationFailed {
516                field: field_name.to_string(),
517                message: format!("Expected u8, found {:?}", value),
518            })
519    }
520}
521
522/// Converts FieldValue representation back to 16-bit unsigned integers
523///
524/// Validates that the FieldValue contains a u16 type and returns
525/// the corresponding integer value with range validation.
526impl FromFieldValue for u16 {
527    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
528        value
529            .as_u16()
530            .map_err(|_| SerializationError::ValidationFailed {
531                field: field_name.to_string(),
532                message: format!("Expected u16, found {:?}", value),
533            })
534    }
535}
536
537/// Converts FieldValue representation back to 32-bit unsigned integers
538///
539/// Validates that the FieldValue contains a u32 type and returns
540/// the corresponding integer value with range validation.
541impl FromFieldValue for u32 {
542    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
543        value
544            .as_u32()
545            .map_err(|_| SerializationError::ValidationFailed {
546                field: field_name.to_string(),
547                message: format!("Expected u32, found {:?}", value),
548            })
549    }
550}
551
552/// Converts FieldValue representation back to 64-bit unsigned integers
553///
554/// Validates that the FieldValue contains a u64 type and returns
555/// the corresponding integer value with range validation.
556impl FromFieldValue for u64 {
557    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
558        value
559            .as_u64()
560            .map_err(|_| SerializationError::ValidationFailed {
561                field: field_name.to_string(),
562                message: format!("Expected u64, found {:?}", value),
563            })
564    }
565}
566
567/// Converts FieldValue representation back to platform-specific size integers
568///
569/// Validates that the FieldValue contains a usize type and returns
570/// the corresponding integer value with platform-appropriate range validation.
571impl FromFieldValue for usize {
572    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
573        value
574            .as_usize()
575            .map_err(|_| SerializationError::ValidationFailed {
576                field: field_name.to_string(),
577                message: format!("Expected usize, found {:?}", value),
578            })
579    }
580}
581
582/// Converts FieldValue representation back to 32-bit floating point numbers
583///
584/// Validates that the FieldValue contains an f32 type and returns
585/// the corresponding floating point value with precision validation.
586impl FromFieldValue for f32 {
587    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
588        value
589            .as_f32()
590            .map_err(|_| SerializationError::ValidationFailed {
591                field: field_name.to_string(),
592                message: format!("Expected f32, found {:?}", value),
593            })
594    }
595}
596
597/// Converts FieldValue representation back to 64-bit floating point numbers
598///
599/// Validates that the FieldValue contains an f64 type and returns
600/// the corresponding floating point value with precision validation.
601impl FromFieldValue for f64 {
602    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
603        value
604            .as_f64()
605            .map_err(|_| SerializationError::ValidationFailed {
606                field: field_name.to_string(),
607                message: format!("Expected f64, found {:?}", value),
608            })
609    }
610}
611
612/// Converts FieldValue representation back to byte vectors
613///
614/// Validates that the FieldValue contains byte data and returns
615/// the corresponding byte vector with proper error handling.
616impl FromFieldValue for Vec<u8> {
617    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
618        value
619            .to_bytes()
620            .map_err(|_| SerializationError::ValidationFailed {
621                field: field_name.to_string(),
622                message: format!("Expected Vec<u8>, found {:?}", value),
623            })
624    }
625}
626
627/// Converts FieldValue representation back to integer vectors
628///
629/// Validates that the FieldValue contains an array of integers and returns
630/// the corresponding vector with element-by-element validation.
631impl FromFieldValue for Vec<i32> {
632    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
633        // Use Array format for JSON compatibility (human-readable numbers)
634        value
635            .as_array()
636            .and_then(|array| {
637                let mut result = Vec::new();
638                for field_value in array {
639                    result.push(field_value.as_i32().map_err(|_| {
640                        SerializationError::ValidationFailed {
641                            field: field_name.to_string(),
642                            message: format!("Expected i32 in array, found {:?}", field_value),
643                        }
644                    })?);
645                }
646                Ok(result)
647            })
648            .map_err(|_| SerializationError::ValidationFailed {
649                field: field_name.to_string(),
650                message: format!("Expected Vec<i32>, found {:?}", value),
651            })
652    }
653}
654
655/// Converts FieldValue representation back to size vectors
656///
657/// Validates that the FieldValue contains an array of size integers and returns
658/// the corresponding vector with platform-appropriate validation.
659impl FromFieldValue for Vec<usize> {
660    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
661        // Use Array format for JSON compatibility (human-readable numbers)
662        value
663            .as_array()
664            .and_then(|array| {
665                let mut result = Vec::new();
666                for field_value in array {
667                    result.push(field_value.as_usize().map_err(|_| {
668                        SerializationError::ValidationFailed {
669                            field: field_name.to_string(),
670                            message: format!("Expected usize in array, found {:?}", field_value),
671                        }
672                    })?);
673                }
674                Ok(result)
675            })
676            .map_err(|_| SerializationError::ValidationFailed {
677                field: field_name.to_string(),
678                message: format!("Expected Vec<usize>, found {:?}", value),
679            })
680    }
681}
682
683/// Converts FieldValue representation back to single-precision float vectors
684///
685/// Validates that the FieldValue contains an array of f32 values and returns
686/// the corresponding vector with indexed error reporting for debugging.
687impl FromFieldValue for Vec<f32> {
688    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
689        // Use Array format for JSON compatibility (human-readable numbers)
690        value
691            .as_array()
692            .and_then(|array| {
693                let mut result = Vec::new();
694                for (index, field_value) in array.iter().enumerate() {
695                    let element_field_name = format!("{}[{}]", field_name, index);
696                    result.push(field_value.as_f32().map_err(|_| {
697                        SerializationError::ValidationFailed {
698                            field: element_field_name,
699                            message: format!("Expected f32 in array, found {:?}", field_value),
700                        }
701                    })?);
702                }
703                Ok(result)
704            })
705            .map_err(|_| SerializationError::ValidationFailed {
706                field: field_name.to_string(),
707                message: format!("Expected Vec<f32>, found {:?}", value),
708            })
709    }
710}
711
712/// Converts FieldValue representation back to double-precision float vectors
713///
714/// Validates that the FieldValue contains an array of f64 values and returns
715/// the corresponding vector with precision validation.
716impl FromFieldValue for Vec<f64> {
717    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
718        // Use Array format for JSON compatibility (human-readable numbers)
719        value
720            .as_array()
721            .and_then(|array| {
722                let mut result = Vec::new();
723                for field_value in array {
724                    result.push(field_value.as_f64().map_err(|_| {
725                        SerializationError::ValidationFailed {
726                            field: field_name.to_string(),
727                            message: format!("Expected f64 in array, found {:?}", field_value),
728                        }
729                    })?);
730                }
731                Ok(result)
732            })
733            .map_err(|_| SerializationError::ValidationFailed {
734                field: field_name.to_string(),
735                message: format!("Expected Vec<f64>, found {:?}", value),
736            })
737    }
738}
739
740/// Converts FieldValue representation back to boolean vectors
741///
742/// Validates that the FieldValue contains an array of boolean values and returns
743/// the corresponding vector with logical validation.
744impl FromFieldValue for Vec<bool> {
745    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
746        value
747            .as_array()
748            .and_then(|array| {
749                let mut result = Vec::new();
750                for field_value in array {
751                    result.push(field_value.as_bool().map_err(|_| {
752                        SerializationError::ValidationFailed {
753                            field: field_name.to_string(),
754                            message: format!("Expected bool in array, found {:?}", field_value),
755                        }
756                    })?);
757                }
758                Ok(result)
759            })
760            .map_err(|_| SerializationError::ValidationFailed {
761                field: field_name.to_string(),
762                message: format!("Expected Vec<bool>, found {:?}", value),
763            })
764    }
765}
766
767/// Converts FieldValue representation back to string vectors
768///
769/// Validates that the FieldValue contains an array of strings and returns
770/// the corresponding vector with UTF-8 validation.
771impl FromFieldValue for Vec<String> {
772    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
773        value
774            .as_array()
775            .and_then(|array| {
776                let mut result = Vec::new();
777                for field_value in array {
778                    result.push(
779                        field_value
780                            .as_string()
781                            .map(|s| s.to_string())
782                            .map_err(|_| SerializationError::ValidationFailed {
783                                field: field_name.to_string(),
784                                message: format!(
785                                    "Expected String in array, found {:?}",
786                                    field_value
787                                ),
788                            })?,
789                    );
790                }
791                Ok(result)
792            })
793            .map_err(|_| SerializationError::ValidationFailed {
794                field: field_name.to_string(),
795                message: format!("Expected Vec<String>, found {:?}", value),
796            })
797    }
798}
799
800/// Converts FieldValue representation back to string hash maps
801///
802/// Validates that the FieldValue contains key-value pairs and returns
803/// the corresponding hash map with flexible value type conversion.
804impl FromFieldValue for HashMap<String, String> {
805    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
806        match value {
807            FieldValue::Object(object) => {
808                let mut result = HashMap::new();
809                for (key, field_value) in object {
810                    // Convert any FieldValue to a string representation for HashMap<String, String>
811                    let string_value = match field_value {
812                        FieldValue::String(s) => s,
813                        FieldValue::Bool(b) => b.to_string(),
814                        FieldValue::I8(i) => i.to_string(),
815                        FieldValue::I16(i) => i.to_string(),
816                        FieldValue::I32(i) => i.to_string(),
817                        FieldValue::I64(i) => i.to_string(),
818                        FieldValue::U8(u) => u.to_string(),
819                        FieldValue::U16(u) => u.to_string(),
820                        FieldValue::U32(u) => u.to_string(),
821                        FieldValue::U64(u) => u.to_string(),
822                        FieldValue::Usize(u) => u.to_string(),
823                        FieldValue::F32(f) => f.to_string(),
824                        FieldValue::F64(f) => f.to_string(),
825                        FieldValue::Bytes(bytes) => {
826                            // Try to interpret bytes as hex string (if that's how they were stored)
827                            String::from_utf8(bytes.clone()).unwrap_or_else(|_| {
828                                // If not valid UTF-8, convert to hex representation
829                                {
830                                    let mut hex_string = String::with_capacity(bytes.len() * 2);
831                                    for b in bytes {
832                                        hex_string.push_str(&format!("{:02x}", b));
833                                    }
834                                    hex_string
835                                }
836                            })
837                        }
838                        FieldValue::JsonObject(json) => json,
839                        _ => {
840                            return Err(SerializationError::ValidationFailed {
841                                field: format!("{}[{}]", field_name, key),
842                                message: format!(
843                                    "Cannot convert {} to string",
844                                    field_value.type_name()
845                                ),
846                            });
847                        }
848                    };
849                    result.insert(key, string_value);
850                }
851                Ok(result)
852            }
853            // Backward compatibility: support old array format
854            FieldValue::Array(array) => {
855                let mut result = HashMap::new();
856                for field_value in array {
857                    let key_value_str = field_value.as_string().map_err(|_| {
858                        SerializationError::ValidationFailed {
859                            field: field_name.to_string(),
860                            message: format!("Expected string in array, found {:?}", field_value),
861                        }
862                    })?;
863
864                    // Parse "key: value" format
865                    if let Some(colon_pos) = key_value_str.find(':') {
866                        let key = key_value_str[..colon_pos].trim().to_string();
867                        let value = key_value_str[colon_pos + 1..].trim().to_string();
868                        result.insert(key, value);
869                    } else {
870                        return Err(SerializationError::ValidationFailed {
871                            field: field_name.to_string(),
872                            message: format!("Invalid key-value format: {}", key_value_str),
873                        });
874                    }
875                }
876                Ok(result)
877            }
878            _ => Err(SerializationError::ValidationFailed {
879                field: field_name.to_string(),
880                message: format!(
881                    "Expected Object or Array for HashMap<String, String>, found {:?}",
882                    value.type_name()
883                ),
884            }),
885        }
886    }
887}
888
889/// Converts FieldValue representation back to strings
890///
891/// Validates that the FieldValue contains string data and returns
892/// the corresponding string with support for both direct strings and JSON objects.
893impl FromFieldValue for String {
894    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
895        // Try string first, then JSON object
896        if let Ok(s) = value.as_string() {
897            Ok(s.to_string())
898        } else if let Ok(json_str) = value.as_json_object() {
899            Ok(json_str.to_string())
900        } else {
901            Err(SerializationError::ValidationFailed {
902                field: field_name.to_string(),
903                message: format!("Expected String or JSON object, found {:?}", value),
904            })
905        }
906    }
907}
908
909/// Converts FieldValue representation back to optional values
910///
911/// Validates that the FieldValue contains optional data and returns
912/// the corresponding optional value with proper None/Some handling.
913impl<T> FromFieldValue for Option<T>
914where
915    T: FromFieldValue,
916{
917    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
918        match value {
919            FieldValue::Optional(Some(inner)) => T::from_field_value(*inner, field_name).map(Some),
920            FieldValue::Optional(None) => Ok(None),
921            // Also allow direct values for convenience
922            _ => T::from_field_value(value, field_name).map(Some),
923        }
924    }
925}
926
927/// Converts FieldValue representation back to serializable struct vectors
928///
929/// Validates that the FieldValue contains an array of struct objects and returns
930/// the corresponding vector with struct-by-struct deserialization.
931impl<T> FromFieldValue for Vec<T>
932where
933    T: StructSerializable,
934{
935    fn from_field_value(value: FieldValue, field_name: &str) -> SerializationResult<Self> {
936        match value {
937            FieldValue::Array(array) => {
938                let mut result = Vec::with_capacity(array.len());
939                for (index, item) in array.into_iter().enumerate() {
940                    match item {
941                        FieldValue::Object(object) => {
942                            // Convert Object back to StructDeserializer
943                            let deserializer =
944                                crate::serialization::core::StructDeserializer { fields: object };
945                            let mut deserializer = deserializer;
946                            let parsed_item =
947                                T::from_deserializer(&mut deserializer).map_err(|e| {
948                                    SerializationError::ValidationFailed {
949                                        field: format!("{}[{}]", field_name, index),
950                                        message: format!("Failed to deserialize struct: {}", e),
951                                    }
952                                })?;
953                            result.push(parsed_item);
954                        }
955                        // Backward compatibility: support old JSON string format
956                        FieldValue::String(json_string) => {
957                            let parsed_item = T::from_json(&json_string).map_err(|e| {
958                                SerializationError::ValidationFailed {
959                                    field: format!("{}[{}]", field_name, index),
960                                    message: format!("Failed to parse JSON: {}", e),
961                                }
962                            })?;
963                            result.push(parsed_item);
964                        }
965                        _ => {
966                            return Err(SerializationError::ValidationFailed {
967                                field: format!("{}[{}]", field_name, index),
968                                message: format!(
969                                    "Expected Object or String, found {}",
970                                    item.type_name()
971                                ),
972                            });
973                        }
974                    }
975                }
976                Ok(result)
977            }
978            _ => Err(SerializationError::ValidationFailed {
979                field: field_name.to_string(),
980                message: format!(
981                    "Expected Array for Vec<{}>, found {}",
982                    std::any::type_name::<T>(),
983                    value.type_name()
984                ),
985            }),
986        }
987    }
988}