Skip to content

Optimize String length computation. #1685

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
52 changes: 50 additions & 2 deletions bson/src/main/org/bson/io/ByteBufferBsonInput.java
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ public String readString() {

@Override
public String readCString() {
ensureOpen();
int size = computeCStringLength(buffer.position());
return readString(size);
}
Expand Down Expand Up @@ -182,11 +183,58 @@ public void skipCString() {
buffer.position(pos + length);
}

/**
* Detects the position of the first NULL (0x00) byte in a 64-bit word using SWAR technique.
* <a href="https://en.wikipedia.org/wiki/SWAR">
*/
private int computeCStringLength(final int prevPos) {
ensureOpen();
int pos = buffer.position();
int pos = prevPos;
int limit = buffer.limit();

// `>>> 3` means dividing without remainder by `Long.BYTES` because `Long.BYTES` is 2^3
int chunks = (limit - pos) >>> 3;
// `<< 3` means multiplying by `Long.BYTES` because `Long.BYTES` is 2^3
int toPos = pos + (chunks << 3);
for (; pos < toPos; pos += Long.BYTES) {
long chunk = buffer.getLong(pos);
/*
Subtract 0x0101010101010101L to cause a borrow on 0x00 bytes.
if original byte is 00000000, then 00000000 - 00000001 = 11111111 (borrow causes the MSB set to 1).
*/
long mask = chunk - 0x0101010101010101L;
/*
mask will only have the MSB set iff it was a 0x00 byte (0x00 becomes 0xFF because of the borrow).
~chunk will have bits that were originally 0 set to 1.
mask & ~chunk will have the MSB set iff original byte was 0x00.
*/
mask &= ~chunk;
/*
0x8080808080808080:
10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000

mask:
00000000 00000000 11111111 00000000 00000001 00000001 00000000 00000111

ANDing mask with 0x8080808080808080 isolates the MSB (0x80) in positions where
the original byte was 0x00, thereby setting the MSB to 1 only at the 0x00 byte position.

result:
00000000 00000000 10000000 00000000 00000000 00000000 00000000 00000000
^^^^^^^^
The MSB is set only at the 0x00 byte position.
*/
mask &= 0x8080808080808080L;
if (mask != 0) {
/*
* Performing >>> 3 (i.e., dividing by 8) gives the byte offset from the LSB.
*/
int offset = Long.numberOfTrailingZeros(mask) >>> 3;
// Find the NULL terminator at pos + offset
return (pos - prevPos) + offset + 1;
}
}

// Process remaining bytes one by one.
while (pos < limit) {
if (buffer.get(pos++) == 0) {
return (pos - prevPos);
Expand Down