joerl 0.7.1

An Erlang-inspired actor model library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! Trait-based message serialization for distributed actor systems.
//!
//! This module provides a flexible serialization framework that allows messages
//! to be serialized for network transmission, persistence, or other purposes.
//!
//! # Overview
//!
//! The serialization system consists of:
//! - [`SerializableMessage`]: Trait for messages that can be serialized
//! - [`MessageRegistry`]: Global registry mapping type IDs to deserializers
//! - [`SerializableEnvelope`]: Wire format for serialized messages
//!
//! # Examples
//!
//! ```rust
//! use joerl::serialization::{SerializableMessage, MessageRegistry, SerializationError};
//! use std::any::Any;
//!
//! #[derive(Debug, Clone, PartialEq)]
//! struct PingMessage {
//!     count: u32,
//! }
//!
//! impl SerializableMessage for PingMessage {
//!     fn message_type_id(&self) -> &'static str {
//!         "PingMessage"
//!     }
//!
//!     fn as_any(&self) -> &dyn Any {
//!         self
//!     }
//!
//!     fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
//!         Ok(self.count.to_le_bytes().to_vec())
//!     }
//! }
//!
//! // Deserializer function
//! fn deserialize_ping(data: &[u8]) -> Result<Box<dyn SerializableMessage>, SerializationError> {
//!     if data.len() != 4 {
//!         return Err(SerializationError::DeserializeFailed(
//!             "Invalid data length".to_string()
//!         ));
//!     }
//!     let count = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
//!     Ok(Box::new(PingMessage { count }))
//! }
//!
//! // Register the deserializer
//! let mut registry = MessageRegistry::new();
//! registry.register("PingMessage", Box::new(deserialize_ping));
//! ```

use crate::Message;
use once_cell::sync::Lazy;
use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, RwLock};

/// Errors that can occur during serialization or deserialization.
#[derive(Debug, Clone)]
pub enum SerializationError {
    /// Failed to serialize a message.
    SerializeFailed(String),

    /// Failed to deserialize a message.
    DeserializeFailed(String),

    /// Message type is not registered in the registry.
    UnknownMessageType(String),

    /// Invalid data format.
    InvalidFormat(String),

    /// Type mismatch during deserialization.
    TypeMismatch { expected: String, found: String },
}

impl fmt::Display for SerializationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SerializationError::SerializeFailed(msg) => {
                write!(f, "Serialization failed: {}", msg)
            }
            SerializationError::DeserializeFailed(msg) => {
                write!(f, "Deserialization failed: {}", msg)
            }
            SerializationError::UnknownMessageType(type_id) => {
                write!(f, "Unknown message type: {}", type_id)
            }
            SerializationError::InvalidFormat(msg) => write!(f, "Invalid format: {}", msg),
            SerializationError::TypeMismatch { expected, found } => {
                write!(f, "Type mismatch: expected {}, found {}", expected, found)
            }
        }
    }
}

impl std::error::Error for SerializationError {}

/// Trait for messages that can be serialized.
///
/// This trait extends the basic message functionality with serialization capabilities.
/// Each message type provides its own serialization logic and a unique type identifier.
///
/// # Type Safety
///
/// The type ID must be unique across all message types in your system. Use namespaced
/// identifiers to avoid collisions (e.g., "my_app::PingMessage").
///
/// # Examples
///
/// ```rust
/// use joerl::serialization::{SerializableMessage, SerializationError};
/// use std::any::Any;
///
/// struct CounterMsg {
///     value: i32,
/// }
///
/// impl SerializableMessage for CounterMsg {
///     fn message_type_id(&self) -> &'static str {
///         "CounterMsg"
///     }
///
///     fn as_any(&self) -> &dyn Any {
///         self
///     }
///
///     fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
///         Ok(self.value.to_le_bytes().to_vec())
///     }
/// }
/// ```
pub trait SerializableMessage: Any + Send + Sync {
    /// Returns a unique type identifier for this message type.
    ///
    /// This identifier is used to look up the appropriate deserializer
    /// when reconstructing messages from serialized data.
    ///
    /// # Important
    ///
    /// Type IDs must be:
    /// - Unique across all message types
    /// - Stable (don't change between versions)
    /// - Descriptive for debugging
    fn message_type_id(&self) -> &'static str;

    /// Returns a reference to self as `&dyn Any` for downcasting.
    ///
    /// This allows the message to be downcast to its concrete type
    /// after deserialization.
    fn as_any(&self) -> &dyn Any;

    /// Serializes the message into bytes.
    ///
    /// Implementations should ensure that the serialized format is:
    /// - Deterministic (same input always produces same output)
    /// - Versioned (handle format changes gracefully)
    /// - Compact (minimize overhead for network transmission)
    ///
    /// # Errors
    ///
    /// Returns `SerializationError::SerializeFailed` if serialization fails.
    fn serialize(&self) -> Result<Vec<u8>, SerializationError>;
}

/// Type alias for deserializer functions.
///
/// Deserializers take a byte slice and return a boxed SerializableMessage
/// or an error if deserialization fails.
pub type Deserializer =
    Box<dyn Fn(&[u8]) -> Result<Box<dyn SerializableMessage>, SerializationError> + Send + Sync>;

/// Registry mapping message type IDs to deserializers.
///
/// The registry provides a global mapping from type identifiers to functions
/// that can reconstruct messages from serialized bytes. This enables dynamic
/// deserialization without compile-time knowledge of all message types.
///
/// # Thread Safety
///
/// The registry is thread-safe and can be shared across actors and threads
/// using `Arc<MessageRegistry>`.
///
/// # Examples
///
/// ```rust
/// use joerl::serialization::{MessageRegistry, SerializableMessage, SerializationError};
/// use std::any::Any;
///
/// struct SimpleMsg(u32);
///
/// impl SerializableMessage for SimpleMsg {
///     fn message_type_id(&self) -> &'static str { "SimpleMsg" }
///     fn as_any(&self) -> &dyn Any { self }
///     fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
///         Ok(self.0.to_le_bytes().to_vec())
///     }
/// }
///
/// let mut registry = MessageRegistry::new();
/// registry.register("SimpleMsg", Box::new(|data| {
///     if data.len() != 4 {
///         return Err(SerializationError::InvalidFormat("Expected 4 bytes".into()));
///     }
///     let value = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
///     Ok(Box::new(SimpleMsg(value)))
/// }));
///
/// // Later, deserialize a message
/// let data = vec![42, 0, 0, 0];
/// let msg = registry.deserialize("SimpleMsg", &data).unwrap();
/// ```
#[derive(Clone)]
pub struct MessageRegistry {
    deserializers: Arc<RwLock<HashMap<String, Deserializer>>>,
}

impl MessageRegistry {
    /// Creates a new empty message registry.
    pub fn new() -> Self {
        Self {
            deserializers: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Registers a deserializer for a message type.
    ///
    /// # Arguments
    ///
    /// * `type_id` - Unique identifier for the message type
    /// * `deserializer` - Function to deserialize bytes into the message
    ///
    /// # Examples
    ///
    /// ```rust
    /// use joerl::serialization::{MessageRegistry, SerializableMessage, SerializationError};
    /// use std::any::Any;
    ///
    /// struct MyMsg(String);
    ///
    /// impl SerializableMessage for MyMsg {
    ///     fn message_type_id(&self) -> &'static str { "MyMsg" }
    ///     fn as_any(&self) -> &dyn Any { self }
    ///     fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
    ///         Ok(self.0.as_bytes().to_vec())
    ///     }
    /// }
    ///
    /// let mut registry = MessageRegistry::new();
    /// registry.register("MyMsg", Box::new(|data| {
    ///     let text = String::from_utf8(data.to_vec())
    ///         .map_err(|e| SerializationError::DeserializeFailed(e.to_string()))?;
    ///     Ok(Box::new(MyMsg(text)))
    /// }));
    /// ```
    pub fn register(&mut self, type_id: &str, deserializer: Deserializer) {
        self.deserializers
            .write()
            .unwrap()
            .insert(type_id.to_string(), deserializer);
    }

    /// Deserializes a message from bytes using the registered deserializer.
    ///
    /// # Arguments
    ///
    /// * `type_id` - The type identifier of the message
    /// * `data` - The serialized message bytes
    ///
    /// # Errors
    ///
    /// Returns `SerializationError::UnknownMessageType` if no deserializer
    /// is registered for the given type ID.
    ///
    /// Returns `SerializationError::DeserializeFailed` if deserialization fails.
    pub fn deserialize(
        &self,
        type_id: &str,
        data: &[u8],
    ) -> Result<Box<dyn SerializableMessage>, SerializationError> {
        let deserializers = self.deserializers.read().unwrap();
        let deserializer = deserializers
            .get(type_id)
            .ok_or_else(|| SerializationError::UnknownMessageType(type_id.to_string()))?;

        deserializer(data)
    }

    /// Returns true if a deserializer is registered for the given type ID.
    pub fn has_type(&self, type_id: &str) -> bool {
        self.deserializers.read().unwrap().contains_key(type_id)
    }

    /// Returns the number of registered message types.
    pub fn len(&self) -> usize {
        self.deserializers.read().unwrap().len()
    }

    /// Returns true if the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.deserializers.read().unwrap().is_empty()
    }

    /// Clears all registered deserializers.
    pub fn clear(&mut self) {
        self.deserializers.write().unwrap().clear();
    }
}

impl Default for MessageRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Global message registry for distributed messaging.
///
/// This singleton registry is shared across all DistributedSystems and must
/// be populated with message type deserializers before sending remote messages.
///
/// # Thread Safety
///
/// The global registry is thread-safe and can be accessed from any thread.
///
/// # Examples
///
/// ```rust
/// use joerl::serialization::{register_message_type, SerializableMessage, SerializationError};
/// use std::any::Any;
///
/// struct MyMsg(u32);
///
/// impl SerializableMessage for MyMsg {
///     fn message_type_id(&self) -> &'static str { "MyMsg" }
///     fn as_any(&self) -> &dyn Any { self }
///     fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
///         Ok(self.0.to_le_bytes().to_vec())
///     }
/// }
///
/// // Register before creating DistributedSystem
/// register_message_type("MyMsg", Box::new(|data| {
///     if data.len() != 4 {
///         return Err(SerializationError::InvalidFormat("Expected 4 bytes".into()));
///     }
///     let value = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
///     Ok(Box::new(MyMsg(value)))
/// }));
/// ```
static GLOBAL_REGISTRY: Lazy<Arc<RwLock<MessageRegistry>>> =
    Lazy::new(|| Arc::new(RwLock::new(MessageRegistry::new())));

/// Registers a message type deserializer in the global registry.
///
/// This function must be called to register message types before they can be
/// sent across distributed nodes. Typically called during actor initialization
/// or at application startup.
///
/// # Arguments
///
/// * `type_id` - Unique identifier for the message type (must match `message_type_id()`)
/// * `deserializer` - Function to deserialize bytes into the message
///
/// # Examples
///
/// ```rust
/// use joerl::serialization::{register_message_type, SerializableMessage, SerializationError};
/// use std::any::Any;
///
/// struct PingMsg;
///
/// impl SerializableMessage for PingMsg {
///     fn message_type_id(&self) -> &'static str { "PingMsg" }
///     fn as_any(&self) -> &dyn Any { self }
///     fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
///         Ok(vec![])
///     }
/// }
///
/// // Register the deserializer
/// register_message_type("PingMsg", Box::new(|_| Ok(Box::new(PingMsg))));
/// ```
pub fn register_message_type(type_id: &str, deserializer: Deserializer) {
    GLOBAL_REGISTRY
        .write()
        .unwrap()
        .register(type_id, deserializer);
}

/// Returns a reference to the global message registry.
///
/// This is used internally by the distributed system for message deserialization.
/// Users typically don't need to call this directly.
///
/// # Examples
///
/// ```rust
/// use joerl::serialization::get_global_registry;
///
/// let registry = get_global_registry();
/// let registry_guard = registry.read().unwrap();
/// let count = registry_guard.len();
/// println!("Registered message types: {}", count);
/// ```
pub fn get_global_registry() -> Arc<RwLock<MessageRegistry>> {
    Arc::clone(&GLOBAL_REGISTRY)
}

/// Envelope for serialized messages.
///
/// This structure represents a message in its serialized form, ready for
/// transmission over the network or storage to disk. It contains both the
/// type identifier and the serialized data.
///
/// # Wire Format
///
/// The envelope uses a simple format:
/// - Type ID (UTF-8 string with length prefix)
/// - Message data (opaque bytes)
///
/// # Examples
///
/// ```rust
/// use joerl::serialization::{SerializableEnvelope, MessageRegistry, SerializableMessage, SerializationError};
/// use std::any::Any;
///
/// struct TestMsg(u32);
///
/// impl SerializableMessage for TestMsg {
///     fn message_type_id(&self) -> &'static str { "TestMsg" }
///     fn as_any(&self) -> &dyn Any { self }
///     fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
///         Ok(self.0.to_le_bytes().to_vec())
///     }
/// }
///
/// // Wrap a message
/// let msg = TestMsg(42);
/// let envelope = SerializableEnvelope::wrap(&msg).unwrap();
///
/// // Convert to wire format
/// let wire_data = envelope.to_bytes();
///
/// // Reconstruct from wire format
/// let envelope2 = SerializableEnvelope::from_bytes(&wire_data).unwrap();
/// assert_eq!(envelope.type_id(), envelope2.type_id());
///
/// // Unwrap with registry
/// let mut registry = MessageRegistry::new();
/// registry.register("TestMsg", Box::new(|data| {
///     let value = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
///     Ok(Box::new(TestMsg(value)))
/// }));
///
/// let unwrapped = envelope2.unwrap(&registry).unwrap();
/// let test_msg = unwrapped.as_any().downcast_ref::<TestMsg>().unwrap();
/// assert_eq!(test_msg.0, 42);
/// ```
#[derive(Debug, Clone)]
pub struct SerializableEnvelope {
    type_id: String,
    data: Vec<u8>,
}

impl SerializableEnvelope {
    /// Wraps a serializable message in an envelope.
    ///
    /// # Errors
    ///
    /// Returns `SerializationError::SerializeFailed` if the message
    /// cannot be serialized.
    pub fn wrap(msg: &dyn SerializableMessage) -> Result<Self, SerializationError> {
        let type_id = msg.message_type_id().to_string();
        let data = msg.serialize()?;

        Ok(Self { type_id, data })
    }

    /// Returns the type ID of the wrapped message.
    pub fn type_id(&self) -> &str {
        &self.type_id
    }

    /// Returns the serialized message data.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Unwraps the envelope, deserializing the message.
    ///
    /// # Arguments
    ///
    /// * `registry` - The message registry containing deserializers
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The message type is not registered
    /// - Deserialization fails
    pub fn unwrap(
        &self,
        registry: &MessageRegistry,
    ) -> Result<Box<dyn SerializableMessage>, SerializationError> {
        registry.deserialize(&self.type_id, &self.data)
    }

    /// Converts the envelope to a wire format (byte representation).
    ///
    /// The format is:
    /// - 4 bytes: type_id length (u32 little-endian)
    /// - N bytes: type_id (UTF-8)
    /// - 4 bytes: data length (u32 little-endian)
    /// - M bytes: data
    pub fn to_bytes(&self) -> Vec<u8> {
        let type_id_bytes = self.type_id.as_bytes();
        let type_id_len = type_id_bytes.len() as u32;
        let data_len = self.data.len() as u32;

        let mut result = Vec::with_capacity(8 + type_id_bytes.len() + self.data.len());
        result.extend_from_slice(&type_id_len.to_le_bytes());
        result.extend_from_slice(type_id_bytes);
        result.extend_from_slice(&data_len.to_le_bytes());
        result.extend_from_slice(&self.data);

        result
    }

    /// Reconstructs an envelope from wire format bytes.
    ///
    /// # Errors
    ///
    /// Returns `SerializationError::InvalidFormat` if the bytes don't
    /// represent a valid envelope.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SerializationError> {
        if bytes.len() < 8 {
            return Err(SerializationError::InvalidFormat(
                "Envelope too short".to_string(),
            ));
        }

        // Read type_id length
        let type_id_len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
        if bytes.len() < 8 + type_id_len {
            return Err(SerializationError::InvalidFormat(
                "Invalid type_id length".to_string(),
            ));
        }

        // Read type_id
        let type_id_bytes = &bytes[4..4 + type_id_len];
        let type_id = String::from_utf8(type_id_bytes.to_vec())
            .map_err(|e| SerializationError::InvalidFormat(format!("Invalid UTF-8: {}", e)))?;

        // Read data length
        let data_len_offset = 4 + type_id_len;
        if bytes.len() < data_len_offset + 4 {
            return Err(SerializationError::InvalidFormat(
                "Missing data length".to_string(),
            ));
        }

        let data_len = u32::from_le_bytes([
            bytes[data_len_offset],
            bytes[data_len_offset + 1],
            bytes[data_len_offset + 2],
            bytes[data_len_offset + 3],
        ]) as usize;

        // Read data
        let data_offset = data_len_offset + 4;
        if bytes.len() < data_offset + data_len {
            return Err(SerializationError::InvalidFormat(
                "Invalid data length".to_string(),
            ));
        }

        let data = bytes[data_offset..data_offset + data_len].to_vec();

        Ok(Self { type_id, data })
    }

    /// Converts a SerializableMessage to a standard joerl Message.
    ///
    /// This allows serializable messages to be used with the regular
    /// actor system send operations.
    pub fn to_message(msg: Box<dyn SerializableMessage>) -> Message {
        Box::new(msg)
    }

    /// Attempts to convert a joerl Message to a SerializableMessage.
    ///
    /// Returns None if the message doesn't implement SerializableMessage.
    pub fn from_message(msg: &Message) -> Option<&dyn SerializableMessage> {
        msg.downcast_ref::<Box<dyn SerializableMessage>>()
            .map(|b| b.as_ref())
    }
}

/// Helper macro to implement SerializableMessage with less boilerplate.
///
/// # Examples
///
/// ```ignore
/// use joerl::impl_serializable;
///
/// #[derive(Debug, Clone)]
/// struct MyMessage {
///     value: i32,
/// }
///
/// impl_serializable!(MyMessage, "my_app::MyMessage", |msg: &MyMessage| {
///     Ok(msg.value.to_le_bytes().to_vec())
/// });
///
/// // Now MyMessage implements SerializableMessage
/// ```
#[macro_export]
macro_rules! impl_serializable {
    ($type:ty, $type_id:expr, $serialize_fn:expr) => {
        impl $crate::serialization::SerializableMessage for $type {
            fn message_type_id(&self) -> &'static str {
                $type_id
            }

            fn as_any(&self) -> &dyn ::std::any::Any {
                self
            }

            fn serialize(&self) -> Result<Vec<u8>, $crate::serialization::SerializationError> {
                let serialize: fn(
                    &Self,
                )
                    -> Result<Vec<u8>, $crate::serialization::SerializationError> = $serialize_fn;
                serialize(self)
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Clone, PartialEq)]
    struct TestMessage {
        value: u32,
    }

    impl SerializableMessage for TestMessage {
        fn message_type_id(&self) -> &'static str {
            "TestMessage"
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn serialize(&self) -> Result<Vec<u8>, SerializationError> {
            Ok(self.value.to_le_bytes().to_vec())
        }
    }

    fn deserialize_test_message(
        data: &[u8],
    ) -> Result<Box<dyn SerializableMessage>, SerializationError> {
        if data.len() != 4 {
            return Err(SerializationError::DeserializeFailed(
                "Invalid length".to_string(),
            ));
        }
        let value = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
        Ok(Box::new(TestMessage { value }))
    }

    #[test]
    fn test_message_serialization() {
        let msg = TestMessage { value: 42 };
        let data = msg.serialize().unwrap();
        assert_eq!(data, vec![42, 0, 0, 0]);
    }

    #[test]
    fn test_registry() {
        let mut registry = MessageRegistry::new();
        assert!(registry.is_empty());

        registry.register("TestMessage", Box::new(deserialize_test_message));
        assert_eq!(registry.len(), 1);
        assert!(registry.has_type("TestMessage"));
        assert!(!registry.has_type("UnknownType"));
    }

    #[test]
    fn test_registry_deserialize() {
        let mut registry = MessageRegistry::new();
        registry.register("TestMessage", Box::new(deserialize_test_message));

        let data = vec![42, 0, 0, 0];
        let msg = registry.deserialize("TestMessage", &data).unwrap();
        let test_msg = msg.as_any().downcast_ref::<TestMessage>().unwrap();
        assert_eq!(test_msg.value, 42);
    }

    #[test]
    fn test_registry_unknown_type() {
        let registry = MessageRegistry::new();
        let result = registry.deserialize("Unknown", &[]);
        assert!(matches!(
            result,
            Err(SerializationError::UnknownMessageType(_))
        ));
    }

    #[test]
    fn test_envelope_wrap_unwrap() {
        let msg = TestMessage { value: 123 };
        let envelope = SerializableEnvelope::wrap(&msg).unwrap();
        assert_eq!(envelope.type_id(), "TestMessage");

        let mut registry = MessageRegistry::new();
        registry.register("TestMessage", Box::new(deserialize_test_message));

        let unwrapped = envelope.unwrap(&registry).unwrap();
        let result = unwrapped.as_any().downcast_ref::<TestMessage>().unwrap();
        assert_eq!(result.value, 123);
    }

    #[test]
    fn test_envelope_to_from_bytes() {
        let msg = TestMessage { value: 999 };
        let envelope = SerializableEnvelope::wrap(&msg).unwrap();

        let bytes = envelope.to_bytes();
        let reconstructed = SerializableEnvelope::from_bytes(&bytes).unwrap();

        assert_eq!(envelope.type_id(), reconstructed.type_id());
        assert_eq!(envelope.data(), reconstructed.data());
    }

    #[test]
    fn test_envelope_from_bytes_invalid() {
        let result = SerializableEnvelope::from_bytes(&[1, 2, 3]);
        assert!(matches!(result, Err(SerializationError::InvalidFormat(_))));
    }

    #[test]
    fn test_registry_clone() {
        let mut registry = MessageRegistry::new();
        registry.register("TestMessage", Box::new(deserialize_test_message));

        let cloned = registry.clone();
        assert!(cloned.has_type("TestMessage"));
    }

    #[test]
    fn test_registry_clear() {
        let mut registry = MessageRegistry::new();
        registry.register("TestMessage", Box::new(deserialize_test_message));
        assert_eq!(registry.len(), 1);

        registry.clear();
        assert!(registry.is_empty());
    }
}