if (_freeSegmentCount <= 0) { // no local buffers available yet
if (_usedSegmentsCount >= _maxSegmentsToAllocate) { // except we are maxed out
return false;
}
// if we are, let's try allocate: will be added to "free" segments first, then used
BytesSegment newFree = _segmentAllocator.allocateSegments(1, _firstFreeSegment);
if (newFree == null) {
return false;
}
_freeSegmentCount += 1;
_firstFreeSegment = newFree;
}
// should be set now so:
final BytesSegment seg = _head;
seg.finishWriting();
// and allocate, init-for-writing new one:
BytesSegment newSeg = _reuseFree().initForWriting();
seg.relink(newSeg);
_head = newSeg;
if (!_head.tryAppend(value)) {
throw new IllegalStateException("Should have room for a byte after allocation");
}