1 module jcli.core.pattern;
2 
3 import std;
4 
5 struct Pattern
6 {
7     static struct Result
8     {
9         bool matched;
10         string pattern;
11     }
12 
13     private string _pattern;
14 
15     @safe @nogc
16     this(string pattern) nothrow pure
17     {
18         this._pattern = pattern;
19     }
20 
21     @safe /*@nogc*/
22     auto patterns() /*nothrow*/ pure inout
23     {
24         return this._pattern.splitter('|');
25     }
26     ///
27     unittest
28     {
29         auto p = Pattern("a|bc|one|two three");
30         assert(p.patterns.equal([
31             "a",
32             "bc",
33             "one",
34             "two three"
35         ]));
36     }
37 
38     @safe /*@nogc*/
39     inout(Result) match(string input, bool insensitive = false) /*nothrow*/ pure inout
40     {
41         Result r;
42         foreach(pattern; this.patterns)
43         {
44             import std.uni : toLower;
45             if(
46                 (!insensitive && pattern == input)
47                 || (insensitive && pattern.equal(input.map!toLower.map!(ch => cast(char)ch)))
48             )
49             {
50                 r = Result(true, pattern);
51                 break;
52             }
53         }
54         return r;
55     }
56     ///
57     unittest
58     {
59         auto p = Pattern("a|bc|one|two three");
60         assert(p.match("a")         == Result(true, "a"));
61         assert(p.match("one")       == Result(true, "one"));
62         assert(p.match("two three") == Result(true, "two three"));
63         assert(p.match("cb")        == Result(false, null));
64     }
65 
66     @safe @nogc
67     string pattern() nothrow pure const
68     {
69         return this._pattern;
70     }
71 }