hexser/adapters/
mapper.rs

1//! Mapper trait for data transformation between layers.
2//!
3//! Mappers transform data between different representations as it crosses
4//! architectural boundaries. They convert between domain models, DTOs,
5//! database models, or API representations, ensuring clean separation
6//! between layers while maintaining data integrity.
7//!
8//! Revision History
9//! - 2025-10-01T00:00:00Z @AI: Initial Mapper trait definition for bidirectional transformation.
10
11/// Trait for mapping data between different representations.
12///
13/// Mappers transform data as it crosses architectural boundaries,
14/// converting between domain models and external representations.
15///
16/// # Type Parameters
17///
18/// * `From` - The source data type
19/// * `To` - The target data type
20///
21/// # Example
22///
23/// ```rust
24/// use hexser::adapters::Mapper;
25/// use hexser::HexResult;
26///
27/// struct DomainUser {
28///     id: String,
29///     email: String,
30/// }
31///
32/// struct DbUserRow {
33///     user_id: String,
34///     user_email: String,
35/// }
36///
37/// struct UserMapper;
38///
39/// impl Mapper<DomainUser, DbUserRow> for UserMapper {
40///     fn map(&self, from: DomainUser) -> HexResult<DbUserRow> {
41///         Ok(DbUserRow {
42///             user_id: from.id,
43///             user_email: from.email,
44///         })
45///     }
46/// }
47///
48/// impl Mapper<DbUserRow, DomainUser> for UserMapper {
49///     fn map(&self, from: DbUserRow) -> HexResult<DomainUser> {
50///         Ok(DomainUser {
51///             id: from.user_id,
52///             email: from.user_email,
53///         })
54///     }
55/// }
56/// ```
57pub trait Mapper<From, To> {
58  /// Map from one representation to another.
59  ///
60  /// Returns the mapped value if successful, or an error if the mapping fails.
61  fn map(&self, from: From) -> crate::result::hex_result::HexResult<To>;
62}
63
64#[cfg(test)]
65mod tests {
66  use super::*;
67
68  struct SourceType {
69    value: i32,
70  }
71
72  struct TargetType {
73    data: i32,
74  }
75
76  struct TestMapper;
77
78  impl Mapper<SourceType, TargetType> for TestMapper {
79    fn map(&self, from: SourceType) -> crate::result::hex_result::HexResult<TargetType> {
80      Result::Ok(TargetType { data: from.value })
81    }
82  }
83
84  #[test]
85  fn test_mapper_transformation() {
86    let mapper = TestMapper;
87    let source = SourceType { value: 42 };
88    let target = mapper.map(source).unwrap();
89    assert_eq!(target.data, 42);
90  }
91}