vibe.utils.dictionarylist 27/134(20%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
40171
410
420
43183
4457
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
6544
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2331
2341
2351
2360
2370
2380
2390
2400
2410
2420
24357
24457
24557
246114
2470
24857
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
264112
265112
266140
26798
26898
26998
2700
2710
2720
2730
2740
2750
2760
2770
27813
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3051106
3060
307140
3080
309196
3100
3110
3120
3130
3140
315140
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
34344
3440
34531
34631
3470
3480
34931
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
/** Defines a string based multi-map with conserved insertion order. Copyright: © 2012-2014 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module vibe.utils.dictionarylist; import vibe.utils.array : removeFromArrayIdx; import vibe.utils.string : icmp2; import std.exception : enforce; /** Behaves similar to $(D VALUE[string]) but the insertion order is not changed and multiple values per key are supported. This kind of map is used for MIME headers (e.g. for HTTP, see vibe.inet.message.InetHeaderMap), or for form data (vibe.inet.webform.FormFields). Note that the map can contain fields with the same key multiple times if addField is used for insertion. Insertion order is preserved. Note that despite case not being relevant for matching keyse, iterating over the map will yield the original case of the key that was put in. Insertion and lookup has O(n) complexity. */ struct DictionaryList(VALUE, bool case_sensitive = true, size_t NUM_STATIC_FIELDS = 32, bool USE_HASHSUM = false) { import std.typecons : Tuple; private { alias KeyValue = Tuple!(string, "key", ValueType, "value"); static struct Field { static if (USE_HASHSUM) uint keyCheckSum; else { enum keyCheckSum = 0; this(uint, string key, VALUE value) { this.key = key; this.value = value; } } KeyValue tuple; @property ref inout(string) key() inout { return tuple.key; } @property ref inout(VALUE) value() inout { return tuple.value; } } Field[NUM_STATIC_FIELDS] m_fields; size_t m_fieldCount = 0; Field[] m_extendedFields; enum bool safeValueCopy = __traits(compiles, (VALUE v) @safe { VALUE vc; vc = v; }); template typedGet(T) { enum typedGet = __traits(compiles, (VALUE v) { return v.get!T; }); } template canAssign(T) { enum canAssign = __traits(compiles, (T t) { VALUE v = t; }); } } alias ValueType = VALUE; struct FieldTuple { string key; ValueType value; } /** The number of fields present in the map. */ @property size_t length() const { return m_fieldCount + m_extendedFields.length; } /// Supports serialization using vibe.data.serialization. static DictionaryList fromRepresentation(FieldTuple[] array) { DictionaryList ret; foreach (ref v; array) ret.addField(v.key, v.value); return ret; } /// ditto FieldTuple[] toRepresentation() { FieldTuple[] ret; foreach (k, ref v; this) ret ~= FieldTuple(k, v); return ret; } /** Generates an associative-array equivalent string representation of the dictionary. */ void toString(scope void delegate(const(char)[] str) @safe sink) const { sink("["); bool first = true; foreach (k, v; this.byKeyValue) { if (!first) sink(", "); else first = false; () @trusted { import std.format : formattedWrite; string[] ka = (&k)[0 .. 1]; ValueType[] va = (&v)[0 .. 1]; sink.formattedWrite("%(%s%): %(%s%)", ka, va); } (); } sink("]"); } /// ditto void toString(scope void delegate(const(char)[] str) @system sink) const { toString(cast(void delegate(const(char)[]) @safe)sink); } /// ditto string toString() const { import std.array : appender; auto ret = appender!string(); toString((s) { ret.put(s); }); return ret.data; } /** Removes the first field that matches the given key. */ void remove(string key) { static if (USE_HASHSUM) auto keysum = computeCheckSumI(key); enum keysum = 0; auto idx = getIndex(m_fields[0 .. m_fieldCount], key, keysum); if( idx >= 0 ){ auto slice = m_fields[0 .. m_fieldCount]; removeFromArrayIdx(slice, idx); m_fieldCount--; } else { idx = getIndex(m_extendedFields, key, keysum); enforce(idx >= 0); removeFromArrayIdx(m_extendedFields, idx); } } /** Removes all fields that matches the given key. */ void removeAll(string key) { static if (USE_HASHSUM) auto keysum = computeCheckSumI(key); else enum keysum = 0; for (size_t i = 0; i < m_fieldCount;) { if (m_fields[i].keyCheckSum == keysum && matches(m_fields[i].key, key)) { auto slice = m_fields[0 .. m_fieldCount]; removeFromArrayIdx(slice, i); m_fieldCount--; } else i++; } for (size_t i = 0; i < m_extendedFields.length;) { if (m_fields[i].keyCheckSum == keysum && matches(m_fields[i].key, key)) removeFromArrayIdx(m_extendedFields, i); else i++; } } /** Adds a new field to the map. The new field will be added regardless of any existing fields that have the same key, possibly resulting in duplicates. Use opIndexAssign if you want to avoid duplicates. */ void addField(string key, ValueType value) { static if (USE_HASHSUM) auto keysum = computeCheckSumI(key); else enum keysum = 0; if (m_fieldCount < m_fields.length) m_fields[m_fieldCount++] = Field(keysum, key, value); else m_extendedFields ~= Field(keysum, key, value); } void addField(T)(string key, T value) if (canAssign!T) { ValueType convertedValue = value; addField(key, convertedValue); } /** Returns the first field that matches the given key. If no field is found, def_val is returned. */ inout(ValueType) get(string key, lazy inout(ValueType) def_val = ValueType.init) inout { if (auto pv = key in this) return *pv; return def_val; } // DMD bug: cannot set T.init as default value for def_val parameter, // because compilation fails with message: // Error: undefined identifier 'T' /// ditto inout(T) get(T)(string key, lazy inout(T) def_val) inout if (typedGet!T) { if (auto pv = key in this) return (*pv).get!T; return def_val; } /// ditto inout(T) get(T)(string key) // Work around DMD bug inout if (typedGet!T) { return get!T(key, T.init); } /** Returns all values matching the given key. Note that the version returning an array will allocate for each call. */ const(ValueType)[] getAll(string key) const @trusted { // appender import std.array; auto ret = appender!(const(ValueType)[])(); getAll(key, (v) @trusted { ret.put(v); }); return ret.data; } /// ditto void getAll(string key, scope void delegate(const(ValueType)) @safe del) const { static if (USE_HASHSUM) uint keysum = computeCheckSumI(key); else enum keysum = 0; foreach (ref f; m_fields[0 .. m_fieldCount]) { static if (USE_HASHSUM) if (f.keyCheckSum != keysum) continue; if (matches(f.key, key)) del(f.value); } foreach (ref f; m_extendedFields) { static if (USE_HASHSUM) if (f.keyCheckSum != keysum) continue; if (matches(f.key, key)) del(f.value); } } /** Returns the first value matching the given key. */ inout(ValueType) opIndex(string key) inout { auto pitm = key in this; enforce(pitm !is null, "Accessing non-existent key '"~key~"'."); return *pitm; } /** Adds or replaces the given field with a new value. */ ValueType opIndexAssign(ValueType val, string key) { static if (USE_HASHSUM) auto keysum = computeCheckSumI(key); else enum keysum = 0; auto pitm = key in this; if (pitm) *pitm = val; else if (m_fieldCount < m_fields.length) m_fields[m_fieldCount++] = Field(keysum, key, val); else m_extendedFields ~= Field(keysum, key, val); return val; } /// ditto ValueType opIndexAssign(T)(T val, string key) if (canAssign!T) { ValueType convertedVal = val; return opIndexAssign(convertedVal, key); } /** Returns a pointer to the first field that matches the given key. */ inout(ValueType)* opBinaryRight(string op)(string key) inout if(op == "in") { static if (USE_HASHSUM) uint keysum = computeCheckSumI(key); else enum keysum = 0; auto idx = getIndex(m_fields[0 .. m_fieldCount], key, keysum); if (idx >= 0) return &m_fields[idx].tuple[1]; idx = getIndex(m_extendedFields, key, keysum); if (idx >= 0) return &m_extendedFields[idx].tuple[1]; return null; } /// ditto bool opBinaryRight(string op)(string key) inout if(op == "!in") { return !(key in this); } /** Iterates over all fields, including duplicates. */ auto byKeyValue() {return Rng!false(&this, 0); } /// ditto auto byKeyValue() const { return Rng!true(&this, 0); } /// ditto auto byKey() inout { import std.algorithm.iteration : map; return byKeyValue().map!(p => p[0]); } /// ditto auto byValue() inout { import std.algorithm.iteration : map; return byKeyValue().map!(p => p[1]); } /// Deprecated in favor of `.byKeyValue` - enables foreach iteration over a `DictionaryList` with two loop variables. deprecated("Iterate over .byKeyValue instead.") alias byKeyValue this; static if (is(typeof({ const(ValueType) v; ValueType w; w = v; }))) { /** Duplicates the header map. */ @property DictionaryList dup() const { DictionaryList ret; ret.m_fields[0 .. m_fieldCount] = m_fields[0 .. m_fieldCount]; ret.m_fieldCount = m_fieldCount; ret.m_extendedFields = m_extendedFields.dup; return ret; } } private ptrdiff_t getIndex(in Field[] map, string key, uint keysum) const { foreach (i, ref const(Field) entry; map) { static if (USE_HASHSUM) if (entry.keyCheckSum != keysum) continue; if (matches(entry.key, key)) return i; } return -1; } private static bool matches(string a, string b) { static if (case_sensitive) return a == b; else return a.length == b.length && icmp2(a, b) == 0; } // very simple check sum function with a good chance to match // strings with different case equal static if (USE_HASHSUM) private static uint computeCheckSumI(string s) @trusted { uint csum = 0; immutable(char)* pc = s.ptr, pe = s.ptr + s.length; for (; pc != pe; pc++) { static if (case_sensitive) csum ^= *pc; else csum ^= *pc & 0x1101_1111; csum = (csum << 1) | (csum >> 31); } return csum; } private static struct Rng(bool CONST) { @safe nothrow @nogc: static if (CONST) { alias KVT = const(KeyValue); const(DictionaryList)* list; } else { alias KVT = KeyValue; DictionaryList* list; } size_t idx; @property bool empty() const { return idx >= list.length; } @property ref KVT front() { if (idx < list.m_fieldCount) return list.m_fields[idx].tuple; return list.m_extendedFields[idx - list.m_fieldCount].tuple; } void popFront() { idx++; } } } @safe unittest { assert(DictionaryList!(string, true, 2).safeValueCopy); } @safe unittest { DictionaryList!(int, true) a; a.addField("a", 1); a.addField("a", 2); assert(a["a"] == 1); assert(a.getAll("a") == [1, 2]); a["a"] = 3; assert(a["a"] == 3); assert(a.getAll("a") == [3, 2]); a.removeAll("a"); assert(a.getAll("a").length == 0); assert(a.get("a", 4) == 4); a.addField("b", 2); a.addField("b", 1); a.remove("b"); assert(a.getAll("b") == [1]); DictionaryList!(int, false) b; b.addField("a", 1); b.addField("A", 2); assert(b["A"] == 1); assert(b.getAll("a") == [1, 2]); } unittest { import std.variant : Variant; DictionaryList!(Variant) c; c["a"] = true; c["b"] = "Hello"; assert(c.get("a").type == typeid(bool)); assert(c.get!string("b") == "Hello"); assert(c.get!int("c") == int.init); c.addField("d", 9); c.addField("d", "bar"); assert(c.getAll("d") == [ cast(Variant) 9, cast(Variant) "bar" ]); } @safe unittest { import std.conv : text; DictionaryList!int l; l["foo"] = 42; l["bar"] = 43; assert(text(l) == `["foo": 42, "bar": 43]`, text(l)); assert(l.toString() == `["foo": 42, "bar": 43]`, l.toString()); }