8339196: Optimize BufWriterImpl#writeU1/U2/Int/Long

Reviewed-by: liach, redestad
This commit is contained in:
Shaojin Wen 2024-08-29 21:21:16 +00:00 committed by Chen Liang
parent f2968b34a5
commit b711c41d44

View File

@ -91,17 +91,30 @@ public final class BufWriterImpl implements BufWriter {
@Override
public void writeU1(int x) {
writeIntBytes(1, x);
reserveSpace(1);
elems[offset++] = (byte) x;
}
@Override
public void writeU2(int x) {
writeIntBytes(2, x);
reserveSpace(2);
byte[] elems = this.elems;
int offset = this.offset;
elems[offset ] = (byte) (x >> 8);
elems[offset + 1] = (byte) x;
this.offset = offset + 2;
}
@Override
public void writeInt(int x) {
writeIntBytes(4, x);
reserveSpace(4);
byte[] elems = this.elems;
int offset = this.offset;
elems[offset ] = (byte) (x >> 24);
elems[offset + 1] = (byte) (x >> 16);
elems[offset + 2] = (byte) (x >> 8);
elems[offset + 3] = (byte) x;
this.offset = offset + 4;
}
@Override
@ -111,7 +124,18 @@ public final class BufWriterImpl implements BufWriter {
@Override
public void writeLong(long x) {
writeIntBytes(8, x);
reserveSpace(8);
byte[] elems = this.elems;
int offset = this.offset;
elems[offset ] = (byte) (x >> 56);
elems[offset + 1] = (byte) (x >> 48);
elems[offset + 2] = (byte) (x >> 40);
elems[offset + 3] = (byte) (x >> 32);
elems[offset + 4] = (byte) (x >> 24);
elems[offset + 5] = (byte) (x >> 16);
elems[offset + 6] = (byte) (x >> 8);
elems[offset + 7] = (byte) x;
this.offset = offset + 8;
}
@Override
@ -153,15 +177,20 @@ public final class BufWriterImpl implements BufWriter {
@Override
public void reserveSpace(int freeBytes) {
if (offset + freeBytes > elems.length) {
int newsize = elems.length * 2;
while (offset + freeBytes > newsize) {
newsize *= 2;
}
elems = Arrays.copyOf(elems, newsize);
int minCapacity = offset + freeBytes;
if (minCapacity > elems.length) {
grow(minCapacity);
}
}
private void grow(int minCapacity) {
int newsize = elems.length * 2;
while (minCapacity > newsize) {
newsize *= 2;
}
elems = Arrays.copyOf(elems, newsize);
}
@Override
public int size() {
return offset;