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