moveit/new/copy_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;
16use core::mem::MaybeUninit;
17use core::ops::Deref;
18use core::pin::Pin;
19
20use crate::new;
21use crate::new::New;
22
23/// A copy constructible type: a destination-aware `Clone`.
24///
25/// # Safety
26///
27/// After [`CopyNew::copy_new()`] is called:
28/// - `this` must have been initialized.
29pub unsafe trait CopyNew: Sized {
30 /// Copy-construct `src` into `this`, effectively re-pinning it at a new
31 /// location.
32 ///
33 /// # Safety
34 ///
35 /// The same safety requirements of [`New::new()`] apply.
36 unsafe fn copy_new(src: &Self, this: Pin<&mut MaybeUninit<Self>>);
37}
38
39/// Returns a new `New` that uses a copy constructor.
40#[inline]
41pub fn copy<P>(ptr: P) -> impl New<Output = P::Target>
42where
43 P: Deref,
44 P::Target: CopyNew,
45{
46 unsafe {
47 new::by_raw(move |this| {
48 CopyNew::copy_new(&*ptr, this);
49
50 // Because `*ptr` is still intact, we can drop it normally.
51 mem::drop(ptr)
52 })
53 }
54}