File: enums.d

package info (click to toggle)
mir-core 1.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 560 kB
  • sloc: makefile: 9; sh: 7
file content (388 lines) | stat: -rw-r--r-- 10,357 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/++
Enum utilities.

License: $(HTTP www.apache.org/licenses/LICENSE-2.0, Apache-2.0)
Authors: Ilia Ki 
Macros:
+/
module mir.enums;

private bool hasSeqGrow(T)(T[] elems)
    if (__traits(isIntegral, T))
{
    assert(elems.length);
    auto min = elems[0];
    foreach (i, e; elems)
        if (i != e - min)
            return false;
    return true;
}

/++
Enum index that corresponds of the list returned by `std.traits.EnumMembers`.
Returns:
    enum member position index in the enum definition that corresponds the `value`.
+/
bool getEnumIndex(T)(const T value, ref uint index)
    @safe pure nothrow @nogc
    if (is(T == enum))
{
    import std.traits: EnumMembers, isSomeString;
        import mir.utility: _expect;

    static if (__traits(isFloating, T))
    {
        // TODO: index based binary searach
        foreach (i, member; enumMembers!T)
        {
            if (value == member)
            {
                index = cast(uint) i;
                return true;
            }
        }
        return false;
    }
    else
    static if (!__traits(isIntegral, T)) //strings
    {
        enum string[1] stringEnumValue(alias symbol) = [symbol];
        return getEnumIndexFromKey!(T, false, stringEnumValue)(value, index);
    }
    else
    static if (hasSeqGrow(enumMembers!T))
    {
        import std.traits: Unsigned;
        const shifted = cast(Unsigned!(typeof(value - T.min)))(value - T.min);
        if (_expect(shifted < enumMembers!T.length, true))
        {
            index = cast(uint) shifted;
            return true;
        }
        return false;
    }
    else
    static if (is(T : bool))
    {
        index = !value;
        return true;
    }
    else
    {
        import std.traits: Unsigned;
        alias U = Unsigned!(typeof(T.max - T.min + 1));

        enum length = cast(size_t)cast(U)(T.max - T.min + 1);

        const shifted = cast(size_t)cast(U)(value - T.min);

        static if (length <= 255)
        {
            static immutable ubyte[length] table = (){
                ubyte[length] ret;
                foreach (i, member; enumMembers!T)
                {
                    ret[member - T.min] = cast(ubyte)(i + 1);
                }
                return ret;
            }();

            if (_expect(shifted < length, true))
            {
                int id = table[shifted] - 1;
                if (_expect(id >= 0, true))
                {
                    index = id;
                    return true;
                }
            }
            return false;
        }
        else
        {
            switch (value)
            {
                foreach (i, member; EnumMembers!T)
                {
                case member:
                    index = i;
                    return true;
                }
                default: return false;
            }
        }
    }
}

///
@safe pure nothrow @nogc
version(mir_core_test) unittest
{
    import std.meta: AliasSeq;

    enum Common { a, b, c }
    enum Reversed { a = 1, b = 0, c = -1 }
    enum Shifted { a = -4, b, c }
    enum Small { a = -4, b, c = 10 }
    enum Big { a = -4, b, c = 1000 }
    enum InverseBool { True = true, False = false }
    enum FP : float { a = -4, b, c }
    enum S : string { a = "а", b = "б", c = "ц" }

    uint index = -1;
    foreach (E; AliasSeq!(Common, Reversed, Shifted, Small, Big, FP, S))
    {
        assert(getEnumIndex(E.a, index) && index == 0);
        assert(getEnumIndex(E.b, index) && index == 1);
        assert(getEnumIndex(E.c, index) && index == 2);
    }

    assert(getEnumIndex(InverseBool.True, index) && index == 0);
    assert(getEnumIndex(InverseBool.False, index) && index == 1);
}

/++
Static immutable instance of `[std.traits.EnumMembers!T]`.
+/
template enumMembers(T)
    if (is(T == enum))
{
    import std.traits: EnumMembers;
    ///
    static immutable T[EnumMembers!T.length] enumMembers = [EnumMembers!T];
}

///
version(mir_core_test) unittest
{
    enum E {a = 1, b = -1, c}
    static assert(enumMembers!E == [E.a, E.b, E.c]);
}

/++
Static immutable instance of Enum Identifiers.
+/
template enumIdentifiers(T)
    if (is(T == enum))
{
    import std.traits: EnumMembers;
    static immutable string[EnumMembers!T.length] enumIdentifiers = () {
        string[EnumMembers!T.length] identifiers;
        static foreach(i, member; EnumMembers!T)
            identifiers[i] = __traits(identifier, EnumMembers!T[i]);
        return identifiers;
    } ();
}

///
version(mir_core_test) unittest
{
    enum E {z = 1, b = -1, c}
    static assert(enumIdentifiers!E == ["z", "b", "c"]);
}

/++
Aliases itself to $(LREF enumMembers) for string enums and
$(LREF enumIdentifiers) for integral and floating point enums.
+/
template enumStrings(T)
    if (is(T == enum))
{
    static if (is(T : C[], C))
        alias enumStrings = enumMembers!T;
    else
        alias enumStrings = enumIdentifiers!T;
}

///
version(mir_core_test) unittest
{
    enum E {z = 1, b = -1, c}
    static assert(enumStrings!E == ["z", "b", "c"]);

    enum S {a = "A", b = "B", c = ""}
    static assert(enumStrings!S == [S.a, S.b, S.c]);
}

/++
Params:
    index  = enum index `std.traits.EnumMembers!T`
Returns:
    A enum value that corresponds to the index.
Note:
    The function doesn't check that index is less then `EnumMembers!T.length`.
+/
T unsafeEnumFromIndex(T)(size_t index)
    @trusted pure nothrow @nogc
    if (is(T == enum))
{
    static if (__traits(isIntegral, T))
        enum bool fastConv = hasSeqGrow(enumMembers!T);
    else
        enum bool fastConv = false;
    
    assert(index < enumMembers!T.length);
    
    static if (fastConv)
    {
        return cast(T) (index + enumMembers!T[0]);
    }
    else
    {
        return enumMembers!T[index];
    }
}

///
version(mir_core_test)
unittest
{
    enum Linear
    {
        one = 1,
        two = 2
    }

    static assert(is(typeof(unsafeEnumFromIndex!Linear(0)) == Linear));
    assert(unsafeEnumFromIndex!Linear(0) == Linear.one);
    assert(unsafeEnumFromIndex!Linear(1) == Linear.two);

    enum Mixed
    {
        one = 1,
        oneAgain = 1,
        two = 2
    }

    assert(unsafeEnumFromIndex!Mixed(0) == Mixed.one);
    assert(unsafeEnumFromIndex!Mixed(1) == Mixed.one);
    assert(unsafeEnumFromIndex!Mixed(2) == Mixed.two);
}

/++
Params:
    T = enum type to introspect
    key = some string that corresponds to some key name of the given enum
    index = resulting enum index if this method returns true.
Returns:
    boolean whether the key was found in the enum keys and if so, index is set.
+/
template getEnumIndexFromKey(T, bool caseInsensitive = true, getKeysTemplate...)
    if (is(T == enum) && getKeysTemplate.length <= 1)
{
    ///
    bool getEnumIndexFromKey(C)(scope const(C)[] key, ref uint index)
        @safe pure nothrow @nogc
        if (is(C == char) || is(C == wchar) || is(C == dchar))
    {
        import mir.string_table;
        import mir.utility: simpleSort, _expect;
        import std.traits: EnumMembers;
        import std.meta: staticIndexOf;

        alias String = immutable(C)[];

        static if (getKeysTemplate.length)
        {
            alias keysOfImpl = getKeysTemplate[0];
            enum String[] keysOf(alias symbol) = keysOfImpl!symbol;
        }
        else
        static if (is(T : W[], W))
            enum String[1] keysOf(alias symbol) = [cast(String)symbol];
        else
            enum String[1] keysOf(alias symbol) = [__traits(identifier, symbol)];

        enum keys = () {
            String[] keys;
            foreach(i, member; EnumMembers!T)
                keys ~= keysOf!(EnumMembers!T[i]);
            return keys;
        } ();

        static if (keys.length == 0)
        {
            return false;
        }
        else
        {
            enum indexLength = keys.length + 1;
            alias ct = createTable!C;
            static immutable table = ct!(keys, caseInsensitive);
            static immutable indices = ()
            {
                minimalSignedIndexType!indexLength[indexLength] indices;

                foreach (i, member; EnumMembers!T)
                foreach (key; keysOf!(EnumMembers!T[i]))
                {
                    static if (caseInsensitive)
                    {
                        key = key.dup.fastToUpperInPlace;
                    }
                    indices[table[key]] = i;
                }

                return indices;
            } ();

            uint stringId = void;
            if (_expect(table.get(key, stringId), true))
            {
                index = indices[stringId];
                return true;
            }
            return false;
        }
    }
}

///
unittest
{
    enum Short
    {
        hello,
        world
    }

    enum Long
    {
        This,
        Is,
        An,
        Enum,
        With,
        Lots,
        Of,
        Very,
        Long,
        EntriesThatArePartiallyAlsoVeryLongInStringLengthAsWeNeedToTestALotOfDifferentCasesThatCouldHappenInRealWorldCode_tm
    }

    uint i;
    assert(getEnumIndexFromKey!Short("hello", i));
    assert(i == 0);
    assert(getEnumIndexFromKey!Short("world", i));
    assert(i == 1);
    assert(!getEnumIndexFromKey!Short("foo", i));

    assert(getEnumIndexFromKey!Short("HeLlO", i));
    assert(i == 0);
    assert(getEnumIndexFromKey!Short("WoRLd", i));
    assert(i == 1);

    assert(!getEnumIndexFromKey!(Short, false)("HeLlO", i));
    assert(!getEnumIndexFromKey!(Short, false)("WoRLd", i));

    assert(getEnumIndexFromKey!Long("Is", i));
    assert(i == 1);
    assert(getEnumIndexFromKey!Long("Long", i));
    assert(i == 8);
    assert(getEnumIndexFromKey!Long("EntriesThatArePartiallyAlsoVeryLongInStringLengthAsWeNeedToTestALotOfDifferentCasesThatCouldHappenInRealWorldCode_tm", i));
    assert(i == 9);
    assert(!getEnumIndexFromKey!Long("EntriesThatArePartiallyAlsoVeryLongInStringLengthAsWeNeedToTestALotOfDifferentCasesThatCouldHappenInRealWorldCodeatm", i));

    assert(!getEnumIndexFromKey!(Long, false)("EntriesThatArePartiallyAlsoVeryLongInStringLengthAsWeNeedToTestALotOfDifferentCasesThatCouldHappenInRealWorldCode_tM", i));
    assert(!getEnumIndexFromKey!(Long, false)("entriesThatArePartiallyAlsoVeryLongInStringLengthAsWeNeedToTestALotOfDifferentCasesThatCouldHappenInRealWorldCode_tm", i));
}