[][src]Crate abistr

C ABI compatible string types

While rust's stdlib has some good basic options for C-string support, it has some glaring issues when dealing with C functions that accept or return arrays of structures containing C-string pointers or arrays. This crate aims to help fill that niche with safe, fast, ergonomic alternatives.

C typeABI compatible Rustnull
const char*abistr::CStrPtr""
const char*Option<abistr::CStrNonNull>None
const char* __attribute__((nonnull))abistr::CStrNonNull❌ undefined behavior ❌
char struct_member[128];abistr::CStrBuf<[u8; 128]>N/A

Alternatives

*const std::os::raw::c_char

  • Pro: Can't get any simpler for basic interop!
  • Con: Requires unsafe to so much as shake a stick at.
  • Con: Easy to create undefined behavior by messing up edge cases involving null.
  • Con: Easy to create undefined behavior by creating dangling poniters and other lifetime issues (raw pointers have no lifetimes.)
  • Con: Fairly unergonomic to use directly.

std::ffi::CStr

  • Pro: Relatively safe!
  • Con: Immediate O(n) length check on construction, even if you never use the string.
  • Con: Being a DST (at least at the time of writing / rust 1.48.0), this isn't ABI compatible with *const c_char and thus cannot be embedded in zero-conversion structures.

std::ffi::CString - per std::ffi::CStr, but also:

  • Pro: Dynamically allocated!
  • Con: Dynamically allocated.

Macros

cstr

Create a &CStrNonNull literal at compile time

Structs

CStrBuf

CStrBuf<[u8; 128]> is ABI compatible with [c_char; 128].

CStrNonNull

Option<CStrNonNull> is ABI compatible with *const c_char.

CStrPtr

CStrPtr is ABI compatible with *const c_char. null() is treated as an empty string.

NotNulTerminatedError

The string in question contains no terminal \0

Traits

AsCStr

Treat self as a C-style string

AsOptCStr

Treat self as a C-style string or null()