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
#![warn(warnings)] // Prevent `-Dwarnings` from causing breakage.
#![allow(clippy::all)]
#![cfg_attr(rustfmt, rustfmt::skip)]
#![cfg_attr(feature = "nightly",
feature(doc_cfg)
)]
#![cfg_attr(not(feature = "std"),
no_std,
)]
#![allow(
nonstandard_style,
trivial_bounds,
unused_parens,
)]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
)]
#![deny(
bare_trait_objects,
elided_lifetimes_in_paths,
unconditional_recursion,
unused_must_use,
)]
#![doc = include_str!("../README.md")]
#[macro_use]
extern crate macro_rules_attribute;
#[macro_use]
#[path = "utils/_mod.rs"]
#[doc(hidden)] /** Not part of the public API **/ pub
mod __utils__;
use __utils__ as utils;
#[apply(hidden_export)]
use ::paste;
/// Export a function to be callable by C.
///
/// # Example
///
/// ```rust
/// use ::safer_ffi::prelude::ffi_export;
///
/// #[ffi_export]
/// /// Add two integers together.
/// fn add (x: i32, y: i32) -> i32
/// {
/// x + y
/// }
/// ```
///
/// - ensures that [the generated headers](/safer_ffi/headers/) will include the
/// following definition:
///
/// ```C
/// #include <stdint.h>
///
/// /* \brief
/// * Add two integers together.
/// */
/// int32_t add (int32_t x, int32_t y);
/// ```
///
/// - exports an `add` symbol pointing to the C-ABI compatible
/// `int32_t (*)(int32_t x, int32_t y)` function.
///
/// (The crate type needs to be `cdylib` or `staticlib` for this to work,
/// and, of course, the C compiler invocation needs to include
/// `-L path/to/the/compiled/library -l name_of_your_crate`)
///
/// - when in doubt, use `staticlib`.
///
/// # `ReprC`
///
/// You can use any Rust types in the singature of an `#[ffi_export]`-
/// function, provided each of the types involved in the signature is [`ReprC`].
///
/// Otherwise the layout of the involved types in the C world is **undefined**,
/// which `#[ffi_export]` will detect, leading to a compilation error.
///
/// To have custom structs implement [`ReprC`], it suffices to annotate the
/// `struct` definitions with the <code>#\[[derive_ReprC]\]</code>
/// (on top of the obviously required `#[repr(C)]`).
pub use ::safer_ffi_proc_macros::ffi_export;
/// Identity macro when `feature = "headers"` is enabled, otherwise
/// this macro outputs nothing.
pub use ::safer_ffi_proc_macros::cfg_headers;
/// Creates a compile-time checked [`char_p::Ref`]`<'static>` out of a
/// string literal.
///
/// # Example
///
/// ```rust
/// use ::safer_ffi::prelude::*;
///
/// #[ffi_export]
/// fn concat (s1: char_p::Ref<'_>, s2: char_p::Ref<'_>)
/// -> char_p::Box
/// {
/// format!("{}{}", s1.to_str(), s2.to_str())
/// .try_into()
/// .unwrap() // No inner nulls in our format string
/// }
///
/// fn main ()
/// {
/// assert_eq!(
/// concat(c!("Hello, "), c!("World!")).as_ref(),
/// c!("Hello, World!"),
/// );
/// }
/// ```
///
/// If the string literal contains an inner null byte, then the macro
/// will detect it at compile time and thus cause a compile-time error
/// (allowing to skip the then unnecessary runtime check!):
///
/// ```rust,compile_fail
/// let _ = ::safer_ffi::c!("Hell\0, World!"); // <- Compile error
/// ```
///
/// [`char_p::Ref`]: `crate::prelude::char_p::Ref`
pub use ::safer_ffi_proc_macros::c_str as c;
/// Safely implement [`ReprC`]
/// for a `#[repr(C)]` struct **when all its fields are [`ReprC`]**.
///
/// # Examples
///
/// ### Simple `struct`
///
/// ```rust
/// use ::safer_ffi::prelude::*;
///
/// #[derive_ReprC]
/// #[repr(C)]
/// struct Instant {
/// seconds: u64,
/// nanos: u32,
/// }
/// ```
///
/// - corresponding to the following C definition:
///
/// ```C
/// typedef struct {
/// uint64_t seconds;
/// uint32_t nanos;
/// } Instant_t;
/// ```
///
/// ### Field-less `enum`
///
/// ```rust
/// use ::safer_ffi::prelude::*;
///
/// #[derive_ReprC]
/// #[repr(u8)]
/// enum Status {
/// Ok = 0,
/// Busy,
/// NotInTheMood,
/// OnStrike,
/// OhNo,
/// }
/// ```
///
/// - corresponding to the following C definition:
///
/// ```C
/// typedef uint8_t Status_t; enum {
/// STATUS_OK = 0,
/// STATUS_BUSY,
/// STATUS_NOT_IN_THE_MOOD,
/// STATUS_ON_STRIKE,
/// STATUS_OH_NO,
/// }
/// ```
///
/// ### Generic `struct`
///
/// In that case, it is required that the struct's generic types carry a
/// `: ReprC` bound each:
///
/// ```rust
/// use ::safer_ffi::prelude::*;
///
/// #[derive_ReprC]
/// #[repr(C)]
/// struct Point<Coordinate : ReprC> {
/// x: Coordinate,
/// y: Coordinate,
/// }
/// #
/// # fn main() {}
/// ```
///
/// Each monomorphization leads to its own C definition:
///
/// - **`Point<i32>`**
///
/// ```C
/// typedef struct {
/// int32_t x;
/// int32_t y;
/// } Point_int32_t;
/// ```
///
/// - **`Point<f64>`**
///
/// ```C
/// typedef struct {
/// double x;
/// double y;
/// } Point_double_t;
/// ```
pub use ::safer_ffi_proc_macros::derive_ReprC;
#[macro_use]
#[path = "layout/_mod.rs"]
pub mod layout;
__cfg_headers__! {
#[doc(hidden)] pub
use ::inventory;
#[cfg_attr(feature = "nightly",
doc(cfg(feature = "headers")),
)]
#[path = "headers/_mod.rs"]
pub
mod headers;
#[allow(missing_copy_implementations, missing_debug_implementations)]
#[doc(hidden)] /** Not part of the public API */ pub
struct FfiExport {
pub
name: &'static str,
pub
gen_def:
fn(&mut dyn headers::Definer, headers::Language)
-> std::io::Result<()>
,
}
self::inventory::collect!(FfiExport);
}
cfg_alloc! {
extern crate alloc;
}
cfg_alloc! {
pub
mod boxed;
}
pub
mod bytes;
#[doc(inline)]
pub use self::c_char_module::c_char;
#[path = "c_char.rs"]
mod c_char_module;
pub
mod char_p;
pub
mod closure;
#[cfg(feature = "dyn-traits")]
#[cfg_attr(feature = "nightly",
doc(cfg(feature = "dyn-traits")),
)]
#[path = "dyn_traits/_mod.rs"]
pub
mod dyn_traits;
#[cfg(feature = "futures")]
#[cfg_attr(all(docs, feature = "nightly"),
doc(cfg(feature = "futures"))
)]
#[doc(no_inline)]
pub use dyn_traits::futures;
pub
mod libc;
pub
mod option;
pub
mod ptr;
pub
mod slice;
#[cfg(feature = "stabby")]
#[cfg_attr(all(docs, feature = "nightly"),
doc(cfg(feature = "stabby"))
)]
#[path = "stabby/_mod.rs"]
pub
mod stabby;
#[path = "string/_mod.rs"]
pub
mod string;
#[doc(no_inline)]
pub
use tuple::*;
pub
mod tuple;
cfg_alloc! {
#[doc(inline)]
pub use string::String;
#[doc(inline)]
pub use vec::Vec;
pub mod vec;
}
#[doc(inline)]
pub use layout::impls::c_int;
pub
mod prelude {
#[doc(no_inline)]
pub use crate::{
ffi_export,
layout::ReprC,
};
pub
mod char_p {
#[doc(no_inline)]
pub use crate::char_p::{
char_p_raw as Raw,
char_p_ref as Ref,
};
cfg_alloc! {
#[doc(no_inline)]
pub use crate::char_p::{
char_p_boxed as Box,
new,
};
}
}
pub
mod c_slice {
#[doc(no_inline)]
pub use crate::slice::{
slice_mut as Mut,
slice_raw as Raw,
slice_ref as Ref,
};
cfg_alloc! {
#[doc(no_inline)]
pub use crate::slice::slice_boxed as Box;
}
}
pub
mod repr_c {
cfg_alloc! {
#[doc(no_inline)]
pub use crate::{
boxed::Box,
string::String,
vec::Vec,
option::TaggedOption,
};
pub
type Arc<T> = <T as crate::boxed::FitForCArc>::CArcWrapped;
}
}
pub
mod str {
#[doc(no_inline)]
pub use crate::string::{
// str_raw as Raw,
str_ref as Ref,
};
cfg_alloc! {
#[doc(no_inline)]
pub use crate::string::str_boxed as Box;
}
}
#[doc(no_inline)]
pub use {
crate::layout::derive_ReprC,
::safer_ffi_proc_macros::derive_ReprC2,
crate::c,
::core::{
convert::{
TryFrom as _,
TryInto as _,
},
ops::Not as _,
},
};
pub use ::uninit::prelude::{
// Out reference itself
Out,
// Helper trait to go from `&mut T` and `&mut MaybeUninit<T>` to `Out<T>`
AsOut,
// Helper trait to have `AsOut` when `T : !Copy`
ManuallyDropMut,
};
#[cfg(feature = "dyn-traits")]
#[cfg_attr(all(docs, feature = "nightly"),
doc(cfg(feature = "dyn-traits"))
)]
pub use crate::dyn_traits::VirtualPtr;
}
#[macro_export]
macro_rules! NULL {() => (
$crate::ඞ::ptr::null_mut()
)}
#[cfg(feature = "log")]
#[apply(hidden_export)]
use ::log;
#[cfg(feature = "js")]
// #[apply(hidden_export)]
#[path = "js/_mod.rs"]
pub mod js;
#[apply(hidden_export)]
#[allow(missing_copy_implementations, missing_debug_implementations)]
struct __PanicOnDrop__ {} impl Drop for __PanicOnDrop__ {
fn drop (self: &'_ mut Self)
{
panic!()
}
}
#[apply(hidden_export)]
macro_rules! __abort_with_msg__ { ($($tt:tt)*) => (
match ($crate::__PanicOnDrop__ {}) { _ => {
$crate::ඞ::__error__!($($tt)*);
$crate::ඞ::panic!($($tt)*);
}}
)}
extern crate self as safer_ffi;
#[apply(hidden_export)]
use __ as ඞ;
#[apply(hidden_export)]
mod __ {
#[cfg(feature = "alloc")]
pub extern crate alloc;
pub use {
::core::{
self,
marker::PhantomData,
pin::Pin,
primitive::{
u8, u16, u32, usize, u64, u128,
i8, i16, i32, isize, i64, i128,
bool,
char,
str,
},
},
::scopeguard::{
self,
},
crate::{
ptr,
layout::{
CLayoutOf,
ConcreteReprC,
CType,
OpaqueKind,
ReprC,
__HasNiche__,
},
prelude::*,
},
};
#[cfg(feature = "headers")]
pub use {
crate::{
headers::{
Definer,
Language,
languages::{
self,
EnumVariant,
FunctionArg,
HeaderLanguage,
StructField,
},
},
inventory,
FfiExport,
},
};
match_cfg! {
feature = "std" => {
pub use ::std::{*,
self,
prelude::rust_2021::*,
};
},
feature = "alloc" => {
pub use {
::core::{*,
prelude::rust_2021::*,
},
::alloc::{
boxed::Box,
string::String,
vec::Vec,
},
};
},
_ => {
pub use ::core::{*,
prelude::rust_2021::*,
};
}
}
/// Hack needed to `feature(trivial_bounds)` in stable Rust:
///
/// Instead of `where Ty : Bounds…`, it suffices to write:
/// `where for<'trivial> Identity<'trivial, Ty> : Bounds…`.
pub
type Identity<'hrtb, T> =
<T as IdentityIgnoring<'hrtb>>::ItSelf
;
// where
pub
trait IdentityIgnoring<'__> {
type ItSelf : ?Sized;
}
impl<T : ?Sized> IdentityIgnoring<'_> for T {
type ItSelf = Self;
}
match_cfg! {
feature = "log" => {
#[apply(hidden_export)]
macro_rules! __error__ {( $($msg:tt)* ) => (
$crate::log::error! { $($msg)* }
)}
},
feature = "std" => {
#[apply(hidden_export)]
macro_rules! __error__ {( $($msg:tt)* ) => (
$crate::ඞ::eprintln! { $($msg)* }
)}
},
_ => {
#[apply(hidden_export)]
macro_rules! __error__ {( $($msg:tt)* ) => (
/* nothing we can do */
)}
},
}
pub use __error__;
#[allow(missing_debug_implementations)]
pub
struct UnwindGuard /* = */ (
pub &'static str,
);
impl Drop for UnwindGuard {
fn drop (self: &'_ mut Self)
{
let &mut Self(fname) = self;
__abort_with_msg__!("\
Error, attempted to panic across the FFI \
boundary of `{fname}()`, \
which is Undefined Behavior.\n\
Aborting for soundness.\
");
}
}
#[cfg(feature = "alloc")]
pub
fn append_unqualified_name (
out: &'_ mut String,
ty_name: &'_ str,
)
{
#[inline(never)]
fn mb_split_with<'r> (
orig: &'r str,
splitter: fn(&'r str) -> Option<(&'r str, &'r str)>,
) -> (&'r str, Option<&'r str>)
{
splitter(orig).map_or((orig, None), |(l, r)| (l, Some(r)))
}
let ty_name = ty_name.trim();
if let Some(tuple_innards) = ty_name.strip_prefix('(') {
// Tuple
tuple_innards
.strip_suffix(')').unwrap()
.split(',')
.for_each(|generic| {
append_unqualified_name(out, generic);
})
;
} else if let Some(bracketed_innards) = ty_name.strip_prefix('[') {
// Array or Slice
let (elem_ty, mb_len) = mb_split_with(
bracketed_innards.strip_suffix(']').unwrap(),
|s| s.rsplit_once(';'),
);
append_unqualified_name(out, elem_ty);
if let Some(len) = mb_len {
append_unqualified_name(out, len);
}
} else {
// Canonical Type Path
out.push('_');
let (mut path, mb_generics) = mb_split_with(
ty_name,
|s| s.split_once('<'),
);
let is_valid_for_ident = |c: char| {
c.is_alphanumeric() || matches!(c, '_')
};
if let Some(trait_path) = path.strip_prefix("dyn ") {
out.push_str("dyn_");
path = trait_path;
}
if path.chars().all(|c| is_valid_for_ident(c) || c == ':') {
let unqualified = path.rsplitn(2, ':').next().unwrap().trim();
out.push_str(unqualified);
} else {
// Weird type, fall back to replacing non_alphanumerics:
path.chars().for_each(|c| {
out.push(if is_valid_for_ident(c) { c } else { '_' });
});
}
if let Some(generics) = mb_generics {
let generics = generics.strip_suffix('>').unwrap();
generics.split(',').for_each(|generic| {
append_unqualified_name(out, generic);
});
}
}
}
#[doc(hidden)] /** Not part of the public API! */
#[macro_export]
macro_rules! ඞassert_expr {( $e:expr $(,)? ) => ( $e )}
#[doc(inline)]
pub use ඞassert_expr as assert_expr;
}