* Finds the index of the first occurrence of a double newline pattern (\r\r, \n\n, \r\n\r\n) in the given buffer. * * @param buffer - The buffer to search for the double newline pattern. * @returns The index right after the first occurrence of the double newline pattern, or -1 if not found.
(buffer: Uint8Array)
| 287 | * @returns The index right after the first occurrence of the double newline pattern, or -1 if not found. |
| 288 | */ |
| 289 | function findDoubleNewlineIndex(buffer: Uint8Array): number { |
| 290 | // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) |
| 291 | // and returns the index right after the first occurrence of any pattern, |
| 292 | // or -1 if none of the patterns are found. |
| 293 | const newline = 0x0a; // \n |
| 294 | const carriage = 0x0d; // \r |
| 295 | |
| 296 | for (let i = 0; i < buffer.length - 2; i++) { |
| 297 | if (buffer[i] === newline && buffer[i + 1] === newline) { |
| 298 | // \n\n |
| 299 | return i + 2; |
| 300 | } |
| 301 | if (buffer[i] === carriage && buffer[i + 1] === carriage) { |
| 302 | // \r\r |
| 303 | return i + 2; |
| 304 | } |
| 305 | if ( |
| 306 | buffer[i] === carriage && |
| 307 | buffer[i + 1] === newline && |
| 308 | i + 3 < buffer.length && |
| 309 | buffer[i + 2] === carriage && |
| 310 | buffer[i + 3] === newline |
| 311 | ) { |
| 312 | // \r\n\r\n |
| 313 | return i + 4; |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | return -1; |
| 318 | } |
| 319 | |
| 320 | /** |
| 321 | * Represents a Server-Sent Event (SSE) decoder. |