swift_rs/types/
data.rs

1use crate::{
2    swift::{self, SwiftObject},
3    Int,
4};
5
6use super::{array::SRArray, SRObject};
7
8use std::ops::Deref;
9
10type Data = SRArray<u8>;
11
12/// Convenience type for working with byte buffers,
13/// analagous to `SRData` in Swift.
14///
15/// ```rust
16/// use swift_rs::{swift, SRData};
17///
18/// swift!(fn get_data() -> SRData);
19///
20/// let data = unsafe { get_data() };
21///
22/// assert_eq!(data.as_ref(), &[1, 2, 3])
23/// ```
24/// [_corresponding Swift code_](https://github.com/Brendonovich/swift-rs/blob/07269e511f1afb71e2fcfa89ca5d7338bceb20e8/tests/swift-pkg/doctests.swift#L68)
25#[repr(transparent)]
26pub struct SRData(SRObject<Data>);
27
28impl SRData {
29    pub fn as_slice(&self) -> &[u8] {
30        self
31    }
32
33    pub fn to_vec(&self) -> Vec<u8> {
34        self.as_slice().to_vec()
35    }
36}
37
38impl SwiftObject for SRData {
39    type Shape = Data;
40
41    fn get_object(&self) -> &SRObject<Self::Shape> {
42        &self.0
43    }
44}
45
46impl Deref for SRData {
47    type Target = [u8];
48
49    fn deref(&self) -> &Self::Target {
50        &self.0
51    }
52}
53
54impl AsRef<[u8]> for SRData {
55    fn as_ref(&self) -> &[u8] {
56        self
57    }
58}
59
60impl From<&[u8]> for SRData {
61    fn from(value: &[u8]) -> Self {
62        unsafe { swift::data_from_bytes(value.as_ptr(), value.len() as Int) }
63    }
64}
65
66#[cfg(feature = "serde")]
67impl serde::Serialize for SRData {
68    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
69    where
70        S: serde::Serializer,
71    {
72        serializer.serialize_bytes(self)
73    }
74}