2014-05-15 23:05:20 +00:00
|
|
|
package org.capnproto;
|
|
|
|
|
|
|
|
import java.nio.ByteBuffer;
|
|
|
|
|
2014-05-19 12:43:58 +00:00
|
|
|
public final class SegmentBuilder extends SegmentReader {
|
2014-06-15 20:38:26 +00:00
|
|
|
|
2014-05-15 23:05:20 +00:00
|
|
|
public static final int FAILED_ALLOCATION = -1;
|
|
|
|
|
2014-05-19 12:43:58 +00:00
|
|
|
public int pos = 0; // in words
|
|
|
|
|
2014-06-15 20:38:26 +00:00
|
|
|
public SegmentBuilder(ByteBuffer buf, Arena arena) {
|
|
|
|
super(buf, arena);
|
2014-05-15 23:05:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// the total number of words the buffer can hold
|
|
|
|
private final int capacity() {
|
|
|
|
this.buffer.reset();
|
|
|
|
return this.buffer.remaining() / 8;
|
|
|
|
}
|
|
|
|
|
|
|
|
// return how many words have already been allocated
|
2014-05-24 18:33:25 +00:00
|
|
|
public final int currentSize() {
|
2014-05-15 23:05:20 +00:00
|
|
|
return this.pos;
|
|
|
|
}
|
|
|
|
|
2014-06-15 20:38:26 +00:00
|
|
|
/*
|
2014-05-24 14:12:44 +00:00
|
|
|
Allocate `amount` words.
|
|
|
|
*/
|
2014-05-15 23:05:20 +00:00
|
|
|
public final int allocate(int amount) {
|
2014-06-15 20:38:26 +00:00
|
|
|
if (amount < 0) {
|
|
|
|
throw new InternalError("tried to allocate a negative number of words");
|
|
|
|
}
|
|
|
|
|
2014-05-15 23:05:20 +00:00
|
|
|
if (amount > this.capacity() - this.currentSize()) {
|
|
|
|
return FAILED_ALLOCATION; // no space left;
|
|
|
|
} else {
|
|
|
|
int result = this.pos;
|
|
|
|
this.pos += amount;
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|
2014-06-15 20:38:26 +00:00
|
|
|
|
|
|
|
public final BuilderArena getArena() {
|
|
|
|
return (BuilderArena)this.arena;
|
|
|
|
}
|
2014-05-15 23:05:20 +00:00
|
|
|
}
|