Crate objc2_encode[][src]

Expand description

Objective-C type-encoding

This is re-exported into the top level of objc2.

The Objective-C directive @encode encodes types as strings, and this is used in various places in the runtime.

This crate provides the Encoding type to efficiently describe and compare these type-encodings.

Additionally it provides traits for annotating types that has an Objective-C encoding: Specifically Encode for structs, RefEncode for references and EncodeArguments for function arguments.

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

Example

Implementing Encode and RefEncode for a custom type:

use objc2_encode::{Encode, Encoding, RefEncode};
// or from objc2:
// use objc2::{Encode, Encoding, RefEncode};

#[repr(C)]
struct MyStruct {
    a: f32, // float
    b: i16, // int16_t
}

unsafe impl Encode for MyStruct {
    const ENCODING: Encoding<'static> = Encoding::Struct(
        "MyStruct", // Must use the same name as defined in C header files
        &[
            f32::ENCODING, // Same as Encoding::Float
            i16::ENCODING, // Same as Encoding::Short
        ],
    );
}

// @encode(MyStruct) -> "{MyStruct=fs}"
assert!(MyStruct::ENCODING.equivalent_to_str("{MyStruct=fs}"));

unsafe impl RefEncode for MyStruct {
    // Note that if `MyStruct` is an Objective-C instance, this should
    // be `Encoding::Object`.
    const ENCODING_REF: Encoding<'static> = Encoding::Pointer(&Self::ENCODING);
}

// @encode(MyStruct*) -> "^{MyStruct=fs}"
assert!(MyStruct::ENCODING_REF.equivalent_to_str("^{MyStruct=fs}"));

See the examples folder for more complex usage.

Further resources:

Enums

An Objective-C type-encoding.

Traits

Types that have an Objective-C type-encoding.

Types that represent an ordered group of function arguments, where each argument has an Objective-C type-encoding.

Types whoose references has an Objective-C type-encoding.