title: Fastest way to split a Stream according to a pattern
body: <p>What would be the most optimal/fastest way to split a Steam into chunks delimited by a byte pattern (eg. <code>new byte[] { 0, 0 }</code>)?</p>
  <p>My current, naieve and slow, implementation reads the stream byte per byte, decrements a counter each time it encounters the delimiter. If the counter is zero, it yields a memory chunk.</p>
  <pre><code>const int NUMBER_CONSECUTIVE_DELIMITER = 2;
  const int DELIMITER = 0;
  
  public IEnumerable&lt;ReadOnlyMemory&lt;byte&gt;&gt; Chunk(Stream stream)
  {
      var chunk = new MemoryStream();
  
      try
      {
          int b; //the byte being read
          int c = NUMBER_CONSECUTIVE_DELIMITER;
  
          while ((b = stream.ReadByte()) != -1) //Read the stream byte by byte, -1 = end of the stream
          {
              chunk.WriteByte((byte)b); //Write this byte to the next chunk
  
              if (b == DELIMITER) 
                  c--; //if we hit the delimiter (ie '0') decrement the counter
              else
                  c = NUMBER_CONSECUTIVE_DELIMITER; //else, reset the couter
  
              if ((c &lt;= 0 || stream.Position == stream.Length) //we hit two subsequent '0's
              {
                  var r = chunk.ToArray().AsMemory(); //parse it to a Memory&lt;T&gt;
  
                  chunk.Dispose();
                  chunk = new();
  
                  yield return r;
              }
          }
      }
      finally
      {
          chunk.Dispose();
      }
  }
  </code></pre>