moveit/new/move_new.rs
1// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use core::mem::MaybeUninit;
16use core::pin::Pin;
17
18use crate::move_ref::AsMove;
19use crate::move_ref::MoveRef;
20use crate::new;
21use crate::new::New;
22use crate::slot;
23
24/// A move constructible type: a destination-aware `Clone` that destroys the
25/// moved-from value.
26///
27/// # Safety
28///
29/// After [`MoveNew::move_new()`] is called:
30/// - `src` should be treated as having been destroyed.
31/// - `this` must have been initialized.
32pub unsafe trait MoveNew: Sized {
33 /// Move-construct `src` into `this`, effectively re-pinning it at a new
34 /// location.
35 ///
36 /// # Safety
37 ///
38 /// The same safety requirements of [`New::new()`] apply, but, in addition,
39 /// `*src` must not be used after this function is called, because it has
40 /// effectively been destroyed.
41 unsafe fn move_new(
42 src: Pin<MoveRef<Self>>,
43 this: Pin<&mut MaybeUninit<Self>>,
44 );
45}
46
47/// Returns a [`New`] that forwards to [`MoveNew`].
48///
49/// ```
50/// # use moveit::{MoveRef, moveit, new};
51/// let foo = Box::new(42);
52/// moveit! {
53/// let bar = &move foo;
54/// let baz = new::mov(bar);
55/// }
56/// ```
57#[inline]
58pub fn mov<P>(ptr: P) -> impl New<Output = P::Target>
59where
60 P: AsMove,
61 P::Target: MoveNew,
62{
63 unsafe {
64 new::by_raw(move |this| {
65 MoveNew::move_new(ptr.as_move(slot!(#[dropping])), this);
66 })
67 }
68}