1use alloc::rc::Rc;
3use alloc::{string::String, vec::Vec};
4
5use crate::{Len, Borrow, AsBytes, FromBytes};
6
7impl<T: Borrow> Borrow for Rc<T> {
8 type Ref<'a> = T::Ref<'a> where T: 'a;
9 type Borrowed<'a> = T::Borrowed<'a>;
10 #[inline(always)] fn borrow<'a>(&'a self) -> Self::Borrowed<'a> { self.as_ref().borrow() }
11 #[inline(always)] fn reborrow<'b, 'a: 'b>(item: Self::Borrowed<'a>) -> Self::Borrowed<'b> where Self: 'a { T::reborrow(item) }
12 #[inline(always)] fn reborrow_ref<'b, 'a: 'b>(item: Self::Ref<'a>) -> Self::Ref<'b> where Self: 'a { T::reborrow_ref(item) }
13}
14impl<T: Len> Len for Rc<T> {
15 #[inline(always)] fn len(&self) -> usize { self.as_ref().len() }
16}
17impl<'a, T: AsBytes<'a>> AsBytes<'a> for Rc<T> {
18 const SLICE_COUNT: usize = T::SLICE_COUNT;
19 #[inline] fn get_byte_slice(&self, index: usize) -> (u64, &'a [u8]) { self.as_ref().get_byte_slice(index) }
20}
21impl<'a, T: FromBytes<'a>> FromBytes<'a> for Rc<T> {
22 const SLICE_COUNT: usize = T::SLICE_COUNT;
23 #[inline(always)] fn from_bytes(bytes: &mut impl Iterator<Item=&'a [u8]>) -> Self { Rc::new(T::from_bytes(bytes)) }
24 #[inline(always)] fn from_store(store: &crate::bytes::indexed::DecodedStore<'a>, offset: &mut usize) -> Self { Rc::new(T::from_store(store, offset)) }
25 #[inline(always)] fn element_sizes(sizes: &mut Vec<usize>) -> Result<(), String> { T::element_sizes(sizes) }
26}
27
28#[cfg(test)]
29mod tests {
30 use alloc::rc::Rc;
31 use alloc::{vec, vec::Vec};
32 use crate::{Borrow, Len, AsBytes, FromBytes};
33
34 #[test]
35 fn test_borrow() {
36 let x = Rc::new(vec![1, 2, 3]);
37 let y: &[i32] = x.borrow();
38 assert_eq!(y, &[1, 2, 3]);
39 }
40
41 #[test]
42 fn test_len() {
43 let x = Rc::new(vec![1, 2, 3]);
44 assert_eq!(x.len(), 3);
45 }
46
47 #[test]
48 fn test_as_from_bytes() {
49 let x = Rc::new(vec![1u8, 2, 3, 4, 5]);
50 let bytes: Vec<_> = x.borrow().as_bytes().map(|(_, b)| b).collect();
51 let y: Rc<&[u8]> = FromBytes::from_bytes(&mut bytes.into_iter());
52 assert_eq!(*x, *y);
53 }
54
55 #[test]
56 fn test_element_sizes() {
57 let mut sizes = Vec::new();
58 <Rc<&[u32]> as FromBytes>::element_sizes(&mut sizes).unwrap();
59 assert_eq!(sizes, [4]);
60 }
61
62 #[test]
63 fn test_borrow_tuple() {
64 let x = (vec![4,5,6,7,], Rc::new(vec![1, 2, 3]));
65 let y: (&[i32], &[i32]) = x.borrow();
66 assert_eq!(y, ([4,5,6,7].as_ref(), [1, 2, 3].as_ref()));
67 }
68}