Skip to content

Commit d53288b

Browse files
committed
Fix subtle bug for SIMD finding new line in chapter 10-4
1 parent c880e39 commit d53288b

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

chapters/10-Optimizing-Branch-Prediction/10-4 Multiple Compares Single Branch.md

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,16 +39,22 @@ uint32_t longestLine(const std::string &str) {
3939
uint64_t vect = *((const uint64_t*)(buf + pos));
4040
// Check all characters in this chunk.
4141
uint8_t mask = compareBytes(vect, eol);
42+
uint8_t offset = 0;
4243
while (mask) {
43-
uint16_t eolPos = tzcnt(mask);
44+
uint16_t localEolPos = tzcnt(mask);
45+
uint16_t eolPos = offset + localEolPos;
4446
// Compute the length of the current string.
4547
uint32_t curLen = (pos - lineBeginPos) + eolPos;
4648
// New line starts with the character after '\n'
4749
lineBeginPos += curLen + 1;
50+
offset = eolPos + 1;
4851
// Is this line the longest?
4952
maxLen = std::max(curLen, maxLen);
5053
// Shift the mask to check if we have more '\n'
51-
mask >>= eolPos + 1;
54+
if (localEolPol + 1 >= 8) {
55+
break; // UB if shift 8 bytes or more on uint8_t type
56+
}
57+
mask >>= localEolPos + 1;
5258
}
5359
}
5460
// process remainder (not shown)

0 commit comments

Comments
 (0)