You are here

public static function ParagonIE_Sodium_Core_Util::compare in Automatic Updates 8

Same name and namespace in other branches
  1. 7 vendor/paragonie/sodium_compat/src/Core/Util.php \ParagonIE_Sodium_Core_Util::compare()

Compares two strings.

@internal You should not use this directly from another application

Parameters

string $left:

string $right:

int $len:

Return value

int

Throws

SodiumException

TypeError

1 call to ParagonIE_Sodium_Core_Util::compare()
ParagonIE_Sodium_Compat::compare in vendor/paragonie/sodium_compat/src/Compat.php
Compare two strings, in constant-time. Compared to memcmp(), compare() is more useful for sorting.

File

vendor/paragonie/sodium_compat/src/Core/Util.php, line 152

Class

ParagonIE_Sodium_Core_Util
Class ParagonIE_Sodium_Core_Util

Code

public static function compare($left, $right, $len = null) {
  $leftLen = self::strlen($left);
  $rightLen = self::strlen($right);
  if ($len === null) {
    $len = max($leftLen, $rightLen);
    $left = str_pad($left, $len, "\0", STR_PAD_RIGHT);
    $right = str_pad($right, $len, "\0", STR_PAD_RIGHT);
  }
  $gt = 0;
  $eq = 1;
  $i = $len;
  while ($i !== 0) {
    --$i;
    $gt |= self::chrToInt($right[$i]) - self::chrToInt($left[$i]) >> 8 & $eq;
    $eq &= (self::chrToInt($right[$i]) ^ self::chrToInt($left[$i])) - 1 >> 8;
  }
  return $gt + $gt + $eq - 1;
}