Search in sources :

Example 16 with CoderResult

use of java.nio.charset.CoderResult in project hs4j by killme2008.

the class AbstractIoBuffer method putPrefixedString.

/**
     * {@inheritDoc}
     */
@Override
public IoBuffer putPrefixedString(CharSequence val, int prefixLength, int padding, byte padValue, CharsetEncoder encoder) throws CharacterCodingException {
    int maxLength;
    switch(prefixLength) {
        case 1:
            maxLength = 255;
            break;
        case 2:
            maxLength = 65535;
            break;
        case 4:
            maxLength = Integer.MAX_VALUE;
            break;
        default:
            throw new IllegalArgumentException("prefixLength: " + prefixLength);
    }
    if (val.length() > maxLength) {
        throw new IllegalArgumentException("The specified string is too long.");
    }
    if (val.length() == 0) {
        switch(prefixLength) {
            case 1:
                put((byte) 0);
                break;
            case 2:
                putShort((short) 0);
                break;
            case 4:
                putInt(0);
                break;
        }
        return this;
    }
    int padMask;
    switch(padding) {
        case 0:
        case 1:
            padMask = 0;
            break;
        case 2:
            padMask = 1;
            break;
        case 4:
            padMask = 3;
            break;
        default:
            throw new IllegalArgumentException("padding: " + padding);
    }
    CharBuffer in = CharBuffer.wrap(val);
    // make a room for the length field
    skip(prefixLength);
    int oldPos = position();
    encoder.reset();
    int expandedState = 0;
    for (; ; ) {
        CoderResult cr;
        if (in.hasRemaining()) {
            cr = encoder.encode(in, buf(), true);
        } else {
            cr = encoder.flush(buf());
        }
        if (position() - oldPos > maxLength) {
            throw new IllegalArgumentException("The specified string is too long.");
        }
        if (cr.isUnderflow()) {
            break;
        }
        if (cr.isOverflow()) {
            if (isAutoExpand()) {
                switch(expandedState) {
                    case 0:
                        autoExpand((int) Math.ceil(in.remaining() * encoder.averageBytesPerChar()));
                        expandedState++;
                        break;
                    case 1:
                        autoExpand((int) Math.ceil(in.remaining() * encoder.maxBytesPerChar()));
                        expandedState++;
                        break;
                    default:
                        throw new RuntimeException("Expanded by " + (int) Math.ceil(in.remaining() * encoder.maxBytesPerChar()) + " but that wasn't enough for '" + val + "'");
                }
                continue;
            }
        } else {
            expandedState = 0;
        }
        cr.throwException();
    }
    // Write the length field
    fill(padValue, padding - (position() - oldPos & padMask));
    int length = position() - oldPos;
    switch(prefixLength) {
        case 1:
            put(oldPos - 1, (byte) length);
            break;
        case 2:
            putShort(oldPos - 2, (short) length);
            break;
        case 4:
            putInt(oldPos - 4, length);
            break;
    }
    return this;
}
Also used : CharBuffer(java.nio.CharBuffer) CoderResult(java.nio.charset.CoderResult)

Example 17 with CoderResult

use of java.nio.charset.CoderResult in project hs4j by killme2008.

the class AbstractIoBuffer method getPrefixedString.

/**
     * Reads a string which has a length field before the actual encoded string,
     * using the specified <code>decoder</code> and returns it.
     * 
     * @param prefixLength
     *            the length of the length field (1, 2, or 4)
     * @param decoder
     *            the decoder to use for decoding the string
     * @return the prefixed string
     * @throws CharacterCodingException
     *             when decoding fails
     * @throws BufferUnderflowException
     *             when there is not enough data available
     */
@Override
public String getPrefixedString(int prefixLength, CharsetDecoder decoder) throws CharacterCodingException {
    if (!prefixedDataAvailable(prefixLength)) {
        throw new BufferUnderflowException();
    }
    int fieldSize = 0;
    switch(prefixLength) {
        case 1:
            fieldSize = getUnsigned();
            break;
        case 2:
            fieldSize = getUnsignedShort();
            break;
        case 4:
            fieldSize = getInt();
            break;
    }
    if (fieldSize == 0) {
        return "";
    }
    boolean utf16 = decoder.charset().name().startsWith("UTF-16");
    if (utf16 && (fieldSize & 1) != 0) {
        throw new BufferDataException("fieldSize is not even for a UTF-16 string.");
    }
    int oldLimit = limit();
    int end = position() + fieldSize;
    if (oldLimit < end) {
        throw new BufferUnderflowException();
    }
    limit(end);
    decoder.reset();
    int expectedLength = (int) (remaining() * decoder.averageCharsPerByte()) + 1;
    CharBuffer out = CharBuffer.allocate(expectedLength);
    for (; ; ) {
        CoderResult cr;
        if (hasRemaining()) {
            cr = decoder.decode(buf(), out, true);
        } else {
            cr = decoder.flush(out);
        }
        if (cr.isUnderflow()) {
            break;
        }
        if (cr.isOverflow()) {
            CharBuffer o = CharBuffer.allocate(out.capacity() + expectedLength);
            out.flip();
            o.put(out);
            out = o;
            continue;
        }
        cr.throwException();
    }
    limit(oldLimit);
    position(end);
    return out.flip().toString();
}
Also used : CharBuffer(java.nio.CharBuffer) BufferUnderflowException(java.nio.BufferUnderflowException) CoderResult(java.nio.charset.CoderResult)

Example 18 with CoderResult

use of java.nio.charset.CoderResult in project rest.li by linkedin.

the class BufferChain method putUtf8CString.

/**
   * Put string into buffer chain as UTF-8 encoded null-terminated string.
   *
   * @param value provides the string to put.
   * @return {@code this}.
   */
public BufferChain putUtf8CString(String value) throws CharacterCodingException {
    reserve(value.length() * 4);
    _encoder.reset();
    CoderResult result = _encoder.encode(CharBuffer.wrap(value), _currentBuffer, true);
    if (result.isError()) {
        result.throwException();
    }
    _encoder.flush(_currentBuffer);
    put(ZERO_BYTE);
    return this;
}
Also used : CoderResult(java.nio.charset.CoderResult)

Example 19 with CoderResult

use of java.nio.charset.CoderResult in project netty by netty.

the class ByteBufUtil method decodeString.

private static void decodeString(CharsetDecoder decoder, ByteBuffer src, CharBuffer dst) {
    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = decoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
}
Also used : CharacterCodingException(java.nio.charset.CharacterCodingException) CoderResult(java.nio.charset.CoderResult)

Example 20 with CoderResult

use of java.nio.charset.CoderResult in project sessdb by ppdai.

the class Slices method encodeString.

public static ByteBuffer encodeString(CharBuffer src, Charset charset) {
    final CharsetEncoder encoder = getEncoder(charset);
    final ByteBuffer dst = ByteBuffer.allocate((int) ((double) src.remaining() * encoder.maxBytesPerChar()));
    try {
        CoderResult cr = encoder.encode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = encoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    dst.flip();
    return dst;
}
Also used : CharacterCodingException(java.nio.charset.CharacterCodingException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer) CoderResult(java.nio.charset.CoderResult)

Aggregations

CoderResult (java.nio.charset.CoderResult)123 CharBuffer (java.nio.CharBuffer)81 ByteBuffer (java.nio.ByteBuffer)35 IOException (java.io.IOException)25 CharsetDecoder (java.nio.charset.CharsetDecoder)25 Charset (java.nio.charset.Charset)15 CharacterCodingException (java.nio.charset.CharacterCodingException)13 CharsetEncoder (java.nio.charset.CharsetEncoder)13 BufferUnderflowException (java.nio.BufferUnderflowException)3 BufferOverflowException (java.nio.BufferOverflowException)2 CloseReason (javax.websocket.CloseReason)2 ArrayDecoder (sun.nio.cs.ArrayDecoder)2 ArrayEncoder (sun.nio.cs.ArrayEncoder)2 JSONException (com.alibaba.fastjson.JSONException)1 SimpleDiagnosticPosition (com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition)1 ParseException (io.druid.java.util.common.parsers.ParseException)1 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)1 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 Cipher (javax.crypto.Cipher)1