File tree Expand file tree Collapse file tree
chapters/10-Optimizing-Branch-Prediction Expand file tree Collapse file tree Original file line number Diff line number Diff 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)
You can’t perform that action at this time.
0 commit comments