seasick 0.3.2

FFI-safe nul-terminated strings with ownership semantics
Documentation
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
//! FFI-safe types for writing and transcribing C APIs.
//!
//! [`&CStr`] and [`CString`] are not FFI safe.
//! ```compile_fail
//! # use std::ffi::{CStr, CString};
//! #[deny(improper_ctypes)]
//! extern "C" {
//!     fn concat(_: &CStr, _: &CStr) -> CString;
//! }
//! ```
//! [`&SeaStr`] and [`SeaString`] are FFI-safe equivalents.
//! ```rust
//! # use seasick::{SeaStr, SeaString};
//! # #[deny(improper_ctypes)]
//! extern "C" {
//!     fn concat(_: &SeaStr, _: &SeaStr) -> SeaString;
//! }
//! ```
//! They use the non-null niche which is filled by [`Option::None`].
//! ```c
//! /** may return null */
//! char *foo(void);
//! ```
//! ```rust
//! # stringify! {
//! extern "C" fn foo() -> Option<SeaString> { .. }
//! # };
//! # use std::{ffi::c_char, mem::size_of}; use seasick::SeaString;
//! assert_eq!(size_of::<Option<SeaString>>(), size_of::<*mut c_char>());
//! ```
//!
//! [`SeaArray`] wraps a `[c_char; N]` array, providing [`SeaStr`]-like capabilities.
//! [`SeaBox`] is an additional owned pointer type, with a pluggable [`Allocator`].
//! [`till_null`] contains iterators for nul-terminated arrays of pointers.
//! [`TransmuteFrom`] is a powerful trait and derive macro for writing wrappers
//! to C types.
//!
//! [`&CStr`]: core::ffi::CStr
//! [`&SeaStr`]: SeaStr
//! [`CString`]: alloc::ffi::CString

#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "alloc")]
extern crate alloc;

mod _alloc;
mod _array;
mod _box;
mod _str;
mod _string;

pub use _alloc::*;
pub use _array::*;
pub use _box::*;
pub use _str::*;
pub use _string::*;

pub mod till_null;

use core::fmt::{self, Write as _};

fn debug_bytes(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str("\"")?;
    for chunk in bytes.utf8_chunks() {
        f.write_fmt(format_args!("{}", chunk.valid().escape_default()))?;
        if !chunk.invalid().is_empty() {
            f.write_char(char::REPLACEMENT_CHARACTER)?
        }
    }
    f.write_str("\"")
}

fn display_bytes(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
    for chunk in bytes.utf8_chunks() {
        f.write_str(chunk.valid())?;
        if !chunk.invalid().is_empty() {
            f.write_char(char::REPLACEMENT_CHARACTER)?
        }
    }
    Ok(())
}

/// For the given `struct`, check that for it, and each of its fields,
/// the size and alignment matches some remote type,
/// such that they can be [transmuted](TransmuteFrom::transmute_from) between one another.
///
/// ```
/// mod bindings {
///     /* automatically generated by rust-bindgen */
///     #[repr(C)]
///     pub struct args {
///         pub left: *const ::std::os::raw::c_char,
///         pub right: *const ::std::os::raw::c_char,
///     }
/// }
///
/// # use seasick::*;
/// #[derive(TransmuteFrom)]
/// #[transmute(from = bindings::args)]
/// struct Args<'a> {
///     left: &'a SeaStr,
///     right: &'a SeaStr,
/// }
/// ```
///
/// You may specify the remote field names and types for individual fields,
/// or skip specific fields.
///
/// If a type is given for a remote field,
/// the macro will assert that the remote field will have the given type.
/// This is useful for ensuring your definitions stay in sync.
///
/// ```
/// # mod bindings {
/// #     #[repr(C)]
/// #     pub struct yak_shaver {
/// #         pub name: *const ::std::os::raw::c_char,
/// #         pub count: ::std::os::raw::c_uint,
/// #         pub __bindgen_anon_1: yak_shaver__bindgen_ty_1,
/// #     }
/// #     #[repr(C)]
/// #     pub struct yak_shaver__bindgen_ty_1 {
/// #         pub byte: u8,
/// #     }
/// # }
/// # use seasick::*;
/// # use core::{marker::PhantomData, ffi::c_uint};
/// #[derive(TransmuteFrom)]
/// #[transmute(from = bindings::yak_shaver)]
/// struct YakShaver<'a> {
///     // Against a different remote field name.
///     #[transmute(name: _)]
///     owner: &'a SeaStr,
///
///     // Check the remote type.
///     #[transmute(c_uint)]
///     count: u32,
///
///     // Specify the full remote field signature.
///     #[transmute(__bindgen_anon_1: bindings::yak_shaver__bindgen_ty_1)]
///     bitfield: u8,
///
///     // Ignore this (zero sized) field.
///     #[transmute(skip)]
///     _phantom: PhantomData<()>,
/// }
/// ```
///
/// By default, if the remote field type isn't specified,
/// no assertions are made on its _type_ (size, align and offset are always checked).
/// If `#[transmute(strict)]` is present on the `struct` definition,
/// the type will always be checked, defaulting to the type of the field on the
/// "local" `struct`.
#[cfg(feature = "macros")]
pub use seasick_macros::TransmuteFrom;

/// Transmute between two types that have the same ABI.
///
/// Implemented with [`derive@TransmuteFrom`].
///
/// # Safety
/// - Must be safe to transmute between the given types.
/// - Blanket impls of [`TransmuteRefFrom`] and [`TransmuteMutFrom`] must be safe.
pub unsafe trait TransmuteFrom<T: Sized>: Sized {
    /// # Safety
    /// - Must be safe to transmute between the given objects.
    unsafe fn transmute_from(src: T) -> Self;
}

unsafe impl<T, U: TransmuteFrom<T>> TransmuteRefFrom<T> for U {
    unsafe fn transmute_ref(src: &T) -> &Self {
        let src = src as *const T as *const U;
        unsafe { &*src }
    }
}
unsafe impl<T, U: TransmuteFrom<T>> TransmuteMutFrom<T> for U {
    unsafe fn transmute_mut(src: &mut T) -> &mut Self {
        let src = src as *mut T as *mut U;
        unsafe { &mut *src }
    }
}

/// Transmute between references of two types that have the same ABI.
///
/// # Safety
/// - Must be safe to transmute between the given types
pub unsafe trait TransmuteRefFrom<T: ?Sized> {
    /// # Safety
    /// - Must be safe to transmute between the given objects
    unsafe fn transmute_ref(src: &T) -> &Self;
}

/// Transmute between mutable references of two types that have the same ABI.
///
/// # Safety
/// - Must be safe to transmute between the given types
pub unsafe trait TransmuteMutFrom<T: ?Sized> {
    /// # Safety
    /// - Must be safe to transmute between the given objects
    unsafe fn transmute_mut(src: &mut T) -> &mut Self;
}

/// Compile-time assertions of equality for arity, offset, size and alignment
/// of struct members and function parameters.
///
/// Suppose you are implementing a C header file:
/// ```c
/// struct args
/// {
///     const char *left;
///     const char *right;
/// };
/// char *concat(struct args);
/// ```
///
/// You could use [`bindgen`](https://docs.rs/bindgen) to create simple bindings,
/// and then write nice rust APIs separately,
/// asserting that the two are ABI compatible:
///
/// ```
/// use seasick::{SeaStr, SeaString, assert_abi};
///
/// struct Args<'a> {
///     front: &'a SeaStr,
///     back: &'a SeaStr,
/// }
///
/// #[no_mangle]
/// # extern "C" fn concat(_: Args) -> Option<SeaString> { todo!() }
/// # const _: &str = stringify! {
/// extern "C" fn concat(args: Args) -> Option<SeaString> { .. }
/// # };
///
/// assert_abi! {
///     struct Args = bindings::args { front = left, back = right };
///     fn concat = bindings::concat as unsafe extern "C" fn (_) -> _;
/// }
///
/// mod bindings {
///     /* automatically generated by rust-bindgen */
///     #[repr(C)]
///     #[derive(Debug, Copy, Clone)]
///     pub struct args {
///         pub left: *const ::std::os::raw::c_char,
///         pub right: *const ::std::os::raw::c_char,
///     }
///     extern "C" {
///         pub fn concat(arg1: args) -> *mut ::std::os::raw::c_char;
///     }
/// }
/// ```
///
/// Compilation will fail if the ABI drifts out of sync.
///
/// ```compile_fail
/// # use bindings::Args;
/// # #[expect(improper_ctypes_definitions)]
/// extern "C" fn concat(args: Args) -> String { String::new() }
///                                  // ^^^^^^ different size and alignment
/// assert_abi! {
///     fn concat = bindings::concat as unsafe extern "C" fn(_) -> _;
/// }
/// # mod bindings { #[repr(C)] pub struct Args(()); extern "C" { pub fn concat(args: Args) -> *mut ::std::os::raw::c_char; } }
/// ```
///
/// <div class="warning">
///
/// This macro only detects ABI changes (e.g size, alignment), and cannot distinguish
/// e.g `Box` from `SeaString` - it is still up to you to write (or generate) your type mappings appropriately.
///
/// </div>
#[macro_export]
macro_rules! assert_abi {
    (fn $left:path = $right:path as $ty:ty $(; $($tt:tt)*)?) => {
        const _: () = {
            let _ = $left as $ty;
            let _ = $right as $ty;
            $crate::__private::assert!($crate::__private::abi_eq($left as $ty, $right as $ty));
        };
        $(
            $crate::assert_abi!($($tt)*);
        )?
    };
    (#[non_exhaustive] struct $left_ty:path = $right_ty:path {
        $($left_field:ident = $right_field:ident),* $(,)?
    } $(; $($tt:tt)*)?) => {
        $crate::assert_abi! {
            __struct $left_ty = $right_ty {
                $($left_field = $right_field,)*
            }
        }
        $(
            $crate::assert_abi!($($tt)*);
        )?
    };
    (struct $left_ty:path = $right_ty:path {
        $($left_field:ident = $right_field:ident),* $(,)?
    } $(; $($tt:tt)*)?) => {
        $crate::assert_abi! {
            __struct $left_ty = $right_ty {
                $($left_field = $right_field,)*
            }
        }
        const _: () = {
            fn exhaustive($left_ty { $($left_field: _),* }: $left_ty, $right_ty { $($right_field: _),* }: $right_ty) {}
            //             ^^^^^^^ must be :path not :ty
        };
        $(
            $crate::assert_abi!($($tt)*);
        )?
    };
    (__struct $left_ty:path = $right_ty:path {
        $($left_field:ident = $right_field:ident),* $(,)?
    } $(; $($tt:tt)*)?) => {
        const _: () = {
            use $crate::__private::*;

            let left = Layout::new::<$left_ty>();
            let right = Layout::new::<$right_ty>();

            assert! {
                left.size() == right.size(),
                concat!("size mismatch between ", stringify!($left_ty), " and ", stringify!($right_ty))
            };
            assert! {
                left.align() == right.align(),
                concat!("aligment mismatch between ", stringify!($left_ty), " and ", stringify!($right_ty))
            };

            $(
                assert! {
                    offset_of!($left_ty, $left_field) == offset_of!($right_ty, $right_field),
                    concat!("mismatched offsets between ", stringify!($left_field), " and ", stringify!($right_field))
                };

                let left = layout_of_field(|it: &$left_ty| &it.$left_field);
                let right = layout_of_field(|it: &$right_ty| &it.$right_field);

                assert! {
                    left.size() == right.size(),
                    concat!("size mismatch between ", stringify!($left_field), " and ", stringify!($right_field))
                };
                assert! {
                    left.align() == right.align(),
                    concat!("aligment mismatch between ", stringify!($left_field), " and ", stringify!($right_field))
                };
            )*
        };
    };
    ($(;)?) => {}; // trailing semi
}

#[doc(hidden)]
pub mod __private {

    pub use core;

    pub const fn layout_of_field<T, U>(_: fn(&T) -> &U) -> Layout {
        Layout::new::<U>()
    }

    pub use ::core::{alloc::Layout, assert, concat, mem::offset_of, stringify};

    pub trait AbiEq<T> {
        const ABI_EQ: bool;
    }

    macro_rules! define {
        ($($l:ident $r:ident)*) => {
            impl<LR, RR, $($l, $r),*> AbiEq<fn($($l),*) -> LR> for fn($($r),*) -> RR {
                const ABI_EQ: bool = layout_eq::<LR, RR>() $(&& layout_eq::<$l, $r>())*;
            }
            impl<LR, RR, $($l, $r),*> AbiEq<unsafe fn($($l),*) -> LR> for unsafe fn($($r),*) -> RR {
                const ABI_EQ: bool = layout_eq::<LR, RR>() $(&& layout_eq::<$l, $r>())*;
            }
            impl<LR, RR, $($l, $r),*> AbiEq<extern "C" fn($($l),*) -> LR> for extern "C" fn($($r),*) -> RR {
                const ABI_EQ: bool = layout_eq::<LR, RR>() $(&& layout_eq::<$l, $r>())*;
            }
            impl<LR, RR, $($l, $r),*> AbiEq<unsafe extern "C" fn($($l),*) -> LR> for unsafe extern "C" fn($($r),*) -> RR {
                const ABI_EQ: bool = layout_eq::<LR, RR>() $(&& layout_eq::<$l, $r>())*;
            }
        };
    }

    define!();
    define!(L0 R0);
    define!(L0 R0 L1 R1);
    define!(L0 R0 L1 R1 L2 R2);
    define!(L0 R0 L1 R1 L2 R2 L3 R3);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7 L8 R8);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7 L8 R8 L9 R9);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7 L8 R8 L9 R9 L10 R10);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7 L8 R8 L9 R9 L10 R10 L11 R11);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7 L8 R8 L9 R9 L10 R10 L11 R11 L12 R12);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7 L8 R8 L9 R9 L10 R10 L11 R11 L12 R12 L13 R13);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7 L8 R8 L9 R9 L10 R10 L11 R11 L12 R12 L13 R13 L14 R14);
    define!(L0 R0 L1 R1 L2 R2 L3 R3 L4 R4 L5 R5 L6 R6 L7 R7 L8 R8 L9 R9 L10 R10 L11 R11 L12 R12 L13 R13 L14 R14 L15 R15);

    const fn layout_eq<L, R>() -> bool {
        let left = Layout::new::<L>();
        let right = Layout::new::<R>();
        left.size() == right.size() && left.align() == right.align()
    }

    pub const fn abi_eq<L, R>(_: L, _: R) -> bool
    where
        L: AbiEq<R>,
        L: Copy,
        R: Copy,
    {
        L::ABI_EQ
    }
}