Debian Codegraph @

vendor/paragonie/constant_time_encoding/src/Binary.php

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