| 1 | package net.minecraft.network;
|
| 2 |
|
| 3 | import io.netty.buffer.ByteBuf;
|
| 4 | import io.netty.buffer.ByteBufUtil;
|
| 5 | import io.netty.handler.codec.DecoderException;
|
| 6 | import io.netty.handler.codec.EncoderException;
|
| 7 | import java.nio.charset.StandardCharsets;
|
| 8 |
|
| 9 | public class Utf8String {
|
| 10 | public static String read(final ByteBuf input, final int maxLength) {
|
| 11 | int maxEncodedLength = ByteBufUtil.utf8MaxBytes(maxLength);
|
| 12 | int bufferLength = VarInt.read(input);
|
| 13 | if (bufferLength > maxEncodedLength) {
|
| 14 | throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + bufferLength + " > " + maxEncodedLength + ")");
|
| 15 | } else if (bufferLength < 0) {
|
| 16 | throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!");
|
| 17 | } else {
|
| 18 | int availableBytes = input.readableBytes();
|
| 19 | if (bufferLength > availableBytes) {
|
| 20 | throw new DecoderException("Not enough bytes in buffer, expected " + bufferLength + ", but got " + availableBytes);
|
| 21 | } else {
|
| 22 | String result = input.toString(input.readerIndex(), bufferLength, StandardCharsets.UTF_8);
|
| 23 | input.readerIndex(input.readerIndex() + bufferLength);
|
| 24 | if (result.length() > maxLength) {
|
| 25 | throw new DecoderException("The received string length is longer than maximum allowed (" + result.length() + " > " + maxLength + ")");
|
| 26 | } else {
|
| 27 | return result;
|
| 28 | }
|
| 29 | }
|
| 30 | }
|
| 31 | }
|
| 32 |
|
| 33 | public static void write(final ByteBuf output, final CharSequence value, final int maxLength) {
|
| 34 | if (value.length() > maxLength) {
|
| 35 | throw new EncoderException("String too big (was " + value.length() + " characters, max " + maxLength + ")");
|
| 36 | }
|
| 37 |
|
| 38 | int maxEncodedValueLength = ByteBufUtil.utf8MaxBytes(value);
|
| 39 | ByteBuf tmp = output.alloc().buffer(maxEncodedValueLength);
|
| 40 |
|
| 41 | try {
|
| 42 | int bytesWritten = ByteBufUtil.writeUtf8(tmp, value);
|
| 43 | int maxAllowedEncodedLength = ByteBufUtil.utf8MaxBytes(maxLength);
|
| 44 | if (bytesWritten > maxAllowedEncodedLength) {
|
| 45 | throw new EncoderException("String too big (was " + bytesWritten + " bytes encoded, max " + maxAllowedEncodedLength + ")");
|
| 46 | }
|
| 47 |
|
| 48 | VarInt.write(output, bytesWritten);
|
| 49 | output.writeBytes(tmp);
|
| 50 | } finally {
|
| 51 | tmp.release();
|
| 52 | }
|
| 53 | }
|
| 54 | }
|
| 55 |
|