4 releases (1 stable)

new 2.0.0-beta.0 Nov 22, 2021
1.1.0 Nov 19, 2021

#39 in macOS and iOS APIs

MIT license

583 lines


Latest version License Documentation Apple CI GNUStep CI

Objective-C type-encoding in Rust.

The Objective-C directive @encode encodes types as strings for usage in various places in the runtime.

This crate provides the Encoding type to describe and compare these type-encodings without memory allocation.

Additionally it provides traits for annotating types that has a corresponding Objective-C encoding, respectively Encode for structs and RefEncode for references (and EncodeArguments for function arguments).

These types are exported under the objc2 crate as well, so usually you would just use that.


Implementing Encode and RefEncode:

use objc2_encode::{Encode, Encoding, RefEncode};

struct MyObject {
    a: f32,
    b: i16,

unsafe impl Encode for MyObject {
    const ENCODING: Encoding<'static> = Encoding::Struct(
        &[f32::ENCODING, i16::ENCODING],

assert_eq!(&MyObject::ENCODING, "{MyObject=fs}");

unsafe impl RefEncode for MyObject {
    const ENCODING_REF: Encoding<'static> = Encoding::Pointer(&Self::ENCODING);

assert_eq!(&MyObject::ENCODING_REF, "^{MyObject=fs}");

An Encoding can be compared with an encoding string from the Objective-C runtime:

use objc2_encode::Encode;
assert!(&i32::ENCODING == "i");

Encoding implements Display as its string representation. This can be generated conveniently through the to_string method:

use objc2_encode::Encode;
assert_eq!(i32::ENCODING.to_string(), "i");

See the examples folder for more complex usage.

No runtime deps