1 module serialport.util;
2 
3 import std.range;
4 import std.algorithm;
5 
6 package bool hasFlag(A,B)(A a, B b) @property { return (a & b) == b; }
7 
8 struct Pair(A,B) { A a; B b; }
9 auto pair(A,B)(A a, B b) { return Pair!(A,B)(a, b); }
10 
11 struct PairList(A,B)
12 {
13     Pair!(A,B)[] list;
14     this(Pair!(A,B)[] list) { this.list = list.dup; }
15 
16     @safe pure @nogc nothrow const
17     {
18         size_t countA(A a) { return list.map!(a=>a.a).count(a); }
19         size_t countB(B b) { return list.map!(a=>a.b).count(b); }
20 
21         bool isUniqA() @property { return list.all!(v=>countA(v.a) == 1); }
22         bool isUniqB() @property { return list.all!(v=>countB(v.b) == 1); }
23 
24         B firstA2B(A a, B defalutValue)
25         {
26             auto f = list.find!(v=>v.a == a);
27             if (f.empty) return defalutValue;
28             else return f.front.b;
29         }
30 
31         A firstB2A(B b, A defalutValue)
32         {
33             auto f = list.find!(v=>v.b == b);
34             if (f.empty) return defalutValue;
35             else return f.front.a;
36         }
37     }
38 
39     @safe pure nothrow const
40     {
41         auto allA2B(A a) { return list.filter!(v=>v.a == a).map!(v=>v.b); }
42         auto allB2A(B b) { return list.filter!(v=>v.b == b).map!(v=>v.a); }
43     }
44 }
45 
46 auto pairList(A,B)(Pair!(A,B)[] list...) { return PairList!(A,B)(list); }
47 
48 unittest
49 {
50     auto pl = pairList(
51         pair(1, "hello"),
52         pair(1, "ololo"),
53         pair(2, "world"),
54         pair(3, "okda")
55     );
56 
57     assert(pl.countA(1) == 2);
58     assert(pl.firstA2B(1, "ok") == "hello");
59     assert(pl.countB("ok") == 0);
60     assert(pl.countB("okda") == 1);
61     assert(pl.firstB2A("okda", 0) == 3);
62     assert(pl.isUniqA == false);
63     assert(pl.isUniqB == true);
64 }
65 
66 unittest
67 {
68     static immutable pl = pairList(
69         pair(1, "hello"),
70         pair(2, "world"),
71         pair(3, "okda")
72     );
73 
74     static assert(pl.firstA2B(2, "ok") == "world");
75 }
76 
77 unittest
78 {
79     import std.algorithm;
80     import std.string;
81 
82     immutable pl = pairList(
83         pair(1, "hello"),
84         pair(2, "okda"),
85         pair(1, "world"),
86         pair(3, "okda")
87     );
88 
89     assert(pl.allA2B(1).join(" ") == "hello world");
90     assert(pl.allB2A("okda").sum == 5);
91 }