-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtility.cs
97 lines (92 loc) · 3.32 KB
/
Utility.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HTMLBuilder
{
public static class Extensions
{
public static string RemoveFirst(this string str, string other)
{
int index = str.IndexOf(other);
return (index < 0) ? str : str.Remove(index, other.Length);
}
}
public static class Parse
{
public static T Flags<T>(string? input, out List<string> failed) where T : Enum
{
int result = 0;
failed = new();
if (input == null || input == string.Empty) return (T)(object)result;
string[] flags = input.Split("", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
foreach (string flag in flags)
{
try
{
result |= (int)Enum.Parse(typeof(T), flag, true);
}
catch (ArgumentException)
{
failed.Add(flag);
}
}
return (T)(object)result;
}
public static T Flags<T>(Arguments.Argument[] args, int startIndex) where T : Enum
{
int result = 0;
for (int i = startIndex; i < args.Length; i++)
{
if (!args[i].IsOption) throw new ArgumentException($"Unexpected token '{args[i].Value}'. Expected reference options.");
try
{
result |= (int)Enum.Parse(typeof(T), args[i].Value, true);
}
catch (ArgumentException)
{
throw new ArgumentException($"ERROR: Unknown reference option '{args[i].Value}'.");
}
}
return (T)(object)result;
}
public static V Key<T, V>(Dictionary<T, V> map, T? key, string errorMessage) where T : notnull
{
if (key == null) throw new ArgumentException(errorMessage);
if (map.TryGetValue(key, out V? value))
{
return value;
}
throw new ArgumentException(errorMessage);
}
}
public static class Validate
{
public static T Value<T>(T? value, string errorMessage)
{
if (value == null) throw new ArgumentException(errorMessage);
return value;
}
public static T Key<T, V>(Dictionary<T,V> map, T? key, string errorMessage) where T : notnull
{
if (key == null) throw new ArgumentException(errorMessage);
if (!map.ContainsKey(key)) throw new ArgumentException(errorMessage);
return key;
}
public static T Key<T>(HashSet<T> map, T? key, string errorMessage)
{
if (key == null) throw new ArgumentException(errorMessage);
if (!map.Contains(key)) throw new ArgumentException(errorMessage);
return key;
}
public static T Key<T, V>(Dictionary<T,V> map, T? key, Func<T?, string> errorGetter) where T : notnull
{
return Key(map, key, errorGetter(key));
}
public static T Key<T>(HashSet<T> map, T? key, Func<T?, string> errorGetter) where T : notnull
{
return Key(map, key, errorGetter(key));
}
}
}