Safely encode Strings to ASCII

(Ported @luciferous's changes against 3.10)

Motivation:

The current implementation of the encoder writes each character of the
String as a single byte to the buffer, however not all characters are
mappable to a single byte.

Modifications:

If a character is outside the ASCII range, it's converted to '?'.

Result:

A safer encoder for String to ASCII, which substitutes unmappable
characters with'?'.
This commit is contained in:
Trustin Lee 2015-03-18 15:53:52 +09:00
parent 0fe67cfba5
commit 61859eefa0

View File

@ -252,9 +252,16 @@ public final class HttpHeaderUtil {
static void encodeAscii0(CharSequence seq, ByteBuf buf) { static void encodeAscii0(CharSequence seq, ByteBuf buf) {
int length = seq.length(); int length = seq.length();
for (int i = 0 ; i < length; i++) { for (int i = 0 ; i < length; i++) {
buf.writeByte((byte) seq.charAt(i)); buf.writeByte(c2b(seq.charAt(i)));
} }
} }
private static byte c2b(char c) {
if (c > 255) {
return '?';
}
return (byte) c;
}
private HttpHeaderUtil() { } private HttpHeaderUtil() { }
} }