Skip to main content

skia_safe/core/
data.rs

1use std::{
2    ffi::{CStr, CString},
3    fmt, io,
4    ops::Deref,
5    path::Path,
6};
7
8use skia_bindings::{self as sb, SkData};
9
10use crate::{interop::RustStream, prelude::*};
11
12pub type Data = RCHandle<SkData>;
13unsafe_send_sync!(Data);
14require_base_type!(SkData, sb::SkNVRefCnt);
15
16impl NativeRefCounted for SkData {
17    fn _ref(&self) {
18        unsafe { sb::C_SkData_ref(self) }
19    }
20
21    fn _unref(&self) {
22        unsafe { sb::C_SkData_unref(self) }
23    }
24
25    fn unique(&self) -> bool {
26        unsafe { sb::C_SkData_unique(self) }
27    }
28}
29
30impl Deref for Data {
31    type Target = [u8];
32    fn deref(&self) -> &Self::Target {
33        self.as_bytes()
34    }
35}
36
37impl PartialEq for Data {
38    // Although there is an implementation in SkData for equality testing, we
39    // prefer to stay on the Rust side for that.
40    fn eq(&self, other: &Self) -> bool {
41        self.deref() == other.deref()
42    }
43}
44
45impl fmt::Debug for Data {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        f.debug_struct("Data").field("size", &self.size()).finish()
48    }
49}
50
51impl Data {
52    pub fn size(&self) -> usize {
53        self.native().fSpan.fSize
54    }
55
56    pub fn is_empty(&self) -> bool {
57        self.size() == 0
58    }
59
60    pub fn as_bytes(&self) -> &[u8] {
61        unsafe { safer::from_raw_parts(self.native().fSpan.fPtr as _, self.size()) }
62    }
63
64    // TODO:
65    // pub unsafe fn writable_data(&mut self) -> &mut [u8]
66
67    pub fn copy_range(&self, offset: usize, buffer: &mut [u8]) -> &Self {
68        buffer.copy_from_slice(&self.as_bytes()[offset..offset + buffer.len()]);
69        self
70    }
71
72    // TODO: rename to copy_from() ? or from_bytes()?
73    pub fn new_copy(data: &[u8]) -> Self {
74        Data::from_ptr(unsafe { sb::C_SkData_MakeWithCopy(data.as_ptr() as _, data.len()) })
75            .unwrap()
76    }
77
78    /// Constructs Data from a given byte slice without copying it.
79    ///
80    /// Users must make sure that the underlying slice will outlive the lifetime of the Data.
81    #[allow(clippy::missing_safety_doc)]
82    pub unsafe fn new_bytes(data: &[u8]) -> Self {
83        unsafe {
84            Data::from_ptr(sb::C_SkData_MakeWithoutCopy(data.as_ptr() as _, data.len())).unwrap()
85        }
86    }
87
88    #[allow(clippy::missing_safety_doc)]
89    pub unsafe fn new_uninitialized(length: usize) -> Data {
90        unsafe { Data::from_ptr(sb::C_SkData_MakeUninitialized(length)).unwrap() }
91    }
92
93    pub fn new_zero_initialized(length: usize) -> Data {
94        Data::from_ptr(unsafe { sb::C_SkData_MakeZeroInitialized(length) }).unwrap()
95    }
96
97    // TODO: use Range as stand in for offset / length?
98    pub fn new_subset(data: &Data, offset: usize, length: usize) -> Data {
99        Data::from_ptr(unsafe { sb::C_SkData_MakeSubset(data.native(), offset, length) }).unwrap()
100    }
101
102    /// Constructs Data from a copy of a &str.
103    ///
104    /// Functions that use `Data` as a string container usually expect it to contain a c-string
105    /// including the terminating 0 byte, so this function converts the Rust `str` to a `CString`
106    /// and calls [`Self::new_cstr()`].
107    pub fn new_str(str: impl AsRef<str>) -> Data {
108        Self::new_cstr(&CString::new(str.as_ref()).unwrap())
109    }
110
111    /// Constructs Data from a &CStr by copying its contents.
112    pub fn new_cstr(cstr: &CStr) -> Data {
113        Data::from_ptr(unsafe { sb::C_SkData_MakeWithCString(cstr.as_ptr()) }).unwrap()
114    }
115
116    /// Create a new `Data` referencing the file with the specified path. If the file cannot be
117    /// opened, the path contains 0 bytes, or the path is not valid UTF-8, this returns `None`.
118    ///
119    /// This function opens the file as a memory mapped file for the lifetime of `Data` returned.
120    pub fn from_filename(path: impl AsRef<Path>) -> Option<Self> {
121        let path = CString::new(path.as_ref().to_str()?).ok()?;
122        Data::from_ptr(unsafe { sb::C_SkData_MakeFromFileName(path.as_ptr()) })
123    }
124
125    // TODO: MakeFromFile (is there a way to wrap this safely?)
126
127    /// Attempt to read size bytes into a [`Data`]. If the read succeeds, return the data,
128    /// else return `None`. Either way the stream's cursor may have been changed as a result
129    /// of calling read().
130    pub fn from_stream(mut stream: impl io::Read, size: usize) -> Option<Self> {
131        let mut stream = RustStream::new(&mut stream);
132        Data::from_ptr(unsafe { sb::C_SkData_MakeFromStream(stream.stream_mut(), size) })
133    }
134
135    pub fn new_empty() -> Self {
136        Data::from_ptr(unsafe { sb::C_SkData_MakeEmpty() }).unwrap()
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    impl RefCount for SkData {
145        fn ref_cnt(&self) -> usize {
146            self._base.ref_cnt()
147        }
148    }
149
150    #[test]
151    fn data_supports_equals() {
152        let x: &[u8] = &[1u8, 2u8, 3u8];
153        let d1 = Data::new_copy(x);
154        let d2 = Data::new_copy(x);
155        assert!(d1 == d2)
156    }
157
158    #[test]
159    fn from_stream_empty() {
160        let data = [];
161        let cursor = io::Cursor::new(data);
162        let data = Data::from_stream(cursor, 0).unwrap();
163        assert_eq!(data.len(), 0);
164    }
165
166    #[test]
167    fn from_stream() {
168        let data = [1u8];
169        let cursor = io::Cursor::new(data);
170        let data = Data::from_stream(cursor, 1).unwrap();
171        assert_eq!(data.len(), 1);
172        assert_eq!(data[0], 1u8);
173    }
174}