From 83ce3f004eb30e5052c7037c92d90ce860f804d0 Mon Sep 17 00:00:00 2001 From: Ray Greenwell Date: Sat, 11 Jul 2009 00:08:41 +0000 Subject: [PATCH] Added ByteEnum interface to ActionScript, and ByteEnumUtil. Use this if you want your enums to persist to a byte reliably. Coming soonesque: narya streaming support for ByteEnum. git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@5859 542714f4-19e9-0310-aa3c-eee0fc999fb1 --- src/as/com/threerings/util/ByteEnum.as | 16 +++++++++++++ src/as/com/threerings/util/ByteEnumUtil.as | 26 ++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/as/com/threerings/util/ByteEnum.as create mode 100644 src/as/com/threerings/util/ByteEnumUtil.as diff --git a/src/as/com/threerings/util/ByteEnum.as b/src/as/com/threerings/util/ByteEnum.as new file mode 100644 index 000000000..d6dee554f --- /dev/null +++ b/src/as/com/threerings/util/ByteEnum.as @@ -0,0 +1,16 @@ +// +// $Id$ + +package com.threerings.util { + +/** + * An enum value that can be persisted as a byte. + */ +public interface ByteEnum +{ + /** + * Return the byte form of this enum. + */ + function toByte () :int; +} +} diff --git a/src/as/com/threerings/util/ByteEnumUtil.as b/src/as/com/threerings/util/ByteEnumUtil.as new file mode 100644 index 000000000..0d5c67e4e --- /dev/null +++ b/src/as/com/threerings/util/ByteEnumUtil.as @@ -0,0 +1,26 @@ +// +// $Id$ + +package com.threerings.util { + +/** + * ByteEnum utility methods. + */ +public class ByteEnumUtil +{ + /** + * Returns the enum value with the specified code in the supplied enum class. + * Throws ArgumentError if the enum lacks a value that maps to the supplied code. + */ + public static function fromByte (clazz :Class, code :int) :Enum + { + // we could do something fancier than this O(n) impl, in the future... + for each (var e :Enum in Enum.values(clazz)) { + if (ByteEnum(e).toByte() == code) { + return e; + } + } + throw new ArgumentError(clazz + " has no value with code " + code); + } +} +}