Binary.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. declare(strict_types=1);
  3. namespace ParagonIE\ConstantTime;
  4. /**
  5. * Copyright (c) 2016 - 2018 Paragon Initiative Enterprises.
  6. * Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. /**
  27. * Class Binary
  28. *
  29. * Binary string operators that don't choke on
  30. * mbstring.func_overload
  31. *
  32. * @package ParagonIE\ConstantTime
  33. */
  34. abstract class Binary
  35. {
  36. /**
  37. * Safe string length
  38. *
  39. * @ref mbstring.func_overload
  40. *
  41. * @param string $str
  42. * @return int
  43. */
  44. public static function safeStrlen(string $str): int
  45. {
  46. if (\function_exists('mb_strlen')) {
  47. return (int) \mb_strlen($str, '8bit');
  48. } else {
  49. return \strlen($str);
  50. }
  51. }
  52. /**
  53. * Safe substring
  54. *
  55. * @ref mbstring.func_overload
  56. *
  57. * @staticvar boolean $exists
  58. * @param string $str
  59. * @param int $start
  60. * @param int $length
  61. * @return string
  62. * @throws \TypeError
  63. */
  64. public static function safeSubstr(
  65. string $str,
  66. int $start = 0,
  67. $length = null
  68. ): string {
  69. if ($length === 0) {
  70. return '';
  71. }
  72. if (\function_exists('mb_substr')) {
  73. return \mb_substr($str, $start, $length, '8bit');
  74. }
  75. // Unlike mb_substr(), substr() doesn't accept NULL for length
  76. if ($length !== null) {
  77. return \substr($str, $start, $length);
  78. } else {
  79. return \substr($str, $start);
  80. }
  81. }
  82. }