slice_rc/
strong.rs

1use std::{borrow::Borrow, cmp::Ordering, fmt::{self, Debug, Formatter, Pointer}, hash::{Hash, Hasher}, marker::PhantomData, mem::{forget, MaybeUninit}, ops::{Bound, Deref, Index}, ptr::NonNull, str::Utf8Error};
2
3use crate::{InnerHeader, SrcIndex, SrcSlice, SrcTarget, UninitSrc, UniqueSrc, WeakSrc};
4
5/// A single-threaded sliceable reference-counting pointer. 'Src' stands for 'Slice Reference Counted'. 
6/// 
7/// See [`std::rc`] for details about general reference-counting pointers.
8/// 
9/// `Src` is a variation on [`Rc`](std::rc::Rc); the functionality that differentiates them can be accessed with the method [`Src::slice`].
10/// 
11/// Many of the inherent methods of `Src` are associated functions, which means that you have to call them as e.g.,
12/// [`Src::downgrade(&value)`](Src::downgrade) instead of `value.downgrade()`;
13/// this avoids conflicts with methods of the inner type `T`.
14/// However, some methods, e.g. [`Src::slice`], are permitted to remain as methods because the inner type is known not to have a conflicting method,
15/// and some, e.g. [`Src::len`], intentionally shadow a known method of the inner type because they use a more efficient computation for the same result.
16pub struct Src<T: SrcTarget + ?Sized> {
17  
18  // SAFETY:
19  // requires:
20  // * initialized from InnerHeader::new_inner::<T::Item>(_)
21  pub(crate) header: NonNull<InnerHeader>,
22  // SAFETY:
23  // requires:
24  // * initialized from either InnerHeader::get_body_ptr::<T::Item>(self.header) or InnerHeader::get_elem_ptr::<T::Item>(self.header, i) where 0 <= i <= InnerHeader::get_header(self.header).len()
25  // * all body elements have been properly initialized (e.g., self.start.as_ref() will not cause UB)
26  pub(crate) start: NonNull<T::Item>,
27  // SAFETY:
28  // requires when T: SrcSlice:
29  // * self.start.add(self.len) <= InnerHeader::get_body_ptr::<T::Item>(self.header).add(InnerHeader::get_header(self.header).len())
30  // requires when T: Sized:
31  // * self.start < InnerHeader::get_body_ptr::<T::Item>(self.header).add(InnerHeader::get_header(self.header).len())
32  pub(crate) len: T::Len,
33  pub(crate) _phantom: PhantomData<*const T>,
34  
35}
36
37impl<T: SrcTarget + ?Sized> Src<T> {
38  
39  fn header(&self) -> &InnerHeader {
40    // SAFETY:
41    // * the invariant for self.header guarantees that it is from InnerHeader::new_inner::<T::Item>
42    // * the header is only accessed from InnerHeader::get_header
43    unsafe { InnerHeader::get_header(self.header) }
44  }
45  
46  /// Returns `true` if the two `Src`s point to slices starting at the same location in memory, akin to [`ptr::eq`](std::ptr::eq).
47  /// 
48  /// ```rust
49  /// use slice_rc::Src;
50  /// 
51  /// let slice = Src::from_array([1, 2, 3]);
52  /// let same_slice = Src::clone(&slice);
53  /// let sub_slice = slice.slice(1..);
54  /// let other_slice = Src::from_array([1, 2, 3]);
55  /// 
56  /// assert!(Src::ptr_eq(&slice, &same_slice));
57  /// assert!(!Src::ptr_eq(&slice, &sub_slice));
58  /// assert!(!Src::ptr_eq(&slice, &other_slice));
59  /// ```
60  /// 
61  /// If `Src::ptr_eq(&a, &b)` returns true, then <code>Src::[same_root](Src::same_root)(&a, &b)</code> will also be true.
62  /// 
63  /// The type parameter, `U`, is to allow `Src`s of different types that _could_ be of the same allocation, and therefore, _could_ be equal by pointer, to be compared, e.g.:
64  /// ```rust
65  /// # use slice_rc::Src;
66  /// let single: Src<i32> = Src::single(4);
67  /// let slice: Src<[i32]> = Src::as_slice(&single);
68  /// 
69  /// assert!(Src::ptr_eq(&single, &slice));
70  /// ```
71  /// 
72  /// Note that this method currently ignores the length of the slice:
73  /// ```rust
74  /// # use slice_rc::Src;
75  /// let root = Src::from_array([1, 2, 3]);
76  /// let first = root.slice(0);
77  /// 
78  /// assert!(Src::ptr_eq(&root, &first));
79  /// 
80  /// let mid_to_end_slice = root.slice(1..);
81  /// let mid_slice = root.slice(1..=1);
82  /// 
83  /// assert!(Src::ptr_eq(&mid_to_end_slice, &mid_slice));
84  /// ```
85  /// It is undecided whether this behavior is desireable, and as such, it may change;
86  /// notably, [`Rc::ptr_eq`](std::rc::Rc::ptr_eq) does ignore metadata for `?Sized` types
87  /// (though that's irrelevant for slices because [`Rc`]s can only point to the whole slice, and therefore the length will always be the same for [`Rc`]s that point to the same allocation),
88  /// while [`ptr::eq`](std::ptr::eq) does consider the metadata (which causes inconsistent results for trait objects, but that is irrelevant here because `Src`s don't support trait objects).
89  /// 
90  /// See also [`Src::same_root`].
91  /// 
92  /// [`Rc`]: std::rc::Rc
93  #[inline]
94  pub fn ptr_eq<U: SrcTarget<Item = T::Item> + ?Sized>(this: &Src<T>, other: &Src<U>) -> bool {
95    this.start == other.start
96  }
97  
98  /// Returns `true` if the two `Src`s share the same [root](crate#root) (i.e., they point to parts of the same allocation).
99  /// 
100  /// ```rust
101  /// use slice_rc::Src;
102  /// 
103  /// let slice = Src::from_array([1, 2, 3]);
104  /// let same_slice = Src::clone(&slice);
105  /// let other_slice = Src::from_array([1, 2, 3]);
106  /// 
107  /// assert!(Src::same_root(&slice, &same_slice));
108  /// assert!(!Src::same_root(&slice, &other_slice));
109  /// ```
110  /// 
111  /// Notably, neither slice has to be the root, nor do they need to overlap at all:
112  /// ```rust
113  /// # use slice_rc::Src;
114  /// let root = Src::from_array([1, 2, 3]);
115  /// let a = root.slice(..1);
116  /// let b = root.slice(2..);
117  /// 
118  /// assert!(Src::same_root(&a, &b));
119  /// ```
120  /// 
121  /// The type parameter, `U`, is to allow `Src`s of different types that _could_ share the same root, to be compared, e.g.:
122  /// ```rust
123  /// # use slice_rc::Src;
124  /// let single: Src<i32> = Src::single(4);
125  /// let slice: Src<[i32]> = Src::as_slice(&single);
126  /// 
127  /// assert!(Src::same_root(&single, &slice));
128  /// ```
129  /// 
130  /// This method ignores the length of the slices in question, but unlike [`Src::ptr_eq`], this will not change,
131  /// as the roots remains the same regardless of which parts of it are included in these slices.
132  /// 
133  /// See also [`Src::ptr_eq`], [`Src::is_root`], and [`Src::root`].
134  #[inline]
135  pub fn same_root<U: SrcTarget<Item = T::Item> + ?Sized>(this: &Src<T>, other: &Src<U>) -> bool {
136    this.header == other.header
137  }
138  
139  /// Returns `true` if this `Src` contains its [root](crate#root) (i.e., it references its entire allocation).
140  /// Notably, this `Src` does not have to be the first one that was initialized, it just has to cover the entire allocation.
141  /// 
142  /// ```rust
143  /// use slice_rc::Src;
144  /// 
145  /// let root = Src::from_array([1, 2, 3]);
146  /// let also_root = root.slice(..);
147  /// let slice = root.slice(1..);
148  /// 
149  /// assert!(Src::is_root(&root));
150  /// assert!(Src::is_root(&also_root));
151  /// assert!(!Src::is_root(&slice));
152  /// ```
153  /// 
154  /// See also [`Src::same_root`] and [`Src::root`].
155  #[inline]
156  pub fn is_root(this: &Src<T>) -> bool {
157    // SAFETY:
158    // * the invariant for this.header guarantees that it is from InnerHeader::new_inner::<T::Item>
159    // * the header is only accessed from InnerHeader::get_header
160    let root_start = unsafe { InnerHeader::get_body_ptr(this.header) };
161    this.start == root_start && T::len_as_usize(this.len) == this.header().len()
162  }
163  
164  /// Creates a [`WeakSrc`] pointer to this slice.
165  /// The [`WeakSrc`] refers to the same slice as this `Src`, and therefore, refers to the [root](crate#root) if and only if this `Src` does.
166  /// 
167  /// ```rust
168  /// use slice_rc::Src;
169  /// 
170  /// let root = Src::from_array([1, 2, 3]);
171  /// 
172  /// let weak_root = Src::downgrade(&root);
173  /// ```
174  pub fn downgrade(this: &Src<T>) -> WeakSrc<T> {
175    this.header().inc_weak_count();
176    WeakSrc {
177      // SAFETY: this.header's invariant implies _.header's invariant
178      header: this.header,
179      // SAFETY: this.header's invariant implies _.header's invariant
180      start: this.start,
181      // SAFETY: this.header's invariant implies _.header's invariant
182      len: this.len,
183      _phantom: PhantomData,
184    }
185  }
186  
187  /// Gets the number of strong (`Src`) pointers to any part of this allocation.
188  /// 
189  /// ```rust
190  /// use slice_rc::Src;
191  /// 
192  /// let root = Src::from_array([1, 2, 3]);
193  /// let _slice = root.slice(1..);
194  /// 
195  /// assert_eq!(2, Src::strong_count(&root));
196  /// ```
197  pub fn strong_count(this: &Src<T>) -> usize {
198    this.header().strong_count()
199  }
200  
201  /// Gets the number of [`WeakSrc`] pointers to any part of this allocation.
202  /// 
203  /// ```rust
204  /// use slice_rc::Src;
205  /// 
206  /// let root = Src::from_array([1, 2, 3]);
207  /// let slice = root.slice(1..);
208  /// let _weak_slice = Src::downgrade(&slice);
209  /// 
210  /// assert_eq!(1, Src::weak_count(&root));
211  /// ```
212  pub fn weak_count(this: &Src<T>) -> usize {
213    this.header().weak_count() - 1
214  }
215  
216  /// Turns this `Src` into a [`UniqueSrc`], if it has only one strong reference.
217  /// 
218  /// Otherwise, an [`Err`] is returned withe the same `Src` that was passed in.
219  /// 
220  /// This will succeed even if there are outstanding weak references,
221  /// though those references will not be able to [`upgrade`](WeakSrc::upgrade) while this allocation is managed by a [`UniqueSrc`].
222  /// 
223  /// ```rust
224  /// use slice_rc::Src;
225  /// 
226  /// let x = Src::single(3);
227  /// assert_eq!(*Src::into_unique(x).unwrap(), 3);
228  /// 
229  /// let x = Src::single(4);
230  /// let _y = Src::clone(&x);
231  /// assert_eq!(*Src::into_unique(x).unwrap_err(), 4);
232  /// ```
233  /// 
234  /// See also [`Src::make_unique`].
235  /// 
236  /// Note that this method (and [`Src::make_unique`]) can currently be used to construct non-[root](crate#root) [`UniqueSrc`]s;
237  /// this behavior has not been thouroghly considered and may be changed or removed in the future.
238  /// As it is, the [`UniqueSrc`] will retain unique ownership of the whole allocation, even the parts it doesn't contain.
239  /// This means that a [`WeakSrc`] to any part of the allocation will not be able to [`upgrade`](WeakSrc::upgrade),
240  /// even if that [`WeakSrc`] does not overlap with the [`UniqueSrc`].
241  pub fn into_unique(this: Src<T>) -> Result<UniqueSrc<T>, Src<T>> {
242    let header = this.header();
243    if header.strong_count() == 1 {
244      // decrease the strong count to 0, but don't drop;
245      // obviously, the UniqueSrc still needs the body to exist, so it shouldn't be dropped,
246      // but the strong count should be 0 so that the weak references can't upgrade (because that Src would be an alias of the UniqueSrc, which violates UniqueSrc's invariant)
247      header.dec_strong_count();
248      let this2 = UniqueSrc {
249        // SAFETY: this.header has the same safety invariant as this2.header, in addition to the requirement that no other strong Src has access to this allocation, which is checked by header.strong_count() == 1
250        header: this.header,
251        // SAFETY: this.start has the same safety invariant as this2.start
252        start: this.start,
253        // SAFETY: this.len has the same safety invariant as this2.len
254        len: this.len,
255        _phantom: PhantomData,
256      };
257      forget(this); // as stated above, don't drop; additionally, now that the strong count has already been set to 0, dropping this would actually cause a panic on debug and probably big problems on release because it would cause integer overflow
258      Ok(this2)
259    } else {
260      Err(this)
261    }
262  }
263  
264  /// If this is the only strong reference to this allocation, then it is turned into a [`UniqueSrc`].
265  /// Otherwise, the contents are cloned and return in a new [`UniqueSrc`].
266  /// 
267  /// This is somewhat like [`Rc::make_mut`](std::rc::Rc::make_mut), but with some subtle differences.
268  /// 
269  /// ```rust
270  /// use slice_rc::{Src, UniqueSrc};
271  /// 
272  /// let data = Src::single(5);
273  /// let mut data = Src::make_unique(data);             // Won't clone anything
274  /// *data += 1;
275  /// let data = UniqueSrc::into_shared(data);
276  /// let other_data = Src::clone(&data);                // Won't clone inner data
277  /// let mut data = Src::make_unique(data);             // Clones inner data
278  /// *data += 1;
279  /// let data = UniqueSrc::into_shared(data);
280  /// let mut data = Src::make_unique(data);             // Won't clone anything
281  /// *data += 1;
282  /// let data = UniqueSrc::into_shared(data);
283  /// let mut other_data = Src::make_unique(other_data); // Won't clone anything
284  /// *other_data *= 2;
285  /// let other_data = UniqueSrc::into_shared(other_data);
286  /// 
287  /// // Now `data` and `other_data` point to different allocations.
288  /// assert_eq!(*data, 8);
289  /// assert_eq!(*other_data, 12);
290  /// ```
291  /// 
292  /// If this is the only `Src` pointer to this allocation,
293  /// but there are some [`WeakSrc`] pointers, then the [`WeakSrc`] pointers will be carried over to the [`UniqueSrc`].
294  /// ```rust
295  /// # use slice_rc::{Src, UniqueSrc};
296  /// let data = Src::single(75);
297  /// let weak = Src::downgrade(&data);
298  /// 
299  /// assert_eq!(75, *data);
300  /// assert_eq!(75, *weak.upgrade().unwrap());
301  /// 
302  /// let mut data = Src::make_unique(data);
303  /// *data += 1;
304  /// 
305  /// assert_eq!(76, *data);
306  /// assert!(weak.upgrade().is_none());
307  /// 
308  /// let data = UniqueSrc::into_shared(data);
309  /// 
310  /// assert_eq!(76, *data);
311  /// assert_eq!(76, *weak.upgrade().unwrap());
312  /// ```
313  /// However, if there are other `Src` pointers to this allocation, any [`WeakSrc`] pointers will remain with the old allocation.
314  /// ```rust
315  /// # use slice_rc::{Src, UniqueSrc};
316  /// let data = Src::single(75);
317  /// let other_data = Src::clone(&data);
318  /// let weak = Src::downgrade(&data);
319  /// 
320  /// assert_eq!(75, *data);
321  /// assert_eq!(75, *other_data);
322  /// assert_eq!(75, *weak.upgrade().unwrap());
323  /// 
324  /// let mut data = Src::make_unique(data);
325  /// *data += 1;
326  /// 
327  /// assert_eq!(76, *data);
328  /// assert_eq!(75, *other_data);
329  /// assert_eq!(75, *weak.upgrade().unwrap());
330  /// 
331  /// let data = UniqueSrc::into_shared(data);
332  /// 
333  /// assert_eq!(76, *data);
334  /// assert_eq!(75, *other_data);
335  /// assert_eq!(75, *weak.upgrade().unwrap());
336  /// ```
337  /// 
338  /// See also [`Src::into_unique`].
339  /// 
340  /// Note that this method (and [`Src::into_unique`]) can currently be used to construct non-[root](crate#root) [`UniqueSrc`]s;
341  /// this behavior has not been thouroghly considered and may be changed or removed in the future.
342  /// As it is, the [`UniqueSrc`] will retain unique ownership of the whole allocation, even the parts it doesn't contain.
343  /// This means that a [`WeakSrc`] to any part of the allocation will not be able to [`upgrade`](WeakSrc::upgrade),
344  /// even if that [`WeakSrc`] does not overlap with the [`UniqueSrc`].
345  pub fn make_unique(this: Src<T>) -> UniqueSrc<T> where T::Item: Clone {
346    Src::into_unique(this).unwrap_or_else(|this| T::new_unique_from_clone(&*this))
347  }
348  
349  /// Returns an `Src` pointer that refers to this `Src`'s [root](crate#root) (i.e., the entire allocation).
350  /// ```rust
351  /// use slice_rc::Src;
352  /// 
353  /// let root = Src::from_array([1, 2, 3]);
354  /// let slice = root.slice(1..);
355  /// drop(root);
356  /// 
357  /// assert_eq!(*slice, [2, 3]);
358  /// 
359  /// let new_root = Src::root(&slice);
360  /// 
361  /// assert_eq!(*new_root, [1, 2, 3]);
362  /// ```
363  /// 
364  /// This method returns an <code>[Src]\<\[T::[Item](crate::SrcTarget::Item)]></code> rather than an <code>[Src]\<T></code> for two reasons:
365  /// * If <code>T: [Sized]</code>, then the root can only be a <code>[Src]\<T></code> if its total length is is `1`, which would prevent situations like this:
366  /// ```rust
367  /// # use slice_rc::Src;
368  /// let root: Src<[i32]> = Src::from_array([1, 2, 3]);
369  /// let slice: Src<i32> = root.slice(1);
370  /// let new_root: Src<[i32]> = Src::root(&slice);
371  /// 
372  /// assert_eq!(*new_root, [1, 2, 3]);
373  /// ```
374  /// * If <code>T = [str]</code>, it could be a UTF-8 slice of a larger allocation that is not entirely UTF-8, which would violate the safety invariant of [`str`]:
375  /// ```rust
376  /// # use slice_rc::Src;
377  /// let root: Src<[u8]> = Src::copied(b"\xFFhello");
378  /// let s: Src<str> = Src::from_utf8(root.slice(1..)).unwrap();
379  /// let new_root: Src<[u8]> = Src::root(&s);
380  /// 
381  /// assert_eq!(&*s, "hello");
382  /// assert!(Src::from_utf8(new_root).is_err());
383  /// ```
384  pub fn root(this: &Src<T>) -> Src<[T::Item]> {
385    let header = this.header();
386    // SAFETY:
387    // * the invariant for self.header guarantees that it is from InnerHeader::new_inner::<T::Item>
388    // * the header is only accessed from InnerHeader::get_header
389    let start = unsafe { InnerHeader::get_body_ptr::<T::Item>(this.header) };
390    header.inc_strong_count();
391    Src {
392      // SAFETY: self.header has the same safety invariant as this.header
393      header: this.header,
394      // SAFETY: start was just aquired from InnerHeader::get_body_ptr::<T::Item>(self.header), which, with the assertions, meets the safety requirement
395      start,
396      // SAFETY: header.len() meets the safety requirements by definition
397      len: header.len(),
398      _phantom: PhantomData,
399    }
400  }
401  
402}
403
404impl<T: SrcSlice + ?Sized> Src<T> {
405  
406  /// Constructs a new [root](crate#root) `Src` of length `0`.
407  /// Note that, because `Src`s are not growable like [`Vec`]s are, this allocation will never become larger.
408  /// Every reference to this allocation is a [root](crate#root).
409  /// 
410  /// ```rust
411  /// use slice_rc::Src;
412  /// 
413  /// let s = Src::<[i32]>::empty();
414  /// 
415  /// assert_eq!(s.len(), 0);
416  /// ```
417  #[inline]
418  pub fn empty() -> Src<T> {
419    UniqueSrc::into_shared(UniqueSrc::empty())
420  }
421  
422  /// Returns the number of elements in this `Src`.
423  /// This method deliberately shadows [`<[T]>::len`](slice::len) and [`str::len`] because this method provides a (slightly) simpler and more efficient implementation.
424  /// 
425  /// This method only returns the length of the whole allocation if `self` is a [root](crate#root) `Src`.
426  /// 
427  /// ```rust
428  /// use slice_rc::Src;
429  /// 
430  /// let s = Src::from_array([1, 2, 3]);
431  /// assert_eq!(s.len(), 3);
432  /// ```
433  #[inline]
434  pub fn len(&self) -> usize {
435    self.len
436  }
437  
438  /// Returns `true` if this `Src` has a length of `0`.
439  /// This method deliberately shadows [`<[T]>::is_empty`](slice::is_empty) and [`str::is_empty`] because this method provides a (slightly) simpler and more efficient implementation.
440  /// 
441  /// Note that this method does not imply that this `Src` was constructed via [`Src::empty`].
442  /// Similarly, it does not imply that the entire allocation is empty, unless `self` is a [root](crate#root) `Src`.
443  /// 
444  /// ```rust
445  /// use slice_rc::Src;
446  /// 
447  /// let a = Src::from_array([1, 2, 3]);
448  /// assert!(!a.is_empty());
449  /// 
450  /// let b = Src::<[i32]>::from_array([]);
451  /// assert!(b.is_empty());
452  /// ```
453  #[inline]
454  pub fn is_empty(&self) -> bool {
455    self.len == 0
456  }
457  
458  /// Returns an `Src` pointer to an element or subslice depending on the type of index.
459  /// * If given a position (only applicable where `Self = Src<[U]>`), returns an `Src<U>` to the element at that position.
460  /// * If given a range, returns the subslice corresponding to that range.
461  /// 
462  /// # Panics
463  /// If the index is in some way out of bounds, or if <code>Self = [Src]\<[str]></code> and the indices are not at [char boundaries](str::is_char_boundary).
464  /// 
465  /// # Examples
466  /// ```rust
467  /// use slice_rc::Src;
468  /// 
469  /// let v = Src::from_array([10, 40, 30]);
470  /// assert_eq!(Src::single(40), v.slice(1));
471  /// assert_eq!(Src::from_array([10, 40]), v.slice(0..2));
472  /// ```
473  /// Panics:
474  /// ```should_panic
475  /// # use slice_rc::Src;
476  /// let v = Src::from_array([10, 40, 30]);
477  /// let _ = v.slice(3);
478  /// let _ = v.slice(0..4);
479  /// ```
480  #[inline]
481  pub fn slice<I: SrcIndex<T>>(&self, index: I) -> Src<I::Output> {
482    index.get(self.clone())
483  }
484  
485  pub(crate) fn into_item(self, index: usize) -> Src<T::Item> {
486    let header = self.header();
487    assert!(index < header.len(), "index {index} out of range for slice of length {}", header.len());
488    // SAFETY: the safety invariant of self.start implies this safety requirement, given the assertion that index <= header.len()
489    let start_ptr = unsafe { self.start.add(index) };
490    let this = Src {
491      // SAFETY: self.header has the same safety invariant as this.header
492      header: self.header,
493      // SAFETY: start_ptr was just aquired from InnerHeader::get_elem_ptr::<T::Item>(self.header, start_inc), which, with the assertions, meets the safety requirement
494      start: start_ptr,
495      // SAFETY: the assertions guarantee the safety requirements
496      len: (),
497      _phantom: PhantomData,
498    };
499    forget(self); // don't modify the strong count because this is logically the same Src
500    this
501  }
502  
503  pub(crate) fn into_slice_from_bounds(self, start: Bound<usize>, end: Bound<usize>) -> Src<T> {
504    let header = self.header();
505    let start_inc = match start {
506      Bound::Excluded(val) => val + 1,
507      Bound::Included(val) => val,
508      Bound::Unbounded => 0,
509    };
510    let end_exc = match end {
511      Bound::Excluded(val) => val,
512      Bound::Included(val) => val + 1,
513      Bound::Unbounded => header.len(),
514    };
515    assert!(start_inc <= end_exc, "slice index starts at {start_inc} but ends at {end_exc}");
516    assert!(end_exc <= header.len(), "range end index {end_exc} out of range for slice of length {}", header.len());
517    T::validate_range(&self, start_inc..end_exc);
518    let len = end_exc - start_inc;
519    // SAFETY: the safety invariant of self.start implies this safety requirement, given the assertion that start_inc <= header.len()
520    let start_ptr = unsafe { self.start.add(start_inc) };
521    let this = Src {
522      // SAFETY: self.header has the same safety invariant as this.header
523      header: self.header,
524      // SAFETY: start_ptr was just aquired from InnerHeader::get_elem_ptr::<T::Item>(self.header, start_inc), which, with the assertions, meets the safety requirement
525      start: start_ptr,
526      // SAFETY: the assertions guarantee the safety requirements
527      len,
528      _phantom: PhantomData,
529    };
530    forget(self); // don't modify the strong count because this is logically the same Src
531    this
532  }
533  
534}
535
536impl<T: Sized> Src<T> {
537  
538  /// Constructs a new [root](crate#root) `Src` that contains only the given value.
539  /// 
540  /// ```rust
541  /// use slice_rc::Src;
542  /// 
543  /// let s = Src::single(42);
544  /// assert_eq!(*s, 42);
545  /// assert_eq!(Src::root(&s).len(), 1);
546  /// ```
547  #[inline]
548  pub fn single(value: T) -> Src<T> {
549    UninitSrc::single().init(value)
550  }
551  
552  /// Constructs a new [root](crate#root) `Src` that contains only the value returned from the given function `f`.
553  /// The [`WeakSrc`] that `f` is given will be a weak reference to this allocation, which allows constructing a self-referential value;
554  /// it will return [`None`] from [`WeakSrc::upgrade`] until after `single_cyclic` has returned.
555  /// 
556  /// This is a convienience method for a specific subset of behavior that can be obtained via [`UninitSrc`].
557  /// 
558  /// ```rust
559  /// use slice_rc::{Src, WeakSrc};
560  /// 
561  /// struct S {
562  ///   me: WeakSrc<S>,
563  /// }
564  /// 
565  /// let s = Src::single_cyclic(|me| S { me: me.clone() });
566  /// 
567  /// assert!(Src::ptr_eq(&s, &s.me.upgrade().unwrap()));
568  /// ```
569  #[inline]
570  pub fn single_cyclic<F: FnOnce(&WeakSrc<T>) -> T>(f: F) -> Src<T> {
571    UniqueSrc::into_shared(UniqueSrc::single_cyclic(f))
572  }
573  
574  /// Constructs a new [root](crate#root) `Src` of length `1` with uninitialized contents.
575  /// 
576  /// ```rust
577  /// use slice_rc::{Src, UniqueSrc};
578  /// 
579  /// let five = Src::<i32>::single_uninit();
580  /// 
581  /// let mut five = Src::into_unique(five).unwrap();
582  /// five.write(5);
583  /// let five = UniqueSrc::into_shared(five);
584  /// 
585  /// let five = unsafe { five.assume_init() };
586  /// 
587  /// assert_eq!(*five, 5);
588  /// ```
589  #[inline]
590  pub fn single_uninit() -> Src<MaybeUninit<T>> {
591    UniqueSrc::into_shared(UniqueSrc::single_uninit())
592  }
593  
594  /// Constructs a new [root](crate#root) `Src` of length `1` with uninitialized contents, with the memory being filled with `0` bytes.
595  /// 
596  /// See [`MaybeUninit::zeroed`] for examples of correct and incorrect usage of this method.
597  /// 
598  /// ```rust
599  /// use slice_rc::Src;
600  /// 
601  /// let zero = Src::<i32>::single_zeroed();
602  /// let zero = unsafe { zero.assume_init() };
603  /// 
604  /// assert_eq!(*zero, 0);
605  /// ```
606  #[inline]
607  pub fn single_zeroed() -> Src<MaybeUninit<T>> {
608    UniqueSrc::into_shared(UniqueSrc::single_zeroed())
609  }
610  
611  /// Returns an `Src` equivalent to this one, but typed as a slice rather than a single element.
612  /// The returned slice will have a length of `1`, and its element `0` will be at the same location in memory as `self`'s value.
613  /// 
614  /// ```rust
615  /// use slice_rc::Src;
616  /// use std::ptr;
617  /// 
618  /// let single = Src::single(42);
619  /// let slice = Src::as_slice(&single);
620  /// 
621  /// assert!(Src::ptr_eq(&single, &slice));
622  /// assert!(ptr::eq(&*single, &slice[0]));
623  /// ```
624  #[inline]
625  pub fn as_slice(this: &Src<T>) -> Src<[T]> {
626    this.header().inc_strong_count();
627    Src {
628      // SAFETY: this.header has the same invariant as this2
629      header: this.header,
630      // SAFETY: this.start has the same invariant as this2
631      start: this.start,
632      // SAFETY: this.len's invariant implies this2.len's invariant
633      len: 1,
634      _phantom: PhantomData,
635    }
636  }
637  
638}
639
640impl<T> Src<[T]> {
641  
642  /// Constructs a new [root](crate#root) `Src` of the given length with uninitialized contents.
643  /// 
644  /// ```rust
645  /// use slice_rc::{Src, UniqueSrc};
646  /// 
647  /// let fives = Src::<[i32]>::new_uninit(3);
648  /// 
649  /// let mut fives = Src::into_unique(fives).unwrap();
650  /// fives[0].write(5);
651  /// fives[1].write(5);
652  /// fives[2].write(5);
653  /// let fives = UniqueSrc::into_shared(fives);
654  /// 
655  /// let fives = unsafe { fives.assume_init() };
656  /// 
657  /// assert_eq!(*fives, [5, 5, 5]);
658  /// ```
659  #[inline]
660  pub fn new_uninit(len: usize) -> Src<[MaybeUninit<T>]> {
661    UniqueSrc::into_shared(UniqueSrc::new_uninit(len))
662  }
663  
664  /// Constructs a new [root](crate#root) `Src` of the given length with uninitialized contents, with the memory being filled with `0` bytes.
665  /// 
666  /// See [`MaybeUninit::zeroed`] for examples of correct and incorrect usage of this method.
667  /// 
668  /// ```rust
669  /// use slice_rc::Src;
670  /// 
671  /// let zeroes = Src::<[i32]>::new_zeroed(3);
672  /// let zeroes = unsafe { zeroes.assume_init() };
673  /// 
674  /// assert_eq!(*zeroes, [0, 0, 0]);
675  /// ```
676  #[inline]
677  pub fn new_zeroed(len: usize) -> Src<[MaybeUninit<T>]> {
678    UniqueSrc::into_shared(UniqueSrc::new_zeroed(len))
679  }
680  
681  /// Constructs a new [root](crate#root) `Src` of the given length where each element is produced by calling `f` with that element's index while walking forward through the slice.
682  /// 
683  /// This essentially the same as writing
684  /// ```text
685  /// Src::from_array([f(0), f(1), f(2), ..., f(len - 2), f(len - 1)])
686  /// ```
687  /// and is similar to `(0..len).map(f)`, just for `Src`s rather than iterators.
688  /// 
689  /// If `len == 0`, this produces an empty `Src` without ever calling `f`.
690  /// 
691  /// ```rust
692  /// use slice_rc::Src;
693  /// 
694  /// let slice = Src::from_fn(5, |i| i);
695  /// assert_eq!(*slice, [0, 1, 2, 3, 4]);
696  /// 
697  /// let slice2 = Src::from_fn(8, |i| i * 2);
698  /// assert_eq!(*slice2, [0, 2, 4, 6, 8, 10, 12, 14]);
699  /// 
700  /// let bool_slice = Src::from_fn(5, |i| i % 2 == 0);
701  /// assert_eq!(*bool_slice, [true, false, true, false, true]);
702  /// ```
703  /// 
704  /// You can also capture things, so you can use closures with mutable state.
705  /// The slice is generated in ascending index order, starting from the front and going towards the back.
706  /// ```rust
707  /// # use slice_rc::Src;
708  /// let mut state = 1;
709  /// let s = Src::from_fn(6, |_| { let x = state; state *= 2; x });
710  /// assert_eq!(*s, [1, 2, 4, 8, 16, 32]);
711  /// ```
712  /// 
713  /// # Panics
714  /// 
715  /// Panics if `f` panics; in this event, any elements that have been initialized will be properly dropped.
716  /// ```rust
717  /// # use slice_rc::Src;
718  /// # use std::cell::Cell;
719  /// thread_local! {
720  ///   static DROPPED: Cell<usize> = Cell::new(0);
721  /// }
722  /// 
723  /// struct Droppable;
724  /// 
725  /// impl Drop for Droppable {
726  ///   fn drop(&mut self) {
727  ///     DROPPED.with(|dropped| dropped.update(|x| x + 1));
728  ///   }
729  /// }
730  /// 
731  /// let _ = std::panic::catch_unwind(|| {
732  ///   Src::from_fn(10, |i| {
733  ///     if i >= 5 { panic!() }
734  ///     Droppable
735  ///   })
736  /// });
737  /// 
738  /// assert_eq!(DROPPED.get(), 5);
739  /// ```
740  #[inline]
741  pub fn from_fn<F: FnMut(usize) -> T>(len: usize, f: F) -> Src<[T]> {
742    UninitSrc::new(len).init_from_fn(f)
743  }
744  
745  /// Constructs a new [root](crate#root) `Src` of the given length where each element is produced by calling `f` with a root [`WeakSrc`] pointer to the new allocation and that element's index while walking forward through the slice.
746  /// 
747  /// This method is like [`Src::from_fn`], but in this the function `f` is passed a root [`WeakSrc`] pointer to the allocation to allow constructing self-referential elements.
748  /// 
749  /// This is a convienience method for a specific subset of behavior that can be obtained via [`UninitSrc`].
750  /// 
751  /// ```rust
752  /// use slice_rc::{Src, WeakSrc};
753  /// 
754  /// struct S {
755  ///   val: usize,
756  ///   root: WeakSrc<[S]>,
757  /// }
758  /// 
759  /// let root = Src::cyclic_from_fn(5, |root, i| S {
760  ///   val: i * 2,
761  ///   root: root.clone(),
762  /// });
763  /// 
764  /// assert_eq!(root.iter().map(|s| s.val).collect::<Vec<_>>(), vec![0, 2, 4, 6, 8]);
765  /// assert!(root.iter().all(|s| Src::ptr_eq(&root, &s.root.upgrade().unwrap())));
766  /// ```
767  /// 
768  /// Note: it should be possible to obtain a weak to just the current element that is being constructed via `weak.slice(i)`,
769  /// but currently a [`WeakSrc`] cannot be sliced while it is non-upgradeable (as it is in this case).
770  /// This is a known issue that will be fixed in the future.
771  pub fn cyclic_from_fn<F: FnMut(&WeakSrc<[T]>, usize) -> T>(len: usize, mut f: F) -> Src<[T]> {
772    let this = UninitSrc::new(len);
773    let weak = this.downgrade();
774    this.init_from_fn(|i| f(&weak, i))
775  }
776  
777  /// Constructs a new [root](crate#root) `Src` from the given iterator.
778  /// 
779  /// This method is essentially shorthand for
780  /// ```rust
781  /// use slice_rc::Src;
782  /// 
783  /// # fn f<T>(iter: impl IntoIterator<Item = T, IntoIter: std::iter::ExactSizeIterator>) -> Src<[T]> {
784  /// let mut iter = iter.into_iter();
785  /// Src::from_fn(iter.len(), |_| iter.next().unwrap())
786  /// # }
787  /// ```
788  /// 
789  /// The iterator must be [`ExactSizeIterator`] because `Src`s cannot be resized,
790  /// so the number of elements must be known at allocation-time, i.e., before any of the elements are initialized.
791  /// If you want to use a non-[`ExactSizeIterator`], use <code>iter.[collect](Iterator::collect)::\<[Vec]\<_>>()</code>.
792  pub fn from_iter<I: IntoIterator<Item = T, IntoIter: ExactSizeIterator>>(iter: I) -> Src<[T]> {
793    let mut iter = iter.into_iter();
794    Self::from_fn(iter.len(), |_| iter.next().unwrap())
795  }
796  
797  /// Constructs a new [root](crate#root) `Src` from the given array.
798  /// 
799  /// This method is effectively equivalent to passing an array to [`Src::from_iter`], but it is more efficient.
800  /// As such, it is effectively shorthand for <code>Src::[from_fn](N, |i| values\[i])</code>, but again, more efficient
801  /// (though not by enough to make <code>Src::from_array([array::from_fn]::<_, N, _>(f))</code> any better than <code>Src::[from_fn](N, f)</code>).
802  /// 
803  /// Note that the my assertions about efficiency are not based any kind of benchmarking,
804  /// just the fact that this method uses a single [`ptr::write`] where [`Src::from_fn`] and [`Src::from_iter`] use `N` arbitrary function calls and `N` [`ptr::write`]s.
805  /// As <code>[array::from_fn]</code> re-introduces at least the `N` arbitrary function calls, its difference (again, without benchmarking) is negligible.
806  /// 
807  /// [from_fn]: Src::from_fn
808  /// [`ptr::write`]: std::ptr::write
809  /// [array::from_fn]: std::array::from_fn
810  #[inline]
811  pub fn from_array<const N: usize>(values: [T; N]) -> Src<[T]> {
812    UniqueSrc::into_shared(UniqueSrc::from_array(values))
813  }
814  
815  /// Constructs a new [root](crate#root) `Src` of the given length where each element is the type's [default](Default::default).
816  /// 
817  /// This method is essentially equivalent to <code>Src::[from_fn](Src::from_fn)(len, |_| [Default::default]\())</code>.
818  #[inline]
819  pub fn from_default(len: usize) -> Src<[T]> where T: Default {
820    Self::from_fn(len, |_| Default::default())
821  }
822  
823  /// Constructs a new [root](crate#root) `Src` of the given length where each element is a clone of `value`.
824  /// 
825  /// This method is essentially equivalent to <code>Src::[from_fn](Src::from_fn)(len, |_| value.[clone](Clone::clone)())</code>.
826  #[inline]
827  pub fn filled(len: usize, value: &T) -> Src<[T]> where T: Clone {
828    Self::from_fn(len, |_| value.clone())
829  }
830  
831  /// Constructs a new [root](crate#root) `Src` of the given length where each element is a clone of the value returned from `f`.
832  /// `f` is passed a root [`WeakSrc`] pointer to the allocation; this can be used to make self-referential structures.
833  /// 
834  /// ```rust
835  /// use slice_rc::{Src, WeakSrc};
836  /// 
837  /// #[derive(Clone)]
838  /// struct S {
839  ///   val: i32,
840  ///   root: WeakSrc<[S]>,
841  /// }
842  /// 
843  /// let root = Src::filled_cyclic(5, |root| S { val: 42, root: root.clone() });
844  /// assert!(root.iter().all(|s| s.val == 42));
845  /// assert!(root.iter().all(|s| Src::ptr_eq(&root, &s.root.upgrade().unwrap())));
846  /// ```
847  #[inline]
848  pub fn filled_cyclic<F: FnOnce(&WeakSrc<[T]>) -> T>(len: usize, f: F) -> Src<[T]> where T: Clone {
849    UniqueSrc::into_shared(UniqueSrc::filled_cyclic(len, f))
850  }
851  
852  /// Constructs a new [root](crate#root) `Src` as a clone of the given slice.
853  /// 
854  /// This method is essentially shorthand for <code>Src::[from_fn](Src::from_fn)(values.[len](slice::len)(), |i| values\[i].clone())</code>,
855  /// but without the implicit bounds checking for slice indexing.
856  #[inline]
857  pub fn cloned(values: &[T]) -> Src<[T]> where T: Clone {
858    UniqueSrc::into_shared(UniqueSrc::cloned(values))
859  }
860  
861  /// Constructs a new [root](crate#root) `Src` as a copy of the given slice.
862  /// 
863  /// This method is functionally shorthand for <code>Src::[from_fn](Src::from_fn)(values.[len](slice::len)(), |i| values\[i])</code>,
864  /// but without the implicit bounds checking for slice indexing.
865  /// 
866  /// This method is fairly efficient, as it is basically just an allocation (requisite for any `Src` constructor) and a [`memcpy`](std::ptr::copy_nonoverlapping).
867  #[inline]
868  pub fn copied(values: &[T]) -> Src<[T]> where T: Copy {
869    UniqueSrc::into_shared(UniqueSrc::copied(values))
870  }
871  
872}
873
874impl<T> Src<MaybeUninit<T>> {
875  
876  /// Converts to `Src<T>`.
877  /// 
878  /// # Safety
879  /// 
880  /// As with [`MaybeUninit::assume_init`], it is up to the caller to guarantee that the inner value really is in an initialized state.
881  /// Calling this when the content is not yet fully initialized causes immediate undefined behavior.
882  /// 
883  /// # Examples
884  /// 
885  /// ```rust
886  /// use slice_rc::Src;
887  /// 
888  /// let zero = Src::<i32>::single_zeroed();
889  /// let zero = unsafe { zero.assume_init() };
890  /// 
891  /// assert_eq!(*zero, 0);
892  /// ```
893  pub unsafe fn assume_init(self) -> Src<T> {
894    // TODO: rephrase the safety requirements for InnerHeader to explicitly allow punning between T and type with T-like layout
895    let this = Src {
896      // SAFETY: self.header has *almost* the same safety invariant as this.header: the only difference is that self uses MaybeUninit<T> where this expects T
897      header: self.header,
898      // SAFETY: self.start has *almost* the same safety invariant as this.start: the only difference is that self uses MaybeUninit<T> where this expects T
899      start: self.start.cast(),
900      // SAFETY: self.len has *almost* the same safety invariant as this.len: the only difference is that self uses MaybeUninit<T> where this expects T
901      len: self.len,
902      _phantom: PhantomData,
903    };
904    forget(self); // don't decrease the strong counter because this is logically the same Src
905    this
906  }
907  
908}
909
910impl<T> Src<[MaybeUninit<T>]> {
911  
912  /// Converts to `Src<[T]>`.
913  /// 
914  /// # Safety
915  /// 
916  /// As with [`MaybeUninit::assume_init`], it is up to the caller to guarantee that the inner value really is in an initialized state.
917  /// Calling this when the content is not yet fully initialized causes immediate undefined behavior.
918  /// 
919  /// # Examples
920  /// 
921  /// ```rust
922  /// use slice_rc::Src;
923  /// 
924  /// let zeroes = Src::<[i32]>::new_zeroed(3);
925  /// let zeroes = unsafe { zeroes.assume_init() };
926  /// 
927  /// assert_eq!(*zeroes, [0, 0, 0]);
928  /// ```
929  pub unsafe fn assume_init(self) -> Src<[T]> {
930    // TODO: rephrase the safety requirements for InnerHeader to explicitly allow punning between T and type with T-like layout
931    let this = Src {
932      // SAFETY: self.header has *almost* the same safety invariant as this.header: the only difference is that self uses MaybeUninit<T> where this expects T
933      header: self.header,
934      // SAFETY: self.start has *almost* the same safety invariant as this.start: the only difference is that self uses MaybeUninit<T> where this expects T
935      start: self.start.cast(),
936      // SAFETY: self.len has *almost* the same safety invariant as this.len: the only difference is that self uses MaybeUninit<T> where this expects T
937      len: self.len,
938      _phantom: PhantomData,
939    };
940    forget(self); // don't decrease the strong counter because this is logically the same Src
941    this
942  }
943  
944}
945
946impl Src<str> {
947  
948  /// Constructs a new [`root`](crate#root) `Src` as a copy of the given string.
949  /// 
950  /// ```rust
951  /// use slice_rc::Src;
952  /// 
953  /// let hello = Src::new("Hello World!");
954  /// 
955  /// assert_eq!(&*hello, "Hello World!");
956  /// ```
957  #[inline]
958  pub fn new(s: impl AsRef<str>) -> Src<str> {
959    UniqueSrc::into_shared(UniqueSrc::new(s))
960  }
961  
962  /// Converts an `Src` of bytes to a string `Src`.
963  /// 
964  /// [`str`] and [`[u8]`](slice) are both slices of bytes, so this function converts between the two.
965  /// Not all byte slices are valid string slices, however: [`str`] must be valid UTF-8.
966  /// This method checks to ensure that the bytes are valid UTF-8, and then does the conversion.
967  /// 
968  /// If you are sure that the byte slice is valid UTF-8, and you don't want to incur the overhead of the validity check,
969  /// there is an unsafe version of this method, [`from_utf8_unchecked`](Src::from_utf8_unchecked),
970  /// which has the same behavior but skips the check.
971  /// 
972  /// # Errors
973  /// 
974  /// Returns `Err` if the slice is not UTF-8 with a description as to why the provided slice is not UTF-8.
975  /// 
976  /// # Examples
977  /// 
978  /// Basic usage:
979  /// 
980  /// ```rust
981  /// use slice_rc::Src;
982  /// 
983  /// let sparkle_heart = Src::from_array([240, 159, 146, 150]);
984  /// 
985  /// let sparkle_heart = Src::from_utf8(sparkle_heart)?;
986  /// 
987  /// assert_eq!("💖", &*sparkle_heart);
988  /// # Ok::<_, std::str::Utf8Error>(())
989  /// ```
990  /// 
991  /// Incorrect bytes:
992  /// 
993  /// ```rust
994  /// # use slice_rc::Src;
995  /// let sparkle_heart = Src::from_array([0, 159, 146, 150]);
996  /// 
997  /// assert!(Src::from_utf8(sparkle_heart).is_err());
998  /// ```
999  #[inline]
1000  pub fn from_utf8(v: Src<[u8]>) -> Result<Src<str>, Utf8Error> {
1001    let _: &str = str::from_utf8(&*v)?;
1002    // SAFETY: <str>::from_utf8() guarantees that the contents are UTF-8
1003    Ok(unsafe { Src::from_utf8_unchecked(v) })
1004  }
1005  
1006  /// Converts an `Src` of bytes to a string `Src` without checking that the string contains valid UTF-8.
1007  /// 
1008  /// See the safe version, [`from_utf8`](Src::from_utf8), for more information.
1009  /// 
1010  /// # Safety
1011  /// 
1012  /// The bytes passed in must be valid UTF-8.
1013  /// 
1014  /// # Examples
1015  /// 
1016  /// ```rust
1017  /// use slice_rc::Src;
1018  /// 
1019  /// let sparkle_heart = Src::from_array([240, 159, 146, 150]);
1020  /// 
1021  /// let sparkle_heart = unsafe { Src::from_utf8_unchecked(sparkle_heart) };
1022  /// 
1023  /// assert_eq!("💖", &*sparkle_heart);
1024  /// ```
1025  #[inline]
1026  pub unsafe fn from_utf8_unchecked(v: Src<[u8]>) -> Src<str> {
1027    // TODO: rephrase the safety requirements for InnerHeader to explicitly allow punning between T and type with T-like layout
1028    let this = Src {
1029      // SAFETY: v.header has *almost* the same safety invariant as this.header: the only difference is that v uses [u8] where this expects str;
1030      //         the pun from [u8] to str adds the safety requirement that v's content is valid UTF-8, but this requirement is passed on to the caller
1031      header: v.header,
1032      // SAFETY: v.start has *almost* the same safety invariant as this.start: the only difference is that v uses [u8] where this expects str;
1033      //         the pun from [u8] to str adds the safety requirement that v's content is valid UTF-8, but this requirement is passed on to the caller
1034      start: v.start,
1035      // SAFETY: v.len has *almost* the same safety invariant as this.len: the only difference is that v uses [u8] where this expects str;
1036      //         the pun from [u8] to str adds the safety requirement that v's content is valid UTF-8, but this requirement is passed on to the caller
1037      len: v.len,
1038      _phantom: PhantomData,
1039    };
1040    forget(v);
1041    this
1042  }
1043  
1044  /// Converts a string `Src` to a `Src` of bytes.
1045  /// To convert the the bytes back to a string, use the [`from_utf8`](Src::from_utf8) method.
1046  /// 
1047  /// # Examples
1048  /// 
1049  /// ```rust
1050  /// use slice_rc::Src;
1051  /// 
1052  /// let bytes = Src::as_bytes(&Src::new("bors"));
1053  /// assert_eq!(b"bors", &*bytes);
1054  /// ```
1055  #[inline]
1056  pub fn as_bytes(this: &Src<str>) -> Src<[u8]> {
1057    this.header().inc_strong_count();
1058    // TODO: rephrase the safety requirements for InnerHeader to explicitly allow punning between T and type with T-like layout
1059    Src {
1060      // SAFETY: this.header has *almost* the same safety invariant as this2.header: the only difference is that this uses str where this2 expects [u8];
1061      //         the pun from str to [u8] relaxes the safety requirement that this's content is valid UTF-8
1062      header: this.header,
1063      // SAFETY: this.start has *almost* the same safety invariant as this2.start: the only difference is that this uses str where this2 expects [u8];
1064      //         the pun from str to [u8] relaxes the safety requirement that this's content is valid UTF-8
1065      start: this.start,
1066      // SAFETY: this.len has *almost* the same safety invariant as this2.len: the only difference is that this uses str where this2 expects [u8];
1067      //         the pun from str to [u8] relaxes the safety requirement that this's content is valid UTF-8
1068      len: this.len,
1069      _phantom: PhantomData,
1070    }
1071  }
1072  
1073}
1074
1075impl<T: SrcTarget + ?Sized> Clone for Src<T> {
1076  
1077  #[inline]
1078  fn clone(&self) -> Self {
1079    self.header().inc_strong_count();
1080    Self {
1081      // SAFETY: this.header has the same safety invariant as _.header
1082      header: self.header,
1083      // SAFETY: this.start has the same safety invariant as _.start
1084      start: self.start,
1085      // SAFETY: this.len has the same safety invariant as _.len
1086      len: self.len,
1087      _phantom: PhantomData,
1088    }
1089  }
1090  
1091}
1092
1093impl<T: Default> Default for Src<T> {
1094  
1095  #[inline]
1096  fn default() -> Self {
1097    Self::single(T::default())
1098  }
1099  
1100}
1101
1102impl<T: SrcTarget + ?Sized> Deref for Src<T> {
1103  
1104  type Target = T;
1105  
1106  #[inline]
1107  fn deref(&self) -> &Self::Target {
1108    T::get(self)
1109  }
1110  
1111}
1112
1113impl<T: SrcTarget + ?Sized> Borrow<T> for Src<T> {
1114  
1115  #[inline]
1116  fn borrow(&self) -> &T {
1117    &**self
1118  }
1119  
1120}
1121
1122impl<T: SrcTarget + ?Sized> AsRef<T> for Src<T> {
1123  
1124  #[inline]
1125  fn as_ref(&self) -> &T {
1126    &**self
1127  }
1128  
1129}
1130
1131impl<T: SrcTarget + Index<I> + ?Sized, I> Index<I> for Src<T> {
1132  
1133  type Output = T::Output;
1134  
1135  #[inline]
1136  fn index(&self, index: I) -> &Self::Output {
1137    &self.deref()[index]
1138  }
1139  
1140}
1141
1142impl<T: Hash + SrcTarget + ?Sized> Hash for Src<T> {
1143  
1144  #[inline]
1145  fn hash<H: Hasher>(&self, state: &mut H) {
1146    T::hash(&**self, state);
1147  }
1148  
1149}
1150
1151impl<T: PartialEq<U> + SrcTarget + ?Sized, U: SrcTarget + ?Sized> PartialEq<Src<U>> for Src<T> {
1152  
1153  #[inline]
1154  fn eq(&self, other: &Src<U>) -> bool {
1155    T::eq(&**self, &**other)
1156  }
1157  
1158  #[inline]
1159  fn ne(&self, other: &Src<U>) -> bool {
1160    T::ne(&**self, &**other)
1161  }
1162  
1163}
1164
1165impl<T: Eq + SrcTarget + ?Sized> Eq for Src<T> {}
1166
1167impl<T: PartialOrd<U> + SrcTarget + ?Sized, U: SrcTarget + ?Sized> PartialOrd<Src<U>> for Src<T> {
1168  
1169  #[inline]
1170  fn ge(&self, other: &Src<U>) -> bool {
1171    T::ge(&**self, &**other)
1172  }
1173  
1174  #[inline]
1175  fn gt(&self, other: &Src<U>) -> bool {
1176    T::gt(&**self, &**other)
1177  }
1178  
1179  #[inline]
1180  fn le(&self, other: &Src<U>) -> bool {
1181    T::le(&**self, &**other)
1182  }
1183  
1184  #[inline]
1185  fn lt(&self, other: &Src<U>) -> bool {
1186    T::lt(&**self, &**other)
1187  }
1188  
1189  #[inline]
1190  fn partial_cmp(&self, other: &Src<U>) -> Option<Ordering> {
1191    T::partial_cmp(&**self, &**other)
1192  }
1193  
1194}
1195
1196impl<T: Ord + SrcTarget + ?Sized> Ord for Src<T> {
1197  
1198  #[inline]
1199  fn cmp(&self, other: &Self) -> Ordering {
1200    T::cmp(&**self, &**other)
1201  }
1202  
1203}
1204
1205impl<T: Debug + SrcTarget + ?Sized> Debug for Src<T> {
1206  
1207  #[inline]
1208  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1209    T::fmt(self, f)
1210  }
1211  
1212}
1213
1214impl<T: SrcTarget + ?Sized> Pointer for Src<T> {
1215  
1216  #[inline]
1217  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1218    Pointer::fmt(&self.start, f)
1219  }
1220  
1221}
1222
1223impl<T: SrcTarget + ?Sized> Drop for Src<T> {
1224  
1225  fn drop(&mut self) {
1226    // SAFETY:
1227    // * all constructor fns for Src initialize header from InnerHeader::new_inner::<T::Item>
1228    // * all constructor fns for Src initialize the elements
1229    // * the header is only accessed from InnerHeader::get_header
1230    // * this is one of two callsites for InnerHeader::drop_strong::<T::Item>, the other being UniqueSrc::drop;
1231    //   as a UniqueSrc cannot co-exist (for the same allocation) with an Src, this will be the last strong reference iff this is the last Src with access to this allocation's body
1232    unsafe { InnerHeader::drop_strong::<T::Item>(self.header); }
1233  }
1234  
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239  
1240  use std::{cell::Cell, mem::MaybeUninit, ops::Deref, panic::{catch_unwind, AssertUnwindSafe}, str::Utf8Error};
1241  
1242  use crate::*;
1243  
1244  #[test]
1245  fn ptr_eq() {
1246    let s1: Src<[u8]> = Src::from_default(0);
1247    let s2: Src<[u8]> = Src::clone(&s1);
1248    assert_eq!(s1, s2);
1249    assert!(Src::ptr_eq(&s1, &s2));
1250    let s3: Src<[u8]> = Src::from_default(0);
1251    assert_eq!(s1, s3);
1252    assert_eq!(s2, s3);
1253    assert!(!Src::ptr_eq(&s1, &s3));
1254    assert!(!Src::ptr_eq(&s2, &s3));
1255  }
1256  
1257  #[test]
1258  fn same_root() {
1259    let s1: Src<[u8]> = Src::from_default(1);
1260    let s2: Src<[u8]> = s1.slice(1..);
1261    assert_ne!(s1, s2);
1262    assert!(!Src::ptr_eq(&s1, &s2));
1263    assert!(Src::same_root(&s1, &s2));
1264    let s3: Src<[u8]> = Src::from_default(1);
1265    let s4: Src<[u8]> = s3.slice(1..);
1266    assert_eq!(s1, s3);
1267    assert_ne!(s3, s4);
1268    assert_eq!(s2, s4);
1269    assert!(!Src::ptr_eq(&s1, &s3));
1270    assert!(!Src::ptr_eq(&s2, &s4));
1271    assert!(!Src::ptr_eq(&s2, &s4));
1272    assert!(!Src::same_root(&s1, &s3));
1273    assert!(!Src::same_root(&s2, &s4));
1274    assert!(Src::same_root(&s3, &s4));
1275  }
1276  
1277  #[test]
1278  fn is_root() {
1279    let s1: Src<[u8]> = Src::from_default(1);
1280    let s2: Src<[u8]> = s1.slice(..);
1281    let s3: Src<[u8]> = s1.slice(1..);
1282    assert!(Src::is_root(&s1));
1283    assert!(Src::is_root(&s2));
1284    assert!(!Src::is_root(&s3));
1285  }
1286  
1287  #[test]
1288  fn downgrade() {
1289    let s1: Src<[u8]> = Src::from_default(0);
1290    let w: WeakSrc<[u8]> = Src::downgrade(&s1);
1291    let s2: Src<[u8]> = w.upgrade().unwrap();
1292    assert_eq!(s1, s2);
1293  }
1294  
1295  #[test]
1296  fn strong_count() {
1297    let s1: Src<[u8]> = Src::from_default(0);
1298    assert_eq!(Src::strong_count(&s1), 1);
1299    let s2: Src<[u8]> = Src::clone(&s1);
1300    assert_eq!(Src::strong_count(&s1), 2);
1301    assert_eq!(Src::strong_count(&s2), 2);
1302    let w1: WeakSrc<[u8]> = Src::downgrade(&s1);
1303    assert_eq!(Src::strong_count(&s1), 2);
1304    assert_eq!(Src::strong_count(&s2), 2);
1305    assert_eq!(w1.strong_count(), 2);
1306    let w2: WeakSrc<[u8]> = Src::downgrade(&s1);
1307    assert_eq!(Src::strong_count(&s1), 2);
1308    assert_eq!(Src::strong_count(&s2), 2);
1309    assert_eq!(w1.strong_count(), 2);
1310    assert_eq!(w2.strong_count(), 2);
1311    std::mem::drop(s1);
1312    assert_eq!(Src::strong_count(&s2), 1);
1313    assert_eq!(w1.strong_count(), 1);
1314    assert_eq!(w2.strong_count(), 1);
1315    std::mem::drop(s2);
1316    assert_eq!(w1.strong_count(), 0);
1317    assert_eq!(w2.strong_count(), 0);
1318  }
1319  
1320  #[test]
1321  fn weak_count() {
1322    let s1: Src<[u8]> = Src::from_default(0);
1323    assert_eq!(Src::weak_count(&s1), 0);
1324    let s2: Src<[u8]> = Src::clone(&s1);
1325    assert_eq!(Src::weak_count(&s1), 0);
1326    assert_eq!(Src::weak_count(&s2), 0);
1327    let w1: WeakSrc<[u8]> = Src::downgrade(&s1);
1328    assert_eq!(Src::weak_count(&s1), 1);
1329    assert_eq!(Src::weak_count(&s2), 1);
1330    assert_eq!(w1.weak_count(), 1);
1331    let w2: WeakSrc<[u8]> = w1.clone();
1332    assert_eq!(Src::weak_count(&s1), 2);
1333    assert_eq!(Src::weak_count(&s2), 2);
1334    assert_eq!(w1.weak_count(), 2);
1335    assert_eq!(w2.weak_count(), 2);
1336    std::mem::drop(s1);
1337    assert_eq!(Src::weak_count(&s2), 2);
1338    assert_eq!(w1.weak_count(), 2);
1339    assert_eq!(w2.weak_count(), 2);
1340    std::mem::drop(w1);
1341    assert_eq!(Src::weak_count(&s2), 1);
1342    assert_eq!(w2.weak_count(), 1);
1343    std::mem::drop(s2);
1344    assert_eq!(w2.weak_count(), 0);
1345  }
1346  
1347  #[test]
1348  fn into_unique() {
1349    let s1: Src<[u8]> = Src::from_default(0);
1350    let s2: Src<[u8]> = Src::clone(&s1);
1351    let s1: Src<[u8]> = Src::into_unique(s1).unwrap_err();
1352    std::mem::drop(s2);
1353    let w: WeakSrc<[u8]> = Src::downgrade(&s1);
1354    assert!(w.upgrade().is_some());
1355    let u: UniqueSrc<[u8]> = Src::into_unique(s1).unwrap();
1356    assert!(w.upgrade().is_none());
1357    let s1: Src<[u8]> = UniqueSrc::into_shared(u);
1358    assert!(w.upgrade().is_some());
1359    _ = s1;
1360  }
1361  
1362  #[test]
1363  fn make_unique() {
1364    { // non-unique
1365      let s1: Src<[u8]> = Src::from_default(0);
1366      let s2: Src<[u8]> = Src::clone(&s1);
1367      let w1: WeakSrc<[u8]> = Src::downgrade(&s1);
1368      let u: UniqueSrc<[u8]> = Src::make_unique(s1);
1369      let w2: WeakSrc<[u8]> = UniqueSrc::downgrade(&u);
1370      assert!(!w1.same_root(&w2));
1371      _ = s2;
1372    }
1373    { // unique
1374      let s: Src<[u8]> = Src::from_default(0);
1375      let w1: WeakSrc<[u8]> = Src::downgrade(&s);
1376      let u: UniqueSrc<[u8]> = Src::make_unique(s);
1377      let w2: WeakSrc<[u8]> = UniqueSrc::downgrade(&u);
1378      assert!(w1.same_root(&w2));
1379    }
1380  }
1381  
1382  #[test]
1383  fn empty() {
1384    let s: Src<[u8]> = Src::empty();
1385    assert!(s.is_empty());
1386    assert_eq!(s.len(), 0);
1387    let s: Src<str> = Src::empty();
1388    assert!(s.is_empty());
1389    assert_eq!(s.len(), 0);
1390  }
1391  
1392  #[test]
1393  fn len() {
1394    let s: Src<[u8]> = Src::from_default(0);
1395    assert_eq!(s.len(), 0);
1396    let s: Src<[u8]> = Src::from_default(1);
1397    assert_eq!(s.len(), 1);
1398    let s: Src<[u8]> = Src::from_default(17);
1399    assert_eq!(s.len(), 17);
1400    let s: Src<[u8]> = s.slice(3..14);
1401    assert_eq!(s.len(), 11);
1402    let s: Src<[u8]> = s.slice(3..3);
1403    assert_eq!(s.len(), 0);
1404  }
1405  
1406  #[test]
1407  fn is_empty() {
1408    let s: Src<[u8]> = Src::from_default(0);
1409    assert!(s.is_empty());
1410    let s: Src<[u8]> = Src::from_default(1);
1411    assert!(!s.is_empty());
1412    let s: Src<[u8]> = Src::from_default(17);
1413    assert!(!s.is_empty());
1414    let s: Src<[u8]> = s.slice(3..14);
1415    assert!(!s.is_empty());
1416    let s: Src<[u8]> = s.slice(3..3);
1417    assert!(s.is_empty());
1418  }
1419  
1420  #[test]
1421  fn root() {
1422    let s1: Src<[u8]> = Src::from_default(1);
1423    assert!(Src::is_root(&s1));
1424    let s1: Src<[u8]> = s1.slice(1..);
1425    assert!(!Src::is_root(&s1));
1426    let s2: Src<[u8]> = Src::root(&s1);
1427    assert!(Src::is_root(&s2));
1428    assert!(Src::same_root(&s1, &s2));
1429  }
1430  
1431  #[test]
1432  fn slice() {
1433    { // slice
1434      let s1: Src<[u8]> = Src::from_array([1, 2, 3]);
1435      assert_eq!(&*s1, &[1, 2, 3]);
1436      let s1: Src<[u8]> = s1.slice(1..);
1437      assert_eq!(&*s1, &[2, 3]);
1438      let s2: Src<[u8]> = s1.slice(..1);
1439      assert_eq!(&*s2, &[2]);
1440      assert!(Src::same_root(&s1, &s2));
1441    }
1442    { // item 1
1443      let s1: Src<[u8]> = Src::from_array([1, 2, 3]);
1444      assert_eq!(&*s1, &[1, 2, 3]);
1445      let s2: Src<u8> = s1.slice(2);
1446      assert_eq!(&*s2, &3);
1447      let s2: Src<[u8]> = Src::as_slice(&s2);
1448      assert_eq!(&*s2, &[3]);
1449      assert!(Src::same_root(&s1, &s2));
1450    }
1451    { // item 2
1452      let s1: Src<[u8]> = Src::from_array([1, 2, 3]);
1453      assert_eq!(&*s1, &[1, 2, 3]);
1454      let s1: Src<[u8]> = s1.slice(1..);
1455      assert_eq!(&*s1, &[2, 3]);
1456      let s2: Src<u8> = s1.slice(0);
1457      assert_eq!(&*s2, &2);
1458      let s2: Src<[u8]> = Src::as_slice(&s2);
1459      assert_eq!(&*s2, &[2]);
1460      assert!(Src::same_root(&s1, &s2));
1461    }
1462  }
1463  
1464  #[test]
1465  fn single() {
1466    let s: Src<u8> = Src::single(42);
1467    assert_eq!(*s, 42);
1468  }
1469  
1470  #[test]
1471  fn single_cyclic() {
1472    { // non-cyclic
1473      let s: Src<u8> = Src::single_cyclic(|_| 42);
1474      assert_eq!(*s, 42);
1475    }
1476    { // cyclic
1477      struct S {
1478        
1479        this: WeakSrc<S>,
1480        i: usize,
1481        
1482      }
1483      let s: Src<S> = Src::single_cyclic(|weak| S { this: weak.clone(), i: 42 });
1484      assert_eq!(s.i, 42);
1485      let w: WeakSrc<S> = Src::downgrade(&s);
1486      assert!(WeakSrc::ptr_eq(&s.this, &w));
1487    }
1488  }
1489  
1490  #[test]
1491  fn single_uninit() {
1492    let s: Src<MaybeUninit<u8>> = Src::single_uninit();
1493    let mut u: UniqueSrc<MaybeUninit<u8>> = Src::make_unique(s);
1494    u.write(42);
1495    let s: Src<MaybeUninit<u8>> = UniqueSrc::into_shared(u);
1496    // SAFETY: just initialized it with u.write()
1497    let s: Src<u8> = unsafe { s.assume_init() };
1498    assert_eq!(*s, 42);
1499  }
1500  
1501  #[test]
1502  fn single_zeroed() {
1503    let s: Src<MaybeUninit<u8>> = Src::single_zeroed();
1504    // SAFETY: u8 is a zeroable type
1505    let s: Src<u8> = unsafe { s.assume_init() };
1506    assert_eq!(*s, 0);
1507  }
1508  
1509  #[test]
1510  fn as_slice() {
1511    { // single root
1512      let s1: Src<u8> = Src::single(42);
1513      let s2: Src<[u8]> = Src::as_slice(&s1);
1514      assert_eq!([*s1], *s2);
1515    }
1516    { // from slice
1517      let s1: Src<[u8]> = Src::from_array([1, 2, 3]);
1518      let s2: Src<u8> = s1.slice(1);
1519      let s3: Src<[u8]> = Src::as_slice(&s2);
1520      assert_eq!(s1[1], *s2);
1521      assert_eq!([*s2], *s3);
1522    }
1523  }
1524  
1525  #[test]
1526  fn new_uninit() {
1527    let s: Src<[MaybeUninit<u8>]> = Src::new_uninit(3);
1528    assert_eq!(s.len(), 3);
1529    let mut u: UniqueSrc<[MaybeUninit<u8>]> = Src::make_unique(s);
1530    for (i, elem) in u.iter_mut().enumerate() {
1531      elem.write(i as _);
1532    }
1533    let s: Src<[MaybeUninit<u8>]> = UniqueSrc::into_shared(u);
1534    // SAFETY: just initialized it with all the elem.write()s
1535    let s: Src<[u8]> = unsafe { s.assume_init() };
1536    assert_eq!(*s, [0, 1, 2]);
1537  }
1538  
1539  #[test]
1540  fn new_zeroed() {
1541    let s: Src<[MaybeUninit<u8>]> = Src::new_zeroed(3);
1542    assert_eq!(s.len(), 3);
1543    // SAFETY: u8 is a zeroable type
1544    let s: Src<[u8]> = unsafe { s.assume_init() };
1545    assert_eq!(*s, [0, 0, 0]);
1546  }
1547  
1548  #[test]
1549  fn from_fn() {
1550    { // normal
1551      let s: Src<[usize]> = Src::from_fn(3, |i| i * 2);
1552      assert_eq!(*s, [0, 2, 4]);
1553    }
1554    { // panic
1555      let drop_flags: [_; 6] = std::array::from_fn(|_| AssertUnwindSafe(Cell::new(false)));
1556      struct DropFlagger<'a>(&'a Cell<bool>);
1557      impl Drop for DropFlagger<'_> {
1558        
1559        fn drop(&mut self) {
1560          self.0.update(|v| !v)
1561        }
1562        
1563      }
1564      let _: Result<_, _> = catch_unwind(|| {
1565        let _: Src<[DropFlagger<'_>]> = Src::from_fn(drop_flags.len(), |i| {
1566          if i >= 3 { panic!() }
1567          DropFlagger(&drop_flags[i])
1568        });
1569      });
1570      assert!(drop_flags[..3].iter().map(Deref::deref).all(Cell::get));
1571      assert!(!drop_flags[3..].iter().map(Deref::deref).any(Cell::get));
1572    }
1573  }
1574  
1575  #[test]
1576  fn cyclic_from_fn() {
1577    { // normal, not cyclic
1578      let s: Src<[usize]> = Src::cyclic_from_fn(3, |_, i| i * 2);
1579      assert_eq!(*s, [0, 2, 4]);
1580    }
1581    { // normal, cyclic
1582      struct S {
1583        
1584        all: WeakSrc<[S]>,
1585        i: usize,
1586        
1587      }
1588      let s1: Src<[S]> = Src::cyclic_from_fn(3, |w, i| S { all: w.clone(), i: i * 2 });
1589      assert_eq!(s1[0].i, 0);
1590      assert_eq!(s1[1].i, 2);
1591      assert_eq!(s1[2].i, 4);
1592      let s2: Src<[S]> = s1[0].all.upgrade().unwrap();
1593      assert!(Src::ptr_eq(&s1, &s2));
1594    }
1595    { // panic
1596      let drop_flags: [_; 6] = std::array::from_fn(|_| AssertUnwindSafe(Cell::new(false)));
1597      struct DropFlagger<'a>(&'a Cell<bool>);
1598      impl Drop for DropFlagger<'_> {
1599        
1600        fn drop(&mut self) {
1601          self.0.update(|v| !v)
1602        }
1603        
1604      }
1605      let _: Result<_, _> = catch_unwind(|| {
1606        let _: Src<[DropFlagger<'_>]> = Src::cyclic_from_fn(drop_flags.len(), |_, i| {
1607          if i >= 3 { panic!() }
1608          DropFlagger(&drop_flags[i])
1609        });
1610      });
1611      assert!(drop_flags[..3].iter().map(Deref::deref).all(Cell::get));
1612      assert!(!drop_flags[3..].iter().map(Deref::deref).any(Cell::get));
1613    }
1614  }
1615  
1616  #[test]
1617  fn from_iter() {
1618    let s: Src<[u8]> = Src::from_iter(vec![1, 2, 3].into_iter().map(|i| i * 2));
1619    assert_eq!(*s, [2, 4, 6]);
1620  }
1621  
1622  #[test]
1623  fn from_array() {
1624    let s: Src<[u8]> = Src::from_array([1, 2, 3]);
1625    assert_eq!(*s, [1, 2, 3]);
1626  }
1627  
1628  #[test]
1629  fn from_default() {
1630    #[derive(Copy, Clone, Eq, PartialEq, Debug)]
1631    struct D42(u8);
1632    impl Default for D42 {
1633      
1634      fn default() -> Self {
1635        Self(42)
1636      }
1637      
1638    }
1639    let s: Src<[u8]> = Src::from_default(3);
1640    assert_eq!(*s, [0, 0, 0]);
1641    let s: Src<[D42]> = Src::from_default(3);
1642    assert_eq!(*s, [D42(42), D42(42), D42(42)]);
1643  }
1644  
1645  #[test]
1646  fn filled() {
1647    let s: Src<[u8]> = Src::filled(3, &42);
1648    assert_eq!(*s, [42, 42, 42]);
1649  }
1650  
1651  #[test]
1652  fn filled_cyclic() {
1653    { // non-cyclic
1654      let s: Src<[u8]> = Src::filled_cyclic(3, |_| 42);
1655      assert_eq!(*s, [42, 42, 42]);
1656    }
1657    { // cyclic
1658      #[derive(Clone)]
1659      struct S {
1660        
1661        all: WeakSrc<[S]>,
1662        i: usize,
1663        
1664      }
1665      let s: Src<[S]> = Src::filled_cyclic(3, |weak| S { all: weak.clone(), i: 42 });
1666      assert_eq!(s[0].i, 42);
1667      assert_eq!(s[1].i, 42);
1668      assert_eq!(s[2].i, 42);
1669      let w: WeakSrc<[S]> = Src::downgrade(&s);
1670      assert!(WeakSrc::ptr_eq(&s[0].all, &w));
1671    }
1672  }
1673  
1674  #[test]
1675  fn cloned() {
1676    #[derive(Clone, Eq, PartialEq, Debug)]
1677    struct NonCopy(u8);
1678    let s: Src<[NonCopy]> = Src::cloned(&[NonCopy(1), NonCopy(2), NonCopy(3)]);
1679    assert_eq!(*s, [NonCopy(1), NonCopy(2), NonCopy(3)]);
1680  }
1681  
1682  #[test]
1683  fn copied() {
1684    let s: Src<[u8]> = Src::copied(&[1, 2, 3]);
1685    assert_eq!(*s, [1, 2, 3]);
1686  }
1687  
1688  #[test]
1689  fn assume_init_single() {
1690    let s: Src<MaybeUninit<u8>> = Src::single_zeroed();
1691    // SAFETY: u8 is a zeroable type
1692    let s: Src<u8> = unsafe { s.assume_init() };
1693    assert_eq!(*s, 0);
1694  }
1695  
1696  #[test]
1697  fn assume_init_slice() {
1698    let s: Src<[MaybeUninit<u8>]> = Src::new_zeroed(3);
1699    // SAFETY: u8 is a zeroable type
1700    let s: Src<[u8]> = unsafe { s.assume_init() };
1701    assert_eq!(*s, [0, 0, 0]);
1702  }
1703  
1704  #[test]
1705  fn new() {
1706    let s: Src<str> = Src::new("Hello World!");
1707    assert_eq!(&*s, "Hello World!");
1708  }
1709  
1710  #[test]
1711  fn from_utf8() {
1712    { // UTF-8
1713      let s: Src<[u8]> = Src::copied(b"Hello World!");
1714      let s: Src<str> = Src::from_utf8(s).unwrap();
1715      assert_eq!(&*s, "Hello World!");
1716    }
1717    { // not UTF-8
1718      let s: Src<[u8]> = Src::copied(&[0xFF]);
1719      let _: Utf8Error = Src::from_utf8(s).unwrap_err();
1720    }
1721  }
1722  
1723  #[test]
1724  fn from_utf8_unchecked() {
1725    let s: Src<[u8]> = Src::copied(b"Hello World!");
1726    // SAFETY: just got the bytes from a str
1727    let s: Src<str> = unsafe { Src::from_utf8_unchecked(s) };
1728    assert_eq!(&*s, "Hello World!");
1729  }
1730  
1731  #[test]
1732  fn as_bytes() {
1733    let s: Src<str> = Src::new("Hello World!");
1734    let s: Src<[u8]> = Src::as_bytes(&s);
1735    assert_eq!(&*s, b"Hello World!");
1736  }
1737  
1738  #[test]
1739  fn clone() {
1740    let s1: Src<[u8]> = Src::from_array([1, 2, 3]);
1741    assert_eq!(Src::strong_count(&s1), 1);
1742    let s2: Src<[u8]> = s1.clone();
1743    assert_eq!(Src::strong_count(&s1), 2);
1744    assert_eq!(*s1, *s2);
1745    assert!(Src::ptr_eq(&s1, &s2));
1746  }
1747  
1748  #[test]
1749  fn deref() {
1750    let s: Src<[u8]> = Src::from_array([1, 2, 3]);
1751    assert_eq!(Deref::deref(&s), &[1, 2, 3]);
1752  }
1753  
1754  #[test]
1755  fn drop() {
1756    let drop_flags: [_; 3] = std::array::from_fn(|_| Cell::new(false));
1757    struct DropFlagger<'a>(&'a Cell<bool>);
1758    impl Drop for DropFlagger<'_> {
1759      
1760      fn drop(&mut self) {
1761        self.0.update(|v| !v)
1762      }
1763      
1764    }
1765    assert!(!drop_flags.iter().any(Cell::get));
1766    let s1: Src<[DropFlagger<'_>]> = Src::from_iter(drop_flags.iter().map(DropFlagger));
1767    assert!(!drop_flags.iter().any(Cell::get));
1768    assert_eq!(Src::strong_count(&s1), 1);
1769    let s2: Src<[DropFlagger<'_>]> = s1.clone();
1770    assert!(!drop_flags.iter().any(Cell::get));
1771    assert_eq!(Src::strong_count(&s1), 2);
1772    assert_eq!(Src::strong_count(&s2), 2);
1773    std::mem::drop(s1);
1774    assert!(!drop_flags.iter().any(Cell::get));
1775    assert_eq!(Src::strong_count(&s2), 1);
1776    std::mem::drop(s2);
1777    assert!(drop_flags.iter().all(Cell::get));
1778  }
1779  
1780}