diffusion
Version:
Diffusion JavaScript client
44 lines (43 loc) • 1.37 kB
JavaScript
;
/**
* @module Serialisers
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.write = exports.read = void 0;
var errors_1 = require("./../../errors/errors");
var Codec = require("./../io/codec");
/**
* Read an enum from a byte reader
*
* @param input the stream from which to read the enum value
* @param enumType the enum type
* @return the value read from the stream if it is a valid enum value
*
* @throws an {@link IllegalArgumentError} if the value read is not a valid enum value
*/
function read(input, enumType) {
var e = Codec.readByte(input);
if (enumType[e] === undefined) {
throw new errors_1.IllegalArgumentError('Unable to decode enum value ' + e);
}
// reverse lookup, then forward lookup
// for enum-like objects storing objects with id, this returns the object instead of the id
return enumType[enumType[e]];
}
exports.read = read;
/**
* Write an enum to a byte writer
*
* @param output the stream to which to write the enum value
* @param val the numeric enum value or an object that contains the enum value
* as `id` property
*/
function write(output, val) {
if (typeof val === 'number') {
Codec.writeByte(output, val);
}
else {
Codec.writeByte(output, val.id);
}
}
exports.write = write;