#enums #string #conversion #derive

cstr-enum

A crate for defining C-style string enums

1 stable release

1.0.0 Feb 12, 2021

#235 in FFI

Download history 8/week @ 2024-07-22 20/week @ 2024-07-29 19/week @ 2024-08-05 22/week @ 2024-08-12 16/week @ 2024-08-19 48/week @ 2024-08-26 13/week @ 2024-09-02 55/week @ 2024-09-09 29/week @ 2024-09-16 46/week @ 2024-09-23 37/week @ 2024-09-30 18/week @ 2024-10-07 40/week @ 2024-10-14 25/week @ 2024-10-21 46/week @ 2024-10-28 31/week @ 2024-11-04

143 downloads per month
Used in 4 crates (via grb)

MIT license

8KB

cstr-enum GitHub tag (latest SemVer)

A crate for defining C-style string enums.

C APIs sometimes require string constants. One could define a bunch of &CStr constants using the constr_cstr crate, but this becomes unergonomic with a large number of constants. It also does not allow the type checking Rust's enums provide.

This crate provides two traits for converting between to and from &CStr: AsCStr and FromCStr. It also provides derive macros for implementing these traits on enums. The implementations provided by the derive macros perform no allocations, using only static [u8] buffers.

Example usage

use cstr_enum::*;
use std::ffi::CStr;
use std::os::raw::c_char;

#[derive(Debug, Eq, PartialEq, FromCStr, AsCStr)]
enum Constants {
  Apple,
  Bacon,
  Cat = 1337, // user discriminants supported
}

assert_eq!(Constants::Apple.as_cstr().to_bytes_with_nul(), b"Apple\0");

let returned_from_c_api = CStr::from_bytes_with_nul(b"Cat\0").unwrap();
assert_eq!(Constants::from_cstr(returned_from_c_api), Ok(Constants::Cat));

let returned_from_c_api = CStr::from_bytes_with_nul(b"unknown\0").unwrap();
assert_eq!(
  Constants::from_cstr(returned_from_c_api),
  Err("unexpected string while parsing for Constants variant")
);

License

Licensed under MIT.

Dependencies

~1.5MB
~37K SLoC