[Issue 9206] New: std.exception.isValidEnumValue
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Tue Dec 25 01:54:28 PST 2012
http://d.puremagic.com/issues/show_bug.cgi?id=9206
Summary: std.exception.isValidEnumValue
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Severity: enhancement
Priority: P2
Component: Phobos
AssignedTo: nobody at puremagic.com
ReportedBy: bearophile_hugs at eml.cc
--- Comment #0 from bearophile_hugs at eml.cc 2012-12-25 01:54:16 PST ---
Sometimes in a program instances of enumerates values contain a value that's
not one of the allowed ones, because of missed initialization ("= void"), data
corruption, badly done casts of integral values to enum instance values, and so
on.
So I sometimes validate an enum instance in function pre-conditions. Below
there is a first implementation of such isValidEnumValue() validating function,
meant to be used mostly in pre-conditions. I suggest to add something similar
to this to std.exception:
//------------------------------------------
import std.traits: EnumMembers, isIntegral, isSomeChar;
import std.algorithm: canFind;
@property bool isCompleteIntervalEnum(E)()
pure nothrow if (is(E == enum)) {
static if (isIntegral!E || isSomeChar!E) {
return EnumMembers!E.length == (E.max - E.min + 1);
} else {
return false;
}
} unittest { // isCompleteIntervalEnum tests
enum E01 : string { S1="abb", S2="booh", S3="zum" }
static assert(!isCompleteIntervalEnum!E01);
enum E02 : byte { A=-3, S2=4 }
static assert(!isCompleteIntervalEnum!E02);
enum E03: byte { A=0, B=1, C=2 }
static assert(isCompleteIntervalEnum!E03);
enum E04: char { A, B, C }
static assert(isCompleteIntervalEnum!E04);
enum E05: ulong { A=ulong.max, B=ulong.min }
static assert(!isCompleteIntervalEnum!E05);
enum E06: ulong { A=ulong.max, B=ulong.max-1 }
static assert(isCompleteIntervalEnum!E06);
enum E07: char { A='a', B='b', C='c' }
static assert(isCompleteIntervalEnum!E07);
}
bool isValidEnumValue(E)(E e)
pure nothrow if (is(E == enum)) {
static if (isCompleteIntervalEnum!E) {
return e >= E.min && e <= E.max; // Optimization.
} else {
return [EnumMembers!Foo].canFind(e);
}
}
enum Foo { A, B, C=10 }
void bar(Foo f)
in {
assert(isValidEnumValue(f));
} body {
}
void main() {
//Foo f;
Foo f = void;
bar(f);
}
//------------------------------------------
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list