|
| 1 | +package io.rsocket.buffer; |
| 2 | + |
| 3 | +import java.lang.reflect.Field; |
| 4 | +import java.nio.Buffer; |
| 5 | +import java.nio.ByteBuffer; |
| 6 | +import java.security.AccessController; |
| 7 | +import java.security.PrivilegedExceptionAction; |
| 8 | +import sun.misc.Unsafe; |
| 9 | + |
| 10 | +abstract class BufferUtil { |
| 11 | + |
| 12 | + private static final Unsafe UNSAFE; |
| 13 | + |
| 14 | + static { |
| 15 | + Unsafe unsafe; |
| 16 | + try { |
| 17 | + final PrivilegedExceptionAction<Unsafe> action = |
| 18 | + () -> { |
| 19 | + final Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
| 20 | + f.setAccessible(true); |
| 21 | + |
| 22 | + return (Unsafe) f.get(null); |
| 23 | + }; |
| 24 | + |
| 25 | + unsafe = AccessController.doPrivileged(action); |
| 26 | + } catch (final Exception ex) { |
| 27 | + throw new RuntimeException(ex); |
| 28 | + } |
| 29 | + |
| 30 | + UNSAFE = unsafe; |
| 31 | + } |
| 32 | + |
| 33 | + private static final long BYTE_BUFFER_ADDRESS_FIELD_OFFSET; |
| 34 | + |
| 35 | + static { |
| 36 | + try { |
| 37 | + BYTE_BUFFER_ADDRESS_FIELD_OFFSET = |
| 38 | + UNSAFE.objectFieldOffset(Buffer.class.getDeclaredField("address")); |
| 39 | + } catch (final Exception ex) { |
| 40 | + throw new RuntimeException(ex); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Allocate a new direct {@link ByteBuffer} that is aligned on a given alignment boundary. |
| 46 | + * |
| 47 | + * @param capacity required for the buffer. |
| 48 | + * @param alignment boundary at which the buffer should begin. |
| 49 | + * @return a new {@link ByteBuffer} with the required alignment. |
| 50 | + * @throws IllegalArgumentException if the alignment is not a power of 2. |
| 51 | + */ |
| 52 | + static ByteBuffer allocateDirectAligned(final int capacity, final int alignment) { |
| 53 | + if (alignment == 0) { |
| 54 | + return ByteBuffer.allocateDirect(capacity); |
| 55 | + } |
| 56 | + |
| 57 | + if (!isPowerOfTwo(alignment)) { |
| 58 | + throw new IllegalArgumentException("Must be a power of 2: alignment=" + alignment); |
| 59 | + } |
| 60 | + |
| 61 | + final ByteBuffer buffer = ByteBuffer.allocateDirect(capacity + alignment); |
| 62 | + |
| 63 | + final long address = UNSAFE.getLong(buffer, BYTE_BUFFER_ADDRESS_FIELD_OFFSET); |
| 64 | + final int remainder = (int) (address & (alignment - 1)); |
| 65 | + final int offset = alignment - remainder; |
| 66 | + |
| 67 | + buffer.limit(capacity + offset); |
| 68 | + buffer.position(offset); |
| 69 | + |
| 70 | + return buffer.slice(); |
| 71 | + } |
| 72 | + |
| 73 | + private static boolean isPowerOfTwo(final int value) { |
| 74 | + return value > 0 && ((value & (~value + 1)) == value); |
| 75 | + } |
| 76 | + |
| 77 | + private BufferUtil() {} |
| 78 | +} |
0 commit comments