-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.mjs
More file actions
497 lines (459 loc) · 11.6 KB
/
Copy pathutils.mjs
File metadata and controls
497 lines (459 loc) · 11.6 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import {
DIR_NAME_LENGTH,
LFN_ALL_NAMES_LENGTH,
LFN_BUFFER_LEN,
LFN_MAX_LEN,
LFN_NAME1_LENGTH,
LFN_NAME2_LENGTH,
LFN_NAME3_LENGTH,
MAX_BYTE,
MAX_WORD,
} from "./const.mjs";
import { CHS, DirEntryLFN } from "./types.mjs";
// @ts-expect-error
// eslint-disable-next-line no-undef
const ASSERTS_ENABLED = typeof USE_ASSERTS === "boolean" ? USE_ASSERTS : true;
/**
* @param {boolean|number} expression
* @param {string} [msg]
*/
export const assert = (expression, msg) => {
if (ASSERTS_ENABLED) {
if (!expression) {
throw new Error(msg ?? "AssertionError");
}
}
};
/**
* @param {string} str
* @return {!Uint8Array}
*/
export const str2bytes = (str) => new Uint8Array([...str].map((/** @type {string} */ it) => it.charCodeAt(0)));
/**
* @type {!Uint8Array}
*/
const SHORT_NAME_SPECIAL_CHARACTERS = str2bytes(" $%'-_@~`!(){}^#&");
/**
* @type {!Uint8Array}
*/
const LONG_NAME_SPECIAL_CHARACTERS = str2bytes(".+,;=[]");
/**
* @param {number} code
* @return {boolean}
*/
const isCapitalLetter = (code) => code > "A".charCodeAt(0) - 1 && code < "Z".charCodeAt(0) + 1;
/**
* @param {number} code
* @return {boolean}
*/
const isSmallLetter = (code) => code > "a".charCodeAt(0) - 1 && code < "z".charCodeAt(0) + 1;
/**
* @param {number} code
* @return {boolean}
*/
const isDigit = (code) => code > "0".charCodeAt(0) - 1 && code < "9".charCodeAt(0) + 1;
/**
* @param {number} code
* @return {boolean}
*/
const isUnicode = (code) => code > 255;
/**
* @param {number} code
* @return {boolean}
*/
const isExtended = (code) => code > 127;
/**
* @param {!Uint8Array} sfn
* @return {number}
*/
export const getChkSum = (sfn) => {
assert(sfn.length === DIR_NAME_LENGTH);
let sum = sfn[0];
for (let i = 1, len = sfn.length; i < len; i++) {
sum = (((sum << 7) | (sum >> 1)) + sfn[i]) & 0xff;
}
return sum;
};
/**
* @param {number} code
* @return {boolean}
*/
export const isShortNameValidCode = (code) => {
assert(code >= 0 && code <= MAX_BYTE);
return isExtended(code) || isCapitalLetter(code) || isDigit(code) || SHORT_NAME_SPECIAL_CHARACTERS.includes(code);
};
/**
* @param {number} wcCode
* @return {boolean}
*/
const isLongNameValidCode = (wcCode) => {
assert(wcCode >= 0 && wcCode <= MAX_WORD);
return isUnicode(wcCode) || isSmallLetter(wcCode) || isShortNameValidCode(wcCode) || LONG_NAME_SPECIAL_CHARACTERS.includes(wcCode);
};
/**
* @param {string} longName
* @return {string}
*/
export const normalizeLongName = (longName) => {
// return longName.replace(/[\s.]*$/gu, "").trim();
let i = 0;
while (i < longName.length && longName.charCodeAt(i) === " ".charCodeAt(0)) {
i++;
}
let j = longName.length - 1;
let ch;
while (j >= i && ((ch = longName.charCodeAt(j)) === " ".charCodeAt(0) || ch === ".".charCodeAt(0))) {
j--;
}
return longName.slice(i, j + 1);
};
/**
* @param {string} path
* @return {!Array<string>}
*/
export const split = (path) => {
const names = [];
const parts = path.split(/[/\\]/u);
for (let i = 0; i < parts.length; i++) {
const part = parts[i].trim();
if (part !== "" && part !== ".") {
if (part === "..") {
if (names.length) {
names.length--;
}
} else {
const name = normalizeLongName(part);
if (name !== "") {
names.push(name);
}
}
}
}
return names;
};
/**
* @param {!Uint8Array} sfn
* @param {!libmount.Codepage} cp
* @return {string}
*/
export const sfnToStr = (sfn, cp) => {
assert(sfn.length === DIR_NAME_LENGTH);
const str = cp.decode(sfn);
const basename = str.slice(0, 8).trimEnd();
const ext = str.slice(8, 11).trimEnd();
return ext === "" ? basename : basename + "." + ext;
};
/**
* @param {!Uint8Array} sfn
* @param {number} offset
* @param {number} len
* @param {!libmount.Codepage} cp
* @param {string} str
* @return {boolean}
*/
const appendToSFN = (sfn, offset, len, cp, str) => {
if (str.startsWith(" ") || str.endsWith(" ")) {
// invalid
return false;
}
let i = 0;
const buf = cp.encode(str);
if (buf.length > len) {
// too long
return false;
}
while (i < buf.length) {
const code = buf[i];
if (!isShortNameValidCode(code)) {
// invalid char
return false;
}
sfn[offset + i] = code;
i++;
}
// pad with spaces
while (i < len) {
sfn[offset + i] = " ".charCodeAt(0);
i++;
}
return true;
};
/**
* @param {string} str
* @param {!libmount.Codepage} codepage
* @return {?Uint8Array}
*/
export const strToSfn = (str, codepage) => {
const i = str.lastIndexOf(".");
const basename = i < 0 ? str : str.substring(0, i);
const ext = i < 0 ? "" : str.substring(i + 1);
if (basename === "" && ext === "") {
// both are empty
return null;
}
const sfn = new Uint8Array(DIR_NAME_LENGTH);
if (!appendToSFN(sfn, 0, 8, codepage, basename)) {
// filename is not valid for short name
return null;
}
if (!appendToSFN(sfn, 8, 3, codepage, ext)) {
// ext is not valid for short name
return null;
}
return sfn;
};
const LFN_BUFFER = new Uint8Array(LFN_BUFFER_LEN);
/**
* @param {string} str
* @return {?Uint8Array}
*/
export const strToLfn = (str) => {
assert(str.length && str.length <= LFN_MAX_LEN);
const lfn = LFN_BUFFER;
let i = 0;
let j = 0;
while (i < str.length) {
let ch = str.charCodeAt(i++);
if (!isLongNameValidCode(ch)) {
// invalid char
return null;
}
lfn[j++] = ch; // & 0xff;
ch >>= 8;
lfn[j++] = ch; // & 0xff;
}
// A name that fits exactly in a set of long name directory entries
// (i.e. is an integer multiple of 13) is not NULL terminated and not padded with 0xFFFF.
if (j % LFN_ALL_NAMES_LENGTH !== 0) {
// NULL-terminator
lfn[j++] = 0;
lfn[j++] = 0;
// 0xFF padding
while (j % LFN_ALL_NAMES_LENGTH !== 0) {
lfn[j++] = MAX_BYTE;
lfn[j++] = MAX_BYTE;
}
}
assert(j <= lfn.length);
return lfn.subarray(0, j);
};
const LFN_DECODE_BUFFER = new Uint16Array(LFN_BUFFER_LEN / 2);
/**
* @param {!Array<!DirEntryLFN>} chain
* @return {string}
*/
export const lfnToStr = (chain) => {
assert(chain.length > 0);
const buf = LFN_DECODE_BUFFER;
let len = 0;
let k = chain.length - 1;
let ch;
do {
const item = chain[k--];
const Name1 = item.Name1;
let i = 0;
while (i < LFN_NAME1_LENGTH && (ch = Name1[i++] | (Name1[i++] << 8))) {
buf[len++] = ch;
}
if (ch) {
const Name2 = item.Name2;
i = 0;
while (i < LFN_NAME2_LENGTH && (ch = Name2[i++] | (Name2[i++] << 8))) {
buf[len++] = ch;
}
if (ch) {
const Name3 = item.Name3;
i = 0;
while (i < LFN_NAME3_LENGTH && (ch = Name3[i++] | (Name3[i++] << 8))) {
buf[len++] = ch;
}
}
}
} while (ch && k >= 0);
return String.fromCharCode(...buf.subarray(0, len));
};
/**
* @param {string} str
* @param {number} max
* @param {!libmount.Codepage} cp
* @return {string}
*/
const toValidShortNameCharacters = (str, max, cp) => {
let ret = "";
let i = 0;
let count = 0;
while (i < str.length && count < max) {
const ch = str.charAt(i);
// skip leading spaces
if (ret !== "" || ch !== " ") {
const buf = cp.encode(ch);
// check 1st byte only
const code = buf[0];
// ignore all characters encoded as "?" as they are "unmapped"
if (code !== "?".charCodeAt(0)) {
if (isShortNameValidCode(code)) {
// character is "mapped" and 1st byte is valid for SFN
ret += ch;
// encoding can be multi-byte
count += buf.length;
} else {
// replace all "mapped" but invalid for SFN characters by "_"
ret += "_";
count++;
}
}
}
i++;
}
return ret;
};
/**
* @param {string} str
* @return {string}
*/
const strToHash = (str) => {
let sum = 0;
for (let i = 0; i < str.length; i++) {
sum = (sum + str.charCodeAt(i)) & 0xffff;
}
return sum.toString(16).padStart(4, "0").toUpperCase();
};
/**
* @param {string} str
* @param {!libmount.Codepage} cp
* @param {!Set<string>} fileNames
* @return {string}
*/
export const strToTildeName = (str, cp, fileNames) => {
str = str.toUpperCase();
const i = str.lastIndexOf(".");
const basename = i < 0 ? str : str.substring(0, i);
const ext = i < 0 ? "" : str.substring(i + 1);
const basename6 = toValidShortNameCharacters(basename, 6, cp);
const ext3 = toValidShortNameCharacters(ext, 3, cp);
assert(!basename6.startsWith(" ") && basename6.length <= 6);
assert(!ext3.startsWith(" ") && ext3.length <= 3);
const prefix = basename6.length > 2 ? basename6 : basename6 + strToHash(str);
const postfix = ext3 === "" ? "" : "." + ext3;
let num = 1;
let numLen = 1;
while (numLen <= 7) {
const filename = prefix.substring(0, 7 - numLen) + "~" + num + postfix;
if (!fileNames.has(filename)) {
return filename;
}
num++;
numLen = num.toString().length;
}
// namespace overflow is impossible
return "";
};
// Dates
/**
* @param {number} date
* @return {?Date}
*/
export const parseDate = (date) => {
if (!date) {
return null;
}
const dayOfMonth = date & 0b11111;
const monthOfYear = (date >> 5) & 0b1111;
const yearSince1980 = (date >> 9) & 0b1111111;
return new Date(1980 + yearSince1980, Math.max(0, monthOfYear - 1), Math.max(1, dayOfMonth));
};
/**
* @param {number} date
* @param {number} time
* @param {number} timeTenth
* @return {?Date}
*/
export const parseDateTime = (date, time, timeTenth) => {
if (!date) {
return null;
}
const dayOfMonth = date & 0b11111;
const monthOfYear = (date >> 5) & 0b1111;
const yearSince1980 = (date >> 9) & 0b1111111;
const millis = (timeTenth % 100) * 10;
const seconds = Math.floor(timeTenth / 100) + ((time & 0b11111) << 1);
const minutes = (time >> 5) & 0b111111;
const hours = (time >> 11) & 0b11111;
return new Date(1980 + yearSince1980, Math.max(0, monthOfYear - 1), Math.max(1, dayOfMonth), hours, minutes, seconds, millis);
};
/**
* @param {?Date} date
* @return {number}
*/
export const toDate = (date) => {
if (!date) {
return 0;
}
const yearSince1980 = date.getFullYear() - 1980;
const monthOfYear = date.getMonth() + 1;
const dayOfMonth = date.getDate();
return (yearSince1980 << 9) | (monthOfYear << 5) | dayOfMonth;
};
/**
* @param {?Date} date
* @return {number}
*/
export const toTime = (date) => {
if (!date) {
return 0;
}
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
return (hours << 11) | (minutes << 5) | (seconds >> 1);
};
/**
* @param {?Date} date
* @return {number}
*/
export const toTimeTenth = (date) => {
if (!date) {
return 0;
}
const seconds = date.getSeconds();
const millis = date.getMilliseconds();
return Math.floor(((seconds % 2) * 1000 + Number(millis)) / 10);
};
/**
* @param {!libmount.Codepage} cp
* @param {number} len
* @param {?string} str
* @return {!Uint8Array}
*/
export const strToUint8Array = (cp, len, str) => {
const data = new Uint8Array(len).fill(" ".charCodeAt(0));
if (str) {
data.set(cp.encode(str.substring(0, len)).subarray(0, len));
}
return data;
};
/**
* @param {!CHS} chs
* @param {number} TH
* @param {number} TS
* @return {number}
*/
export const chs2lba = (chs, TH, TS) => (chs.Cylinder * TH + chs.Head) * TS + (chs.Sector - 1);
/**
* @param {number} LBA
* @param {number} TH
* @param {number} TS
* @return {!CHS}
*/
export const lba2chs = (LBA, TH, TS) => {
const Cylinder = Math.floor(LBA / (TS * TH));
const i = Cylinder * TH * TS;
const Head = Math.floor((LBA - i) / TS);
const j = Head * TS;
const Sector = LBA - i - j + 1;
return {
Cylinder,
Head,
Sector,
};
};