Skip to content

Commit

Permalink
text-serializer-legacy: Properly passthrough invalid RGB codes
Browse files Browse the repository at this point in the history
  • Loading branch information
zml2008 committed Apr 14, 2021
1 parent 79bc38a commit d9b6f63
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
Expand Up @@ -155,20 +155,34 @@ final class LegacyComponentSerializerImpl implements LegacyComponentSerializer {
return null;
}
if(foundFormat == FormatCodeType.KYORI_HEX) {
return new DecodedFormat(foundFormat, TextColor.fromHexString('#' + input.substring(pos, pos + 6)));
final @Nullable TextColor parsed = tryParseHexColor(input.substring(pos, pos + 6));
if(parsed != null) {
return new DecodedFormat(foundFormat, parsed);
}
} else if(foundFormat == FormatCodeType.MOJANG_LEGACY) {
return new DecodedFormat(foundFormat, FORMATS.get(LEGACY_CHARS.indexOf(legacy)));
} else if(foundFormat == FormatCodeType.BUNGEECORD_UNUSUAL_HEX) {
final StringBuilder foundHex = new StringBuilder();
final StringBuilder foundHex = new StringBuilder(6);
for(int i = pos - 1; i >= pos - 11; i -= 2) {
foundHex.append(input.charAt(i));
}
foundHex.append('#');
return new DecodedFormat(foundFormat, TextColor.fromHexString(foundHex.reverse().toString()));
final @Nullable TextColor parsed = tryParseHexColor(foundHex.reverse().toString());
if(parsed != null) {
return new DecodedFormat(foundFormat, parsed);
}
}
return null;
}

private static @Nullable TextColor tryParseHexColor(final String hexDigits) {
try {
final int color = Integer.parseInt(hexDigits, 16);
return TextColor.color(color);
} catch(final NumberFormatException ex) {
return null;
}
}

private static boolean isHexTextColor(final TextFormat format) {
return format instanceof TextColor && !(format instanceof NamedTextColor);
}
Expand Down
Expand Up @@ -310,4 +310,12 @@ void testNoRedundantReset() {
final String roundtripped = LegacyComponentSerializer.legacyAmpersand().serialize(deserialized);
assertEquals(text, roundtripped);
}

@Test
void testInvalidHexStringsPassedThrough() {
final String text = "Hello&#hellos world";
final Component deserialized = LegacyComponentSerializer.legacyAmpersand().deserialize(text);

assertEquals(Component.text(text), deserialized);
}
}

0 comments on commit d9b6f63

Please sign in to comment.