Google is committed to advancing racial equity for Black communities. See how.

Safe Union

safe_union in HIDL represents an explicitly tagged union type. This is similar to a union except safe_union keeps track of the underlying type and is compatible with Java. The safe_union type is available in Android 10 and higher for new and upgraded devices.

Syntax

A safe_union is expressed in HIDL exactly like a union or struct.

safe_union MySafeUnion {
     TypeA a;
     TypeB b;
     ...
};

Usage

At runtime, a safe_union is only ever one type. By default, it will be the first type in the union. For instance, above, MySafeUnion is by default TypeA.

hidl-gen generates a custom class or struct for a safe_union in both C++ and Java. This class includes a discriminator for each member (in hidl_discriminator), a method to get the current discriminator (getDiscriminator), and setters and getters for each member. Each setter and getter is named exactly as its member. For instance, the getter for TypeA a will be called "a", and it will return something of TypeA. The corresponding setter will also be called "a" and take a parameter of TypeA. Setting the value in a safe_union will update the value of the discriminator as returned by getDiscriminator. Accessing a value from a discriminator that is not the current discriminator aborts the program. For instance, if calling getDiscriminator on an instance of MySafeUnion returns hidl_discriminator::b, then trying to retrieve a will abort the program.

Monostate

A safe_union always has a value, but if it is desired to not have a value, use android.hidl.safe_union@1.0::Monostate as a placeholder. For instance, the following union can either be noinit (empty) or foo:

import android.hidl.safe_union@1.0::Monostate;

safe_union OptionalFoo {
     Monostate noinit;
     Foo foo;
};