Skip to content

Commit

Permalink
Handle buffer overflows
Browse files Browse the repository at this point in the history
  • Loading branch information
sgammon committed Nov 13, 2019
1 parent 8a82029 commit 613e267
Showing 1 changed file with 21 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -158,26 +158,34 @@ ByteBuf exportChunk(int maxBytes) {
return buffer.readSlice(Math.min(maxBytes, availableBytes)).asReadOnly().retain();
}

private void ensureChunkSize(int size) {
if (chunk.capacity() > (chunk.writerIndex() + size)) {
// we need to allocate a new chunk real fast
buffer.addComponent(true, chunk);
chunk = allocateChunk();
} else {
chunk.ensureWritable(size);
}
}

// -- Incoming Data -- //

@Override
public AdvisingAppendable append(CharSequence charSequence) {
int size = charSequence.length();
ensureChunkSize(size);
int available = (chunk.capacity() - chunk.writerIndex() - 1);
int balance = available - size;
if (balance < 0) {
// there is not enough space for the whole write to fit, but perhaps a partial
// write can be performed
CharSequence subSequence = charSequence.subSequence(0, available);
charSequence = charSequence.subSequence(available + 1, Math.abs(balance));
chunk.writeCharSequence(subSequence, charset);

if (LOG.isTraceEnabled()) {
LOG.trace("Appended partial char seq of size = " + subSequence.length() +
" (c: " + chunk.writerIndex() + ", b: " + buffer.writerIndex() + ")");
}
return this.append(charSequence);
}

// we can write it, there is either enough space or we made enough space
chunk.ensureWritable(size);
chunk.writeCharSequence(charSequence, charset);

if (LOG.isTraceEnabled()) {
LOG.trace("Appended char seq of size = " + charSequence.length() +
" (c: " + chunk.writerIndex() + ", b: " + buffer.writerIndex() + ")");
" (c: " + chunk.writerIndex() + ", b: " + buffer.writerIndex() + ")");
}
return this;
}
Expand All @@ -189,13 +197,8 @@ public AdvisingAppendable append(CharSequence csq, int start, int end) {

@Override
public AdvisingAppendable append(char c) {
ensureChunkSize(1);
char[] item = {c};
chunk.writeCharSequence(CharBuffer.wrap(item), charset);
if (LOG.isTraceEnabled()) {
LOG.trace("Appended char seq of size = 1 (c: " +
chunk.writerIndex() + ", b: " + buffer.writerIndex() + ")");
}
append(CharBuffer.wrap(item));
return this;
}

Expand Down

0 comments on commit 613e267

Please sign in to comment.