@keeex/utils 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +105 -0
  3. package/lib/array.d.ts +28 -0
  4. package/lib/array.js +36 -0
  5. package/lib/arraybuffer.d.ts +138 -0
  6. package/lib/arraybuffer.js +141 -0
  7. package/lib/async/asynctrigger.d.ts +50 -0
  8. package/lib/async/asynctrigger.js +108 -0
  9. package/lib/async/deferredpromise.d.ts +32 -0
  10. package/lib/async/deferredpromise.js +66 -0
  11. package/lib/async/keycache.d.ts +56 -0
  12. package/lib/async/keycache.js +103 -0
  13. package/lib/async/queues.d.ts +69 -0
  14. package/lib/async/queues.js +135 -0
  15. package/lib/async/timecache.d.ts +58 -0
  16. package/lib/async/timecache.js +118 -0
  17. package/lib/base58.d.ts +27 -0
  18. package/lib/base58.js +83 -0
  19. package/lib/base64.d.ts +51 -0
  20. package/lib/base64.js +126 -0
  21. package/lib/benchmark.d.ts +126 -0
  22. package/lib/benchmark.js +177 -0
  23. package/lib/bits/arraybuffer.d.ts +35 -0
  24. package/lib/bits/arraybuffer.js +64 -0
  25. package/lib/bits/base64.d.ts +35 -0
  26. package/lib/bits/base64.js +70 -0
  27. package/lib/bits/hex.d.ts +17 -0
  28. package/lib/bits/hex.js +30 -0
  29. package/lib/bits/uint8array.d.ts +28 -0
  30. package/lib/bits/uint8array.js +42 -0
  31. package/lib/bytebuffer.d.ts +27 -0
  32. package/lib/bytebuffer.js +29 -0
  33. package/lib/consts.d.ts +33 -0
  34. package/lib/consts.js +33 -0
  35. package/lib/cron/logger.d.ts +22 -0
  36. package/lib/cron/logger.js +31 -0
  37. package/lib/cron/scheduledtask.d.ts +71 -0
  38. package/lib/cron/scheduledtask.js +137 -0
  39. package/lib/cron/types.d.ts +53 -0
  40. package/lib/cron/types.js +31 -0
  41. package/lib/cron.d.ts +29 -0
  42. package/lib/cron.js +47 -0
  43. package/lib/dict.d.ts +56 -0
  44. package/lib/dict.js +74 -0
  45. package/lib/error.d.ts +25 -0
  46. package/lib/error.js +41 -0
  47. package/lib/global.d.ts +27 -0
  48. package/lib/global.js +53 -0
  49. package/lib/hex.d.ts +32 -0
  50. package/lib/hex.js +58 -0
  51. package/lib/idx.d.ts +51 -0
  52. package/lib/idx.js +81 -0
  53. package/lib/json.d.ts +57 -0
  54. package/lib/json.js +116 -0
  55. package/lib/marshalling/marshaller.d.ts +51 -0
  56. package/lib/marshalling/marshaller.js +155 -0
  57. package/lib/marshalling/unmarshaller.d.ts +53 -0
  58. package/lib/marshalling/unmarshaller.js +124 -0
  59. package/lib/marshalling/util.d.ts +25 -0
  60. package/lib/marshalling/util.js +25 -0
  61. package/lib/number.d.ts +17 -0
  62. package/lib/number.js +21 -0
  63. package/lib/path.d.ts +25 -0
  64. package/lib/path.js +29 -0
  65. package/lib/promise.d.ts +42 -0
  66. package/lib/promise.js +78 -0
  67. package/lib/starttime.d.ts +23 -0
  68. package/lib/starttime.js +29 -0
  69. package/lib/string.d.ts +65 -0
  70. package/lib/string.js +108 -0
  71. package/lib/types/array.d.ts +34 -0
  72. package/lib/types/array.js +64 -0
  73. package/lib/types/enum.d.ts +30 -0
  74. package/lib/types/enum.js +44 -0
  75. package/lib/types/predicateerror.d.ts +40 -0
  76. package/lib/types/predicateerror.js +107 -0
  77. package/lib/types/primitive.d.ts +23 -0
  78. package/lib/types/primitive.js +34 -0
  79. package/lib/types/record.d.ts +67 -0
  80. package/lib/types/record.js +235 -0
  81. package/lib/types/types.d.ts +64 -0
  82. package/lib/types/types.js +115 -0
  83. package/lib/types/utils.d.ts +18 -0
  84. package/lib/types/utils.js +67 -0
  85. package/lib/uint8array.d.ts +176 -0
  86. package/lib/uint8array.js +438 -0
  87. package/lib/units.d.ts +159 -0
  88. package/lib/units.js +290 -0
  89. package/lib/utils/buffer.d.ts +49 -0
  90. package/lib/utils/buffer.js +79 -0
  91. package/lib/utils/fourbytes.d.ts +29 -0
  92. package/lib/utils/fourbytes.js +45 -0
  93. package/package.json +1 -0
  94. package/web/array.d.ts +28 -0
  95. package/web/array.js +34 -0
  96. package/web/arraybuffer.d.ts +138 -0
  97. package/web/arraybuffer.js +141 -0
  98. package/web/async/asynctrigger.d.ts +50 -0
  99. package/web/async/asynctrigger.js +106 -0
  100. package/web/async/deferredpromise.d.ts +32 -0
  101. package/web/async/deferredpromise.js +65 -0
  102. package/web/async/keycache.d.ts +56 -0
  103. package/web/async/keycache.js +97 -0
  104. package/web/async/queues.d.ts +69 -0
  105. package/web/async/queues.js +131 -0
  106. package/web/async/timecache.d.ts +58 -0
  107. package/web/async/timecache.js +107 -0
  108. package/web/base58.d.ts +27 -0
  109. package/web/base58.js +78 -0
  110. package/web/base64.d.ts +51 -0
  111. package/web/base64.js +136 -0
  112. package/web/benchmark.d.ts +126 -0
  113. package/web/benchmark.js +183 -0
  114. package/web/bits/arraybuffer.d.ts +35 -0
  115. package/web/bits/arraybuffer.js +59 -0
  116. package/web/bits/base64.d.ts +35 -0
  117. package/web/bits/base64.js +67 -0
  118. package/web/bits/hex.d.ts +17 -0
  119. package/web/bits/hex.js +27 -0
  120. package/web/bits/uint8array.d.ts +28 -0
  121. package/web/bits/uint8array.js +41 -0
  122. package/web/bytebuffer.d.ts +27 -0
  123. package/web/bytebuffer.js +29 -0
  124. package/web/consts.d.ts +33 -0
  125. package/web/consts.js +33 -0
  126. package/web/cron/logger.d.ts +22 -0
  127. package/web/cron/logger.js +30 -0
  128. package/web/cron/scheduledtask.d.ts +71 -0
  129. package/web/cron/scheduledtask.js +136 -0
  130. package/web/cron/types.d.ts +53 -0
  131. package/web/cron/types.js +31 -0
  132. package/web/cron.d.ts +29 -0
  133. package/web/cron.js +47 -0
  134. package/web/dict.d.ts +56 -0
  135. package/web/dict.js +67 -0
  136. package/web/error.d.ts +25 -0
  137. package/web/error.js +39 -0
  138. package/web/global.d.ts +27 -0
  139. package/web/global.js +49 -0
  140. package/web/hex.d.ts +32 -0
  141. package/web/hex.js +52 -0
  142. package/web/idx.d.ts +51 -0
  143. package/web/idx.js +76 -0
  144. package/web/json.d.ts +57 -0
  145. package/web/json.js +98 -0
  146. package/web/marshalling/marshaller.d.ts +51 -0
  147. package/web/marshalling/marshaller.js +150 -0
  148. package/web/marshalling/unmarshaller.d.ts +53 -0
  149. package/web/marshalling/unmarshaller.js +115 -0
  150. package/web/marshalling/util.d.ts +25 -0
  151. package/web/marshalling/util.js +25 -0
  152. package/web/number.d.ts +17 -0
  153. package/web/number.js +21 -0
  154. package/web/path.d.ts +25 -0
  155. package/web/path.js +26 -0
  156. package/web/promise.d.ts +42 -0
  157. package/web/promise.js +74 -0
  158. package/web/starttime.d.ts +23 -0
  159. package/web/starttime.js +29 -0
  160. package/web/string.d.ts +65 -0
  161. package/web/string.js +101 -0
  162. package/web/types/array.d.ts +34 -0
  163. package/web/types/array.js +63 -0
  164. package/web/types/enum.d.ts +30 -0
  165. package/web/types/enum.js +40 -0
  166. package/web/types/predicateerror.d.ts +40 -0
  167. package/web/types/predicateerror.js +128 -0
  168. package/web/types/primitive.d.ts +23 -0
  169. package/web/types/primitive.js +33 -0
  170. package/web/types/record.d.ts +67 -0
  171. package/web/types/record.js +213 -0
  172. package/web/types/types.d.ts +64 -0
  173. package/web/types/types.js +123 -0
  174. package/web/types/utils.d.ts +18 -0
  175. package/web/types/utils.js +30 -0
  176. package/web/uint8array.d.ts +176 -0
  177. package/web/uint8array.js +412 -0
  178. package/web/units.d.ts +159 -0
  179. package/web/units.js +312 -0
  180. package/web/utils/buffer.d.ts +49 -0
  181. package/web/utils/buffer.js +76 -0
  182. package/web/utils/fourbytes.d.ts +29 -0
  183. package/web/utils/fourbytes.js +45 -0
@@ -0,0 +1,412 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import TextEncodingShim from "text-encoding-shim";
17
+ import { arrayEqual } from "./array.js";
18
+ import { b642ab as bitsB642ab } from "./bits/arraybuffer.js";
19
+ import { clearHexInput } from "./bits/hex.js";
20
+ import { getUint8Array as getUint8ArrayBits, pureBuf82B64, buf82b64 } from "./bits/uint8array.js";
21
+ import { HEXBYTE_CHR_COUNT, HEX_DIGITS, MAX_RADIX } from "./consts.js";
22
+ import { bufferB642Buf8, bufferBuf82Hex, bufferBuf82Utf8, bufferHex2Buf8, bufferUtf82Buf8, haveBufferBase64, haveBufferHex, haveBufferUTF8 } from "./utils/buffer.js";
23
+ import FourBytes from "./utils/fourbytes.js";
24
+ /**
25
+ * Return a Uint8Array view on the provided ArrayBuffer.
26
+ *
27
+ * If clone is set to true, return a clone of the source array. Otherwise a view is returned.
28
+ *
29
+ * @public
30
+ */
31
+ export const getUint8Array = getUint8ArrayBits;
32
+ /**
33
+ * Convert an Uint8Array to a raw string.
34
+ *
35
+ * @public
36
+ */
37
+ export const buf82str = buf8 => {
38
+ const charArray = [];
39
+ const length = buf8.byteLength;
40
+ charArray.length = length;
41
+ for (let i = 0; i < length; i++) charArray[i] = String.fromCharCode(buf8[i]);
42
+ return charArray.join("");
43
+ };
44
+ /**
45
+ * Convert a string to an Uint8Array
46
+ *
47
+ * @public
48
+ */
49
+ export const str2buf8 = str => {
50
+ const buf8 = new Uint8Array(str.length);
51
+ for (let i = 0, strLen = str.length; i < strLen; i++) buf8[i] = str.charCodeAt(i);
52
+ return buf8;
53
+ };
54
+ /** @internal */
55
+ export const pureBuf82Hex = (buf8, addPrefix) => {
56
+ const hexArray = [];
57
+ const length = buf8.length;
58
+ hexArray.length = length * HEXBYTE_CHR_COUNT;
59
+ for (let i = 0; i < length; i++) {
60
+ hexArray[i] = buf8[i].toString(HEX_DIGITS).padStart(HEXBYTE_CHR_COUNT, "0");
61
+ }
62
+ const hexResult = hexArray.join("");
63
+ return addPrefix ? `0x${hexResult}` : hexResult;
64
+ };
65
+ /**
66
+ * Convert an Uint8Array to a hex string.
67
+ *
68
+ * @public
69
+ */
70
+ export const buf82hex = haveBufferHex() ? bufferBuf82Hex : pureBuf82Hex;
71
+ /** @internal */
72
+ export const pureHex2Buf8 = hex => {
73
+ const input = clearHexInput(hex);
74
+ const buf8 = new Uint8Array(input.length / HEXBYTE_CHR_COUNT);
75
+ for (let i = 0; i < buf8.length; ++i) {
76
+ buf8[i] = parseInt(input[i * HEXBYTE_CHR_COUNT] + input[i * HEXBYTE_CHR_COUNT + 1], HEX_DIGITS);
77
+ }
78
+ return buf8;
79
+ };
80
+ /**
81
+ * Convert an hex string to an Uint8Array.
82
+ *
83
+ * @public
84
+ */
85
+ export const hex2buf8 = haveBufferHex() ? bufferHex2Buf8 : pureHex2Buf8;
86
+ const lengthAsUint8Array = length => {
87
+ const lengthAsString = length.toString(MAX_RADIX);
88
+ const maxByteValue = 255;
89
+ if (lengthAsString.length > maxByteValue) throw new Error("Unsupported buffer length");
90
+ return str2buf8(lengthAsString);
91
+ };
92
+ /**
93
+ * Concatenate multiple Uint8Array into one output.
94
+ *
95
+ * The output will have each individual buffer length stored so that they can be
96
+ * split afterward using explodeBuf8List(). Simple concatenation is available with merge().
97
+ *
98
+ * Output have the following format for each buffer:
99
+ *
100
+ * - 1 byte: the character "!", that identifies the kind of data that follows
101
+ * - 1 byte: length of the "buffer length as a string(base36)"
102
+ * - x bytes: buffer length as a string(base36)
103
+ * - y bytes: buffer content
104
+ *
105
+ * A special byte set to '#' can be appended to indicate the end of the buffers list. This allows
106
+ * the output of this function to be followed by other data while still being able to use the
107
+ * explode function.
108
+ *
109
+ * @public
110
+ */
111
+ export const concatenateBuf8List = (buf8s, addEndMarker = false) => {
112
+ const inputs = buf8s.map(buf8Input => ({
113
+ buf8Input,
114
+ lengthBuf8: lengthAsUint8Array(buf8Input.length)
115
+ }));
116
+ const totalOutputLength = inputs.reduce(
117
+ // + 2 because of the length's length and the '!' prefix
118
+ (acc, cur) => acc + cur.buf8Input.length + cur.lengthBuf8.length + 1 + 1, 0) + (addEndMarker ? 1 : 0);
119
+ const buf8 = new Uint8Array(totalOutputLength);
120
+ let cursor = 0;
121
+ const EXCLAMATION_CODE = "!".charCodeAt(0);
122
+ for (const input of inputs) {
123
+ buf8[cursor++] = EXCLAMATION_CODE;
124
+ buf8[cursor++] = input.lengthBuf8.length;
125
+ buf8.set(input.lengthBuf8, cursor);
126
+ cursor += input.lengthBuf8.length;
127
+ buf8.set(input.buf8Input, cursor);
128
+ cursor += input.buf8Input.length;
129
+ }
130
+ if (addEndMarker) buf8[cursor] = "#".charCodeAt(0);
131
+ return buf8;
132
+ };
133
+ /** Helper for explodeBuf8List() */
134
+ const extractConcatenatedBuffer = (mergedBuf8s, start, length) => {
135
+ const buffer = mergedBuf8s.slice(start, start + length);
136
+ return {
137
+ buffer,
138
+ newCursorPos: start + length
139
+ };
140
+ };
141
+ /** Helper for explodeBuf8List() */
142
+ const readNewConcatenatedBuffer = (mergedBuf8s, initialCursor) => {
143
+ // Skip '!'
144
+ let cursor = initialCursor + 1;
145
+ const bufferLengthLength = mergedBuf8s[cursor++];
146
+ const bufferLength = parseInt(buf82str(mergedBuf8s.slice(cursor, cursor + bufferLengthLength)), MAX_RADIX);
147
+ cursor += bufferLengthLength;
148
+ return extractConcatenatedBuffer(mergedBuf8s, cursor, bufferLength);
149
+ };
150
+ /**
151
+ * Try to read a "middle" version buffer; the intermediate version with no delimiters.
152
+ *
153
+ * This format was short-lived and we just assume the buffers reach the end.
154
+ */
155
+ const tryReadMiddleVersionBuffer = mergedBuf8s => {
156
+ if (mergedBuf8s.byteLength < 1) return;
157
+ // Don't lose time fake-decoding a newer buffer
158
+ const firstChar = mergedBuf8s[0];
159
+ if (firstChar === "!".charCodeAt(0) || firstChar === "#".charCodeAt(0)) return;
160
+ let cursor = 0;
161
+ const result = [];
162
+ while (cursor < mergedBuf8s.byteLength) {
163
+ const lengthStringLength = mergedBuf8s[cursor++];
164
+ if (cursor + lengthStringLength > mergedBuf8s.byteLength) return;
165
+ const lengthString = buf82str(getUint8Array(mergedBuf8s, cursor, lengthStringLength));
166
+ const length = parseInt(lengthString, MAX_RADIX);
167
+ cursor += lengthStringLength;
168
+ if (cursor + length > mergedBuf8s.byteLength) return;
169
+ const extraction = extractConcatenatedBuffer(mergedBuf8s, cursor, length);
170
+ cursor = extraction.newCursorPos;
171
+ result.push(extraction.buffer);
172
+ }
173
+ // Somewhat redundant but kept because I'm not sure the whole logic is sound
174
+ if (cursor !== mergedBuf8s.byteLength) return;
175
+ return result;
176
+ };
177
+ /** Helper for explodeBuf8List() */
178
+ const readOldConcatenatedBuffer = (mergedBuf8s, initialCursor) => {
179
+ let cursor = initialCursor;
180
+ const lengthCharacters = [];
181
+ const COMMA_CODE = ",".charCodeAt(0);
182
+ while (cursor < mergedBuf8s.length) {
183
+ const readChar = mergedBuf8s[cursor++];
184
+ if (readChar === COMMA_CODE) break;
185
+ lengthCharacters.push(readChar);
186
+ }
187
+ const bufferLength = parseInt(lengthCharacters.map(charCode => String.fromCharCode(charCode)).join(""), HEX_DIGITS);
188
+ return extractConcatenatedBuffer(mergedBuf8s, cursor, bufferLength);
189
+ };
190
+ const parseBuf8List = mergedBuf8s => {
191
+ let cursor = 0;
192
+ // Compatibility layer
193
+ const result = tryReadMiddleVersionBuffer(mergedBuf8s) ?? [];
194
+ if (result.length === 0) {
195
+ while (cursor < mergedBuf8s.length) {
196
+ // Read buffer's length's length
197
+ const bufferFirstChar = mergedBuf8s[cursor];
198
+ // eslint-disable-next-line @typescript-eslint/init-declarations
199
+ let bufferResult;
200
+ if (bufferFirstChar === "!".charCodeAt(0)) {
201
+ // Read new buffer
202
+ bufferResult = readNewConcatenatedBuffer(mergedBuf8s, cursor);
203
+ } else if (bufferFirstChar === "#".charCodeAt(0)) {
204
+ ++cursor;
205
+ break;
206
+ } else {
207
+ bufferResult = readOldConcatenatedBuffer(mergedBuf8s, cursor);
208
+ }
209
+ result.push(bufferResult.buffer);
210
+ cursor = bufferResult.newCursorPos;
211
+ }
212
+ } else {
213
+ // This result comes from the compatibility layer, we used all the input buffer
214
+ cursor = mergedBuf8s.byteLength;
215
+ }
216
+ return {
217
+ data: result,
218
+ inputBytesUsed: cursor
219
+ };
220
+ };
221
+ /**
222
+ * Separate Uint8Array previously merged using concatenateBuf8List().
223
+ *
224
+ * Each buffer prefixed by a "!" uses the format described in `concatenateBuf8List()`.
225
+ * If a buffer is not prefixed by a "!", it uses the old format:
226
+ *
227
+ * - x bytes: the length of the buffer, as an hexadecimal string
228
+ * - 1 bytes: the "," character
229
+ * - y bytes: buffer content
230
+ *
231
+ * As a special case, if the first byte read for the next buffer is "#", which is an impossible
232
+ * character for both the old and new format, it is interpreted as the end of the buffer list.
233
+ *
234
+ * @public
235
+ */
236
+ export const explodeBuf8List = mergedBuf8s => parseBuf8List(mergedBuf8s).data;
237
+ /**
238
+ * Return the length of the buffer list, up to either the end marker or the buffer size.
239
+ *
240
+ * @public
241
+ */
242
+ export const concatenatedBuf8ListSize = mergedBuf8s => parseBuf8List(mergedBuf8s).inputBytesUsed;
243
+ /**
244
+ * Merge Uint8Arrays into one.
245
+ *
246
+ * This performs a simple concatenation;
247
+ *
248
+ * @public
249
+ */
250
+ export const merge = buf8s => {
251
+ const fullLength = buf8s.reduce((acc, cur) => acc + cur.length, 0);
252
+ const buf8 = new Uint8Array(fullLength);
253
+ let cursor = 0;
254
+ for (const buf8Input of buf8s) {
255
+ buf8.set(buf8Input, cursor);
256
+ cursor += buf8Input.length;
257
+ }
258
+ return buf8;
259
+ };
260
+ /** @internal */
261
+ export const pureB642Buf8 = (b64, strict = false) => getUint8Array(bitsB642ab(b64, strict));
262
+ /**
263
+ * Convert a B64 string to an Uint8Array.
264
+ *
265
+ * @public
266
+ */
267
+ export const b642buf8 = haveBufferBase64() ? bufferB642Buf8 : pureB642Buf8;
268
+ /** @internal */
269
+ export const pureUtf82Buf8 = str => new TextEncodingShim.TextEncoder().encode(str);
270
+ /**
271
+ * Convert an UTF-8 string into an Uint8Array.
272
+ *
273
+ * @public
274
+ */
275
+ export const utf82buf8 = haveBufferUTF8() ? bufferUtf82Buf8 : pureUtf82Buf8;
276
+ /** @internal */
277
+ export const pureBuf82Utf8 = buf8 => new TextEncodingShim.TextDecoder().decode(buf8);
278
+ /**
279
+ * Convert an Uint8Array into an UTF-8 string
280
+ *
281
+ * @public
282
+ */
283
+ export const buf82utf8 = haveBufferUTF8() ? bufferBuf82Utf8 : pureBuf82Utf8;
284
+ /**
285
+ * Check that the content of two Uint8Array is equal.
286
+ *
287
+ * @public
288
+ */
289
+ export const buf8Equal = (op1, op2) => arrayEqual(op1, op2);
290
+ /**
291
+ * Find the position of a string in a buffer
292
+ *
293
+ * @param needle - String to find. Only work with 1 byte-wide characters.
294
+ *
295
+ * @param ab - Buffer to look into
296
+ *
297
+ * @param startPosition - Starting index to look from
298
+ *
299
+ * @returns
300
+ * The position of the string in the buffer. If not found returns -1
301
+ *
302
+ * @public
303
+ */
304
+ export const findString = (needle, buf8, startPosition = 0) => {
305
+ let position = startPosition;
306
+ const charCodes = needle.split("").map(strChr => strChr.charCodeAt(0));
307
+ while (position < buf8.length) {
308
+ position = buf8.indexOf(charCodes[0], position);
309
+ // First character not found in buffer?
310
+ if (position === -1) break;
311
+ // Maybe we're too late
312
+ if (position > buf8.length - charCodes.length) break;
313
+ let valid = true;
314
+ // Possible match, test all upcoming characters
315
+ for (let i = 1; valid && i < charCodes.length; ++i) {
316
+ // Mismatch?
317
+ if (buf8[position + i] !== charCodes[i]) valid = false;
318
+ }
319
+ // Found string
320
+ if (valid) return position;
321
+ ++position;
322
+ }
323
+ return -1;
324
+ };
325
+ /**
326
+ * Find the position of a string in a buffer from the end
327
+ *
328
+ * @param needle - String to find. Only work with 1 byte characters.
329
+ *
330
+ * @param ab - Buffer to look into
331
+ *
332
+ * @param startPosition - Starting index to look from
333
+ *
334
+ * @param endPosition - Last index to look from. The needle must fit completely before this.
335
+ * -1 mean end of the file.
336
+ *
337
+ * @returns
338
+ * The position of the string in the buffer. If not found returns -1
339
+ *
340
+ * @public
341
+ */
342
+ export const findLastString = (needle, buf8, startPosition = 0, endPosition = -1) => {
343
+ let position = endPosition === -1 ? buf8.length - 1 : endPosition;
344
+ const charCodes = needle.split("").reverse().map(strChr => strChr.charCodeAt(0));
345
+ while (position >= startPosition) {
346
+ position = buf8.lastIndexOf(charCodes[0], position);
347
+ // First character not found in buffer?
348
+ if (position === -1) break;
349
+ // Maybe we're too late
350
+ if (position < startPosition + charCodes.length) break;
351
+ let valid = true;
352
+ // Possible match, test all upcoming characters
353
+ for (let i = 1; valid && i < charCodes.length; ++i) {
354
+ // Mismatch?
355
+ if (buf8[position - i] !== charCodes[i]) valid = false;
356
+ }
357
+ // Found string
358
+ if (valid) return position - charCodes.length + 1;
359
+ --position;
360
+ }
361
+ return -1;
362
+ };
363
+ /* eslint-disable @typescript-eslint/no-magic-numbers */
364
+ const isInvalidFollowByte = value => value === undefined || value < 0b10000000 || value >= 0b11000000;
365
+ const utf8SequenceLength = byte1 => {
366
+ if (byte1 < 0b10000000) return 1;
367
+ if (byte1 < 0b11100000) return 2;
368
+ if (byte1 < 0b11110000) return 3;
369
+ if (byte1 < 0b11111000) return 4;
370
+ throw new Error("Invalid first byte");
371
+ };
372
+ /**
373
+ * Check if a byte sequence looks like a valid UTF-8 sequence that *does* have wide characters.
374
+ *
375
+ * https://en.wikipedia.org/wiki/UTF-8
376
+ *
377
+ * @returns
378
+ * `true` if the byte sequence does contain UTF-8 sequences.
379
+ * Regular ASCII string will return `false` as they won't contain such sequence.
380
+ */
381
+ export const isUTF8Sequence = bytes => {
382
+ try {
383
+ let haveUTF8 = false;
384
+ const b = new FourBytes(bytes);
385
+ while (b.byte1 !== undefined) {
386
+ const seqLength = utf8SequenceLength(b.byte1);
387
+ // Voluntary fallthrough
388
+ /* eslint-disable no-fallthrough */
389
+ switch (seqLength) {
390
+ // Range 0x10000-0x10FFFF
391
+ case 4:
392
+ if (isInvalidFollowByte(b.byte4)) return false;
393
+ // Range 0x0800-0xFFFF
394
+ case 3:
395
+ if (isInvalidFollowByte(b.byte3)) return false;
396
+ // Range 0x80-0x07FF
397
+ case 2:
398
+ if (isInvalidFollowByte(b.byte2)) return false;
399
+ haveUTF8 = true;
400
+ // Range 0x00-0x7F
401
+ case 1:
402
+ }
403
+ /* eslint-enable no-fallthrough */
404
+ b.advance(seqLength);
405
+ }
406
+ return haveUTF8;
407
+ } catch {
408
+ return false;
409
+ }
410
+ };
411
+ /* eslint-enable @typescript-eslint/no-magic-numbers */
412
+ export { buf82b64, pureBuf82B64 };
package/web/units.d.ts ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2023 KeeeX SAS
8
+ *
9
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
12
+ *
13
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ *
15
+ */
16
+ import ms from "ms";
17
+ /** Coerce a delay value to milliseconds using `ms` if a string is provided */
18
+ export declare const delayInMs: (delayInMsValue: number | ms.StringValue) => number;
19
+ /**
20
+ * How to convert from one level to the next for a given unit.
21
+ *
22
+ * @public
23
+ */
24
+ interface UnitConversion {
25
+ prefix?: string;
26
+ unitName?: string;
27
+ suffix?: string;
28
+ multiplierFromPrevious: number;
29
+ }
30
+ /**
31
+ * Description of a unit system to convert from one level to another.
32
+ *
33
+ * @public
34
+ */
35
+ interface UnitDescription {
36
+ prefixUnit?: boolean;
37
+ /** The base name of the unit that will be prefixed/suffixed for each level */
38
+ basename: string;
39
+ /** All conversion levels in order from smallest to largest */
40
+ levels: Array<UnitConversion>;
41
+ }
42
+ /**
43
+ * Convert description for byte based values
44
+ *
45
+ * @public
46
+ */
47
+ export declare const byteUnit: UnitDescription;
48
+ /**
49
+ * Convert description for small time based values
50
+ *
51
+ * Handles `ms`, `s`, `m` (minutes), `h`, `d`, `w` (weeks)
52
+ *
53
+ * @public
54
+ */
55
+ export declare const timeUnit: UnitDescription;
56
+ type InputAllType = string | number | bigint;
57
+ /**
58
+ * Convert a numerical value from a given unit multiplier to another.
59
+ *
60
+ * @param value - Either the value in the base unit multiplier, or a string with a unit
61
+ *
62
+ * @public
63
+ */
64
+ export declare const unitConvert: (unitDescription: UnitDescription, value: string | number, target?: string) => number;
65
+ /**
66
+ * Convert a numerical value from a given unit multiplier to another.
67
+ *
68
+ * This is the bigint variant, and can only handle integer values.
69
+ *
70
+ * @param value - Either the value in the base unit multiplier, or a string with a unit
71
+ *
72
+ * @public
73
+ */
74
+ export declare const unitConvertBigint: (unitDescription: UnitDescription, value: string | bigint | number, target?: string) => bigint;
75
+ /**
76
+ * Display a value in the largest relevant unit.
77
+ *
78
+ * For example, a call with "5678B" would return "5.68kB".
79
+ * This will lose precision and is destined to human reading.
80
+ *
81
+ * @public
82
+ */
83
+ export declare const unitString: (unitDescription: UnitDescription, value: string | number, decimalPlaces?: number) => string;
84
+ /**
85
+ * Display a value in the largest relevant unit.
86
+ *
87
+ * Bigint variant, will not return decimal values.
88
+ *
89
+ * For example, a call with "5678B" would return "5,7kB".
90
+ * This will lose precision and is destined to human reading.
91
+ *
92
+ * @public
93
+ */
94
+ export declare const unitStringBigint: (unitDescription: UnitDescription, value: string | bigint) => string;
95
+ /**
96
+ * Convert a size in bytes from one unit to another.
97
+ *
98
+ * @param targetUnit - Target unit (`kB`, `MB`, etc.). Defaults to `B`.
99
+ *
100
+ * @public
101
+ */
102
+ export declare const byteConvert: (value: string | number, targetUnit?: string) => number;
103
+ /**
104
+ * Convert a size in bytes from one unit to another.
105
+ *
106
+ * Bigint based function; can only handle integer values.
107
+ *
108
+ * @param targetUnit - Target unit (`kB`, `MB`, etc.). Defaults to `B`.
109
+ *
110
+ * @public
111
+ */
112
+ export declare const byteConvertBigint: (value: InputAllType, targetUnit?: string) => bigint;
113
+ /**
114
+ * Display a human-readable byte size value.
115
+ *
116
+ * @public
117
+ */
118
+ export declare const byteString: (value: string | number, decimalPlaces?: number) => string;
119
+ /**
120
+ * Display a human-readable byte size value.
121
+ *
122
+ * Bigint variant, only handle integer values.
123
+ *
124
+ * @public
125
+ */
126
+ export declare const byteStringBigint: (value: string | bigint) => string;
127
+ /**
128
+ * Convert a short time from one unit to another.
129
+ *
130
+ * @param targetUnit - Target unit (`ms`, `h`, etc.). Defaults to `s`.
131
+ *
132
+ * @public
133
+ */
134
+ export declare const timeConvert: (value: string | number, targetUnit?: string) => number;
135
+ /**
136
+ * Convert a short time from one unit to another.
137
+ *
138
+ * Biting based function; can only handle integer values.
139
+ *
140
+ * @param targetUnit - Target unit (`ms`, `h`, etc.). Defaults to `s`.
141
+ *
142
+ * @public
143
+ */
144
+ export declare const timeConvertBigint: (value: InputAllType, targetUnit?: string) => bigint;
145
+ /**
146
+ * Display a human-readable short time value.
147
+ *
148
+ * @public
149
+ */
150
+ export declare const timeString: (value: string | number, decimalPlaces?: number) => string;
151
+ /**
152
+ * Display a human-readable short time value.
153
+ *
154
+ * Bigint variant, only handle integer values.
155
+ *
156
+ * @public
157
+ */
158
+ export declare const timeStringBigint: (value: string | bigint) => string;
159
+ export {};