/
ColorNameSerializer.java
51 lines (44 loc) · 1.92 KB
/
ColorNameSerializer.java
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
package mezz.jei.library.config.serializers;
import mezz.jei.library.color.ColorName;
import mezz.jei.core.config.file.serializers.DeserializeResult;
import mezz.jei.core.config.file.serializers.IConfigValueSerializer;
import org.apache.commons.lang3.StringUtils;
import java.util.Locale;
public class ColorNameSerializer implements IConfigValueSerializer<ColorName> {
public static final ColorNameSerializer INSTANCE = new ColorNameSerializer();
private ColorNameSerializer() {}
@Override
public String serialize(ColorName value) {
String name = value.name();
String color = Integer.toHexString(value.color()).toUpperCase(Locale.ROOT);
return "%s:%s".formatted(name, StringUtils.leftPad(color, 6, '0'));
}
@Override
public DeserializeResult<ColorName> deserialize(String string) {
string = string.trim();
if (string.startsWith("\"") && string.endsWith("\"")) {
string = string.substring(1, string.length() - 1);
}
String[] values = string.split(":");
if (values.length == 2) {
String name = values[0];
try {
Integer color = Integer.decode("0x" + values[1]);
ColorName colorName = new ColorName(name, color);
return new DeserializeResult<>(colorName);
} catch (NumberFormatException e) {
String errorMsg = """
Color entry must have an RGB hex color.
Got an exception when parsing:
%s""".formatted(e.getMessage());
return new DeserializeResult<>(null, errorMsg);
}
}
String errorMsg = "Color entry must be a name and an RGB hex color, separated by a ':'.";
return new DeserializeResult<>(null, errorMsg);
}
@Override
public String getValidValuesDescription() {
return "Any color name and an RGB hex color, separated by a ':'";
}
}