From db947515aca4a97af67fbdaf5fe54743050580d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elan=20Ruusam=C3=A4e?= Date: Fri, 5 Mar 2021 14:18:09 +0200 Subject: [PATCH] Introduce local variable and exccessively document the logic in the loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Elan Ruusamäe --- src/Protocol/Smtp.php | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/Protocol/Smtp.php b/src/Protocol/Smtp.php index 2d6c1325..1abe9a0c 100644 --- a/src/Protocol/Smtp.php +++ b/src/Protocol/Smtp.php @@ -201,8 +201,25 @@ private static function chunkedReader(string $data, int $chunkSize = 4096): Gene while (($buffer = fgets($fp, $chunkSize)) !== false) { $line .= $buffer; + // This is optimization to avoid calling length() in a loop. + // We need to match a condition that is when: + // 1. maximum was read from fgets, which is $chunkSize-1 + // 2. last byte of the buffer is not \n + // + // to access last byte of buffer, we can do + // - $buffer[strlen($buffer)-1] + // and when maximum is read from fgets, then: + // - strlen($buffer) === $chunkSize-1 + // - strlen($buffer)-1 === $chunkSize-2 + // which means this is also true: + // - $buffer[strlen($buffer)-1] === $buffer[$chunkSize-2] + // + // the null coalesce works, as string offset can never be null + $lastByte = $buffer[$chunkSize - 2] ?? null; + // partial read, continue loop to read again to complete the line - if (isset($buffer[$chunkSize - 2]) && $buffer[$chunkSize - 2] !== "\n") { + // compare \n first as that's usually false + if ($lastByte !== "\n" && $lastByte !== null) { continue; }