Bug 24540 – Add order/index to enum member to return its position

Status
NEW
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2024-05-06T13:08:35Z
Last change time
2024-12-13T19:35:09Z
Assigned to
No Owner
Creator
apham
Moved to GitHub: dmd#18239 →

Comments

Comment #0 by apz28 — 2024-05-06T13:08:35Z
Currently to get the order/index of an enum member to be done in loop which is slow. Provide such member will speedup the lookup enum Foo { one=100, // First order/index=0 two=399, // Next is 1 ... } auto checkingMember = Foo.two; size_t index; foreach (e; EnumMembers!Foo) { if (e == checkingMember) return index; index++; } One of the use case is provide a set of Foo using ubyte/ushort/uint/ulong struct Set(E) { void set(Foo e) { v |= 1 << e.order; } bool isSet(Foo e) { return (v & (1 << e.order)) != 0; } More...functions uint v; }
Comment #1 by apz28 — 2024-05-06T13:28:12Z
The value is also needed to be known at compile time static assert(Foo.one.order == 0); static assert(Foo.two.order == 1);
Comment #2 by nick — 2024-05-06T15:59:18Z
(In reply to apham from comment #0) > void set(Foo e) > { > v |= 1 << e.order; > } > > bool isSet(Foo e) > { > return (v & (1 << e.order)) != 0; > } It's not possible to take a runtime enum value and produce its index in an enum without some runtime overhead. Another issue is that `e.order` is already valid code, meaning call `order(e)`.
Comment #3 by robert.schadek — 2024-12-13T19:35:09Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/18239 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB