autocxx_idalib/lib.rs
1#![doc = include_str!("../README.md")]
2#![cfg_attr(nightly, feature(unsize))]
3#![cfg_attr(nightly, feature(dispatch_from_dyn))]
4#![cfg_attr(nightly, feature(arbitrary_self_types))]
5
6// Copyright 2020 Google LLC
7//
8// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
9// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
10// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
11// option. This file may not be copied, modified, or distributed
12// except according to those terms.
13
14// The crazy macro_rules magic in this file is thanks to dtolnay@
15// and is a way of attaching rustdoc to each of the possible directives
16// within the include_cpp outer macro. None of the directives actually
17// do anything - all the magic is handled entirely by
18// autocxx_macro::include_cpp_impl.
19
20mod reference_wrapper;
21mod rvalue_param;
22pub mod subclass;
23mod value_param;
24
25pub use reference_wrapper::{
26 AsCppMutRef, AsCppRef, CppLtRef, CppMutLtRef, CppMutRef, CppPin, CppRef, CppUniquePtrPin,
27};
28
29#[cfg_attr(doc, aquamarine::aquamarine)]
30/// Include some C++ headers in your Rust project.
31///
32/// This macro allows you to include one or more C++ headers within
33/// your Rust code, and call their functions fairly naturally.
34///
35/// # Examples
36///
37/// C++ header (`input.h`):
38/// ```cpp
39/// #include <cstdint>
40///
41/// uint32_t do_math(uint32_t a);
42/// ```
43///
44/// Rust code:
45/// ```
46/// # use autocxx_macro::include_cpp_impl as include_cpp;
47/// include_cpp!(
48/// # parse_only!()
49/// #include "input.h"
50/// generate!("do_math")
51/// safety!(unsafe)
52/// );
53///
54/// # mod ffi { pub fn do_math(a: u32) -> u32 { a+3 } }
55/// # fn main() {
56/// ffi::do_math(3);
57/// # }
58/// ```
59///
60/// The resulting bindings will use idiomatic Rust wrappers for types from the [cxx]
61/// crate, for example [`cxx::UniquePtr`] or [`cxx::CxxString`]. Due to the care and thought
62/// that's gone into the [cxx] crate, such bindings are pleasant and idiomatic to use
63/// from Rust, and usually don't require the `unsafe` keyword.
64///
65/// For full documentation, see [the manual](https://google.github.io/autocxx/).
66///
67/// # The [`include_cpp`] macro
68///
69/// Within the braces of the `include_cpp!{...}` macro, you should provide
70/// a list of at least the following:
71///
72/// * `#include "cpp_header.h"`: a header filename to parse and include
73/// * `generate!("type_or_function_name")`: a type or function name whose declaration
74/// should be made available to C++. (See the section on Allowlisting, below).
75/// * Optionally, `safety!(unsafe)` - see discussion of [`safety`].
76///
77/// Other directives are possible as documented in this crate.
78///
79/// Now, try to build your Rust project. `autocxx` may fail to generate bindings
80/// for some of the items you specified with [generate] directives: remove
81/// those directives for now, then see the next section for advice.
82///
83/// # Allowlisting
84///
85/// How do you inform autocxx which bindings to generate? There are three
86/// strategies:
87///
88/// * *Recommended*: provide various [`generate`] directives in the
89/// [`include_cpp`] macro. This can specify functions or types.
90/// * *Not recommended*: in your `build.rs`, call `Builder::auto_allowlist`.
91/// This will attempt to spot _uses_ of FFI bindings anywhere in your Rust code
92/// and build the allowlist that way. This is experimental and has known limitations.
93/// * *Strongly not recommended*: use [`generate_all`]. This will attempt to
94/// generate Rust bindings for _any_ C++ type or function discovered in the
95/// header files. This is generally a disaster if you're including any
96/// remotely complex header file: we'll try to generate bindings for all sorts
97/// of STL types. This will be slow, and some may well cause problems.
98/// Effectively this is just a debug option to discover such problems. Don't
99/// use it!
100///
101/// # Internals
102///
103/// For documentation on how this all actually _works_, see
104/// `IncludeCppEngine` within the `autocxx_engine` crate.
105#[macro_export]
106macro_rules! include_cpp {
107 (
108 $(#$include:ident $lit:literal)*
109 $($mac:ident!($($arg:tt)*))*
110 ) => {
111 $($crate::$include!{__docs})*
112 $($crate::$mac!{__docs})*
113 $crate::include_cpp_impl! {
114 $(#include $lit)*
115 $($mac!($($arg)*))*
116 }
117 };
118}
119
120/// Include a C++ header. A directive to be included inside
121/// [include_cpp] - see [include_cpp] for details
122#[macro_export]
123macro_rules! include {
124 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
125}
126
127/// Generate Rust bindings for the given C++ type or function.
128/// A directive to be included inside
129/// [include_cpp] - see [include_cpp] for general information.
130/// See also [generate_pod].
131#[macro_export]
132macro_rules! generate {
133 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
134}
135
136/// Generate as "plain old data" and add to allowlist.
137/// Generate Rust bindings for the given C++ type such that
138/// it can be passed and owned by value in Rust. This only works
139/// for C++ types which have trivial move constructors and no
140/// destructor - you'll encounter a compile error otherwise.
141/// If your type doesn't match that description, use [generate]
142/// instead, and own the type using [UniquePtr][cxx::UniquePtr].
143/// A directive to be included inside
144/// [include_cpp] - see [include_cpp] for general information.
145#[macro_export]
146macro_rules! generate_pod {
147 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
148}
149
150/// Generate Rust bindings for all C++ types and functions
151/// in a given namespace.
152/// A directive to be included inside
153/// [include_cpp] - see [include_cpp] for general information.
154/// See also [generate].
155#[macro_export]
156macro_rules! generate_ns {
157 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
158}
159
160/// Generate Rust bindings for all C++ types and functions
161/// found. Highly experimental and not recommended.
162/// A directive to be included inside
163/// [include_cpp] - see [include_cpp] for general information.
164/// See also [generate].
165#[macro_export]
166macro_rules! generate_all {
167 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
168}
169
170/// Generate as "plain old data". For use with [generate_all]
171/// and similarly experimental.
172#[macro_export]
173macro_rules! pod {
174 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
175}
176
177/// Skip the normal generation of a `make_string` function
178/// and other utilities which we might generate normally.
179/// A directive to be included inside
180/// [include_cpp] - see [include_cpp] for general information.
181#[macro_export]
182macro_rules! exclude_utilities {
183 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
184}
185
186/// Entirely block some type from appearing in the generated
187/// code. This can be useful if there is a type which is not
188/// understood by bindgen or autocxx, and incorrect code is
189/// otherwise generated.
190/// This is 'greedy' in the sense that any functions/methods
191/// which take or return such a type will _also_ be blocked.
192/// See also [`opaque`].
193///
194/// A directive to be included inside
195/// [include_cpp] - see [include_cpp] for general information.
196#[macro_export]
197macro_rules! block {
198 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
199}
200
201/// Instruct `bindgen` to generate a type as an opaque type -
202/// that is, without fields inside it. This should be used
203/// only when there's a need to workaround some `bindgen`
204/// issue where it's incorrectly generating the type.
205/// See the [bindgen documentation](https://rust-lang.github.io/rust-bindgen/opaque.html)
206/// for what exactly this means.
207///
208/// At first glance, this might seem to have no effect for
209/// types which are marked non-POD. However, it prevents
210/// autocxx from inferring whether the type has implicit
211/// constructors, and thus limits the options for even
212/// allocating the type. This should therefore only be used
213/// when trying to work around a bug.
214///
215/// The types which are generated when you use this are
216/// rather useless - it's hard to interact with them at all
217/// from within the generated Rust. Worse still, if they're
218/// included as members of any other type, those types are
219/// "infected" and also become useless (in the sense that
220/// we can't figure out what constructors those types might
221/// have). Use with caution and only when really needed.
222///
223/// A directive to be included inside
224/// [include_cpp] - see [include_cpp] for general information.
225#[macro_export]
226macro_rules! opaque {
227 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
228}
229
230/// Avoid generating implicit constructors for this type.
231/// The rules for when to generate C++ implicit constructors
232/// are complex, and if autocxx gets it wrong, you can block
233/// such constructors using this.
234///
235/// A directive to be included inside
236/// [include_cpp] - see [include_cpp] for general information.
237#[macro_export]
238macro_rules! block_constructors {
239 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
240}
241
242/// The name of the mod to be generated with the FFI code.
243/// The default is `ffi`.
244///
245/// A directive to be included inside
246/// [include_cpp] - see [include_cpp] for general information.
247#[macro_export]
248macro_rules! name {
249 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
250}
251
252/// A concrete type to make, for example
253/// `concrete!("Container<Contents>")`.
254/// All types must already be on the allowlist by having used
255/// `generate!` or similar.
256///
257/// A directive to be included inside
258/// [include_cpp] - see [include_cpp] for general information.
259#[macro_export]
260macro_rules! concrete {
261 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
262}
263
264/// Specifies a global safety policy for functions generated
265/// from these headers. By default (without such a `safety!`
266/// directive) all such functions are marked as `unsafe` and
267/// therefore can only be called within an `unsafe {}` block
268/// or some `unsafe` function which you create.
269///
270/// Alternatively, by specifying a `safety!` block you can
271/// declare that most generated functions are in fact safe.
272/// Specifically, you'd specify:
273/// `safety!(unsafe)`
274/// or
275/// `safety!(unsafe_ffi)`
276/// These two options are functionally identical. If you're
277/// unsure, simply use `unsafe`. The reason for the
278/// latter option is if you have code review policies which
279/// might want to give a different level of scrutiny to
280/// C++ interop as opposed to other types of unsafe Rust code.
281/// Maybe in your organization, C++ interop is less scary than
282/// a low-level Rust data structure using pointer manipulation.
283/// Or maybe it's more scary. Either way, using `unsafe` for
284/// the data structure and using `unsafe_ffi` for the C++
285/// interop allows you to apply different linting tools and
286/// policies to the different options.
287///
288/// Irrespective, C++ code is of course unsafe. It's worth
289/// noting that use of C++ can cause unexpected unsafety at
290/// a distance in faraway Rust code. As with any use of the
291/// `unsafe` keyword in Rust, *you the human* are declaring
292/// that you've analyzed all possible ways that the code
293/// can be used and you are guaranteeing to the compiler that
294/// no badness can occur. Good luck.
295///
296/// Generated C++ APIs which use raw pointers remain `unsafe`
297/// no matter what policy you choose.
298///
299/// There's an additional possible experimental safety
300/// policy available here:
301/// `safety!(unsafe_references_wrapped)`
302/// This policy treats C++ references as scary and requires
303/// them to be wrapped in a `CppRef` type: see [`CppRef`].
304/// This only works on nightly Rust because it
305/// depends upon an unstable feature
306/// (`arbitrary_self_types`). However, it should
307/// eliminate all undefined behavior related to Rust's
308/// stricter aliasing rules than C++.
309#[macro_export]
310macro_rules! safety {
311 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
312}
313
314/// Whether to avoid generating [`cxx::UniquePtr`] and [`cxx::Vector`]
315/// implementations. This is primarily useful for reducing test cases and
316/// shouldn't be used in normal operation.
317///
318/// A directive to be included inside
319/// [include_cpp] - see [include_cpp] for general information.
320#[macro_export]
321macro_rules! exclude_impls {
322 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
323}
324
325/// Indicates that a C++ type is not to be generated by autocxx in this case,
326/// but instead should refer to some pre-existing Rust type.
327///
328/// If you wish for the type to be POD, you can use a `pod!` directive too
329/// (but see the "requirements" section below).
330///
331/// The syntax is:
332/// `extern_cpp_type!("CppNameGoesHere", path::to::rust::type)`
333///
334/// Generally speaking, this should be used only to refer to types
335/// generated elsewhere by `autocxx` or `cxx` to ensure that they meet
336/// all the right requirements. It's possible - but fragile - to
337/// define such types yourself.
338///
339/// # Requirements for externally defined Rust types
340///
341/// It's generally expected that you would make such a type
342/// in Rust using a separate `include_cpp!` macro, or
343/// a manual `#[cxx::bridge]` directive somehwere. That is, this
344/// directive is intended mainly for use in cross-linking different
345/// sets of bindings in different mods, rather than truly to point to novel
346/// external types.
347///
348/// But with that in mind, here are the requirements you must stick to.
349///
350/// For non-POD external types:
351/// * The size and alignment of this type *must* be correct.
352///
353/// For POD external types:
354/// * As above
355/// * Your type must correspond to the requirements of
356/// [`cxx::kind::Trivial`]. In general, that means, no move constructor
357/// and no destructor. If you generate this type using `cxx` itself
358/// (or `autocxx`) this will be enforced using `static_assert`s
359/// within the generated C++ code. Without using those tools, you're
360/// on your own for determining this... and it's hard because the presence
361/// of particular fields or base classes may well result in your type
362/// violating those rules.
363///
364/// A directive to be included inside
365/// [include_cpp] - see [include_cpp] for general information.
366#[macro_export]
367macro_rules! extern_cpp_type {
368 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
369}
370
371/// Indicates that a C++ type is not to be generated by autocxx in this case,
372/// but instead should refer to some pre-existing Rust type. Unlike
373/// `extern_cpp_type!`, there's no need for the size and alignment of this
374/// type to be correct.
375///
376/// The syntax is:
377/// `extern_cpp_opaque_type!("CppNameGoesHere", path::to::rust::type)`
378///
379/// A directive to be included inside
380/// [include_cpp] - see [include_cpp] for general information.
381#[macro_export]
382macro_rules! extern_cpp_opaque_type {
383 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
384}
385
386/// Deprecated - use [`extern_rust_type`] instead.
387#[macro_export]
388#[deprecated]
389macro_rules! rust_type {
390 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
391}
392
393/// See [`extern_rust::extern_rust_type`].
394#[macro_export]
395macro_rules! extern_rust_type {
396 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
397}
398
399/// See [`subclass::subclass`].
400#[macro_export]
401macro_rules! subclass {
402 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
403}
404
405/// Indicates that a C++ type can definitely be instantiated. This has effect
406/// only in a very specific case:
407/// * the type is a typedef to something else
408/// * the 'something else' can't be fully inspected by autocxx, possibly
409/// becaue it relies on dependent qualified types or some other template
410/// arrangement that bindgen cannot fully understand.
411///
412/// In such circumstances, autocxx normally has to err on the side of caution
413/// and assume that some type within the 'something else' is itself a forward
414/// declaration. That means, the opaque typedef won't be storable within
415/// a [`cxx::UniquePtr`]. If you know that no forward declarations are involved,
416/// you can declare the typedef type is instantiable and then you'll be able to
417/// own it within Rust.
418///
419/// The syntax is:
420/// `instantiable!("CppNameGoesHere")`
421///
422/// A directive to be included inside
423/// [include_cpp] - see [include_cpp] for general information.
424#[macro_export]
425macro_rules! instantiable {
426 ($($tt:tt)*) => { $crate::usage!{$($tt)*} };
427}
428
429#[doc(hidden)]
430#[macro_export]
431macro_rules! usage {
432 (__docs) => {};
433 ($($tt:tt)*) => {
434 compile_error! {r#"usage: include_cpp! {
435 #include "path/to/header.h"
436 generate!(...)
437 generate_pod!(...)
438 }
439"#}
440 };
441}
442
443use std::pin::Pin;
444
445#[doc(hidden)]
446pub use autocxx_macro::include_cpp_impl;
447
448#[doc(hidden)]
449pub use autocxx_macro::cpp_semantics;
450
451macro_rules! ctype_wrapper {
452 ($r:ident, $c:expr, $d:expr) => {
453 #[doc=$d]
454 #[derive(Debug, Eq, Copy, Clone, PartialEq, Hash)]
455 #[allow(non_camel_case_types)]
456 #[repr(transparent)]
457 pub struct $r(pub ::std::os::raw::$r);
458
459 /// # Safety
460 ///
461 /// We assert that the namespace and type ID refer to a C++
462 /// type which is equivalent to this Rust type.
463 unsafe impl cxx::ExternType for $r {
464 type Id = cxx::type_id!($c);
465 type Kind = cxx::kind::Trivial;
466 }
467
468 impl From<::std::os::raw::$r> for $r {
469 fn from(val: ::std::os::raw::$r) -> Self {
470 Self(val)
471 }
472 }
473
474 impl From<$r> for ::std::os::raw::$r {
475 fn from(val: $r) -> Self {
476 val.0
477 }
478 }
479 };
480}
481
482ctype_wrapper!(
483 c_ulonglong,
484 "c_ulonglong",
485 "Newtype wrapper for an unsigned long long"
486);
487ctype_wrapper!(c_longlong, "c_longlong", "Newtype wrapper for a long long");
488ctype_wrapper!(c_ulong, "c_ulong", "Newtype wrapper for an unsigned long");
489ctype_wrapper!(c_long, "c_long", "Newtype wrapper for a long");
490ctype_wrapper!(
491 c_ushort,
492 "c_ushort",
493 "Newtype wrapper for an unsigned short"
494);
495ctype_wrapper!(c_short, "c_short", "Newtype wrapper for an short");
496ctype_wrapper!(c_uint, "c_uint", "Newtype wrapper for an unsigned int");
497ctype_wrapper!(c_int, "c_int", "Newtype wrapper for an int");
498ctype_wrapper!(c_uchar, "c_uchar", "Newtype wrapper for an unsigned char");
499
500/// Newtype wrapper for a C void. Only useful as a `*c_void`
501#[allow(non_camel_case_types)]
502#[repr(transparent)]
503pub struct c_void(pub ::std::os::raw::c_void);
504
505/// # Safety
506///
507/// We assert that the namespace and type ID refer to a C++
508/// type which is equivalent to this Rust type.
509unsafe impl cxx::ExternType for c_void {
510 type Id = cxx::type_id!(c_void);
511 type Kind = cxx::kind::Trivial;
512}
513
514/// A C++ `char16_t`
515#[allow(non_camel_case_types)]
516#[repr(transparent)]
517pub struct c_char16_t(pub u16);
518
519/// # Safety
520///
521/// We assert that the namespace and type ID refer to a C++
522/// type which is equivalent to this Rust type.
523unsafe impl cxx::ExternType for c_char16_t {
524 type Id = cxx::type_id!(c_char16_t);
525 type Kind = cxx::kind::Trivial;
526}
527
528/// autocxx couldn't generate these bindings.
529/// If you come across a method, type or function which refers to this type,
530/// it indicates that autocxx couldn't generate that binding. A documentation
531/// comment should be attached indicating the reason.
532#[allow(dead_code)]
533pub struct BindingGenerationFailure {
534 _unallocatable: [*const u8; 0],
535 _pinned: core::marker::PhantomData<core::marker::PhantomPinned>,
536}
537
538/// Tools to export Rust code to C++.
539// These are in a mod to avoid shadowing the definitions of the
540// directives above, which, being macro_rules, are unavoidably
541// in the crate root but must be function-style macros to keep
542// the include_cpp impl happy.
543pub mod extern_rust {
544
545 /// Declare that this is a Rust type which is to be exported to C++.
546 /// You can use this in two ways:
547 /// * as an attribute macro on a Rust type, for instance:
548 /// ```
549 /// # use autocxx_macro::extern_rust_type as extern_rust_type;
550 /// #[extern_rust_type]
551 /// struct Bar;
552 /// ```
553 /// * as a directive within the [include_cpp] macro, in which case
554 /// provide the type path in brackets:
555 /// ```
556 /// # use autocxx_macro::include_cpp_impl as include_cpp;
557 /// include_cpp!(
558 /// # parse_only!()
559 /// #include "input.h"
560 /// extern_rust_type!(Bar)
561 /// safety!(unsafe)
562 /// );
563 /// struct Bar;
564 /// ```
565 /// These may be used within references in the signatures of C++ functions,
566 /// for instance. This will contribute to an `extern "Rust"` section of the
567 /// generated `cxx` bindings, and this type will appear in the C++ header
568 /// generated for use in C++.
569 ///
570 /// # Finding these bindings from C++
571 ///
572 /// You will likely need to forward-declare this type within your C++ headers
573 /// before you can use it in such function signatures. autocxx can't generate
574 /// headers (with this type definition) until it's parsed your header files;
575 /// logically therefore if your header files mention one of these types
576 /// it's impossible for them to see the definition of the type.
577 ///
578 /// If you're using multiple sets of `include_cpp!` directives, or
579 /// a mixture of `include_cpp!` and `#[cxx::bridge]` bindings, then you
580 /// may be able to `#include "cxxgen.h"` to refer to the generated C++
581 /// function prototypes. In this particular circumstance, you'll want to know
582 /// how exactly the `cxxgen.h` header is named, because one will be
583 /// generated for each of the sets of bindings encountered. The pattern
584 /// can be set manually using `autocxxgen`'s command-line options. If you're
585 /// using `autocxx`'s `build.rs` support, those headers will be named
586 /// `cxxgen.h`, `cxxgen1.h`, `cxxgen2.h` according to the order in which
587 /// the `include_cpp` or `cxx::bridge` bindings are encountered.
588 pub use autocxx_macro::extern_rust_type;
589
590 /// Declare that a given function is a Rust function which is to be exported
591 /// to C++. This is used as an attribute macro on a Rust function, for instance:
592 /// ```
593 /// # use autocxx_macro::extern_rust_function as extern_rust_function;
594 /// #[extern_rust_function]
595 /// pub fn call_me_from_cpp() { }
596 /// ```
597 ///
598 /// See [`extern_rust_type`] for details of how to find the generated
599 /// declarations from C++.
600 pub use autocxx_macro::extern_rust_function;
601}
602
603/// Equivalent to [`std::convert::AsMut`], but returns a pinned mutable reference
604/// such that cxx methods can be called on it.
605pub trait PinMut<T>: AsRef<T> {
606 /// Return a pinned mutable reference to a type.
607 fn pin_mut(&mut self) -> std::pin::Pin<&mut T>;
608}
609
610/// Provides utility functions to emplace any [`moveit::New`] into a
611/// [`cxx::UniquePtr`]. Automatically imported by the autocxx prelude
612/// and implemented by any (autocxx-related) [`moveit::New`].
613pub trait WithinUniquePtr {
614 type Inner: UniquePtrTarget + MakeCppStorage;
615 /// Create this item within a [`cxx::UniquePtr`].
616 fn within_unique_ptr(self) -> cxx::UniquePtr<Self::Inner>;
617}
618
619/// Provides utility functions to emplace any [`moveit::New`] into a
620/// [`Box`]. Automatically imported by the autocxx prelude
621/// and implemented by any (autocxx-related) [`moveit::New`].
622pub trait WithinBox {
623 type Inner;
624 /// Create this item inside a pinned box. This is a good option if you
625 /// want to own this object within Rust, and want to create Rust references
626 /// to it.
627 fn within_box(self) -> Pin<Box<Self::Inner>>;
628 /// Create this item inside a [`CppPin`]. This is a good option if you
629 /// want to own this option within Rust, but you want to create [`CppRef`]
630 /// C++ references to it.
631 fn within_cpp_pin(self) -> CppPin<Self::Inner>;
632}
633
634use cxx::kind::Trivial;
635use cxx::ExternType;
636use moveit::Emplace;
637use moveit::MakeCppStorage;
638
639impl<N, T> WithinUniquePtr for N
640where
641 N: New<Output = T>,
642 T: UniquePtrTarget + MakeCppStorage,
643{
644 type Inner = T;
645 fn within_unique_ptr(self) -> cxx::UniquePtr<T> {
646 UniquePtr::emplace(self)
647 }
648}
649
650impl<N, T> WithinBox for N
651where
652 N: New<Output = T>,
653{
654 type Inner = T;
655 fn within_box(self) -> Pin<Box<T>> {
656 Box::emplace(self)
657 }
658 fn within_cpp_pin(self) -> CppPin<Self::Inner> {
659 CppPin::from_pinned_box(Box::emplace(self))
660 }
661}
662
663/// Emulates the [`WithinUniquePtr`] trait, but for trivial (plain old data) types.
664/// This allows such types to behave identically if a type is changed from
665/// `generate!` to `generate_pod!`.
666///
667/// (Ideally, this would be the exact same trait as [`WithinUniquePtr`] but this runs
668/// the risk of conflicting implementations. Negative trait bounds would solve
669/// this!)
670pub trait WithinUniquePtrTrivial: UniquePtrTarget + Sized + Unpin {
671 fn within_unique_ptr(self) -> cxx::UniquePtr<Self>;
672}
673
674impl<T> WithinUniquePtrTrivial for T
675where
676 T: UniquePtrTarget + ExternType<Kind = Trivial> + Sized + Unpin,
677{
678 fn within_unique_ptr(self) -> cxx::UniquePtr<T> {
679 UniquePtr::new(self)
680 }
681}
682
683/// Emulates the [`WithinBox`] trait, but for trivial (plain old data) types.
684/// This allows such types to behave identically if a type is changed from
685/// `generate!` to `generate_pod!`.
686///
687/// (Ideally, this would be the exact same trait as [`WithinBox`] but this runs
688/// the risk of conflicting implementations. Negative trait bounds would solve
689/// this!)
690pub trait WithinBoxTrivial: Sized + Unpin {
691 fn within_box(self) -> Pin<Box<Self>>;
692}
693
694impl<T> WithinBoxTrivial for T
695where
696 T: ExternType<Kind = Trivial> + Sized + Unpin,
697{
698 fn within_box(self) -> Pin<Box<T>> {
699 Pin::new(Box::new(self))
700 }
701}
702
703use cxx::memory::UniquePtrTarget;
704use cxx::UniquePtr;
705use moveit::New;
706pub use rvalue_param::RValueParam;
707pub use rvalue_param::RValueParamHandler;
708pub use value_param::as_copy;
709pub use value_param::as_mov;
710pub use value_param::as_new;
711pub use value_param::ValueParam;
712pub use value_param::ValueParamHandler;
713
714/// Imports which you're likely to want to use.
715pub mod prelude {
716 pub use crate::as_copy;
717 pub use crate::as_mov;
718 pub use crate::as_new;
719 pub use crate::c_int;
720 pub use crate::c_long;
721 pub use crate::c_longlong;
722 pub use crate::c_short;
723 pub use crate::c_uchar;
724 pub use crate::c_uint;
725 pub use crate::c_ulong;
726 pub use crate::c_ulonglong;
727 pub use crate::c_ushort;
728 pub use crate::c_void;
729 pub use crate::cpp_semantics;
730 pub use crate::include_cpp;
731 pub use crate::AsCppMutRef;
732 pub use crate::AsCppRef;
733 pub use crate::CppMutRef;
734 pub use crate::CppPin;
735 pub use crate::CppRef;
736 pub use crate::CppUniquePtrPin;
737 pub use crate::PinMut;
738 pub use crate::RValueParam;
739 pub use crate::ValueParam;
740 pub use crate::WithinBox;
741 pub use crate::WithinBoxTrivial;
742 pub use crate::WithinUniquePtr;
743 pub use crate::WithinUniquePtrTrivial;
744 pub use cxx::UniquePtr;
745 pub use moveit::moveit;
746 pub use moveit::new::New;
747 pub use moveit::Emplace;
748}
749
750/// Re-export moveit for ease of consumers.
751pub use moveit;
752
753/// Re-export cxx such that clients can use the same version as
754/// us. This doesn't enable clients to avoid depending on the cxx
755/// crate too, unfortunately, since generated cxx::bridge code
756/// refers explicitly to ::cxx. See
757/// <https://github.com/google/autocxx/issues/36>
758pub use cxx;