Skip to content

Commit

Permalink
Introduce local variable and exccessively document the logic in the loop
Browse files Browse the repository at this point in the history
Signed-off-by: Elan Ruusamäe <glen@pld-linux.org>
  • Loading branch information
glensc committed Mar 15, 2021
1 parent 4105ce6 commit db94751
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Protocol/Smtp.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down

0 comments on commit db94751

Please sign in to comment.