1//! Internal crate used by foreign-types
2
3#![no_std]
4#![warn(missing_docs)]
5#![doc(html_root_url="https://docs.rs/foreign-types-shared/0.1")]
6
7use core::cell::UnsafeCell;
8
9/// An opaque type used to define `ForeignTypeRef` types.
10///
11/// A type implementing `ForeignTypeRef` should simply be a newtype wrapper around this type.
12pub struct Opaque(UnsafeCell<()>);
13
14/// A type implemented by wrappers over foreign types.
15pub trait ForeignType: Sized {
16 /// The raw C type.
17 type CType;
18
19 /// The type representing a reference to this type.
20 type Ref: ForeignTypeRef<CType = Self::CType>;
21
22 /// Constructs an instance of this type from its raw type.
23 unsafe fn from_ptr(ptr: *mut Self::CType) -> Self;
24
25 /// Returns a raw pointer to the wrapped value.
26 fn as_ptr(&self) -> *mut Self::CType;
27}
28
29/// A trait implemented by types which reference borrowed foreign types.
30pub trait ForeignTypeRef: Sized {
31 /// The raw C type.
32 type CType;
33
34 /// Constructs a shared instance of this type from its raw type.
35 #[inline]
36 unsafe fn from_ptr<'a>(ptr: *mut Self::CType) -> &'a Self {
37 &*(ptr as *mut _)
38 }
39
40 /// Constructs a mutable reference of this type from its raw type.
41 #[inline]
42 unsafe fn from_ptr_mut<'a>(ptr: *mut Self::CType) -> &'a mut Self {
43 &mut *(ptr as *mut _)
44 }
45
46 /// Returns a raw pointer to the wrapped value.
47 #[inline]
48 fn as_ptr(&self) -> *mut Self::CType {
49 self as *const _ as *mut _
50 }
51}
52