I want to manage a chunk of memory through a buddy memory allocator system that I write. I can use use unsafe to allocate a chunk of memory and manage it using my algorithm. I need to provide a ByteBuffer interface to these chunks so that java NIO can use them for networking code. I am not sure how I can do this without actually implementing every single function of the ByteBuffer interface on top of the unsafe chunk. This seems like an overkill.
One option I can think of is maybe using reflection to get hold of a byte buffer object and alter it’s private capacity and memory address fields and also mark it as direct so that I could just piggyback off the existing implementation. Somehow this seems like it wouldn’t work.
I also thought of using a big direct ByteBuffer and then represent chunks from it as slices with their position and capacity fields changed. That also seems like it wouldn’t work because operations like rewind would just set the position back to zero.
Is there a better way? Maybe I’ll just have to implement the entire interface.
What is the general way to implement the ByteBuffer interface?
For any one curious, I ended up using a single direct byte buffer to get the initial chunk of memory. To represent smaller chunks within it, I duplicated it and used reflection to change the capacity and address fields. This way I could just use the existing direct byte buffer implementation.