glib/collections/
slice.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{fmt, marker::PhantomData, mem, ptr};
4
5use crate::{ffi, translate::*};
6
7// rustdoc-stripper-ignore-next
8/// Minimum size of the `Slice` allocation in bytes.
9const MIN_SIZE: usize = 256;
10
11// rustdoc-stripper-ignore-next
12/// Slice of elements of type `T` allocated by the GLib allocator.
13///
14/// This can be used like a `&[T]`, `&mut [T]` and `Vec<T>`.
15pub struct Slice<T: TransparentType> {
16    ptr: ptr::NonNull<T::GlibType>,
17    len: usize,
18    capacity: usize,
19}
20
21unsafe impl<T: TransparentType + Send> Send for Slice<T> {}
22
23unsafe impl<T: TransparentType + Sync> Sync for Slice<T> {}
24
25impl<T: fmt::Debug + TransparentType> fmt::Debug for Slice<T> {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        self.as_slice().fmt(f)
28    }
29}
30
31impl<T: PartialEq + TransparentType> PartialEq for Slice<T> {
32    #[inline]
33    fn eq(&self, other: &Self) -> bool {
34        self.as_slice() == other.as_slice()
35    }
36}
37
38impl<T: Eq + TransparentType> Eq for Slice<T> {}
39
40impl<T: PartialOrd + TransparentType> PartialOrd for Slice<T> {
41    #[inline]
42    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
43        self.as_slice().partial_cmp(other.as_slice())
44    }
45}
46
47impl<T: Ord + TransparentType> Ord for Slice<T> {
48    #[inline]
49    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
50        self.as_slice().cmp(other.as_slice())
51    }
52}
53
54impl<T: std::hash::Hash + TransparentType> std::hash::Hash for Slice<T> {
55    #[inline]
56    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
57        self.as_slice().hash(state)
58    }
59}
60
61impl<T: PartialEq + TransparentType> PartialEq<[T]> for Slice<T> {
62    #[inline]
63    fn eq(&self, other: &[T]) -> bool {
64        self.as_slice() == other
65    }
66}
67
68impl<T: PartialEq + TransparentType> PartialEq<Slice<T>> for [T] {
69    #[inline]
70    fn eq(&self, other: &Slice<T>) -> bool {
71        self == other.as_slice()
72    }
73}
74
75impl<T: TransparentType> Drop for Slice<T> {
76    #[inline]
77    fn drop(&mut self) {
78        unsafe {
79            if mem::needs_drop::<T>() {
80                for i in 0..self.len {
81                    ptr::drop_in_place::<T>(self.ptr.as_ptr().add(i) as *mut T);
82                }
83            }
84
85            if self.capacity != 0 {
86                ffi::g_free(self.ptr.as_ptr() as ffi::gpointer);
87            }
88        }
89    }
90}
91
92impl<T: TransparentType> AsRef<[T]> for Slice<T> {
93    #[inline]
94    fn as_ref(&self) -> &[T] {
95        self.as_slice()
96    }
97}
98
99impl<T: TransparentType> AsMut<[T]> for Slice<T> {
100    #[inline]
101    fn as_mut(&mut self) -> &mut [T] {
102        self.as_mut_slice()
103    }
104}
105
106impl<T: TransparentType> std::borrow::Borrow<[T]> for Slice<T> {
107    #[inline]
108    fn borrow(&self) -> &[T] {
109        self.as_slice()
110    }
111}
112
113impl<T: TransparentType> std::borrow::BorrowMut<[T]> for Slice<T> {
114    #[inline]
115    fn borrow_mut(&mut self) -> &mut [T] {
116        self.as_mut_slice()
117    }
118}
119
120impl<T: TransparentType> std::ops::Deref for Slice<T> {
121    type Target = [T];
122
123    #[inline]
124    fn deref(&self) -> &[T] {
125        self.as_slice()
126    }
127}
128
129impl<T: TransparentType> std::ops::DerefMut for Slice<T> {
130    #[inline]
131    fn deref_mut(&mut self) -> &mut [T] {
132        self.as_mut_slice()
133    }
134}
135
136impl<T: TransparentType> Default for Slice<T> {
137    #[inline]
138    fn default() -> Self {
139        Self::new()
140    }
141}
142
143impl<T: TransparentType> std::iter::Extend<T> for Slice<T> {
144    #[inline]
145    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
146        let iter = iter.into_iter();
147        self.reserve(iter.size_hint().0);
148
149        for item in iter {
150            self.push(item);
151        }
152    }
153}
154
155impl<'a, T: TransparentType + 'a> std::iter::Extend<&'a T> for Slice<T> {
156    #[inline]
157    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
158        let iter = iter.into_iter();
159        self.reserve(iter.size_hint().0);
160
161        for item in iter {
162            self.push(item.clone());
163        }
164    }
165}
166
167impl<T: TransparentType> std::iter::FromIterator<T> for Slice<T> {
168    #[inline]
169    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
170        let iter = iter.into_iter();
171        let mut s = Self::with_capacity(iter.size_hint().0);
172        for item in iter {
173            s.push(item);
174        }
175        s
176    }
177}
178
179impl<'a, T: TransparentType> std::iter::IntoIterator for &'a Slice<T> {
180    type Item = &'a T;
181    type IntoIter = std::slice::Iter<'a, T>;
182
183    #[inline]
184    fn into_iter(self) -> Self::IntoIter {
185        self.as_slice().iter()
186    }
187}
188
189impl<'a, T: TransparentType> std::iter::IntoIterator for &'a mut Slice<T> {
190    type Item = &'a mut T;
191    type IntoIter = std::slice::IterMut<'a, T>;
192
193    #[inline]
194    fn into_iter(self) -> Self::IntoIter {
195        self.as_mut_slice().iter_mut()
196    }
197}
198
199impl<T: TransparentType> std::iter::IntoIterator for Slice<T> {
200    type Item = T;
201    type IntoIter = IntoIter<T>;
202
203    #[inline]
204    fn into_iter(self) -> Self::IntoIter {
205        IntoIter::new(self)
206    }
207}
208
209pub struct IntoIter<T: TransparentType> {
210    ptr: ptr::NonNull<T::GlibType>,
211    idx: ptr::NonNull<T::GlibType>,
212    len: usize,
213    empty: bool,
214}
215
216impl<T: TransparentType> IntoIter<T> {
217    #[inline]
218    fn new(slice: Slice<T>) -> Self {
219        let slice = mem::ManuallyDrop::new(slice);
220        IntoIter {
221            ptr: slice.ptr,
222            idx: slice.ptr,
223            len: slice.len,
224            empty: slice.capacity == 0,
225        }
226    }
227
228    // rustdoc-stripper-ignore-next
229    /// Returns the remaining items as slice.
230    #[inline]
231    pub fn as_slice(&self) -> &[T] {
232        unsafe {
233            if self.len == 0 {
234                &[]
235            } else {
236                std::slice::from_raw_parts(self.idx.as_ptr() as *mut T, self.len)
237            }
238        }
239    }
240
241    // rustdoc-stripper-ignore-next
242    /// Returns the remaining items as mutable slice.
243    #[inline]
244    pub fn as_mut_slice(&mut self) -> &mut [T] {
245        unsafe {
246            if self.len == 0 {
247                &mut []
248            } else {
249                std::slice::from_raw_parts_mut(self.idx.as_ptr() as *mut T, self.len)
250            }
251        }
252    }
253}
254
255impl<T: TransparentType> Drop for IntoIter<T> {
256    #[inline]
257    fn drop(&mut self) {
258        unsafe {
259            if mem::needs_drop::<T>() {
260                for i in 0..self.len {
261                    ptr::drop_in_place::<T>(self.idx.as_ptr().add(i) as *mut T);
262                }
263            }
264
265            if !self.empty {
266                ffi::g_free(self.ptr.as_ptr() as ffi::gpointer);
267            }
268        }
269    }
270}
271
272impl<T: TransparentType> Iterator for IntoIter<T> {
273    type Item = T;
274
275    #[inline]
276    fn next(&mut self) -> Option<Self::Item> {
277        if self.len == 0 {
278            return None;
279        }
280
281        unsafe {
282            let p = self.idx.as_ptr();
283            self.len -= 1;
284            self.idx = ptr::NonNull::new_unchecked(p.add(1));
285            Some(ptr::read(p as *mut T))
286        }
287    }
288
289    #[inline]
290    fn size_hint(&self) -> (usize, Option<usize>) {
291        (self.len, Some(self.len))
292    }
293
294    #[inline]
295    fn count(self) -> usize {
296        self.len
297    }
298
299    #[inline]
300    fn last(mut self) -> Option<T> {
301        if self.len == 0 {
302            None
303        } else {
304            self.len -= 1;
305            Some(unsafe { ptr::read(self.idx.as_ptr().add(self.len) as *mut T) })
306        }
307    }
308}
309
310impl<T: TransparentType> DoubleEndedIterator for IntoIter<T> {
311    #[inline]
312    fn next_back(&mut self) -> Option<T> {
313        if self.len == 0 {
314            None
315        } else {
316            self.len -= 1;
317            Some(unsafe { ptr::read(self.idx.as_ptr().add(self.len) as *mut T) })
318        }
319    }
320}
321
322impl<T: TransparentType> ExactSizeIterator for IntoIter<T> {}
323
324impl<T: TransparentType> std::iter::FusedIterator for IntoIter<T> {}
325
326impl<T: TransparentType> From<Slice<T>> for Vec<T> {
327    #[inline]
328    fn from(mut value: Slice<T>) -> Self {
329        unsafe {
330            let mut s = Vec::with_capacity(value.len);
331            ptr::copy_nonoverlapping(value.ptr.as_ptr() as *const T, s.as_mut_ptr(), value.len);
332            s.set_len(value.len);
333            value.len = 0;
334            s
335        }
336    }
337}
338
339impl<T: TransparentType> From<Vec<T>> for Slice<T> {
340    #[inline]
341    fn from(mut value: Vec<T>) -> Self {
342        unsafe {
343            let mut s = Self::with_capacity(value.len());
344            ptr::copy_nonoverlapping(value.as_ptr(), s.ptr.as_ptr() as *mut T, value.len());
345            s.len = value.len();
346            value.set_len(0);
347            s
348        }
349    }
350}
351
352impl<T: TransparentType, const N: usize> From<[T; N]> for Slice<T> {
353    #[inline]
354    fn from(value: [T; N]) -> Self {
355        unsafe {
356            let value = mem::ManuallyDrop::new(value);
357            let len = value.len();
358            let mut s = Self::with_capacity(len);
359            ptr::copy_nonoverlapping(value.as_ptr(), s.ptr.as_ptr() as *mut T, len);
360            s.len = len;
361            s
362        }
363    }
364}
365
366impl<'a, T: TransparentType> From<&'a [T]> for Slice<T> {
367    #[inline]
368    fn from(value: &'a [T]) -> Self {
369        unsafe {
370            let mut s = Self::with_capacity(value.len());
371            for (i, item) in value.iter().enumerate() {
372                ptr::write(s.ptr.as_ptr().add(i) as *mut T, item.clone());
373            }
374            s.len = value.len();
375            s
376        }
377    }
378}
379
380impl<'a, T: TransparentType> From<&'a [&'a T]> for Slice<T> {
381    #[inline]
382    fn from(value: &'a [&'a T]) -> Self {
383        unsafe {
384            let mut s = Self::with_capacity(value.len());
385            for (i, item) in value.iter().enumerate() {
386                ptr::write(s.ptr.as_ptr().add(i) as *mut T, (*item).clone());
387            }
388            s.len = value.len();
389            s
390        }
391    }
392}
393
394impl<T: TransparentType> Clone for Slice<T> {
395    #[inline]
396    fn clone(&self) -> Self {
397        Self::from(self.as_slice())
398    }
399}
400
401impl<T: TransparentType> Slice<T> {
402    // rustdoc-stripper-ignore-next
403    /// Borrows a C array.
404    #[inline]
405    pub unsafe fn from_glib_borrow_num<'a>(ptr: *const T::GlibType, len: usize) -> &'a [T] {
406        debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<T::GlibType>());
407        debug_assert!(!ptr.is_null() || len == 0);
408
409        if len == 0 {
410            &[]
411        } else {
412            std::slice::from_raw_parts(ptr as *const T, len)
413        }
414    }
415
416    // rustdoc-stripper-ignore-next
417    /// Borrows a mutable C array.
418    #[inline]
419    pub unsafe fn from_glib_borrow_num_mut<'a>(ptr: *mut T::GlibType, len: usize) -> &'a mut [T] {
420        debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<T::GlibType>());
421        debug_assert!(!ptr.is_null() || len == 0);
422
423        if len == 0 {
424            &mut []
425        } else {
426            std::slice::from_raw_parts_mut(ptr as *mut T, len)
427        }
428    }
429
430    // rustdoc-stripper-ignore-next
431    /// Borrows a C array of references.
432    #[inline]
433    pub unsafe fn from_glib_ptr_borrow_num<'a>(
434        ptr: *const *const T::GlibType,
435        len: usize,
436    ) -> &'a [&'a T] {
437        debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<T::GlibType>());
438        debug_assert!(!ptr.is_null() || len == 0);
439
440        if len == 0 {
441            &[]
442        } else {
443            std::slice::from_raw_parts(ptr as *const &T, len)
444        }
445    }
446
447    // rustdoc-stripper-ignore-next
448    /// Borrows a mutable C array.
449    #[inline]
450    pub unsafe fn from_glib_ptr_borrow_num_mut<'a>(
451        ptr: *mut *mut T::GlibType,
452        len: usize,
453    ) -> &'a mut [&'a mut T] {
454        debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<T::GlibType>());
455        debug_assert!(!ptr.is_null() || len == 0);
456
457        if len == 0 {
458            &mut []
459        } else {
460            std::slice::from_raw_parts_mut(ptr as *mut &mut T, len)
461        }
462    }
463
464    // rustdoc-stripper-ignore-next
465    /// Create a new `Slice` around a C array.
466    #[inline]
467    pub unsafe fn from_glib_none_num(ptr: *const T::GlibType, len: usize) -> Self {
468        debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<T::GlibType>());
469        debug_assert!(!ptr.is_null() || len == 0);
470
471        if len == 0 {
472            Slice::default()
473        } else {
474            // Need to fully copy the array here.
475            let s = Self::from_glib_borrow_num(ptr, len);
476            Self::from(s)
477        }
478    }
479
480    // rustdoc-stripper-ignore-next
481    /// Create a new `Slice` around a C array.
482    #[inline]
483    pub unsafe fn from_glib_container_num(ptr: *mut T::GlibType, len: usize) -> Self {
484        debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<T::GlibType>());
485        debug_assert!(!ptr.is_null() || len == 0);
486
487        if len == 0 {
488            ffi::g_free(ptr as ffi::gpointer);
489            Slice::default()
490        } else {
491            // Need to clone every item because we don't own it here but only
492            // if this type requires explicit drop.
493            if mem::needs_drop::<T>() {
494                for i in 0..len {
495                    let p = ptr.add(i) as *mut T;
496                    let clone: T = (*p).clone();
497                    ptr::write(p, clone);
498                }
499            }
500
501            // And now it can be handled exactly the same as `from_glib_full_num()`.
502            Self::from_glib_full_num(ptr, len)
503        }
504    }
505
506    // rustdoc-stripper-ignore-next
507    /// Create a new `Slice` around a C array.
508    #[inline]
509    pub unsafe fn from_glib_full_num(ptr: *mut T::GlibType, len: usize) -> Self {
510        debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<T::GlibType>());
511        debug_assert!(!ptr.is_null() || len == 0);
512
513        if len == 0 {
514            ffi::g_free(ptr as ffi::gpointer);
515            Slice::default()
516        } else {
517            Slice {
518                ptr: ptr::NonNull::new_unchecked(ptr),
519                len,
520                capacity: len,
521            }
522        }
523    }
524
525    // rustdoc-stripper-ignore-next
526    /// Creates a new empty slice.
527    #[inline]
528    pub fn new() -> Self {
529        debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<T::GlibType>());
530
531        Slice {
532            ptr: ptr::NonNull::dangling(),
533            len: 0,
534            capacity: 0,
535        }
536    }
537
538    // rustdoc-stripper-ignore-next
539    /// Creates a new empty slice with the given capacity.
540    #[inline]
541    pub fn with_capacity(capacity: usize) -> Self {
542        let mut s = Self::new();
543        s.reserve(capacity);
544        s
545    }
546
547    // rustdoc-stripper-ignore-next
548    /// Returns the underlying pointer.
549    ///
550    /// This is guaranteed to be `NULL`-terminated.
551    #[inline]
552    pub fn as_ptr(&self) -> *const T::GlibType {
553        if self.len == 0 {
554            ptr::null()
555        } else {
556            self.ptr.as_ptr()
557        }
558    }
559
560    // rustdoc-stripper-ignore-next
561    /// Returns the underlying pointer.
562    ///
563    /// This is guaranteed to be `NULL`-terminated.
564    #[inline]
565    pub fn as_mut_ptr(&mut self) -> *mut T::GlibType {
566        if self.len == 0 {
567            ptr::null_mut()
568        } else {
569            self.ptr.as_ptr()
570        }
571    }
572
573    // rustdoc-stripper-ignore-next
574    /// Consumes the slice and returns the underlying pointer.
575    ///
576    /// This is guaranteed to be `NULL`-terminated.
577    #[inline]
578    pub fn into_raw(mut self) -> *mut T::GlibType {
579        if self.len == 0 {
580            ptr::null_mut()
581        } else {
582            self.len = 0;
583            self.capacity = 0;
584            self.ptr.as_ptr()
585        }
586    }
587
588    // rustdoc-stripper-ignore-next
589    /// Gets the length of the slice.
590    #[inline]
591    pub fn len(&self) -> usize {
592        self.len
593    }
594
595    // rustdoc-stripper-ignore-next
596    /// Returns `true` if the slice is empty.
597    #[inline]
598    pub fn is_empty(&self) -> bool {
599        self.len == 0
600    }
601
602    // rustdoc-stripper-ignore-next
603    /// Returns the capacity of the slice.
604    #[inline]
605    pub fn capacity(&self) -> usize {
606        self.capacity
607    }
608
609    // rustdoc-stripper-ignore-next
610    /// Sets the length of the slice to `len`.
611    ///
612    /// # SAFETY
613    ///
614    /// There must be at least `len` valid items.
615    pub unsafe fn set_len(&mut self, len: usize) {
616        self.len = len;
617    }
618
619    // rustdoc-stripper-ignore-next
620    /// Reserves at least this much additional capacity.
621    pub fn reserve(&mut self, additional: usize) {
622        // Nothing new to reserve as there's still enough space
623        if self.len + additional <= self.capacity {
624            return;
625        }
626
627        let new_capacity = usize::next_power_of_two(std::cmp::max(
628            self.len + additional,
629            MIN_SIZE / mem::size_of::<T>(),
630        ));
631        assert_ne!(new_capacity, 0);
632        assert!(new_capacity > self.capacity);
633
634        unsafe {
635            let ptr = if self.capacity == 0 {
636                ptr::null_mut()
637            } else {
638                self.ptr.as_ptr() as *mut _
639            };
640            let new_ptr =
641                ffi::g_realloc(ptr, mem::size_of::<T>().checked_mul(new_capacity).unwrap())
642                    as *mut T::GlibType;
643            self.ptr = ptr::NonNull::new_unchecked(new_ptr);
644            self.capacity = new_capacity;
645        }
646    }
647
648    // rustdoc-stripper-ignore-next
649    /// Borrows this slice as a `&[T]`.
650    #[inline]
651    pub fn as_slice(&self) -> &[T] {
652        unsafe {
653            if self.len == 0 {
654                &[]
655            } else {
656                std::slice::from_raw_parts(self.ptr.as_ptr() as *const T, self.len)
657            }
658        }
659    }
660
661    // rustdoc-stripper-ignore-next
662    /// Borrows this slice as a `&mut [T]`.
663    #[inline]
664    pub fn as_mut_slice(&mut self) -> &mut [T] {
665        unsafe {
666            if self.len == 0 {
667                &mut []
668            } else {
669                std::slice::from_raw_parts_mut(self.ptr.as_ptr() as *mut T, self.len)
670            }
671        }
672    }
673
674    // rustdoc-stripper-ignore-next
675    /// Removes all items from the slice.
676    #[inline]
677    pub fn clear(&mut self) {
678        unsafe {
679            if mem::needs_drop::<T>() {
680                for i in 0..self.len {
681                    ptr::drop_in_place::<T>(self.ptr.as_ptr().add(i) as *mut T);
682                }
683            }
684
685            self.len = 0;
686        }
687    }
688
689    // rustdoc-stripper-ignore-next
690    /// Clones and appends all elements in `slice` to the slice.
691    #[inline]
692    pub fn extend_from_slice(&mut self, other: &[T]) {
693        // Nothing new to reserve as there's still enough space
694        if self.len + other.len() > self.capacity {
695            self.reserve(other.len());
696        }
697
698        unsafe {
699            for item in other {
700                ptr::write(self.ptr.as_ptr().add(self.len) as *mut T, item.clone());
701                self.len += 1;
702            }
703        }
704    }
705
706    // rustdoc-stripper-ignore-next
707    /// Inserts `item` at position `index` of the slice, shifting all elements after it to the
708    /// right.
709    #[inline]
710    #[allow(clippy::int_plus_one)]
711    pub fn insert(&mut self, index: usize, item: T) {
712        assert!(index <= self.len);
713
714        // Nothing new to reserve as there's still enough space
715        if self.len + 1 > self.capacity {
716            self.reserve(1);
717        }
718
719        unsafe {
720            if index == self.len {
721                ptr::write(self.ptr.as_ptr().add(self.len) as *mut T, item);
722            } else {
723                let p = self.ptr.as_ptr().add(index);
724                ptr::copy(p, p.add(1), self.len - index);
725                ptr::write(self.ptr.as_ptr().add(index) as *mut T, item);
726            }
727
728            self.len += 1;
729        }
730    }
731
732    // rustdoc-stripper-ignore-next
733    /// Pushes `item` to the end of the slice.
734    #[inline]
735    #[allow(clippy::int_plus_one)]
736    pub fn push(&mut self, item: T) {
737        // Nothing new to reserve as there's still enough space
738        if self.len + 1 > self.capacity {
739            self.reserve(1);
740        }
741
742        unsafe {
743            ptr::write(self.ptr.as_ptr().add(self.len) as *mut T, item);
744            self.len += 1;
745        }
746    }
747
748    // rustdoc-stripper-ignore-next
749    /// Removes item from position `index` of the slice, shifting all elements after it to the
750    /// left.
751    #[inline]
752    pub fn remove(&mut self, index: usize) -> T {
753        assert!(index < self.len);
754
755        unsafe {
756            let p = self.ptr.as_ptr().add(index);
757            let item = ptr::read(p as *mut T);
758            ptr::copy(p.add(1), p, self.len - index - 1);
759
760            self.len -= 1;
761
762            item
763        }
764    }
765
766    // rustdoc-stripper-ignore-next
767    /// Removes the last item of the slice and returns it.
768    #[inline]
769    pub fn pop(&mut self) -> Option<T> {
770        if self.len == 0 {
771            return None;
772        }
773
774        unsafe {
775            self.len -= 1;
776            let p = self.ptr.as_ptr().add(self.len);
777            let item = ptr::read(p as *mut T);
778
779            Some(item)
780        }
781    }
782
783    // rustdoc-stripper-ignore-next
784    /// Shortens the slice by keeping the last `len` items.
785    ///
786    /// If there are fewer than `len` items then this has no effect.
787    #[inline]
788    pub fn truncate(&mut self, len: usize) {
789        if self.len <= len {
790            return;
791        }
792
793        unsafe {
794            while self.len > len {
795                self.len -= 1;
796                let p = self.ptr.as_ptr().add(self.len);
797                ptr::drop_in_place::<T>(p as *mut T);
798            }
799        }
800    }
801}
802
803impl<T: TransparentType + 'static> FromGlibContainer<T::GlibType, *mut T::GlibType> for Slice<T> {
804    unsafe fn from_glib_none_num(ptr: *mut T::GlibType, num: usize) -> Self {
805        Self::from_glib_none_num(ptr, num)
806    }
807
808    #[inline]
809    unsafe fn from_glib_container_num(ptr: *mut T::GlibType, num: usize) -> Self {
810        Self::from_glib_container_num(ptr, num)
811    }
812
813    #[inline]
814    unsafe fn from_glib_full_num(ptr: *mut T::GlibType, num: usize) -> Self {
815        Self::from_glib_full_num(ptr, num)
816    }
817}
818
819impl<T: TransparentType + 'static> FromGlibContainer<T::GlibType, *const T::GlibType> for Slice<T> {
820    unsafe fn from_glib_none_num(ptr: *const T::GlibType, num: usize) -> Self {
821        Self::from_glib_none_num(ptr, num)
822    }
823
824    unsafe fn from_glib_container_num(_ptr: *const T::GlibType, _num: usize) -> Self {
825        unimplemented!();
826    }
827
828    unsafe fn from_glib_full_num(_ptr: *const T::GlibType, _num: usize) -> Self {
829        unimplemented!();
830    }
831}
832
833impl<'a, T: TransparentType + 'a> ToGlibPtr<'a, *mut T::GlibType> for Slice<T> {
834    type Storage = PhantomData<&'a Self>;
835
836    #[inline]
837    fn to_glib_none(&'a self) -> Stash<'a, *mut T::GlibType, Self> {
838        Stash(self.as_ptr() as *mut _, PhantomData)
839    }
840
841    #[inline]
842    fn to_glib_container(&'a self) -> Stash<'a, *mut T::GlibType, Self> {
843        unsafe {
844            let ptr = ffi::g_malloc(mem::size_of::<T>().checked_mul(self.len()).unwrap())
845                as *mut T::GlibType;
846            ptr::copy_nonoverlapping(self.as_ptr(), ptr, self.len());
847            Stash(ptr, PhantomData)
848        }
849    }
850
851    #[inline]
852    fn to_glib_full(&self) -> *mut T::GlibType {
853        self.clone().into_raw()
854    }
855}
856
857impl<'a, T: TransparentType + 'a> ToGlibPtr<'a, *const T::GlibType> for Slice<T> {
858    type Storage = PhantomData<&'a Self>;
859
860    #[inline]
861    fn to_glib_none(&'a self) -> Stash<'a, *const T::GlibType, Self> {
862        Stash(self.as_ptr(), PhantomData)
863    }
864}
865
866impl<'a, T: TransparentType + 'a> ToGlibPtrMut<'a, *mut T::GlibType> for Slice<T> {
867    type Storage = PhantomData<&'a mut Self>;
868
869    #[inline]
870    fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut T::GlibType, Self> {
871        StashMut(self.as_mut_ptr(), PhantomData)
872    }
873}
874
875impl<T: TransparentType + 'static> IntoGlibPtr<*mut T::GlibType> for Slice<T> {
876    #[inline]
877    unsafe fn into_glib_ptr(self) -> *mut T::GlibType {
878        self.into_raw()
879    }
880}
881
882impl<T: TransparentPtrType> From<super::PtrSlice<T>> for Slice<T> {
883    fn from(value: super::PtrSlice<T>) -> Self {
884        let len = value.len();
885        let capacity = value.capacity();
886        unsafe {
887            let ptr = value.into_raw();
888            Slice::<T> {
889                ptr: ptr::NonNull::new_unchecked(ptr),
890                len,
891                capacity,
892            }
893        }
894    }
895}
896
897#[cfg(test)]
898mod test {
899    use super::*;
900
901    #[test]
902    fn test_from_glib_full() {
903        let items = [
904            crate::Date::from_dmy(20, crate::DateMonth::November, 2021).unwrap(),
905            crate::Date::from_dmy(21, crate::DateMonth::November, 2021).unwrap(),
906            crate::Date::from_dmy(22, crate::DateMonth::November, 2021).unwrap(),
907            crate::Date::from_dmy(23, crate::DateMonth::November, 2021).unwrap(),
908        ];
909
910        let slice = unsafe {
911            let ptr = ffi::g_malloc(mem::size_of::<ffi::GDate>() * 4) as *mut ffi::GDate;
912            ptr::write(ptr.add(0), *items[0].to_glib_none().0);
913            ptr::write(ptr.add(1), *items[1].to_glib_none().0);
914            ptr::write(ptr.add(2), *items[2].to_glib_none().0);
915            ptr::write(ptr.add(3), *items[3].to_glib_none().0);
916
917            Slice::<crate::Date>::from_glib_full_num(ptr, 4)
918        };
919
920        assert_eq!(&items[..], &*slice);
921    }
922
923    #[test]
924    fn test_from_glib_none() {
925        let items = [
926            crate::Date::from_dmy(20, crate::DateMonth::November, 2021).unwrap(),
927            crate::Date::from_dmy(21, crate::DateMonth::November, 2021).unwrap(),
928            crate::Date::from_dmy(22, crate::DateMonth::November, 2021).unwrap(),
929            crate::Date::from_dmy(23, crate::DateMonth::November, 2021).unwrap(),
930        ];
931
932        let slice = unsafe {
933            Slice::<crate::Date>::from_glib_none_num(items.as_ptr() as *const ffi::GDate, 4)
934        };
935
936        assert_eq!(&items[..], &*slice);
937    }
938
939    #[test]
940    fn test_safe_api() {
941        let items = [
942            crate::Date::from_dmy(20, crate::DateMonth::November, 2021).unwrap(),
943            crate::Date::from_dmy(21, crate::DateMonth::November, 2021).unwrap(),
944            crate::Date::from_dmy(22, crate::DateMonth::November, 2021).unwrap(),
945        ];
946
947        let mut slice = Slice::from(&items[..]);
948        assert_eq!(slice.len(), 3);
949        slice.push(crate::Date::from_dmy(23, crate::DateMonth::November, 2021).unwrap());
950        assert_eq!(slice.len(), 4);
951
952        for (a, b) in Iterator::zip(items.iter(), slice.iter()) {
953            assert_eq!(a, b);
954        }
955        assert_eq!(
956            (slice[3].day(), slice[3].month(), slice[3].year()),
957            (23, crate::DateMonth::November, 2021)
958        );
959
960        let vec = Vec::from(slice);
961        assert_eq!(vec.len(), 4);
962        for (a, b) in Iterator::zip(items.iter(), vec.iter()) {
963            assert_eq!(a, b);
964        }
965        assert_eq!(
966            (vec[3].day(), vec[3].month(), vec[3].year()),
967            (23, crate::DateMonth::November, 2021)
968        );
969
970        let mut slice = Slice::from(vec);
971        assert_eq!(slice.len(), 4);
972        let e = slice.pop().unwrap();
973        assert_eq!(
974            (e.day(), e.month(), e.year()),
975            (23, crate::DateMonth::November, 2021)
976        );
977        assert_eq!(slice.len(), 3);
978        slice.insert(2, e);
979        assert_eq!(slice.len(), 4);
980        assert_eq!(slice[0].day(), 20);
981        assert_eq!(slice[1].day(), 21);
982        assert_eq!(slice[2].day(), 23);
983        assert_eq!(slice[3].day(), 22);
984        let e = slice.remove(2);
985        assert_eq!(
986            (e.day(), e.month(), e.year()),
987            (23, crate::DateMonth::November, 2021)
988        );
989        assert_eq!(slice.len(), 3);
990        slice.push(e);
991        assert_eq!(slice.len(), 4);
992
993        for (a, b) in Iterator::zip(items.iter(), slice.into_iter()) {
994            assert_eq!(a, &b);
995        }
996    }
997}