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
use crate::{Any, ByteString};
use alloc::{sync::Arc, vec, vec::Vec};

#[repr(C)]
#[derive(Clone)]
pub struct StringArray {
    inner: Any,
}

impl StringArray {
    pub fn new(vector: Vec<ByteString>) -> Self {
        Self {
            inner: StringArrayInner::new(vector).into(),
        }
    }

    pub fn get(&self, index: usize) -> Option<ByteString> {
        StringArrayInner::try_from(self.inner.clone())
            .unwrap()
            .get(index)
    }

    pub fn len(&self) -> usize {
        StringArrayInner::try_from(self.inner.clone())
            .unwrap()
            .len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Default for StringArray {
    fn default() -> Self {
        Self::new(vec![])
    }
}

impl<T: Into<ByteString>> From<Vec<T>> for StringArray {
    fn from(vector: Vec<T>) -> Self {
        Self::new(vector.into_iter().map(|x| x.into()).collect())
    }
}

#[pen_ffi_macro::any(crate = "crate")]
#[allow(clippy::redundant_allocation)]
#[derive(Clone)]
struct StringArrayInner {
    vector: Arc<Vec<ByteString>>,
}

impl StringArrayInner {
    pub fn new(vector: Vec<ByteString>) -> Self {
        Self {
            vector: Arc::new(vector),
        }
    }

    pub fn get(&self, index: usize) -> Option<ByteString> {
        self.vector.get(index).cloned()
    }

    pub fn len(&self) -> usize {
        self.vector.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::mem::{drop, forget, size_of};

    mod string_array {
        use super::*;

        #[test]
        fn clone() {
            let x = StringArray::from(vec!["foo"]);

            forget(x.clone());
            forget(x);
        }

        #[test]
        fn drop_() {
            let x = StringArray::from(vec!["foo"]);

            drop(x.clone());
            drop(x);
        }

        #[test]
        fn get_element() {
            assert_eq!(
                StringArray::new(vec!["foo".into()]).get(0),
                Some("foo".into())
            );
        }
    }

    mod string_array_inner {
        use super::*;

        #[test]
        fn is_small_enough() {
            assert!(size_of::<StringArrayInner>() <= size_of::<usize>());
        }

        #[test]
        fn drop_() {
            let x = StringArrayInner::new(vec!["foo".into()]);

            drop(x.clone());
            drop(x);
        }

        #[test]
        fn get_element() {
            assert_eq!(
                StringArrayInner::new(vec!["foo".into()]).get(0),
                Some("foo".into())
            );
        }
    }
}