use of java.nio.ByteOrder in project netty by netty.
the class WebSocket08FrameDecoder method unmask.
private void unmask(ByteBuf frame) {
int i = frame.readerIndex();
int end = frame.writerIndex();
ByteOrder order = frame.order();
// Remark: & 0xFF is necessary because Java will do signed expansion from
// byte to int which we don't want.
int intMask = ((maskingKey[0] & 0xFF) << 24) | ((maskingKey[1] & 0xFF) << 16) | ((maskingKey[2] & 0xFF) << 8) | (maskingKey[3] & 0xFF);
// into the same format, because getInt() and writeInt() will use a reversed byte order
if (order == ByteOrder.LITTLE_ENDIAN) {
intMask = Integer.reverseBytes(intMask);
}
for (; i + 3 < end; i += 4) {
int unmasked = frame.getInt(i) ^ intMask;
frame.setInt(i, unmasked);
}
for (; i < end; i++) {
frame.setByte(i, frame.getByte(i) ^ maskingKey[i % 4]);
}
}
use of java.nio.ByteOrder in project netty by netty.
the class WebSocket08FrameEncoder method encode.
@Override
protected void encode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception {
final ByteBuf data = msg.content();
byte[] mask;
byte opcode;
if (msg instanceof TextWebSocketFrame) {
opcode = OPCODE_TEXT;
} else if (msg instanceof PingWebSocketFrame) {
opcode = OPCODE_PING;
} else if (msg instanceof PongWebSocketFrame) {
opcode = OPCODE_PONG;
} else if (msg instanceof CloseWebSocketFrame) {
opcode = OPCODE_CLOSE;
} else if (msg instanceof BinaryWebSocketFrame) {
opcode = OPCODE_BINARY;
} else if (msg instanceof ContinuationWebSocketFrame) {
opcode = OPCODE_CONT;
} else {
throw new UnsupportedOperationException("Cannot encode frame of type: " + msg.getClass().getName());
}
int length = data.readableBytes();
if (logger.isTraceEnabled()) {
logger.trace("Encoding WebSocket Frame opCode={} length={}", opcode, length);
}
int b0 = 0;
if (msg.isFinalFragment()) {
b0 |= 1 << 7;
}
b0 |= msg.rsv() % 8 << 4;
b0 |= opcode % 128;
if (opcode == OPCODE_PING && length > 125) {
throw new TooLongFrameException("invalid payload for PING (payload length must be <= 125, was " + length);
}
boolean release = true;
ByteBuf buf = null;
try {
int maskLength = maskPayload ? 4 : 0;
if (length <= 125) {
int size = 2 + maskLength;
if (maskPayload || length <= GATHERING_WRITE_THRESHOLD) {
size += length;
}
buf = ctx.alloc().buffer(size);
buf.writeByte(b0);
byte b = (byte) (maskPayload ? 0x80 | (byte) length : (byte) length);
buf.writeByte(b);
} else if (length <= 0xFFFF) {
int size = 4 + maskLength;
if (maskPayload || length <= GATHERING_WRITE_THRESHOLD) {
size += length;
}
buf = ctx.alloc().buffer(size);
buf.writeByte(b0);
buf.writeByte(maskPayload ? 0xFE : 126);
buf.writeByte(length >>> 8 & 0xFF);
buf.writeByte(length & 0xFF);
} else {
int size = 10 + maskLength;
if (maskPayload || length <= GATHERING_WRITE_THRESHOLD) {
size += length;
}
buf = ctx.alloc().buffer(size);
buf.writeByte(b0);
buf.writeByte(maskPayload ? 0xFF : 127);
buf.writeLong(length);
}
// Write payload
if (maskPayload) {
int random = PlatformDependent.threadLocalRandom().nextInt(Integer.MAX_VALUE);
mask = ByteBuffer.allocate(4).putInt(random).array();
buf.writeBytes(mask);
ByteOrder srcOrder = data.order();
ByteOrder dstOrder = buf.order();
int counter = 0;
int i = data.readerIndex();
int end = data.writerIndex();
if (srcOrder == dstOrder) {
// Use the optimized path only when byte orders match
// Remark: & 0xFF is necessary because Java will do signed expansion from
// byte to int which we don't want.
int intMask = ((mask[0] & 0xFF) << 24) | ((mask[1] & 0xFF) << 16) | ((mask[2] & 0xFF) << 8) | (mask[3] & 0xFF);
// into the same format, because getInt() and writeInt() will use a reversed byte order
if (srcOrder == ByteOrder.LITTLE_ENDIAN) {
intMask = Integer.reverseBytes(intMask);
}
for (; i + 3 < end; i += 4) {
int intData = data.getInt(i);
buf.writeInt(intData ^ intMask);
}
}
for (; i < end; i++) {
byte byteData = data.getByte(i);
buf.writeByte(byteData ^ mask[counter++ % 4]);
}
out.add(buf);
} else {
if (buf.writableBytes() >= data.readableBytes()) {
// merge buffers as this is cheaper then a gathering write if the payload is small enough
buf.writeBytes(data);
out.add(buf);
} else {
out.add(buf);
out.add(data.retain());
}
}
release = false;
} finally {
if (release && buf != null) {
buf.release();
}
}
}
use of java.nio.ByteOrder in project netty by netty.
the class ByteBufUtil method firstIndexOf.
/**
* This is using a SWAR (SIMD Within A Register) batch read technique to minimize bound-checks and improve memory
* usage while searching for {@code value}.
*/
static int firstIndexOf(AbstractByteBuf buffer, int fromIndex, int toIndex, byte value) {
fromIndex = Math.max(fromIndex, 0);
if (fromIndex >= toIndex || buffer.capacity() == 0) {
return -1;
}
final int length = toIndex - fromIndex;
buffer.checkIndex(fromIndex, length);
if (!PlatformDependent.isUnaligned()) {
return linearFirstIndexOf(buffer, fromIndex, toIndex, value);
}
assert PlatformDependent.isUnaligned();
int offset = fromIndex;
final int byteCount = length & 7;
if (byteCount > 0) {
final int index = unrolledFirstIndexOf(buffer, fromIndex, byteCount, value);
if (index != -1) {
return index;
}
offset += byteCount;
if (offset == toIndex) {
return -1;
}
}
final int longCount = length >>> 3;
final ByteOrder nativeOrder = ByteOrder.nativeOrder();
final boolean isNative = nativeOrder == buffer.order();
final boolean useLE = nativeOrder == ByteOrder.LITTLE_ENDIAN;
final long pattern = SWARByteSearch.compilePattern(value);
for (int i = 0; i < longCount; i++) {
// use the faster available getLong
final long word = useLE ? buffer._getLongLE(offset) : buffer._getLong(offset);
int index = SWARByteSearch.firstAnyPattern(word, pattern, isNative);
if (index < Long.BYTES) {
return offset + index;
}
offset += Long.BYTES;
}
return -1;
}
use of java.nio.ByteOrder in project netty by netty.
the class Unpooled method copiedBuffer.
/**
* Creates a new buffer whose content is a merged copy of the specified
* {@code buffers}' slices. The new buffer's {@code readerIndex} and
* {@code writerIndex} are {@code 0} and the sum of all buffers'
* {@code remaining} respectively.
*
* @throws IllegalArgumentException
* if the specified buffers' endianness are different from each
* other
*/
public static ByteBuf copiedBuffer(ByteBuffer... buffers) {
switch(buffers.length) {
case 0:
return EMPTY_BUFFER;
case 1:
return copiedBuffer(buffers[0]);
}
// Merge the specified buffers into one buffer.
ByteOrder order = null;
int length = 0;
for (ByteBuffer b : buffers) {
int bLen = b.remaining();
if (bLen <= 0) {
continue;
}
if (Integer.MAX_VALUE - length < bLen) {
throw new IllegalArgumentException("The total length of the specified buffers is too big.");
}
length += bLen;
if (order != null) {
if (!order.equals(b.order())) {
throw new IllegalArgumentException("inconsistent byte order");
}
} else {
order = b.order();
}
}
if (length == 0) {
return EMPTY_BUFFER;
}
byte[] mergedArray = PlatformDependent.allocateUninitializedArray(length);
for (int i = 0, j = 0; i < buffers.length; i++) {
// Duplicate the buffer so we not adjust the position during our get operation.
// See https://github.com/netty/netty/issues/3896
ByteBuffer b = buffers[i].duplicate();
int bLen = b.remaining();
b.get(mergedArray, j, bLen);
j += bLen;
}
return wrappedBuffer(mergedArray).order(order);
}
use of java.nio.ByteOrder in project hazelcast by hazelcast.
the class AbstractDomConfigProcessor method parseSerialization.
@SuppressWarnings({ "checkstyle:cyclomaticcomplexity" })
protected SerializationConfig parseSerialization(final Node node) {
SerializationConfig serializationConfig = new SerializationConfig();
for (Node child : childElements(node)) {
final String name = cleanNodeName(child);
if (matches("portable-version", name)) {
String value = getTextContent(child);
serializationConfig.setPortableVersion(getIntegerValue(name, value));
} else if (matches("check-class-def-errors", name)) {
String value = getTextContent(child);
serializationConfig.setCheckClassDefErrors(getBooleanValue(value));
} else if (matches("use-native-byte-order", name)) {
serializationConfig.setUseNativeByteOrder(getBooleanValue(getTextContent(child)));
} else if (matches("byte-order", name)) {
String value = getTextContent(child);
ByteOrder byteOrder = null;
if (ByteOrder.BIG_ENDIAN.toString().equals(value)) {
byteOrder = ByteOrder.BIG_ENDIAN;
} else if (ByteOrder.LITTLE_ENDIAN.toString().equals(value)) {
byteOrder = ByteOrder.LITTLE_ENDIAN;
}
serializationConfig.setByteOrder(byteOrder != null ? byteOrder : ByteOrder.BIG_ENDIAN);
} else if (matches("enable-compression", name)) {
serializationConfig.setEnableCompression(getBooleanValue(getTextContent(child)));
} else if (matches("enable-shared-object", name)) {
serializationConfig.setEnableSharedObject(getBooleanValue(getTextContent(child)));
} else if (matches("allow-unsafe", name)) {
serializationConfig.setAllowUnsafe(getBooleanValue(getTextContent(child)));
} else if (matches("allow-override-default-serializers", name)) {
serializationConfig.setAllowOverrideDefaultSerializers(getBooleanValue(getTextContent(child)));
} else if (matches("data-serializable-factories", name)) {
fillDataSerializableFactories(child, serializationConfig);
} else if (matches("portable-factories", name)) {
fillPortableFactories(child, serializationConfig);
} else if (matches("serializers", name)) {
fillSerializers(child, serializationConfig);
} else if (matches("java-serialization-filter", name)) {
fillJavaSerializationFilter(child, serializationConfig);
} else if (matches("compact-serialization", name)) {
handleCompactSerialization(child, serializationConfig);
}
}
return serializationConfig;
}
Aggregations