i_slint_core/slice.rs
1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! FFI-friendly slice
5
6#![allow(unsafe_code)]
7#![warn(missing_docs)]
8
9use core::{cmp::PartialEq, fmt::Debug, marker::PhantomData, ptr::NonNull};
10
11/// That's basically the same as `&'a [T]` but `repr(C)`
12///
13/// Can be constructed from a slice using the from trait.
14///
15/// ```
16/// use i_slint_core::slice::Slice;
17/// let x = Slice::from_slice(&[1, 2, 3]);
18/// assert_eq!(x.len(), 3);
19/// assert_eq!(x[1], 2);
20/// let slice : &'static [u32] = x.as_slice();
21/// ```
22///
23/// Comparing two Slice compare their pointer, not the content.
24/// ```
25/// use i_slint_core::slice::Slice;
26/// let a = Slice::from_slice(&[1, 2, 3]);
27/// let slice = [1, 2, 3, 4];
28/// let b = Slice::from(&slice[..3]);
29/// // two slice coming from the same pointer are equal.
30/// assert_eq!(b, Slice::from(&slice[..3]));
31/// // these are different because the pointers are different
32/// assert_ne!(a, b);
33/// // use as_slice to compare the contents
34/// assert_eq!(a.as_slice(), b.as_slice());
35/// ```
36#[repr(C)]
37#[derive(PartialEq)]
38pub struct Slice<'a, T> {
39 /// Invariant, this is a valid slice of len `len`
40 ptr: NonNull<T>,
41 len: usize,
42 phantom: PhantomData<&'a [T]>,
43}
44
45impl<T: Debug> Debug for Slice<'_, T> {
46 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
47 self.as_slice().fmt(f)
48 }
49}
50
51// Need to implement manually otherwise it is not implemented if T do not implement Copy / Clone
52impl<T> Copy for Slice<'_, T> {}
53
54impl<T> Clone for Slice<'_, T> {
55 fn clone(&self) -> Self {
56 *self
57 }
58}
59
60impl<'a, T> Slice<'a, T> {
61 /// Return a slice
62 pub fn as_slice(self) -> &'a [T] {
63 // Safety: it ptr is supposed to be a valid slice of given length
64 unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
65 }
66
67 /// Create from a native slice
68 pub const fn from_slice(slice: &'a [T]) -> Self {
69 Slice {
70 // Safety: a slice is never null
71 ptr: unsafe { NonNull::new_unchecked(slice.as_ptr() as *mut T) },
72 len: slice.len(),
73 phantom: PhantomData,
74 }
75 }
76}
77
78impl<'a, T> From<&'a [T]> for Slice<'a, T> {
79 fn from(slice: &'a [T]) -> Self {
80 Self::from_slice(slice)
81 }
82}
83
84impl<T> core::ops::Deref for Slice<'_, T> {
85 type Target = [T];
86 fn deref(&self) -> &[T] {
87 self.as_slice()
88 }
89}
90
91impl<T> Default for Slice<'_, T> {
92 fn default() -> Self {
93 Self::from_slice(&[])
94 }
95}
96
97/// Safety: Slice is the same as a rust slice, and a slice of Sync T is Sync
98unsafe impl<T: Sync> Sync for Slice<'_, T> {}
99/// Safety: Slice is the same as a rust slice, and a slice of Send T is Sync
100unsafe impl<T: Sync> Send for Slice<'_, T> {}