1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix;
19
20 import java.io.Serializable;
21 import java.util.HashSet;
22 import java.util.Objects;
23 import java.util.Set;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27
28
29
30
31
32
33
34
35 @NonNullByDefault
36 public class NamedInteger implements Serializable {
37 private static final long serialVersionUID = 1L;
38
39
40
41
42 private final String name;
43
44
45
46
47 private final int id;
48
49
50
51
52
53 public interface HasOfValue {
54
55 }
56
57
58
59
60
61
62
63 protected NamedInteger(int id) {
64 this("UNDEFINED", id);
65 }
66
67
68
69
70
71
72
73 protected NamedInteger(String name, int id) {
74 this.name = name;
75 this.id = id;
76 }
77
78
79
80
81
82
83 public final String name() {
84 return name;
85 }
86
87
88
89
90
91
92 public final int value() {
93 return id;
94 }
95
96 @Override
97 public final String toString() {
98 return name() + "(" + id + ")";
99 }
100
101 @Override
102 public final int hashCode() {
103 return Objects.hash(id);
104 }
105
106 @Override
107 public final boolean equals(@Nullable Object obj) {
108 if (this == obj) {
109 return true;
110 } else if (obj == null) {
111 return false;
112 } else if (getClass() != obj.getClass()) {
113 return false;
114 }
115 NamedInteger other = (NamedInteger) obj;
116 return id == other.value();
117 }
118
119
120
121
122
123
124
125
126 protected static final <T extends NamedInteger> T[] init(T[] values) {
127 Set<Integer> seenValues = new HashSet<>();
128 for (T val : values) {
129 if (!seenValues.add(val.value())) {
130 throw new IllegalStateException("Duplicate value: " + val.value());
131 }
132 }
133 return values;
134 }
135
136
137
138
139
140
141 @FunctionalInterface
142 protected interface UndefinedValueConstructor<T extends NamedInteger> {
143
144
145
146
147
148
149 T newInstance(int id);
150 }
151
152
153
154
155
156
157
158
159
160
161 protected static final <T extends NamedInteger> T ofValue(T[] values,
162 UndefinedValueConstructor<T> constr, int v) {
163 for (T e : values) {
164 if (e.value() == v) {
165 return e;
166 }
167 }
168 return constr.newInstance(v);
169 }
170 }