Skip to content

Feature/tuple frames #614

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
552 changes: 552 additions & 0 deletions rsocket-core/src/main/java/io/rsocket/buffer/AbstractTupleByteBuf.java

Large diffs are not rendered by default.

78 changes: 78 additions & 0 deletions rsocket-core/src/main/java/io/rsocket/buffer/BufferUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package io.rsocket.buffer;

import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import sun.misc.Unsafe;

abstract class BufferUtil {

private static final Unsafe UNSAFE;

static {
Unsafe unsafe;
try {
final PrivilegedExceptionAction<Unsafe> action =
() -> {
final Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);

return (Unsafe) f.get(null);
};

unsafe = AccessController.doPrivileged(action);
} catch (final Exception ex) {
throw new RuntimeException(ex);
}

UNSAFE = unsafe;
}

private static final long BYTE_BUFFER_ADDRESS_FIELD_OFFSET;

static {
try {
BYTE_BUFFER_ADDRESS_FIELD_OFFSET =
UNSAFE.objectFieldOffset(Buffer.class.getDeclaredField("address"));
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}

/**
* Allocate a new direct {@link ByteBuffer} that is aligned on a given alignment boundary.
*
* @param capacity required for the buffer.
* @param alignment boundary at which the buffer should begin.
* @return a new {@link ByteBuffer} with the required alignment.
* @throws IllegalArgumentException if the alignment is not a power of 2.
*/
static ByteBuffer allocateDirectAligned(final int capacity, final int alignment) {
if (alignment == 0) {
return ByteBuffer.allocateDirect(capacity);
}

if (!isPowerOfTwo(alignment)) {
throw new IllegalArgumentException("Must be a power of 2: alignment=" + alignment);
}

final ByteBuffer buffer = ByteBuffer.allocateDirect(capacity + alignment);

final long address = UNSAFE.getLong(buffer, BYTE_BUFFER_ADDRESS_FIELD_OFFSET);
final int remainder = (int) (address & (alignment - 1));
final int offset = alignment - remainder;

buffer.limit(capacity + offset);
buffer.position(offset);

return buffer.slice();
}

private static boolean isPowerOfTwo(final int value) {
return value > 0 && ((value & (~value + 1)) == value);
}

private BufferUtil() {}
}
Loading