forked from Mhassanbughio/-AR---AI-Cut-Paste-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBase64
95 lines (83 loc) · 2.71 KB
/
Base64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// https://stackoverflow.com/questions/42829838/react-native-atob-btoa-not-working-without-remote-js-debugging
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const Base64 = {
btoa: (input: string = "") => {
let str = input;
let output = "";
for (
let block = 0, charCode, i = 0, map = chars;
str.charAt(i | 0) || ((map = "="), i % 1);
output += map.charAt(63 & (block >> (8 - (i % 1) * 8)))
) {
charCode = str.charCodeAt((i += 3 / 4));
if (charCode > 0xff) {
throw new Error(
"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."
);
}
block = (block << 8) | charCode;
}
return output;
},
atob: (input: string = "") => {
let str = input.replace(/=+$/, "");
let output = "";
if (str.length % 4 == 1) {
throw new Error(
"'atob' failed: The string to be decoded is not correctly encoded."
);
}
for (
let bc = 0, bs = 0, buffer, i = 0;
(buffer = str.charAt(i++));
~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)
? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))
: 0
) {
buffer = chars.indexOf(buffer);
}
return output;
},
};
FileReader.prototype.readAsArrayBuffer = function (blob) {
if (this.readyState === this.LOADING) throw new Error("InvalidStateError");
this._setReadyState(this.LOADING);
this._result = null;
this._error = null;
const fr = new FileReader();
fr.onloadend = () => {
const content = Base64.atob(
fr.result.substr("data:application/octet-stream;base64,".length)
);
const buffer = new ArrayBuffer(content.length);
const view = new Uint8Array(buffer);
view.set(Array.from(content).map((c) => c.charCodeAt(0)));
this._result = buffer;
this._setReadyState(this.DONE);
};
fr.readAsDataURL(blob);
};
// from: https://stackoverflow.com/questions/42829838/react-native-atob-btoa-not-working-without-remote-js-debugging
// const chars =
// "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// const atob = (input = "") => {
// let str = input.replace(/=+$/, "");
// let output = "";
// if (str.length % 4 == 1) {
// throw new Error(
// "'atob' failed: The string to be decoded is not correctly encoded."
// );
// }
// for (
// let bc = 0, bs = 0, buffer, i = 0;
// (buffer = str.charAt(i++));
// ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4)
// ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6))))
// : 0
// ) {
// buffer = chars.indexOf(buffer);
// }
// return output;
// };
export default Base64;