1use std::sync::Arc;
2
3use fusio::{SeqRead, Write};
4
5use super::{Decode, Encode};
6
7impl<T> Decode for Arc<T>
8where
9 T: Decode,
10{
11 type Error = T::Error;
12
13 async fn decode<R>(reader: &mut R) -> Result<Self, Self::Error>
14 where
15 R: SeqRead,
16 {
17 Ok(Arc::from(T::decode(reader).await?))
18 }
19}
20
21impl<T> Encode for Arc<T>
22where
23 T: Encode + Send + Sync,
24{
25 type Error = T::Error;
26
27 async fn encode<W>(&self, writer: &mut W) -> Result<(), Self::Error>
28 where
29 W: Write,
30 {
31 self.as_ref().encode(writer).await
32 }
33
34 fn size(&self) -> usize {
35 Encode::size(self.as_ref())
36 }
37}
38
39#[cfg(test)]
40mod tests {
41 use std::{io::Cursor, sync::Arc};
42
43 use tokio::io::AsyncSeekExt;
44
45 use crate::serdes::{Decode, Encode};
46
47 #[tokio::test]
48 async fn test_encode_decode() {
49 let source_0 = Arc::new(1u64);
50 let source_1 = Arc::new("Hello! Tonbo".to_string());
51
52 let mut bytes = Vec::new();
53 let mut cursor = Cursor::new(&mut bytes);
54
55 source_0.encode(&mut cursor).await.unwrap();
56 source_1.encode(&mut cursor).await.unwrap();
57
58 cursor.seek(std::io::SeekFrom::Start(0)).await.unwrap();
59 let decoded_0 = Arc::<u64>::decode(&mut cursor).await.unwrap();
60 let decoded_1 = Arc::<String>::decode(&mut cursor).await.unwrap();
61
62 assert_eq!(source_0, decoded_0);
63 assert_eq!(source_1, decoded_1);
64 }
65}