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.

This crate is exported under the objc2 crate as objc2::encode, so usually you would just use it 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.

Caveats

We’ve taken the pragmatic approach with Encode and RefEncode, and have implemented it for as many types as possible (instead of defining a bunch of subtraits for very specific purposes). However, that might sometimes be slightly surprising.

Notably we have implemented these for bool, which, in reality, you would never actually see in an Objective-C method (they use BOOL, see objc2::runtime::Bool), but which can techincally occur, and as such does make sense to define an encoding for.

The other example is (), which doesn’t make sense as a method argument, but is a very common return type, and hence implements Encode.

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.