public static Slice copiedBuffer(ByteBuffer source) { Preconditions.checkNotNull(source, "source is null"); Slice copy = allocate(source.limit() - source.position()); copy.setBytes(0, source.duplicate().order(ByteOrder.LITTLE_ENDIAN)); return copy; }
public static Slice copiedBuffer(ByteBuffer source, int sourceOffset, int length) { Preconditions.checkNotNull(source, "source is null"); int newPosition = source.position() + sourceOffset; return copiedBuffer((ByteBuffer) source.duplicate().order(ByteOrder.LITTLE_ENDIAN).clear() .limit(newPosition + length).position(newPosition)); }
/** * Decodes this buffer's sub-region into a string with the specified * character set. */ public String toString(int index, int length, Charset charset) { if (length == 0) { return ""; } return Slices.decodeString(toByteBuffer(index, length), charset); }
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; }
public static String decodeString(ByteBuffer src, Charset charset) { final CharsetDecoder decoder = getDecoder(charset); final CharBuffer dst = CharBuffer.allocate( (int) ((double) src.remaining() * decoder.maxCharsPerByte())); 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); } return dst.flip().toString(); }
public static Slice copiedBuffer(String string, Charset charset) { Preconditions.checkNotNull(string, "string is null"); Preconditions.checkNotNull(charset, "charset is null"); return wrappedBuffer(string.getBytes(charset)); }
public static Slice ensureSize(Slice existingSlice, int minWritableBytes) { if (existingSlice == null) { existingSlice = EMPTY_SLICE; } if (minWritableBytes <= existingSlice.length()) { return existingSlice; } int newCapacity; if (existingSlice.length() == 0) { newCapacity = 1; } else { newCapacity = existingSlice.length(); } int minNewCapacity = existingSlice.length() + minWritableBytes; while (newCapacity < minNewCapacity) { newCapacity <<= 1; } Slice newSlice = Slices.allocate(newCapacity); newSlice.setBytes(0, existingSlice, 0, existingSlice.length()); return newSlice; }