xref: /webtrees/app/Encodings/UTF16LE.php (revision 2c685d76b4ab2ea8f166ab8a2e4112fa1ba8de5d)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Encodings;
21
22use function chr;
23use function intdiv;
24use function ord;
25use function str_split;
26
27/**
28 * Convert between UTF-16LE and UTF-8.
29 */
30class UTF16LE extends AbstractUTF16Encoding
31{
32    public const NAME = 'UTF-16LE';
33
34    public const BYTE_ORDER_MARK       = "\xFF\xFE";
35    public const REPLACEMENT_CHARACTER = "\xFD\xFF";
36
37    /**
38     * Convert two bytes to a code-point, taking care of byte-order.
39     *
40     * @param string $character
41     *
42     * @return int
43     */
44    protected function characterToCodePoint(string $character): int
45    {
46        return ord($character[0]) + 256 * ord($character[1]);
47    }
48
49    /**
50     * Convert a code-point to two bytes, taking care of byte-order.
51     *
52     * @param int $code_point
53     *
54     * @return string
55     */
56    protected function codePointToCharacter(int $code_point): string
57    {
58        if ($code_point >= 0xD800 && $code_point <= 0xDFFF) {
59            return self::REPLACEMENT_CHARACTER;
60        }
61
62        return chr($code_point % 256) . chr(intdiv($code_point, 256));
63    }
64}
65