-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMultiBool.cs
More file actions
111 lines (94 loc) · 2.27 KB
/
MultiBool.cs
File metadata and controls
111 lines (94 loc) · 2.27 KB
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
public struct MultiBool {
private int count;
private bool hasMin;
private bool hasMax;
private int max;
private int min;
private bool defaultValue;
public MultiBool(bool defaultValue) : this(defaultValue, false, 0, false, 0) {}
public MultiBool(bool defaultValue, bool hasMin, int min, bool hasMax, int max) {
count = 0;
this.defaultValue = defaultValue;
this.hasMin = hasMin;
this.min = min;
this.hasMax = hasMax;
this.max = max;
}
public static MultiBool WithMin(int min) => WithMin(min, true);
public static MultiBool WithMin(int min, bool defaultValue) {
MultiBool b = new MultiBool(defaultValue);
b.hasMin = true;
b.min = min;
return b;
}
public static MultiBool WithMax(int max) => WithMax(max, true);
public static MultiBool WithMax(int max, bool defaultValue) {
MultiBool b = new MultiBool(defaultValue);
b.hasMax = true;
b.max = max;
return b;
}
public static MultiBool WithMinAndMax(int min, int max) => WithMinAndMax(min, max, true);
public static MultiBool WithMinAndMax(int min, int max, bool defaultValue) {
MultiBool b = new MultiBool(defaultValue);
b.hasMin = true;
b.hasMax = true;
if (min <= max) {
b.min = min;
b.max = max;
} else {
b.min = max;
b.max = min;
}
return b;
}
public void Set(int amount) {
count = amount;
ClampCount();
}
public void Reset() {
count = 0;
ClampCount();
}
public void AddTrue() {
count++;
ClampCount();
}
public void AddFalse() {
count--;
ClampCount();
}
public void Add(bool value) {
Add(value ? 1 : -1);
}
public void Add(int amount) {
count += amount;
ClampCount();
}
private void ClampCount() {
if (hasMin && count < min)
count = min;
else if (hasMax && count > max)
count = max;
}
public static implicit operator bool(MultiBool b) => b.count > 0 || b.defaultValue && b.count == 0;
public static implicit operator MultiBool(bool b) => new MultiBool(b);
public static MultiBool operator ++(MultiBool b) {
b.AddTrue();
return b;
}
public static MultiBool operator --(MultiBool b) {
b.AddFalse();
return b;
}
public override string ToString() {
int value = count;
if (value >= 0 && defaultValue)
value++;
else if (value <= 0 && !defaultValue) {
value--;
value *= -1;
}
return $"{(bool)this} ({value})";
}
}