slice_rc/unique.rs
1use std::{borrow::{Borrow, BorrowMut}, cmp::Ordering, fmt::{self, Debug, Formatter, Pointer}, hash::{Hash, Hasher}, marker::PhantomData, mem::{forget, MaybeUninit}, ops::{Deref, DerefMut, Index, IndexMut}, ptr::NonNull, str::Utf8Error};
2
3use crate::{inner::{AllocUninit, AllocZeroed}, InnerHeader, Src, SrcSlice, SrcTarget, UninitSrc, WeakSrc};
4
5/// A uniquely owned [`Src`].
6///
7/// This represents an [`Src`] that is known to be uniquely owned - that is, have exactly one strong reference.
8/// Multiple [weak pointers](WeakSrc) can be created, but attempts to upgrade those to strong references will fail unless the `UniqueSrc` has been converted to a regular shared [`Src`].
9///
10/// Because they are uniquely owned, the contents of a `UniqueSrc` can be freely mutated.
11/// This could be used as an initialization step (that is the suggested usage of [`UniqueRc`](std::rc::UniqueRc)),
12/// but I find [`UninitSrc`] to be better for initialization, as there is no intermediate step with [dangling](WeakSrc#dangling) weak pointers.
13///
14/// Still, the ability to mutably access the contents of an [`Src`] can be useful, hence this type's inclusion in the crate.
15/// (Also, [`Src::into_unique`] and [`Src::make_unique`] are currently this crate's substitutes for [`Rc::get_mut`](std::rc::Rc::get_mut) and [`Rc::make_mut`](std::rc::Rc::make_mut) respectively;
16/// since I made that decision, I have since realized that they are not equivalent, and will therefore probably add `get_mut` and `make_mut` methods to [`Src`] at some point.
17/// In the mean time, this is the next best thing.)
18///
19/// Note that, while this struct currently has no methods to explicitly support non-[root](crate#root) `UniqueSrc`s,
20/// it is technically possible to construct them by making a non-[root](crate#root) [`Src`] and turning into a `UniqueSrc` via [`Src::into_unique`] or [`Src::make_unique`];
21/// The behavior of these non-[root](crate#root) `UniqueSrc`s has not been thoroughly considered and may be changed or removed.
22///
23/// Many of the inherent methods of `UniqueSrc` are associated functions, which means that you have to call them as e.g.,
24/// [`UniqueSrc::downgrade(&value)`](UniqueSrc::downgrade) instead of `value.downgrade()`;
25/// this avoids conflicts with methods of the inner type `T`.
26/// However, some methods, e.g. [`Src::len`], intentionally shadow a known method of the inner type because they use a more efficient computation for the same result,
27/// and there may be some in the future (e.g. the hypothetical `UniqueSrc::slice`), which will be permitted to remain as methods because their inner type will be known not to have a conflicting method.
28pub struct UniqueSrc<T: SrcTarget + ?Sized> {
29
30 // SAFETY:
31 // requires:
32 // * initialized from InnerHeader::new_inner::<T::Item>(_)
33 pub(crate) header: NonNull<InnerHeader>,
34 // SAFETY:
35 // requires:
36 // * 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()
37 // * all body elements have been properly initialized (e.g., self.start.as_ref() will not cause UB)
38 pub(crate) start: NonNull<T::Item>,
39 // SAFETY:
40 // requires when T: SrcSlice:
41 // * self.start.add(self.len) <= InnerHeader::get_body_ptr::<T::Item>(self.header).add(InnerHeader::get_header(self.header).len())
42 // requires when T: Sized:
43 // * self.start < InnerHeader::get_body_ptr::<T::Item>(self.header).add(InnerHeader::get_header(self.header).len())
44 pub(crate) len: T::Len,
45 pub(crate) _phantom: PhantomData<*const T>,
46
47}
48
49impl<T: SrcTarget + ?Sized> UniqueSrc<T> {
50
51 fn header(&self) -> &InnerHeader {
52 // SAFETY:
53 // * all constructor fns for Src initialize header from InnerHeader::new_inner::<T::Item>
54 // * the header is only accessed from InnerHeader::get_header
55 unsafe { InnerHeader::get_header(self.header) }
56 }
57
58 /// Creates a [`WeakSrc`] pointer to this slice.
59 /// The [`WeakSrc`] refers to the same slice as this `UniqueSrc`, and therefore, refers to the [root](crate#root) if and only if this `UniqueSrc` does.
60 ///
61 /// ```rust
62 /// use slice_rc::UniqueSrc;
63 ///
64 /// let root = UniqueSrc::from_array([1, 2, 3]);
65 ///
66 /// let weak_root = UniqueSrc::downgrade(&root);
67 /// ```
68 pub fn downgrade(this: &UniqueSrc<T>) -> WeakSrc<T> {
69 // safety note: the strong count is 0 until this UniqueSrc is turned into a Src, so the WeakSrc will never read or write from the body during the lifetime of the UniqueSrc
70 this.header().inc_weak_count();
71 WeakSrc {
72 // SAFETY: the safety invariant of this.header implies that of _.header
73 header: this.header,
74 // SAFETY: the safety invariant of this.start implies that of _.start
75 start: this.start,
76 // SAFETY: the safety invariant of this.len implies that of _.len
77 len: this.len,
78 _phantom: PhantomData,
79 }
80 }
81
82 /// Turns this `UniqueSrc` into an [`Src`].
83 /// Because `UniqueSrc` has strictly stronger guarantees, this conversion is not fallible.
84 ///
85 /// ```rust
86 /// use slice_rc::UniqueSrc;
87 ///
88 /// let x = UniqueSrc::single(3);
89 /// assert_eq!(*UniqueSrc::into_shared(x), 3);
90 /// ```
91 ///
92 /// See also [`Src::into_unique`] and [`Src::make_unique`].
93 pub fn into_shared(this: UniqueSrc<T>) -> Src<T> {
94 this.header().inc_strong_count();
95 let this2 = Src {
96 // SAFETY: the safety invariant of this.header is the same as this2.header
97 header: this.header,
98 // SAFETY: the safety invariant of this.start is the same as this2.start
99 start: this.start,
100 // SAFETY: the safety invariant of this.len is the same as this2.len
101 len: this.len,
102 _phantom: PhantomData,
103 };
104 forget(this);
105 this2
106 }
107
108}
109
110impl<T: SrcSlice + ?Sized> UniqueSrc<T> {
111
112 /// Constructs a new [root](crate#root) `UniqueSrc` of length `0`.
113 /// Note that, because `UniqueSrc`s are not growable like [`Vec`]s are, this allocation will never become larger.
114 /// Every reference to this allocation is a [root](crate#root).
115 ///
116 /// ```rust
117 /// use slice_rc::UniqueSrc;
118 ///
119 /// let s = UniqueSrc::<[i32]>::empty();
120 ///
121 /// assert_eq!(s.len(), 0);
122 /// ```
123 #[inline]
124 pub fn empty() -> UniqueSrc<T> {
125 let this = UniqueSrc::<[T::Item]>::from_array([]);
126 debug_assert_eq!(this.len, 0);
127 let this2 = UniqueSrc {
128 // SAFETY: the safety invariant of this.header is the same as this2.header
129 header: this.header,
130 // SAFETY: the safety invariant of this.start is the same as this2.start
131 start: this.start,
132 // SAFETY: the safety invariant of this.len implies that of this.len
133 len: this.len,
134 _phantom: PhantomData,
135 };
136 forget(this);
137 this2
138 }
139
140 /// Returns the number of elements in this `UniqueSrc`.
141 /// This method deliberately shadows [`<[T]>::len`](slice::len) and [`str::len`] because this method provides a (slightly) simpler and more efficient implementation.
142 ///
143 /// This method only returns the length of the whole allocation if `self` is a [root](crate#root) `UniqueSrc`.
144 ///
145 /// ```rust
146 /// use slice_rc::UniqueSrc;
147 ///
148 /// let s = UniqueSrc::from_array([1, 2, 3]);
149 /// assert_eq!(s.len(), 3);
150 /// ```
151 #[inline]
152 pub fn len(&self) -> usize {
153 self.len
154 }
155
156 /// Returns `true` if this `UniqueSrc` has a length of `0`.
157 /// 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.
158 ///
159 /// Note that this method does not imply that this `UniqueSrc` was constructed via [`UniqueSrc::empty`].
160 /// Similarly, it does not imply that the entire allocation is empty, unless `self` is a [root](crate#root) `UniqueSrc`.
161 ///
162 /// ```rust
163 /// use slice_rc::UniqueSrc;
164 ///
165 /// let a = UniqueSrc::from_array([1, 2, 3]);
166 /// assert!(!a.is_empty());
167 ///
168 /// let b = UniqueSrc::<[i32]>::from_array([]);
169 /// assert!(b.is_empty());
170 /// ```
171 #[inline]
172 pub fn is_empty(&self) -> bool {
173 self.len == 0
174 }
175
176}
177
178impl<T: Sized> UniqueSrc<T> {
179
180 /// Constructs a new [root](crate#root) `UniqueSrc` that contains only the given value.
181 ///
182 /// ```rust
183 /// use slice_rc::UniqueSrc;
184 ///
185 /// let s = UniqueSrc::single(42);
186 /// assert_eq!(*s, 42);
187 /// ```
188 #[inline]
189 pub fn single(value: T) -> UniqueSrc<T> {
190 UninitSrc::single().init_unique(value)
191 }
192
193 /// Constructs a new [root](crate#root) `UniqueSrc` that contains only the value returned from the given function `f`.
194 /// The [`WeakSrc`] that `f` is given will be a weak reference to this allocation, which allows constructing a self-referential value;
195 /// it will return [`None`] from [`WeakSrc::upgrade`] until after `single_cyclic` has returned.
196 ///
197 /// This is a convienience method for a specific subset of behavior that can be obtained via [`UninitSrc`].
198 ///
199 /// ```rust
200 /// use slice_rc::{Src, UniqueSrc, WeakSrc};
201 ///
202 /// struct S {
203 /// me: WeakSrc<S>,
204 /// }
205 ///
206 /// let s = UniqueSrc::single_cyclic(|me| S { me: me.clone() });
207 ///
208 /// assert!(s.me.upgrade().is_none());
209 ///
210 /// let s = UniqueSrc::into_shared(s);
211 ///
212 /// assert!(Src::ptr_eq(&s, &s.me.upgrade().unwrap()));
213 /// ```
214 pub fn single_cyclic<F: FnOnce(&WeakSrc<T>) -> T>(f: F) -> UniqueSrc<T> {
215 let this = UninitSrc::single();
216 let weak = this.downgrade();
217 this.init_unique(f(&weak))
218 }
219
220 /// Constructs a new [root](crate#root) `UniqueSrc` of length `1` with uninitialized contents.
221 ///
222 /// ```rust
223 /// use slice_rc::{UniqueSrc};
224 ///
225 /// let mut five = UniqueSrc::<i32>::single_uninit();
226 ///
227 /// five.write(5);
228 ///
229 /// let five = unsafe { five.assume_init() };
230 ///
231 /// assert_eq!(*five, 5);
232 /// ```
233 #[inline]
234 pub fn single_uninit() -> UniqueSrc<MaybeUninit<T>> {
235 let this = UniqueSrc::<[T]>::new_uninit(1);
236 debug_assert_eq!(this.len, 1);
237 let this2 = UniqueSrc {
238 // SAFETY: the safety invariant of this.header is the same as this2.header
239 header: this.header,
240 // SAFETY: the safety invariant of this.start is the same as this2.start
241 start: this.start,
242 // SAFETY: the safety invariant of this.len implies that of this.len
243 len: (),
244 _phantom: PhantomData,
245 };
246 forget(this);
247 this2
248 }
249
250 /// Constructs a new [root](crate#root) `UniqueSrc` of length `1` with uninitialized contents, with the memory being filled with `0` bytes.
251 ///
252 /// See [`MaybeUninit::zeroed`] for examples of correct and incorrect usage of this method.
253 ///
254 /// ```rust
255 /// use slice_rc::UniqueSrc;
256 ///
257 /// let zero = UniqueSrc::<i32>::single_zeroed();
258 /// let zero = unsafe { zero.assume_init() };
259 ///
260 /// assert_eq!(*zero, 0);
261 /// ```
262 #[inline]
263 pub fn single_zeroed() -> UniqueSrc<MaybeUninit<T>> {
264 let this = UniqueSrc::<[T]>::new_zeroed(1);
265 debug_assert_eq!(this.len, 1);
266 let this2 = UniqueSrc {
267 // SAFETY: the safety invariant of this.header is the same as this2.header
268 header: this.header,
269 // SAFETY: the safety invariant of this.start is the same as this2.start
270 start: this.start,
271 // SAFETY: the safety invariant of this.len implies that of this2.len
272 len: (),
273 _phantom: PhantomData,
274 };
275 forget(this);
276 this2
277 }
278
279 /// Returns a `UniqueSrc` equivalent to this one, but typed as a slice rather than a single element.
280 /// 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.
281 ///
282 /// ```rust
283 /// use slice_rc::{Src, UniqueSrc};
284 /// use std::ptr;
285 ///
286 /// let single = UniqueSrc::single(42);
287 /// let single_weak = UniqueSrc::downgrade(&single);
288 /// let slice = UniqueSrc::as_slice(single);
289 /// let slice = UniqueSrc::into_shared(slice);
290 /// let single = single_weak.upgrade().unwrap();
291 ///
292 /// assert!(Src::ptr_eq(&single, &slice));
293 /// assert!(ptr::eq(&*single, &slice[0]));
294 /// ```
295 #[inline]
296 pub fn as_slice(this: UniqueSrc<T>) -> UniqueSrc<[T]> {
297 let this2 = UniqueSrc {
298 // SAFETY: the safety invariant of this.header is the same as this2.header
299 header: this.header,
300 // SAFETY: the safety invariant of this.start is the same as this2.start
301 start: this.start,
302 // SAFETY: the safety invariant of this.len implies this2.len
303 len: 1,
304 _phantom: PhantomData,
305 };
306 forget(this);
307 this2
308 }
309
310}
311
312impl<T> UniqueSrc<[T]> {
313
314 /// Constructs a new [root](crate#root) `UniqueSrc` of the given length with uninitialized contents.
315 ///
316 /// ```rust
317 /// use slice_rc::{Src, UniqueSrc};
318 ///
319 /// let mut fives = UniqueSrc::<[i32]>::new_uninit(3);
320 ///
321 /// fives[0].write(5);
322 /// fives[1].write(5);
323 /// fives[2].write(5);
324 ///
325 /// let fives = unsafe { fives.assume_init() };
326 ///
327 /// assert_eq!(*fives, [5, 5, 5]);
328 /// ```
329 pub fn new_uninit(len: usize) -> UniqueSrc<[MaybeUninit<T>]> {
330 let header = InnerHeader::new_inner::<T, AllocUninit>(len);
331 // SAFETY:
332 // * we just got this from InnerHeader::new_inner::<T>
333 // * no one else has seen the ptr yet, so the read/write requirements are fine
334 let start = unsafe { InnerHeader::get_body_ptr::<T>(header) }.cast();
335 UniqueSrc {
336 // the safety invariant of _.header is fulfilled by definition
337 header,
338 // the safety invariant of _.start is fulfilled by definition
339 start,
340 // the safety invariant of _.len is fulfilled by definition
341 len,
342 _phantom: PhantomData,
343 }
344 }
345
346 /// Constructs a new [root](crate#root) `UniqueSrc` of the given length with uninitialized contents, with the memory being filled with `0` bytes.
347 ///
348 /// See [`MaybeUninit::zeroed`] for examples of correct and incorrect usage of this method.
349 ///
350 /// ```rust
351 /// use slice_rc::UniqueSrc;
352 ///
353 /// let zeroes = UniqueSrc::<[i32]>::new_zeroed(3);
354 /// let zeroes = unsafe { zeroes.assume_init() };
355 ///
356 /// assert_eq!(*zeroes, [0, 0, 0]);
357 /// ```
358 pub fn new_zeroed(len: usize) -> UniqueSrc<[MaybeUninit<T>]> {
359 let header = InnerHeader::new_inner::<T, AllocZeroed>(len);
360 // SAFETY:
361 // * we just got this from InnerHeader::new_inner::<T>
362 // * no one else has seen the ptr yet, so the read/write requirements are fine
363 let start = unsafe { InnerHeader::get_body_ptr::<T>(header) }.cast();
364 UniqueSrc {
365 // the safety invariant of _.header is fulfilled by definition
366 header,
367 // the safety invariant of _.start is fulfilled by definition
368 start,
369 // the safety invariant of _.len is fulfilled by definition
370 len,
371 _phantom: PhantomData,
372 }
373 }
374
375 /// Constructs a new [root](crate#root) `UniqueSrc` of the given length where each element is produced by calling `f` with that element's index while walking forward through the slice.
376 ///
377 /// This essentially the same as writing
378 /// ```text
379 /// UniqueSrc::from_array([f(0), f(1), f(2), ..., f(len - 2), f(len - 1)])
380 /// ```
381 /// and is similar to `(0..len).map(f)`, just for `UniqueSrc`s rather than iterators.
382 ///
383 /// If `len == 0`, this produces an empty `UniqueSrc` without ever calling `f`.
384 ///
385 /// ```rust
386 /// use slice_rc::UniqueSrc;
387 ///
388 /// let slice = UniqueSrc::from_fn(5, |i| i);
389 /// assert_eq!(*slice, [0, 1, 2, 3, 4]);
390 ///
391 /// let slice2 = UniqueSrc::from_fn(8, |i| i * 2);
392 /// assert_eq!(*slice2, [0, 2, 4, 6, 8, 10, 12, 14]);
393 ///
394 /// let bool_slice = UniqueSrc::from_fn(5, |i| i % 2 == 0);
395 /// assert_eq!(*bool_slice, [true, false, true, false, true]);
396 /// ```
397 ///
398 /// You can also capture things, so you can use closures with mutable state.
399 /// The slice is generated in ascending index order, starting from the front and going towards the back.
400 /// ```rust
401 /// # use slice_rc::UniqueSrc;
402 /// let mut state = 1;
403 /// let s = UniqueSrc::from_fn(6, |_| { let x = state; state *= 2; x });
404 /// assert_eq!(*s, [1, 2, 4, 8, 16, 32]);
405 /// ```
406 ///
407 /// # Panics
408 ///
409 /// Panics if `f` panics; in this event, any elements that have been initialized will be properly dropped.
410 /// ```rust
411 /// # use slice_rc::UniqueSrc;
412 /// # use std::cell::Cell;
413 /// thread_local! {
414 /// static DROPPED: Cell<usize> = Cell::new(0);
415 /// }
416 ///
417 /// struct Droppable;
418 ///
419 /// impl Drop for Droppable {
420 /// fn drop(&mut self) {
421 /// DROPPED.with(|dropped| dropped.update(|x| x + 1));
422 /// }
423 /// }
424 ///
425 /// let _ = std::panic::catch_unwind(|| {
426 /// UniqueSrc::from_fn(10, |i| {
427 /// if i >= 5 { panic!() }
428 /// Droppable
429 /// })
430 /// });
431 ///
432 /// assert_eq!(DROPPED.get(), 5);
433 /// ```
434 #[inline]
435 pub fn from_fn<F: FnMut(usize) -> T>(len: usize, f: F) -> UniqueSrc<[T]> {
436 UninitSrc::new(len).init_unique_from_fn(f)
437 }
438
439 /// Constructs a new [root](crate#root) `UniqueSrc` 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.
440 ///
441 /// This method is like [`UniqueSrc::from_fn`], but in this the function `f` is passed a root [`WeakSrc`] pointer to the allocation to allow constructing self-referential elements.
442 ///
443 /// This is a convienience method for a specific subset of behavior that can be obtained via [`UninitSrc`].
444 ///
445 /// ```rust
446 /// use slice_rc::{Src, UniqueSrc, WeakSrc};
447 ///
448 /// struct S {
449 /// val: usize,
450 /// root: WeakSrc<[S]>,
451 /// }
452 ///
453 /// let root = UniqueSrc::cyclic_from_fn(5, |root, i| S {
454 /// val: i * 2,
455 /// root: root.clone(),
456 /// });
457 ///
458 /// assert_eq!(root.iter().map(|s| s.val).collect::<Vec<_>>(), vec![0, 2, 4, 6, 8]);
459 ///
460 /// let root = UniqueSrc::into_shared(root);
461 ///
462 /// assert!(root.iter().all(|s| Src::ptr_eq(&root, &s.root.upgrade().unwrap())));
463 /// ```
464 ///
465 /// It is possible to obtain a `WeakSrc` to the individual element that is being initialized via [`WeakSrc::slice`]:
466 ///
467 /// ```rust
468 /// # use slice_rc::{Src, UniqueSrc, WeakSrc};
469 /// struct S {
470 /// val: usize,
471 /// me: WeakSrc<S>,
472 /// }
473 ///
474 /// let root = UniqueSrc::cyclic_from_fn(5, |root, i| S {
475 /// val: i * 2,
476 /// me: root.slice(i),
477 /// });
478 ///
479 /// let root = UniqueSrc::into_shared(root);
480 ///
481 /// assert!(root.iter().enumerate().all(|(i, s)| Src::ptr_eq(&root.slice(i), &s.me.upgrade().unwrap())));
482 /// ```
483 pub fn cyclic_from_fn<F: FnMut(&WeakSrc<[T]>, usize) -> T>(len: usize, mut f: F) -> UniqueSrc<[T]> {
484 let this = UninitSrc::new(len);
485 let weak = this.downgrade();
486 this.init_unique_from_fn(|i| f(&weak, i))
487 }
488
489 /// Constructs a new [root](crate#root) `UniqueSrc` from the given iterator.
490 ///
491 /// This method is essentially shorthand for
492 /// ```rust
493 /// use slice_rc::UniqueSrc;
494 ///
495 /// # fn f<T>(iter: impl IntoIterator<Item = T, IntoIter: std::iter::ExactSizeIterator>) -> UniqueSrc<[T]> {
496 /// let mut iter = iter.into_iter();
497 /// UniqueSrc::from_fn(iter.len(), |_| iter.next().unwrap())
498 /// # }
499 /// ```
500 ///
501 /// The iterator must be [`ExactSizeIterator`] because `UniqueSrc`s cannot be resized,
502 /// so the number of elements must be known at allocation-time, i.e., before any of the elements are initialized.
503 /// If you want to use a non-[`ExactSizeIterator`], use <code>iter.[collect](Iterator::collect)::\<[Vec]\<_>>()</code>.
504 #[inline]
505 pub fn from_iter<I: IntoIterator<Item = T, IntoIter: ExactSizeIterator>>(iter: I) -> UniqueSrc<[T]> {
506 let mut iter = iter.into_iter();
507 UniqueSrc::from_fn(iter.len(), |_| iter.next().unwrap())
508 }
509
510 /// Constructs a new [root](crate#root) `UniqueSrc` from the given array.
511 ///
512 /// This method is effectively equivalent to passing an array to [`UniqueSrc::from_iter`], but it is more efficient.
513 /// As such, it is effectively shorthand for <code>UniqueSrc::[from_fn](N, |i| values\[i])</code>, but again, more efficient
514 /// (though not by enough to make <code>UniqueSrc::from_array([array::from_fn]::<_, N, _>(f))</code> any better than <code>UniqueSrc::[from_fn](N, f)</code>).
515 ///
516 /// Note that the my assertions about efficiency are not based any kind of benchmarking,
517 /// just the fact that this method uses a single [`ptr::write`] where [`UniqueSrc::from_fn`] and [`UniqueSrc::from_iter`] use `N` arbitrary function calls and `N` [`ptr::write`]s.
518 /// As <code>[array::from_fn]</code> re-introduces at least the `N` arbitrary function calls, its difference (again, without benchmarking) is negligible.
519 ///
520 /// [from_fn]: UniqueSrc::from_fn
521 /// [`ptr::write`]: std::ptr::write
522 /// [array::from_fn]: std::array::from_fn
523 pub fn from_array<const N: usize>(values: [T; N]) -> UniqueSrc<[T]> {
524 let header = InnerHeader::new_inner::<T, AllocUninit>(N);
525 // SAFETY:
526 // * we just got this from InnerHeader::new_inner::<T>
527 // * no one else has seen the ptr yet, so the read/write requirements are fine
528 let start = unsafe { InnerHeader::get_body_ptr::<T>(header) };
529 // SAFETY: no one else has seen the body, so write is fine; InnerHeader::new_inner::<T>(N) guarantees N elements, so we definitely have room for [T; N]
530 unsafe { start.cast().write(values) };
531 UniqueSrc {
532 // the safety invariant of _.header is fulfilled by definition
533 header,
534 // with start.write(_), the safety invariant of _.start is fulfilled by definition
535 start,
536 // the safety invariant of _.len is fulfilled by definition
537 len: N,
538 _phantom: PhantomData,
539 }
540 }
541
542 /// Constructs a new [root](crate#root) `UniqueSrc` of the given length where each element is the type's [default](Default::default).
543 ///
544 /// This method is essentially equivalent to <code>UniqueSrc::[from_fn](UniqueSrc::from_fn)(len, |_| [Default::default]\())</code>.
545 #[inline]
546 pub fn from_default(len: usize) -> UniqueSrc<[T]> where T: Default {
547 UniqueSrc::from_fn(len, |_| Default::default())
548 }
549
550 /// Constructs a new [root](crate#root) `UniqueSrc` of the given length where each element is a clone of `value`.
551 ///
552 /// This method is essentially equivalent to <code>UniqueSrc::[from_fn](UniqueSrc::from_fn)(len, |_| value.[clone](Clone::clone)())</code>.
553 #[inline]
554 pub fn filled(len: usize, value: &T) -> UniqueSrc<[T]> where T: Clone {
555 UniqueSrc::from_fn(len, |_| value.clone())
556 }
557
558 /// Constructs a new [root](crate#root) `UniqueSrc` of the given length where each element is a clone of the value returned from `f`.
559 /// `f` is passed a root [`WeakSrc`] pointer to the allocation; this can be used to make self-referential structures.
560 ///
561 /// ```rust
562 /// use slice_rc::{Src, UniqueSrc, WeakSrc};
563 ///
564 /// #[derive(Clone)]
565 /// struct S {
566 /// val: i32,
567 /// root: WeakSrc<[S]>,
568 /// }
569 ///
570 /// let root = UniqueSrc::filled_cyclic(5, |root| S { val: 42, root: root.clone() });
571 ///
572 /// assert!(root.iter().all(|s| s.val == 42));
573 ///
574 /// let root = UniqueSrc::into_shared(root);
575 ///
576 /// assert!(root.iter().all(|s| Src::ptr_eq(&root, &s.root.upgrade().unwrap())));
577 /// ```
578 pub fn filled_cyclic<F: FnOnce(&WeakSrc<[T]>) -> T>(len: usize, f: F) -> UniqueSrc<[T]> where T: Clone {
579 let this = UninitSrc::new(len);
580 let weak = this.downgrade();
581 this.init_unique_filled(&f(&weak))
582 }
583
584 /// Constructs a new [root](crate#root) `UniqueSrc` as a clone of the given slice.
585 ///
586 /// This method is essentially shorthand for <code>UniqueSrc::[from_fn](UniqueSrc::from_fn)(values.[len](slice::len)(), |i| values\[i].clone())</code>,
587 /// but without the implicit bounds checking for slice indexing.
588 #[inline]
589 pub fn cloned(values: &[T]) -> UniqueSrc<[T]> where T: Clone {
590 UniqueSrc::from_fn(values.len(), |i| {
591 // SAFETY: i ranges from 0..len==src.len()
592 unsafe { values.get_unchecked(i) }.clone()
593 })
594 }
595
596 /// Constructs a new [root](crate#root) `UniqueSrc` as a copy of the given slice.
597 ///
598 /// This method is functionally shorthand for <code>UniqueSrc::[from_fn](UniqueSrc::from_fn)(values.[len](slice::len)(), |i| values\[i])</code>,
599 /// but without the implicit bounds checking for slice indexing.
600 ///
601 /// This method is fairly efficient, as it is basically just an allocation (requisite for any `UniqueSrc` constructor) and a [`memcpy`](std::ptr::copy_nonoverlapping).
602 #[inline]
603 pub fn copied(values: &[T]) -> UniqueSrc<[T]> where T: Copy {
604 let len = values.len();
605 let header = InnerHeader::new_inner::<T, AllocUninit>(len);
606 // SAFETY:
607 // * we just got this from InnerHeader::new_inner::<T>
608 // * no one else has seen the ptr yet, so the read/write requirements are fine
609 let start = unsafe { InnerHeader::get_body_ptr::<T>(header) };
610 let values = NonNull::from_ref(values).cast();
611 // SAFETY:
612 // * values is from a reference, and is therefore valid
613 // * InnerHeader::new_inner::<T>(len) guarantees that start is valid for len * size_of::<T>() bytes and aligned for T
614 // * start just came from a new allocation, and therefore doesn't overlap with a slice that was passed into this function
615 unsafe { values.copy_to_nonoverlapping(start, len); }
616 UniqueSrc {
617 // the safety invariant of _.header is fulfilled by definition
618 header,
619 // with values.copy_to_nonoverlapping(_, _), the safety invariant of _.start is fulfilled by definition
620 start,
621 // the safety invariant of _.len is fulfilled by definition
622 len,
623 _phantom: PhantomData,
624 }
625 }
626
627}
628
629impl<T> UniqueSrc<MaybeUninit<T>> {
630
631 /// Converts to `UniqueSrc<T>`.
632 ///
633 /// # Safety
634 ///
635 /// As with [`MaybeUninit::assume_init`], it is up to the caller to guarantee that the inner value really is in an initialized state.
636 /// Calling this when the content is not yet fully initialized causes immediate undefined behavior.
637 ///
638 /// # Examples
639 ///
640 /// ```rust
641 /// use slice_rc::UniqueSrc;
642 ///
643 /// let zero = UniqueSrc::<i32>::single_zeroed();
644 /// let zero = unsafe { zero.assume_init() };
645 ///
646 /// assert_eq!(*zero, 0);
647 /// ```
648 pub unsafe fn assume_init(self) -> UniqueSrc<T> {
649 // TODO: rephrase the safety requirements for InnerHeader to explicitly allow punning between T and type with T-like layout
650 let this = UniqueSrc {
651 // 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
652 header: self.header,
653 // 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
654 start: self.start.cast(),
655 // 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
656 len: self.len,
657 _phantom: PhantomData,
658 };
659 forget(self);
660 this
661 }
662
663}
664
665impl<T> UniqueSrc<[MaybeUninit<T>]> {
666
667 /// Converts to `UniqueSrc<[T]>`.
668 ///
669 /// # Safety
670 ///
671 /// As with [`MaybeUninit::assume_init`], it is up to the caller to guarantee that the inner value really is in an initialized state.
672 /// Calling this when the content is not yet fully initialized causes immediate undefined behavior.
673 ///
674 /// # Examples
675 ///
676 /// ```rust
677 /// use slice_rc::UniqueSrc;
678 ///
679 /// let zeroes = UniqueSrc::<[i32]>::new_zeroed(3);
680 /// let zeroes = unsafe { zeroes.assume_init() };
681 ///
682 /// assert_eq!(*zeroes, [0, 0, 0]);
683 /// ```
684 pub unsafe fn assume_init(self) -> UniqueSrc<[T]> {
685 // TODO: rephrase the safety requirements for InnerHeader to explicitly allow punning between T and type with T-like layout
686 let this = UniqueSrc {
687 // 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
688 header: self.header,
689 // 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
690 start: self.start.cast(),
691 // 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
692 len: self.len,
693 _phantom: PhantomData,
694 };
695 forget(self);
696 this
697 }
698
699}
700
701impl UniqueSrc<str> {
702
703 /// Constructs a new [`root`](crate#root) `UniqueSrc` as a copy of the given string.
704 ///
705 /// ```rust
706 /// use slice_rc::UniqueSrc;
707 ///
708 /// let hello = UniqueSrc::new("Hello World!");
709 ///
710 /// assert_eq!(&*hello, "Hello World!");
711 /// ```
712 #[inline]
713 pub fn new(s: impl AsRef<str>) -> UniqueSrc<str> {
714 let s = s.as_ref();
715 let this = UniqueSrc::copied(s.as_bytes());
716 // SAFETY: the bytes here came from a str, which already upholds the UTF-8 safety invariant
717 unsafe { UniqueSrc::from_utf8_unchecked(this) }
718 }
719
720 /// Converts an `UniqueSrc` of bytes to a string `UniqueSrc`.
721 ///
722 /// [`str`] and [`[u8]`](slice) are both slices of bytes, so this function converts between the two.
723 /// Not all byte slices are valid string slices, however: [`str`] must be valid UTF-8.
724 /// This method checks to ensure that the bytes are valid UTF-8, and then does the conversion.
725 ///
726 /// 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,
727 /// there is an unsafe version of this method, [`from_utf8_unchecked`](Src::from_utf8_unchecked),
728 /// which has the same behavior but skips the check.
729 ///
730 /// # Errors
731 ///
732 /// Returns `Err` if the slice is not UTF-8 with a description as to why the provided slice is not UTF-8.
733 ///
734 /// # Examples
735 ///
736 /// Basic usage:
737 ///
738 /// ```rust
739 /// use slice_rc::UniqueSrc;
740 ///
741 /// let sparkle_heart = UniqueSrc::from_array([240, 159, 146, 150]);
742 ///
743 /// let sparkle_heart = UniqueSrc::from_utf8(sparkle_heart)?;
744 ///
745 /// assert_eq!("💖", &*sparkle_heart);
746 /// # Ok::<_, std::str::Utf8Error>(())
747 /// ```
748 ///
749 /// Incorrect bytes:
750 ///
751 /// ```rust
752 /// # use slice_rc::UniqueSrc;
753 /// let sparkle_heart = UniqueSrc::from_array([0, 159, 146, 150]);
754 ///
755 /// assert!(UniqueSrc::from_utf8(sparkle_heart).is_err());
756 /// ```
757 #[inline]
758 pub fn from_utf8(v: UniqueSrc<[u8]>) -> Result<UniqueSrc<str>, Utf8Error> {
759 let _: &str = <str>::from_utf8(&*v)?;
760 // SAFETY: <str>::from_utf8() guarantees that the contents are UTF-8
761 Ok(unsafe { UniqueSrc::from_utf8_unchecked(v) })
762 }
763
764 /// Converts an `UniqueSrc` of bytes to a string `UniqueSrc` without checking that the string contains valid UTF-8.
765 ///
766 /// See the safe version, [`from_utf8`](UniqueSrc::from_utf8), for more information.
767 ///
768 /// # Safety
769 ///
770 /// The bytes passed in must be valid UTF-8.
771 ///
772 /// # Examples
773 ///
774 /// ```rust
775 /// use slice_rc::UniqueSrc;
776 ///
777 /// let sparkle_heart = UniqueSrc::from_array([240, 159, 146, 150]);
778 ///
779 /// let sparkle_heart = unsafe { UniqueSrc::from_utf8_unchecked(sparkle_heart) };
780 ///
781 /// assert_eq!("💖", &*sparkle_heart);
782 /// ```
783 #[inline]
784 pub unsafe fn from_utf8_unchecked(v: UniqueSrc<[u8]>) -> UniqueSrc<str> {
785 // TODO: rephrase the safety requirements for InnerHeader to explicitly allow punning between T and type with T-like layout
786 let this = UniqueSrc {
787 // SAFETY: v.header has *almost* the same safety invariant as this.header: the only difference is that v uses [u8] where this expects str;
788 // 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
789 header: v.header,
790 // SAFETY: v.start has *almost* the same safety invariant as this.start: the only difference is that v uses [u8] where this expects str;
791 // 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
792 start: v.start,
793 // SAFETY: v.len has *almost* the same safety invariant as this.len: the only difference is that v uses [u8] where this expects str;
794 // 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
795 len: v.len,
796 _phantom: PhantomData,
797 };
798 forget(v);
799 this
800 }
801
802 /// Converts a string `UniqueSrc` to a `UniqueSrc` of bytes.
803 /// To convert the the bytes back to a string, use the [`from_utf8`](UniqueSrc::from_utf8) method.
804 ///
805 /// # Examples
806 ///
807 /// ```rust
808 /// use slice_rc::UniqueSrc;
809 ///
810 /// let bytes = UniqueSrc::as_bytes(UniqueSrc::new("bors"));
811 /// assert_eq!(b"bors", &*bytes);
812 /// ```
813 #[inline]
814 pub fn as_bytes(this: UniqueSrc<str>) -> UniqueSrc<[u8]> {
815 // TODO: rephrase the safety requirements for InnerHeader to explicitly allow punning between T and type with T-like layout
816 let this2 = UniqueSrc {
817 // SAFETY: this.header has *almost* the same safety invariant as this2.header: the only difference is that this uses str where this2 expects [u8];
818 // the pun from str to [u8] relaxes the safety requirement that this's content is valid UTF-8
819 header: this.header,
820 // SAFETY: this.start has *almost* the same safety invariant as this2.start: the only difference is that this uses str where this2 expects [u8];
821 // the pun from str to [u8] relaxes the safety requirement that this's content is valid UTF-8
822 start: this.start,
823 // SAFETY: this.len has *almost* the same safety invariant as this2.len: the only difference is that this uses str where this2 expects [u8];
824 // the pun from str to [u8] relaxes the safety requirement that this's content is valid UTF-8
825 len: this.len,
826 _phantom: PhantomData,
827 };
828 forget(this);
829 this2
830 }
831
832}
833
834impl<T: Default> Default for UniqueSrc<T> {
835
836 #[inline]
837 fn default() -> Self {
838 Self::single(T::default())
839 }
840
841}
842
843impl<T: SrcTarget + ?Sized> Deref for UniqueSrc<T> {
844
845 type Target = T;
846
847 #[inline]
848 fn deref(&self) -> &Self::Target {
849 T::get_unique(self)
850 }
851
852}
853
854impl<T: SrcTarget + ?Sized> DerefMut for UniqueSrc<T> {
855
856 #[inline]
857 fn deref_mut(&mut self) -> &mut Self::Target {
858 T::get_unique_mut(self)
859 }
860
861}
862
863impl<T: SrcTarget + ?Sized> Borrow<T> for UniqueSrc<T> {
864
865 #[inline]
866 fn borrow(&self) -> &T {
867 &**self
868 }
869
870}
871
872impl<T: SrcTarget + ?Sized> BorrowMut<T> for UniqueSrc<T> {
873
874 #[inline]
875 fn borrow_mut(&mut self) -> &mut T {
876 &mut **self
877 }
878
879}
880
881impl<T: SrcTarget + ?Sized> AsRef<T> for UniqueSrc<T> {
882
883 #[inline]
884 fn as_ref(&self) -> &T {
885 &**self
886 }
887
888}
889
890impl<T: SrcTarget + ?Sized> AsMut<T> for UniqueSrc<T> {
891
892 #[inline]
893 fn as_mut(&mut self) -> &mut T {
894 &mut **self
895 }
896
897}
898
899impl<T: SrcTarget + Index<I> + ?Sized, I> Index<I> for UniqueSrc<T> {
900
901 type Output = T::Output;
902
903 #[inline]
904 fn index(&self, index: I) -> &Self::Output {
905 &self.deref()[index]
906 }
907
908}
909
910impl<T: SrcTarget + IndexMut<I> + ?Sized, I> IndexMut<I> for UniqueSrc<T> {
911
912 #[inline]
913 fn index_mut(&mut self, index: I) -> &mut Self::Output {
914 &mut self.deref_mut()[index]
915 }
916
917}
918
919impl<T: Hash + SrcTarget + ?Sized> Hash for UniqueSrc<T> {
920
921 #[inline]
922 fn hash<H: Hasher>(&self, state: &mut H) {
923 T::hash(&**self, state);
924 }
925
926}
927
928impl<T: PartialEq<U> + SrcTarget + ?Sized, U: SrcTarget + ?Sized> PartialEq<UniqueSrc<U>> for UniqueSrc<T> {
929
930 #[inline]
931 fn eq(&self, other: &UniqueSrc<U>) -> bool {
932 T::eq(&**self, &**other)
933 }
934
935 #[inline]
936 fn ne(&self, other: &UniqueSrc<U>) -> bool {
937 T::ne(&**self, &**other)
938 }
939
940}
941
942impl<T: Eq + SrcTarget + ?Sized> Eq for UniqueSrc<T> {}
943
944impl<T: PartialOrd<U> + SrcTarget + ?Sized, U: SrcTarget + ?Sized> PartialOrd<UniqueSrc<U>> for UniqueSrc<T> {
945
946 #[inline]
947 fn ge(&self, other: &UniqueSrc<U>) -> bool {
948 T::ge(&**self, &**other)
949 }
950
951 #[inline]
952 fn gt(&self, other: &UniqueSrc<U>) -> bool {
953 T::gt(&**self, &**other)
954 }
955
956 #[inline]
957 fn le(&self, other: &UniqueSrc<U>) -> bool {
958 T::le(&**self, &**other)
959 }
960
961 #[inline]
962 fn lt(&self, other: &UniqueSrc<U>) -> bool {
963 T::lt(&**self, &**other)
964 }
965
966 #[inline]
967 fn partial_cmp(&self, other: &UniqueSrc<U>) -> Option<Ordering> {
968 T::partial_cmp(&**self, &**other)
969 }
970
971}
972
973impl<T: Ord + SrcTarget + ?Sized> Ord for UniqueSrc<T> {
974
975 #[inline]
976 fn cmp(&self, other: &Self) -> Ordering {
977 T::cmp(&**self, &**other)
978 }
979
980}
981
982impl<T: Debug + SrcTarget + ?Sized> Debug for UniqueSrc<T> {
983
984 #[inline]
985 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
986 T::fmt(self, f)
987 }
988
989}
990
991impl<T: SrcTarget + ?Sized> Pointer for UniqueSrc<T> {
992
993 #[inline]
994 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
995 Pointer::fmt(&self.start, f)
996 }
997
998}
999
1000impl<T: SrcTarget + ?Sized> Drop for UniqueSrc<T> {
1001
1002 fn drop(&mut self) {
1003 // the UninqueSrc doesn't hold a strong ref so that the weaks can't be upgraded, but for most purposes it is just a Src that is known to be the only one; so drop it as if it were one
1004 self.header().inc_strong_count();
1005 // SAFETY:
1006 // * all constructor fns for Src initialize header from InnerHeader::new_inner::<T::Item>
1007 // * all constructor fns for Src initialize the elements
1008 // * the header is only accessed from InnerHeader::get_header
1009 // * this is guaranteed to be the last strong reference, because UniqueSrc's invariant prevents any other strong references from existing
1010 unsafe { InnerHeader::drop_strong::<T::Item>(self.header); }
1011 }
1012
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017
1018 use std::{cell::Cell, mem::MaybeUninit, ops::{Deref, DerefMut}, panic::{catch_unwind, AssertUnwindSafe}, str::Utf8Error};
1019 use crate::*;
1020
1021 #[test]
1022 fn downgrade() {
1023 let u: UniqueSrc<[u8]> = UniqueSrc::from_default(3);
1024 let w: WeakSrc<[u8]> = UniqueSrc::downgrade(&u);
1025 assert!(w.upgrade().is_none());
1026 let s1: Src<[u8]> = UniqueSrc::into_shared(u);
1027 let s2: Src<[u8]> = w.upgrade().unwrap();
1028 assert_eq!(s1, s2);
1029 assert!(Src::ptr_eq(&s1, &s2));
1030 }
1031
1032 #[test]
1033 fn into_shared() {
1034 let u: UniqueSrc<[u8]> = UniqueSrc::from_array([1, 2, 3]);
1035 let s1: Src<[u8]> = UniqueSrc::into_shared(u);
1036 let s2: Src<[u8]> = s1.clone();
1037 assert_eq!(*s1, [1, 2, 3]);
1038 assert!(Src::ptr_eq(&s1, &s2));
1039 }
1040
1041 #[test]
1042 fn empty() {
1043 let u: UniqueSrc<[u8]> = UniqueSrc::empty();
1044 assert!(u.is_empty());
1045 assert_eq!(u.len(), 0);
1046 let u: UniqueSrc<str> = UniqueSrc::empty();
1047 assert!(u.is_empty());
1048 assert_eq!(u.len(), 0);
1049 }
1050
1051 #[test]
1052 fn len() {
1053 let u: UniqueSrc<[u8]> = UniqueSrc::from_default(0);
1054 assert_eq!(u.len(), 0);
1055 let u: UniqueSrc<[u8]> = UniqueSrc::from_default(1);
1056 assert_eq!(u.len(), 1);
1057 let u: UniqueSrc<[u8]> = UniqueSrc::from_default(17);
1058 assert_eq!(u.len(), 17);
1059 }
1060
1061 #[test]
1062 fn is_empty() {
1063 let u: UniqueSrc<[u8]> = UniqueSrc::from_default(0);
1064 assert!(u.is_empty());
1065 let u: UniqueSrc<[u8]> = UniqueSrc::from_default(1);
1066 assert!(!u.is_empty());
1067 let u: UniqueSrc<[u8]> = UniqueSrc::from_default(17);
1068 assert!(!u.is_empty());
1069 }
1070
1071 #[test]
1072 fn single() {
1073 let u: UniqueSrc<u8> = UniqueSrc::single(42);
1074 let s: Src<u8> = UniqueSrc::into_shared(u);
1075 assert!(Src::is_root(&s));
1076 let s: Src<[u8]> = Src::as_slice(&s);
1077 assert_eq!(s.len(), 1);
1078 }
1079
1080 #[test]
1081 fn single_cyclic() {
1082 { // non-cyclic
1083 let u: UniqueSrc<u8> = UniqueSrc::single_cyclic(|_| 42);
1084 assert_eq!(*u, 42);
1085 }
1086 { // cyclic
1087 struct S {
1088
1089 this: WeakSrc<S>,
1090 i: usize,
1091
1092 }
1093 let u: UniqueSrc<S> = UniqueSrc::single_cyclic(|weak| S { this: weak.clone(), i: 42 });
1094 assert_eq!(u.i, 42);
1095 let w: WeakSrc<S> = UniqueSrc::downgrade(&u);
1096 assert!(WeakSrc::ptr_eq(&u.this, &w));
1097 }
1098 }
1099
1100 #[test]
1101 fn single_uninit() {
1102 let mut u: UniqueSrc<MaybeUninit<u8>> = UniqueSrc::single_uninit();
1103 u.write(42);
1104 // SAFETY: just initialized this with u.write()
1105 let u: UniqueSrc<u8> = unsafe { u.assume_init() };
1106 assert_eq!(*u, 42);
1107 }
1108
1109 #[test]
1110 fn single_zeroed() {
1111 let u: UniqueSrc<MaybeUninit<u8>> = UniqueSrc::single_zeroed();
1112 // SAFETY: u8 is a zeroable type
1113 let u: UniqueSrc<u8> = unsafe { u.assume_init() };
1114 assert_eq!(*u, 0);
1115 }
1116
1117 #[test]
1118 fn as_slice() {
1119 let u: UniqueSrc<u8> = UniqueSrc::single(42);
1120 let u: UniqueSrc<[u8]> = UniqueSrc::as_slice(u);
1121 assert_eq!([42], *u);
1122 }
1123
1124 #[test]
1125 fn new_uninit() {
1126 let mut u: UniqueSrc<[MaybeUninit<u8>]> = UniqueSrc::new_uninit(3);
1127 assert_eq!(u.len(), 3);
1128 for (i, elem) in u.iter_mut().enumerate() {
1129 elem.write(i as _);
1130 }
1131 // SAFETY: just initialized it with all the elem.write()s
1132 let u: UniqueSrc<[u8]> = unsafe { u.assume_init() };
1133 assert_eq!(*u, [0, 1, 2]);
1134 }
1135
1136 #[test]
1137 fn new_zeroed() {
1138 let u: UniqueSrc<[MaybeUninit<u8>]> = UniqueSrc::new_zeroed(3);
1139 assert_eq!(u.len(), 3);
1140 // SAFETY: u8 is a zeroable type
1141 let u: UniqueSrc<[u8]> = unsafe { u.assume_init() };
1142 assert_eq!(*u, [0, 0, 0]);
1143 }
1144
1145 #[test]
1146 fn from_fn() {
1147 { // normal
1148 let u: UniqueSrc<[usize]> = UniqueSrc::from_fn(3, |i| i * 2);
1149 assert_eq!(*u, [0, 2, 4]);
1150 }
1151 { // panic
1152 let drop_flags: [_; 6] = std::array::from_fn(|_| AssertUnwindSafe(Cell::new(false)));
1153 struct DropFlagger<'a>(&'a Cell<bool>);
1154 impl Drop for DropFlagger<'_> {
1155
1156 fn drop(&mut self) {
1157 self.0.update(|v| !v)
1158 }
1159
1160 }
1161 let _: Result<_, _> = catch_unwind(|| {
1162 let _: UniqueSrc<[DropFlagger<'_>]> = UniqueSrc::from_fn(drop_flags.len(), |i| {
1163 if i >= 3 { panic!() }
1164 DropFlagger(&drop_flags[i])
1165 });
1166 });
1167 assert!(drop_flags[..3].iter().map(Deref::deref).all(Cell::get));
1168 assert!(!drop_flags[3..].iter().map(Deref::deref).any(Cell::get));
1169 }
1170 }
1171
1172 #[test]
1173 fn cyclic_from_fn() {
1174 { // normal, not cyclic
1175 let u: UniqueSrc<[usize]> = UniqueSrc::cyclic_from_fn(3, |_, i| i * 2);
1176 assert_eq!(*u, [0, 2, 4]);
1177 }
1178 { // normal, cyclic
1179 struct S {
1180
1181 all: WeakSrc<[S]>,
1182 i: usize,
1183
1184 }
1185 let u: UniqueSrc<[S]> = UniqueSrc::cyclic_from_fn(3, |w, i| S { all: w.clone(), i: i * 2 });
1186 assert_eq!(u[0].i, 0);
1187 assert_eq!(u[1].i, 2);
1188 assert_eq!(u[2].i, 4);
1189 assert!(u[0].all.upgrade().is_none());
1190 let s1: Src<[S]> = UniqueSrc::into_shared(u);
1191 let s2: Src<[S]> = s1[0].all.upgrade().unwrap();
1192 assert!(Src::ptr_eq(&s1, &s2));
1193 }
1194 { // panic
1195 let drop_flags: [_; 6] = std::array::from_fn(|_| AssertUnwindSafe(Cell::new(false)));
1196 struct DropFlagger<'a>(&'a Cell<bool>);
1197 impl Drop for DropFlagger<'_> {
1198
1199 fn drop(&mut self) {
1200 self.0.update(|v| !v)
1201 }
1202
1203 }
1204 let _: Result<_, _> = catch_unwind(|| {
1205 let _: UniqueSrc<[DropFlagger<'_>]> = UniqueSrc::cyclic_from_fn(drop_flags.len(), |_, i| {
1206 if i >= 3 { panic!() }
1207 DropFlagger(&drop_flags[i])
1208 });
1209 });
1210 assert!(drop_flags[..3].iter().map(Deref::deref).all(Cell::get));
1211 assert!(!drop_flags[3..].iter().map(Deref::deref).any(Cell::get));
1212 }
1213 }
1214
1215 #[test]
1216 fn from_iter() {
1217 let u: UniqueSrc<[u8]> = UniqueSrc::from_iter(vec![1, 2, 3].into_iter().map(|i| i * 2));
1218 assert_eq!(*u, [2, 4, 6]);
1219 }
1220
1221 #[test]
1222 fn from_array() {
1223 let u: UniqueSrc<[u8]> = UniqueSrc::from_array([1, 2, 3]);
1224 assert_eq!(*u, [1, 2, 3]);
1225 }
1226
1227 #[test]
1228 fn from_default() {
1229 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
1230 struct D42(u8);
1231 impl Default for D42 {
1232
1233 fn default() -> Self {
1234 Self(42)
1235 }
1236
1237 }
1238 let u: UniqueSrc<[u8]> = UniqueSrc::from_default(3);
1239 assert_eq!(*u, [0, 0, 0]);
1240 let u: UniqueSrc<[D42]> = UniqueSrc::from_default(3);
1241 assert_eq!(*u, [D42(42), D42(42), D42(42)]);
1242 }
1243
1244 #[test]
1245 fn filled() {
1246 let u: UniqueSrc<[u8]> = UniqueSrc::filled(3, &42);
1247 assert_eq!(*u, [42, 42, 42]);
1248 }
1249
1250 #[test]
1251 fn filled_cyclic() {
1252 { // non-cyclic
1253 let u: UniqueSrc<[u8]> = UniqueSrc::filled_cyclic(3, |_| 42);
1254 assert_eq!(*u, [42, 42, 42]);
1255 }
1256 { // cyclic
1257 #[derive(Clone)]
1258 struct S {
1259
1260 all: WeakSrc<[S]>,
1261 i: usize,
1262
1263 }
1264 let u: UniqueSrc<[S]> = UniqueSrc::filled_cyclic(3, |weak| S { all: weak.clone(), i: 42 });
1265 assert_eq!(u[0].i, 42);
1266 assert_eq!(u[1].i, 42);
1267 assert_eq!(u[2].i, 42);
1268 let w: WeakSrc<[S]> = UniqueSrc::downgrade(&u);
1269 assert!(WeakSrc::ptr_eq(&u[0].all, &w));
1270 }
1271 }
1272
1273 #[test]
1274 fn cloned() {
1275 #[derive(Clone, Eq, PartialEq, Debug)]
1276 struct NonCopy(u8);
1277 let u: UniqueSrc<[NonCopy]> = UniqueSrc::cloned(&[NonCopy(1), NonCopy(2), NonCopy(3)]);
1278 assert_eq!(*u, [NonCopy(1), NonCopy(2), NonCopy(3)]);
1279 }
1280
1281 #[test]
1282 fn copied() {
1283 let u: UniqueSrc<[u8]> = UniqueSrc::copied(&[1, 2, 3]);
1284 assert_eq!(*u, [1, 2, 3]);
1285 }
1286
1287 #[test]
1288 fn assume_init_single() {
1289 let u: UniqueSrc<MaybeUninit<u8>> = UniqueSrc::single_zeroed();
1290 // SAFETY: u8 is a zeroable type
1291 let u: UniqueSrc<u8> = unsafe { u.assume_init() };
1292 assert_eq!(*u, 0);
1293 }
1294
1295 #[test]
1296 fn assume_init_slice() {
1297 let u: UniqueSrc<[MaybeUninit<u8>]> = UniqueSrc::new_zeroed(3);
1298 // SAFETY: u8 is a zeroable type
1299 let u: UniqueSrc<[u8]> = unsafe { u.assume_init() };
1300 assert_eq!(*u, [0, 0, 0]);
1301 }
1302
1303 #[test]
1304 fn new() {
1305 let u: UniqueSrc<str> = UniqueSrc::new("Hello World!");
1306 assert_eq!(&*u, "Hello World!");
1307 }
1308
1309 #[test]
1310 fn from_utf8() {
1311 { // UTF-8
1312 let u: UniqueSrc<[u8]> = UniqueSrc::copied(b"Hello World!");
1313 let u: UniqueSrc<str> = UniqueSrc::from_utf8(u).unwrap();
1314 assert_eq!(&*u, "Hello World!");
1315 }
1316 { // not UTF-8
1317 let u: UniqueSrc<[u8]> = UniqueSrc::copied(&[0xFF]);
1318 let _: Utf8Error = UniqueSrc::from_utf8(u).unwrap_err();
1319 }
1320 }
1321
1322 #[test]
1323 fn from_utf8_unchecked() {
1324 let u: UniqueSrc<[u8]> = UniqueSrc::copied(b"Hello World!");
1325 // SAFETY: just got the bytes from a str
1326 let u: UniqueSrc<str> = unsafe { UniqueSrc::from_utf8_unchecked(u) };
1327 assert_eq!(&*u, "Hello World!");
1328 }
1329
1330 #[test]
1331 fn as_bytes() {
1332 let u: UniqueSrc<str> = UniqueSrc::new("Hello World!");
1333 let u: UniqueSrc<[u8]> = UniqueSrc::as_bytes(u);
1334 assert_eq!(&*u, b"Hello World!");
1335 }
1336
1337 #[test]
1338 fn deref() {
1339 let u: UniqueSrc<[u8]> = UniqueSrc::from_array([1, 2, 3]);
1340 assert_eq!(Deref::deref(&u), &[1, 2, 3]);
1341 }
1342
1343 #[test]
1344 fn deref_mut() {
1345 let mut u: UniqueSrc<[i8]> = UniqueSrc::from_array([1, 2, 3]);
1346 assert_eq!(DerefMut::deref_mut(&mut u), &mut [1, 2, 3]);
1347 u[0] -= 4;
1348 u[1] = 42;
1349 u[2] *= 2;
1350 assert_eq!(DerefMut::deref_mut(&mut u), &mut [-3, 42, 6]);
1351 }
1352
1353 #[test]
1354 fn drop() {
1355 let drop_flags: [_; 3] = std::array::from_fn(|_| Cell::new(false));
1356 struct DropFlagger<'a>(&'a Cell<bool>);
1357 impl Drop for DropFlagger<'_> {
1358
1359 fn drop(&mut self) {
1360 self.0.update(|v| !v)
1361 }
1362
1363 }
1364 assert!(!drop_flags.iter().any(Cell::get));
1365 let u: UniqueSrc<[DropFlagger<'_>]> = UniqueSrc::from_iter(drop_flags.iter().map(DropFlagger));
1366 assert!(!drop_flags.iter().any(Cell::get));
1367 std::mem::drop(u);
1368 assert!(drop_flags.iter().all(Cell::get));
1369 }
1370
1371}