@Override public CompositeByteBuf capacity(int newCapacity) { assert !freed; if (newCapacity < 0 || newCapacity > maxCapacity()) { throw new IllegalArgumentException("newCapacity: " + newCapacity); } int oldCapacity = capacity(); if (newCapacity > oldCapacity) { final int paddingLength = newCapacity - oldCapacity; ByteBuf padding; int nComponents = components.size(); if (nComponents < maxNumComponents) { padding = allocBuffer(paddingLength); padding.setIndex(0, paddingLength); addComponent0(0, padding, true); } else { padding = allocBuffer(paddingLength); padding.setIndex(0, paddingLength); // FIXME: No need to create a padding buffer and consolidate. // Just create a big single buffer and put the current content there. addComponent0(components.size(), padding, true); consolidateIfNeeded(); } } else if (newCapacity < oldCapacity) { int bytesToTrim = oldCapacity - newCapacity; for (ListIterator<Component> i = components.listIterator(components.size()); i.hasPrevious(); ) { Component c = i.previous(); if (bytesToTrim >= c.length) { bytesToTrim -= c.length; i.remove(); continue; } // Replace the last component with the trimmed slice. Component newC = new Component(c.buf.slice(0, c.length - bytesToTrim), c.allocatedBySelf); newC.offset = c.offset; newC.endOffset = newC.offset + newC.length; i.set(newC); break; } if (readerIndex() > newCapacity) { setIndex(newCapacity, newCapacity); } else if (writerIndex() > newCapacity) { writerIndex(newCapacity); } } return this; }
@Override public void capacity(int newCapacity) { if (newCapacity < 0 || newCapacity > maxCapacity()) { throw new IllegalArgumentException("newCapacity: " + newCapacity); } int oldCapacity = capacity(); if (newCapacity > oldCapacity) { final int paddingLength = newCapacity - oldCapacity; ByteBuf padding; if (components.isEmpty()) { padding = new HeapByteBuf(paddingLength, paddingLength); } else { Component last = components.get(components.size() - 1); padding = last.buf.unsafe().newBuffer(paddingLength); } padding.setIndex(0, paddingLength); addComponent(padding); } else if (newCapacity < oldCapacity) { int bytesToTrim = oldCapacity - newCapacity; for (ListIterator<Component> i = components.listIterator(components.size()); i.hasPrevious(); ) { Component c = i.previous(); if (bytesToTrim >= c.length) { bytesToTrim -= c.length; i.remove(); continue; } // Replace the last component with the trimmed slice. Component newC = new Component(c.buf.slice(0, c.length - bytesToTrim)); newC.offset = c.offset; newC.endOffset = newC.offset + newC.length; c.buf.unsafe().release(); i.set(newC); break; } if (readerIndex() > newCapacity) { setIndex(newCapacity, newCapacity); } else if (writerIndex() > newCapacity) { writerIndex(newCapacity); } } }
@Override public ByteBuf setIndex(int readerIndex, int writerIndex) { buf.setIndex(readerIndex, writerIndex); return this; }