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