adriacabeza commented on issue #2459:
URL: https://github.com/apache/fory/issues/2459#issuecomment-3184028627

   That would be great. Something like this comes to mind: 
   
   ```java
    public interface MemoryAllocator {
         MemoryBuffer allocate(int initialCapacity);
         MemoryBuffer grow(MemoryBuffer buffer, int newCapacity);
         default boolean supportsInPlaceGrowth() {
             return false;
         }
     }
   ```
   we add it in the `MemoryBuffer` and a method to override the default one 
`MemoryBuffer.setGlobalAllocator(byteBufAllocator);`
   
   so that I could write something based on netty's ByteBuf i.e.: 
   ```java
    public class ByteBufMemoryAllocator implements MemoryAllocator {
         private final ByteBuf targetBuf;
         private final int startIndex;
   
         public ByteBufMemoryAllocator(ByteBuf targetBuf) {
             this.targetBuf = targetBuf;
             this.startIndex = targetBuf.writerIndex();
         }
   
         @Override
         public MemoryBuffer allocate(int initialCapacity) {
             targetBuf.ensureWritable(initialCapacity);
             ByteBuffer bb = targetBuf.nioBuffer(startIndex, initialCapacity);
             return MemoryBuffer.fromByteBuffer(bb);
         }
   
         @Override
         public MemoryBuffer grow(MemoryBuffer buffer, int newCapacity) {
             if (canGrowInPlace(buffer, newCapacity)) {
                 // Expand the ByteBuffer view
                 targetBuf.ensureWritable(newCapacity);
                 ByteBuffer expandedBB = targetBuf.nioBuffer(startIndex, 
newCapacity);
                 return MemoryBuffer.fromByteBuffer(expandedBB);
             } else {
                 // Fallback to heap allocation
                 return MemoryBuffer.newHeapBuffer(newCapacity);
             }
         }
   
         @Override
         public boolean supportsInPlaceGrowth() {
             return true;
         }
   
         private boolean canGrowInPlace(MemoryBuffer buffer, int newCapacity) {
             return !buffer.isOffHeap() &&
                    targetBuf.writableBytes() >= newCapacity &&
                    isContiguousWithTarget(buffer);
         }
     }
   ```
   
   and then use it in my code i.e.
   ```java
    ByteBufMemoryAllocator byteBufAllocator = new ByteBufMemoryAllocator(buf);
    MemoryBuffer.setGlobalAllocator(byteBufAllocator);
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to