public IByteBuffer Cumulate(IByteBufferAllocator alloc, IByteBuffer cumulation, IByteBuffer input) { if (!cumulation.IsReadable()) { _ = cumulation.Release(); return(input); } CompositeByteBuffer composite = null; try { composite = cumulation as CompositeByteBuffer; if (composite is object && 0u >= (uint)(cumulation.ReferenceCount - 1)) { // Writer index must equal capacity if we are going to "write" // new components to the end if (composite.WriterIndex != composite.Capacity) { _ = composite.AdjustCapacity(composite.WriterIndex); } } else { composite = alloc.CompositeBuffer(int.MaxValue).AddFlattenedComponents(true, cumulation); } _ = composite.AddFlattenedComponents(true, input); input = null; return(composite); } finally { if (input is object) { // We must release if the ownership was not transferred as otherwise it may produce a leak _ = input.Release(); // Also release any new buffer allocated if we're not returning it if (composite is object && composite != cumulation) { _ = composite.Release(); } } } }