placid 0.1.0

Separated ownership and in-place construction in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
//! Owned references and related utilities.
//!
//! This module provides the [`Own<T>`] type, which represents an owned
//! reference to a fully initialized value in a place. It also includes macros
//! and traits for creating and manipulating owned references.
//!
//! For constructing owned references onto the stack, see the [`own!`] macro.
//!
//! For converting containers into owned references, see the [`IntoOwn`] trait
//! and the [`into_own!`] macro.
//!
//! [`Own<T>`]: crate::owned::Own
//! [`own!`]: crate::own
//! [`IntoOwn`]: crate::owned::IntoOwn
//! [`into_own!`]: crate::into_own

#[cfg(feature = "alloc")]
use alloc::{boxed::Box, rc::Rc, sync::Arc};
#[cfg(feature = "alloc")]
use core::{alloc::Allocator, mem::MaybeUninit};
use core::{
    any::Any,
    borrow::{Borrow, BorrowMut},
    error::Error,
    fmt,
    hash::{Hash, Hasher},
    mem,
    ops::{Deref, DerefMut},
    pin::Pin,
    ptr::NonNull,
    task::{Context, Poll},
};

use crate::{
    pin::{DropSlot, POwn},
    place::{Owned, Place, PlaceRef},
    uninit::Uninit,
};

/// An owned reference that contains a fully initialized value of type `T`.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
///
/// let mut my_place: Own<i32> = placid::own!(42);
/// assert_eq!(*my_place, 42);
/// *my_place += 1;
/// assert_eq!(*my_place, 43);
/// ```
pub type Own<'a, T> = PlaceRef<'a, T, Owned>;

/// Creates a new place initialized with the given expression.
///
/// The expression is evaluated and stored on the current call stack. The macro
/// then creates a `PlaceRef` pointing to that storage. This means the created
/// place is only valid within the scope it was created in.
///
/// # Examples
///
/// ```rust
/// let my_place = placid::own!(10);
/// assert_eq!(*my_place, 10);
/// ```
#[macro_export]
#[allow_internal_unstable(super_let)]
macro_rules! own {
    ($e:expr) => {{
        super let mut place = ::core::mem::MaybeUninit::uninit();
        $crate::place::Place::write(&mut place, $e)
    }};
}

impl<'a, T: ?Sized> Deref for Own<'a, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        // SAFETY: PlaceRef is owned, so the value is initialized.
        unsafe { self.inner.as_ref() }
    }
}

impl<'a, T: ?Sized> DerefMut for Own<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: PlaceRef is owned, so the value is initialized.
        unsafe { self.inner.as_mut() }
    }
}

impl<'a, T: ?Sized> AsRef<T> for Own<'a, T> {
    #[inline]
    fn as_ref(&self) -> &T {
        self
    }
}

impl<'a, T: ?Sized> AsMut<T> for Own<'a, T> {
    #[inline]
    fn as_mut(&mut self) -> &mut T {
        self
    }
}

impl<'a, T: ?Sized> Borrow<T> for Own<'a, T> {
    #[inline]
    fn borrow(&self) -> &T {
        self
    }
}

impl<'a, T: ?Sized> BorrowMut<T> for Own<'a, T> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut T {
        self
    }
}

impl<'a, T: ?Sized> Own<'a, T> {
    /// Converts the owned reference into a pinned owned reference. If the value
    /// inside the place is not `!Unpin`, this ensures that it cannot be moved
    /// out of the place.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let owned = own!(String::from("Hello"));
    /// let drop_slot = placid::drop_slot!();
    /// let pinned = Own::into_pin(owned, drop_slot);
    /// // The value is now pinned and cannot be moved
    /// ```
    #[inline]
    pub fn into_pin<'b>(this: Self, slot: DropSlot<'a, 'b, T>) -> POwn<'b, T> {
        POwn::new(this, slot)
    }

    /// Returns a raw pointer to the value inside the owned reference.
    ///
    /// The returned pointer is valid as long as the owned reference is valid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let my_place = own!(42i32);
    /// let ptr = Own::as_ptr(&my_place);
    /// assert_eq!(unsafe { *ptr }, 42);
    /// ```
    #[inline]
    pub const fn as_ptr(this: &Self) -> *const T {
        this.inner.as_ptr()
    }

    /// Returns a raw mutable pointer to the value inside the owned reference.
    ///
    /// The returned pointer is valid as long as the owned reference is valid.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut my_place = own!(42i32);
    /// let ptr = Own::as_mut_ptr(&mut my_place);
    /// unsafe { *ptr = 100; }
    /// assert_eq!(*my_place, 100);
    /// ```
    #[inline]
    pub const fn as_mut_ptr(this: &mut Self) -> *mut T {
        this.inner.as_ptr()
    }

    /// Leaks the value inside the owned reference, returning a mutable
    /// reference with the same lifetime as the place.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let my_place = own!(String::from("Hello"));
    /// let leaked_str: &mut String = Own::leak(my_place);
    /// leaked_str.push_str(", world!");
    /// assert_eq!(leaked_str, "Hello, world!");
    /// #
    /// # // Clean up to avoid leak in test
    /// # unsafe { core::ptr::from_mut(leaked_str).drop_in_place() };
    /// ```
    #[inline]
    pub const fn leak(this: Self) -> &'a mut T {
        let mut inner = this.inner;
        mem::forget(this);
        // SAFETY: We have exclusive ownership of the value, so we can return a
        // mutable reference to it.
        unsafe { inner.as_mut() }
    }

    /// Converts the owned reference into a raw pointer, consuming the original
    /// object.
    ///
    /// The caller is responsible for managing the memory and ensuring that the
    /// value is properly dropped when no longer needed. The memory itself
    /// remains valid for the original lifetime of the place.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let my_place = own!(String::from("Hello"));
    /// let ptr = Own::into_raw(my_place);
    /// unsafe {
    ///     let recovered = Own::from_raw(ptr);
    ///     assert_eq!(&*recovered, "Hello");
    /// }
    /// ```
    #[inline]
    pub const fn into_raw(this: Self) -> *mut T {
        let inner = this.inner;
        mem::forget(this);
        inner.as_ptr()
    }

    /// Creates an owned reference from a raw pointer.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the pointer is previously obtained from
    /// [`Own::into_raw`] and that the value is still valid and initialized.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let my_place = own!(vec![1, 2, 3]);
    /// let ptr = Own::into_raw(my_place);
    /// let recovered: Own<Vec<i32>> = unsafe { Own::from_raw(ptr) };
    /// assert_eq!(&*recovered, &[1, 2, 3]);
    /// ```
    #[inline]
    pub const unsafe fn from_raw(ptr: *mut T) -> Self {
        // SAFETY: The caller must ensure that the pointer is valid and points to
        // an initialized value.
        let inner = unsafe { NonNull::new_unchecked(ptr) };
        unsafe { Own::from_inner(inner) }
    }

    /// Creates an owned reference from a mutable place.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the place is fully initialized and
    /// valid for the lifetime `'a`.
    ///
    /// For the safe counterpart, see [`Uninit::from_mut`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    /// use core::mem::MaybeUninit;
    ///
    /// let mut uninit_place = MaybeUninit::new(10);
    /// let owned_place: Own<i32> = unsafe { Own::from_mut(&mut uninit_place) };
    /// assert_eq!(*owned_place, 10);
    /// ```
    #[inline]
    pub unsafe fn from_mut(place: &'a mut impl Place<T>) -> Self {
        unsafe { Own::from_raw(place.as_mut_ptr()) }
    }

    /// Drops the value inside the place and converts it into an uninitialized
    /// reference.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let my_place = own!(String::from("Hello"));
    /// let uninit_place = Own::drop(my_place);
    /// // At this point, the String has been dropped.
    /// // We can now re-initialize the place.
    /// let my_place_again = uninit_place.write(String::from("World"));
    /// assert_eq!(&*my_place_again, "World");
    /// ```
    #[inline]
    pub fn drop(this: Self) -> Uninit<'a, T> {
        let inner = this.inner;
        mem::forget(this);

        // SAFETY: We have exclusive ownership of the value, so we can drop it.
        unsafe { inner.drop_in_place() };
        unsafe { Uninit::from_inner(inner) }
    }
}

impl<'a, T> Own<'a, T> {
    /// Takes the value out of the owned reference, leaving it uninitialized.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let my_place: Own<i32> = own!(100);
    /// let (value, uninit_place): (i32, Uninit<i32>) = Own::take(my_place);
    /// assert_eq!(value, 100);
    /// // The place is now uninitialized, we can re-initialize it.
    /// let my_place_again: Own<i32> = uninit_place.write(200);
    /// assert_eq!(*my_place_again, 200);
    /// ```
    #[inline]
    pub const fn take(this: Self) -> (T, Uninit<'a, T>) {
        let inner = this.inner;
        mem::forget(this);
        // SAFETY: We have exclusive ownership of the value, so we can take it out.
        let value = unsafe { inner.read() };
        let place = unsafe { Uninit::from_inner(inner) };
        (value, place)
    }
}

macro_rules! impl_downcast {
    ($([$($t:tt)*])*) => {$(
        impl<'a> Own<'a, dyn $($t)*> {
            /// Attempts to downcast the owned reference to a concrete type.
            ///
            /// # Errors
            ///
            /// Returns the original owned reference if the downcast fails.
            ///
            /// # Examples
            ///
            /// ```rust,ignore
            /// use placid::prelude::*;
            /// use std::any::Any;
            ///
            #[doc = concat!("let value: Own<dyn ", stringify!($($t)*), "> = own!(42i32);")]
            /// match value.downcast::<i32>() {
            ///     Ok(owned) => assert_eq!(*owned, 42),
            ///     Err(_) => panic!("Downcast failed"),
            /// }
            /// ```
            #[inline]
            pub fn downcast<U: $($t)*>(self) -> Result<Own<'a, U>, Self> {
                if (*self).is::<U>() {
                    // SAFETY: We have checked that the type is correct.
                    Ok(unsafe { self.downcast_unchecked() })
                } else {
                    Err(self)
                }
            }

            /// Downcasts the owned reference to a concrete type without
            /// checking.
            ///
            /// # Safety
            ///
            /// The caller must ensure that the type is correct.
            ///
            /// # Examples
            ///
            /// ```rust,ignore
            /// use placid::prelude::*;
            /// use std::any::Any;
            ///
            #[doc = concat!("let value: Own<dyn ", stringify!($($t)*), "> = own!(\"hello\");")]
            /// let downcast: Own<&str> = unsafe { value.downcast_unchecked() };
            /// ```
            #[inline]
            pub unsafe fn downcast_unchecked<U: $($t)*>(self) -> Own<'a, U> {
                let raw = Own::into_raw(self).cast::<U>();
                // SAFETY: The caller must ensure that the type is correct.
                unsafe { Own::from_raw(raw) }
            }
        }
    )*};
}

impl_downcast!([Any][Any + Send][Any + Send + Sync]);

impl<'a, T: ?Sized + fmt::Debug> fmt::Debug for Own<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<'a, T: ?Sized + fmt::Display> fmt::Display for Own<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<'a, T: ?Sized> fmt::Pointer for Own<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&self.inner, f)
    }
}

impl<'a, T: Clone> Own<'a, T> {
    /// Clones the value inside the owned reference into another place.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let owned = placid::own!(String::from("Hello"));
    /// let mut another_place = core::mem::MaybeUninit::uninit();
    /// let cloned = owned.clone(&mut another_place);
    /// assert_eq!(&*cloned, "Hello");
    /// ```
    #[inline]
    pub fn clone<'b>(&self, to: &'b mut impl Place<T>) -> Own<'b, T> {
        to.write(|| (**self).clone())
    }
}

impl<'a, T: Default> Own<'a, T> {
    /// Initializes the place with the default value of `T`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use placid::prelude::*;
    ///
    /// let mut place = core::mem::MaybeUninit::uninit();
    /// let owned: Own<Vec<i32>> = Own::default(&mut place);
    /// assert_eq!(&*owned, &[]);
    #[inline]
    pub fn default(place: &'a mut impl Place<T>) -> Self {
        place.write(T::default)
    }
}

impl<'a, T> Default for Own<'a, [T]> {
    #[inline]
    fn default() -> Self {
        unsafe { Own::from_inner(NonNull::from_mut(&mut [])) }
    }
}

impl<'a> Default for Own<'a, str> {
    #[inline]
    fn default() -> Self {
        unsafe { Own::from_inner(NonNull::from_ref("")) }
    }
}

impl<'a> Default for Own<'a, core::ffi::CStr> {
    #[inline]
    fn default() -> Self {
        unsafe { Own::from_inner(NonNull::from_ref(c"")) }
    }
}

impl<'a, 'b, T: ?Sized + PartialEq<U>, U: ?Sized> PartialEq<Own<'b, U>> for Own<'a, T> {
    #[inline]
    fn eq(&self, other: &Own<'b, U>) -> bool {
        **self == **other
    }
}

impl<'a, T: ?Sized + Eq> Eq for Own<'a, T> {}

impl<'a, 'b, T: ?Sized + PartialOrd<U>, U: ?Sized> PartialOrd<Own<'b, U>> for Own<'a, T> {
    #[inline]
    fn partial_cmp(&self, other: &Own<'b, U>) -> Option<core::cmp::Ordering> {
        (**self).partial_cmp(&**other)
    }
}

impl<'a, T: ?Sized + Ord> Ord for Own<'a, T> {
    #[inline]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (**self).cmp(&**other)
    }
}

impl<'a, T: ?Sized + Hash> Hash for Own<'a, T> {
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        (**self).hash(state)
    }
}

impl<'a, T: ?Sized + Hasher> Hasher for Own<'a, T> {
    #[inline]
    fn finish(&self) -> u64 {
        (**self).finish()
    }

    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        (**self).write(bytes);
    }
}

impl<'a, T: ?Sized + Error> Error for Own<'a, T> {
    #[inline]
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        (**self).source()
    }
}

impl<'a, F: ?Sized + Future + Unpin> Future for Own<'a, F> {
    type Output = F::Output;

    #[inline]
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut **self).poll(cx)
    }
}

#[cfg(feature = "alloc")]
#[allow(dead_code)]
#[inline]
fn into_undrop_box<T: ?Sized>(own: Own<'_, T>) -> Box<T, impl Allocator> {
    use core::alloc::{AllocError, Allocator, Layout};

    let inner = own.inner;
    mem::forget(own);

    // SAFETY: Hack to call the function, moving out the possible DST from the
    // pointer. FIXME: Error-prone. Use a better way when available.
    unsafe {
        struct NullAlloc;

        unsafe impl Allocator for NullAlloc {
            fn allocate(&self, _layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
                Err(AllocError)
            }

            unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {
                // No-op
            }
        }
        Box::from_raw_in(inner.as_ptr(), NullAlloc)
    }
}

impl<'a, I: ?Sized + Iterator> Iterator for Own<'a, I> {
    type Item = I::Item;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        (**self).next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (**self).size_hint()
    }

    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        (**self).nth(n)
    }
}

#[cfg(feature = "fn-impl")]
mod fn_impl;

/// A trait for types that can be converted into owned places.
///
/// This trait allows for "extracting" an [owned] reference from various
/// container types that hold values. It is primarily used to facilitate the
/// creation of owned places from standard library containers like `Box`, `Rc`,
/// and `Arc`.
///
/// This trait is not meant to be used directly, as there is no such method as
/// `IntoOwn::into_own`, since the place itself should be converted. Instead,
/// callers of this trait can use the [`into_own!`] and [`into_pown!`] macros to
/// conveniently convert expressions into owned references.
///
/// # Safety
///
/// Implementors must ensure that `into_own_place` correctly converts the
/// container into a place that wraps the current contained value, i.e. the
/// place must be initialized with the value inside the container.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
/// use core::mem::MaybeUninit;
///
/// fn use_owned<T: IntoOwn>(value: T) -> T::Place {
///     let mut place: T::Place;
///     {
///         let owned = into_own!(place <- value);
///         // Use the owned reference...
///     }
///     place
/// }
///
/// let place: Box<MaybeUninit<i32>> = use_owned(Box::new(42));
/// // The place now can be re-initialized or used further.
/// ```
///
/// [owned]: crate::owned::Own
/// [`into_own!`]: crate::into_own!
/// [`into_pown!`]: crate::into_pown!
pub unsafe trait IntoOwn: Deref + Sized {
    /// The type of place associated with this container.
    type Place: Place<Self::Target, Init = Self>;

    /// Converts the container into its associated place wrapping the contained
    /// value.
    ///
    /// This method should not be used directly. Instead, use the [`into_own!`]
    /// macro.
    ///
    /// [`into_own!`]: crate::into_own!
    #[inline]
    fn into_own_place(self) -> Self::Place {
        Place::from_init(self)
    }
}

#[cfg(feature = "alloc")]
macro_rules! impl_std_alloc {
    (@IMP $ty:ident) => {
        unsafe impl<T, A: Allocator> IntoOwn for $ty<T, A> {
            type Place = $ty<MaybeUninit<T>, A>;
        }

        unsafe impl<T, A: Allocator> IntoOwn for $ty<[T], A> {
            type Place = $ty<[MaybeUninit<T>], A>;
        }

        unsafe impl<A: Allocator> IntoOwn for $ty<str, A> {
            type Place = $ty<[MaybeUninit<u8>], A>;
        }
    };
    ($($ty:ident),*) => {
        $(impl_std_alloc!(@IMP $ty);)*
    };
}

#[cfg(feature = "alloc")]
impl_std_alloc!(Box, Arc, Rc);

/// Creates an [owned reference] from a container, extracting the contained
/// value.
///
/// The macro converts the given expression into an owned place by extracting
/// the value inside the container. The resulting owned reference can be used
/// like any other `&own T`.
///
/// For the pinned counterpart, see the [`into_pown!`] macro.
///
/// # Arguments
///
/// * `$e:expr` - An expression that evaluates to a container implementing the
///   `IntoOwn` trait.
/// * `$p:ident` - (optional) An identifier to bind the resulting place to. If
///   omitted, a temporary variable is created.
///
/// # Examples
///
/// ```rust
/// use placid::prelude::*;
/// let my_place: Own<i32> = into_own!(Box::new(55));
/// assert_eq!(*my_place, 55);
/// ```
///
/// ```rust
/// use placid::prelude::*;
/// use std::rc::Rc;
///
/// let mut place; // Rc<MaybeUninit<String>>
/// let owned = into_own!(place <- Rc::new(String::from("Hello")));
/// assert_eq!(&*owned, "Hello");
/// drop(owned);
///
/// let owned_again = place.write(String::from("World"));
/// assert_eq!(&*owned_again, "World");
/// ```
///
/// [owned reference]: crate::owned::Own
/// [`into_pown!`]: crate::into_pown!
#[macro_export]
#[allow_internal_unstable(super_let)]
macro_rules! into_own {
    ($p:ident <- $e:expr) => {{
        $p = $crate::owned::IntoOwn::into_own_place($e);
        unsafe { $crate::owned::Own::from_mut(&mut $p) }
    }};
    ($e:expr) => {{
        super let mut p;
        $crate::into_own!(p <- $e)
    }};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_place_macro() {
        let my_place = own!(10);
        assert_eq!(*my_place, 10);
    }

    #[test]
    fn test_own_take() {
        let my_place = own!(100);
        let (value, uninit_place) = Own::take(my_place);
        assert_eq!(value, 100);
        let my_place_again = uninit_place.write(200);
        assert_eq!(*my_place_again, 200);
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_into_own() {
        let mut my_place;
        let owned = into_own!(my_place <- Box::new(55));
        assert_eq!(*owned, 55);
        drop(owned);
        my_place.write(123);

        let owned2 = into_own!(Box::new(77));
        assert_eq!(*owned2, 77);
    }
}