Skip to main content

Function: defineEnum()

defineEnum(members, type?): EnumDef

Describe a C enum as a name -> value mapping, for use as a defineStruct field type: the field then packs from a member name and unpacks back to one.

A name the mapping does not have, or bytes holding a value it has no name for, throw a RangeError naming the field. A raw value may be packed as well, but only if the mapping declares it.

import { defineEnum, defineStruct } from 'tjs:ffi';

// enum log_level { LOG_DEBUG, LOG_INFO, LOG_ERROR };
const LogLevel = defineEnum({ DEBUG: 0, INFO: 1, ERROR: 2 });
const Message = defineStruct([['level', LogLevel], ['code', 'u32']]);

console.log(Message.unpack(Message.pack({ level: 'ERROR', code: 42 })));

Parameters​

members​

Record<string, number>

The enumerators, as { NAME: value }. Values must be safe integers; two names for one value is legal C, and the last one declared is what unpacking reports.

type?​

TypeOrAlias

The integer type the enum is stored in. Defaults to types.sint (C's int), which is also the only default under which a negative enumerator round trips.

Returns​

EnumDef