Pop-up dictionary browser extension for language learning. Successor to Yomichan. (PERSONAL FORK)
1/*
2 * Copyright (C) 2023-2025 Yomitan Authors
3 * Copyright (C) 2021-2022 Yomichan Authors
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
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 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19/**
20 * Decodes the contents of an ArrayBuffer using UTF8.
21 * @param {ArrayBuffer} arrayBuffer The input ArrayBuffer.
22 * @returns {string} A UTF8-decoded string.
23 */
24export function arrayBufferUtf8Decode(arrayBuffer) {
25 try {
26 return new TextDecoder('utf-8').decode(arrayBuffer);
27 } catch (e) {
28 return decodeURIComponent(escape(arrayBufferToBinaryString(arrayBuffer)));
29 }
30}
31
32/**
33 * Converts the contents of an ArrayBuffer to a base64 string.
34 * @param {ArrayBuffer} arrayBuffer The input ArrayBuffer.
35 * @returns {string} A base64 string representing the binary content.
36 */
37export function arrayBufferToBase64(arrayBuffer) {
38 return btoa(arrayBufferToBinaryString(arrayBuffer));
39}
40
41/**
42 * Converts the contents of an ArrayBuffer to a binary string.
43 * @param {ArrayBuffer} arrayBuffer The input ArrayBuffer.
44 * @returns {string} A string representing the binary content.
45 */
46export function arrayBufferToBinaryString(arrayBuffer) {
47 const bytes = new Uint8Array(arrayBuffer);
48 try {
49 return String.fromCharCode(...bytes);
50 } catch (e) {
51 let binary = '';
52 for (let i = 0, ii = bytes.byteLength; i < ii; ++i) {
53 binary += String.fromCharCode(bytes[i]);
54 }
55 return binary;
56 }
57}
58
59/**
60 * Converts a base64 string to an ArrayBuffer.
61 * @param {string} content The binary content string encoded in base64.
62 * @returns {ArrayBuffer} A new `ArrayBuffer` object corresponding to the specified content.
63 */
64export function base64ToArrayBuffer(content) {
65 const binaryContent = atob(content);
66 const length = binaryContent.length;
67 const array = new Uint8Array(length);
68 for (let i = 0; i < length; ++i) {
69 array[i] = binaryContent.charCodeAt(i);
70 }
71 return array.buffer;
72}