title: Fastest way to find first occurrence of byte in buffer
body: <p><em>Disclaimer</em></p>
  
  <ul>
  <li><em>I have read <a href="https://stackoverflow.com/questions/3183582/what-is-the-fastest-substring-search-algorithm">What is the fastest substring search algorithm?</a>, which may be suboptimal for the single character case.</em></li>
  <li><em><code>strchr</code> requires a NUL-terminated string</em></li>
  </ul>
  
  <hr>
  
  <p>I am looking for the fastest way to identify the first occurrence of a given byte in a byte buffer.</p>
  
  <p>This is reminiscent of looking for the first occurrence of a character in a string except that:</p>
  
  <ul>
  <li>the byte buffer is not NUL-terminated, instead I have an explicit length (and possibly embedded NUL characters)</li>
  <li>the byte buffer is not allocated in a <code>string</code> or <code>vector</code>, I am only handed down a <em>slice</em> (aka, pointer &amp; length)</li>
  </ul>
  
  <p>The basic solution is:</p>
  
  <pre><code>size_t search(char const* buffer, size_t length, char c) {
      return std::find(buffer, buffer + length, c) - buffer;
  }
  </code></pre>
  
  <p>However, a quick round-trip with the Godbolt compiler (<code>-O2 -msse2 -mavx</code>) does not show any hint of a vectorized instruction, only some unrolling, so I am wondering whether this is the optimal.</p>
  
  <p>Is there a faster way to find the first occurrence of a given byte in a buffer?</p>
  
  <p><em>Note: only the first occurrence matters.</em></p>
  
  <p><em>Note: I am exclusively concerned with modern x86_64 CPUs on Linux, though I encourage answers to be as generic as possible and mention assumptions clearly.</em></p>