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