begining of MD5 implementation and some more work on the other code

This commit is contained in:
2026-05-14 23:29:47 +02:00
parent 619de5e1f8
commit 105bdc8c75
4 changed files with 476 additions and 58 deletions
+118 -2
View File
@@ -1,5 +1,5 @@
import type { TreeNode } from './fs';
import type { Bash } from './bash';
import type { TreeNode } from './fs';
import { Posix } from './posix';
export enum SortNodeBy {
@@ -20,7 +20,10 @@ export class Sort {
reverse: boolean = false,
sortBy: SortNodeBy = SortNodeBy.NAME
): TreeNode[] {
if (nodes.length === 0) {console.warn('Tried to sort an empty node array!'); return [];}
if (nodes.length === 0) {
console.warn('Tried to sort an empty node array!');
return [];
}
const parsedNodes: TreeNode[] = [];
if (typeof nodes[0] === 'number') {
@@ -140,3 +143,116 @@ export class Sort {
}
}
}
class Posix {
private static readonly CharTable = {
// Space and punctuation (32-47)
' ': 32,
'!': 33,
'"': 34,
'#': 35,
$: 36,
'%': 37,
'&': 38,
"'": 39,
'(': 40,
')': 41,
'*': 42,
'+': 43,
',': 44,
'-': 45,
'.': 46,
'/': 47,
// Numbers 0-9 (48-57)
'0': 48,
'1': 49,
'2': 50,
'3': 51,
'4': 52,
'5': 53,
'6': 54,
'7': 55,
'8': 56,
'9': 57,
// More punctuation (58-64)
':': 58,
';': 59,
'<': 60,
'=': 61,
'>': 62,
'?': 63,
'@': 64,
// LETTERS - INTERLEAVED AaBbCc... (65-116)
A: 65,
a: 66,
B: 67,
b: 68,
C: 69,
c: 70,
D: 71,
d: 72,
E: 73,
e: 74,
F: 75,
f: 76,
G: 77,
g: 78,
H: 79,
h: 80,
I: 81,
i: 82,
J: 83,
j: 84,
K: 85,
k: 86,
L: 87,
l: 88,
M: 89,
m: 90,
N: 91,
n: 92,
O: 93,
o: 94,
P: 95,
p: 96,
Q: 97,
q: 98,
R: 99,
r: 100,
S: 101,
s: 102,
T: 103,
t: 104,
U: 105,
u: 106,
V: 107,
v: 108,
W: 109,
w: 110,
X: 111,
x: 112,
Y: 113,
y: 114,
Z: 115,
z: 116,
// Specials after letters (now 117-126)
'[': 117,
'\\': 118,
']': 119,
'^': 120,
_: 121,
'`': 122,
'{': 123,
'|': 124,
'}': 125,
'~': 126
} as const;
public static GetCharWeight(char: string): number {
return this.CharTable[char as keyof typeof this.CharTable];
}
}
+48 -33
View File
@@ -1,4 +1,5 @@
import type { User } from '../shell/shell';
import { MD5 } from '../util/hash';
export class FileSystem {
static #instance: FileSystem;
@@ -6,14 +7,23 @@ export class FileSystem {
private _root: number;
private constructor() {
const
this._fs = this._jsonToNodeTable();
this._root = this._fs.values().next().value!.inode;
if (!this._root) throw new Error('First entry in the filesystem map empty!');
}
public static async Init() {
const fsJson: JSON = await this._fetchFileSystem('/temp/path');
const checksum: any = MD5.hash(JSON.stringify(fsJson));
}
private static async _fetchFileSystem(path: string): Promise<JSON> {
const response = await fetch(path);
if (!response.ok) throw new Error('Failed to fetch the file system json');
return await response.json();
}
private async _fetchFsSignature(path: string): Promise<any> {
try {
const response = await fetch(path);
@@ -26,15 +36,7 @@ export class FileSystem {
} catch (error) {
console.error('Failed to fetch the file system signature', error);
}
}
private async _fetchFileSystem(path: string): Promise<any> {
const response = await fetch(path);
if (!response.ok) throw new Error('Failed to fetch the file system json');
const data = await response.json();
return data;
}
}
private async fetchFsJson(sig: string): Promise<JSON> {
const signature: string | null = localStorage.getItem('signature');
@@ -55,7 +57,7 @@ export class FileSystem {
return JSON.parse(fs);
}
}
}
private _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
@@ -152,19 +154,23 @@ export class FileSystem {
this._fs.delete(inode);
}
private _iNodeToPathString(inode: number): string | null {
private _iNodeToPathString(inode: number): string {
const currentNode = this._fs.get(inode);
if (!currentNode) return null;
if (!currentNode)
throw new Error(`Failed to parse the path from inode, inode doesnt exist - ${inode}`);
if (!currentNode.parent || currentNode.inode === this._root) return '/';
const parentPath: string | null = this._iNodeToPathString(currentNode.parent);
if (!parentPath) return null;
if (!parentPath)
throw new Error(
`Failed to parse the path from inode, inode doesnt exist - ${currentNode.parent}`
);
return parentPath === '/' ? `/${currentNode.name}` : `${parentPath}/${currentNode.name}`;
}
private _pathStringToNode(path: string): TreeNode | null {
private _pathStringToNode(path: string): TreeNode {
// Truncates all slatshes at the start and end of the string
const normalizedPath: string = path.replace(/^\/+|\/+$/g, '');
@@ -172,18 +178,19 @@ export class FileSystem {
const pathComponents: string[] = normalizedPath.split('/').filter((node) => node.length > 0);
let currentNode: TreeNode | undefined = this._fs.get(this._root);
if (!currentNode) return null;
if (!currentNode)
throw new Error(`WARNING! - Root node not found under FileSystem._root - ${this._root}`);
if (pathComponents.length === 0) return currentNode;
for (const component of pathComponents) {
const childINode: number | undefined = this._getChildNodeByName(
currentNode!,
component
)?.inode;
if (!childINode) return null;
const childINode: number = this._getChildNodeByName(currentNode!, component)?.inode;
if (!childINode)
throw new Error(`Failed to parse the child node from path, is the path correct?`);
const nextNode = this._fs.get(childINode);
if (!nextNode) return null;
if (!nextNode)
throw new Error(`Failed to parse the child node from path, is the path correct?`);
currentNode = nextNode;
}
@@ -191,19 +198,21 @@ export class FileSystem {
return currentNode;
}
private _getChildNodeByName(node: TreeNode, name: string): TreeNode | null {
private _getChildNodeByName(node: TreeNode, name: string): TreeNode {
for (const inode of node.children) {
const child = this._fs.get(inode);
if (child && child.name === name) return child;
}
return null;
throw new Error(
`Node under the name ${name} not found in the child list of ${node.name} - ${node.inode}`
);
}
private _isAbsolutePath = (path: string): boolean => {
return typeof path === 'string' && path.startsWith('/');
};
public getPathByINode(inode: number): string | null {
public getPathByINode(inode: number): string {
return this._iNodeToPathString(inode);
}
@@ -212,7 +221,13 @@ export class FileSystem {
return path;
}
public resolvePath(path: string, user: User): TreeNode | null {
public getNodeByInode(inode: number): TreeNode {
const node: TreeNode | undefined = this._fs.get(inode);
if (!node) throw new Error(`No node exists under inode - ${inode}`);
return node;
}
public resolvePath(path: string, user: User): TreeNode {
if (path === '/') return this._fs.get(this._root)!;
let parsedPath: string = path;
@@ -242,13 +257,14 @@ export class FileSystem {
callback: (param: TreeNode) => void,
childIndex?: number[],
depthIndex?: number
): void | null {
): void {
if (!depthIndex) depthIndex = 0;
if (!childIndex) childIndex = [0];
if (node.type != Type.File && node.children[childIndex[depthIndex]]) {
let unNode = this._fs.get(node.children[childIndex[depthIndex]]);
if (!unNode) return null;
if (!unNode)
throw new Error(`Node does not exist under inode ${node.children[childIndex[depthIndex]]}`);
node = unNode;
depthIndex++;
@@ -257,7 +273,7 @@ export class FileSystem {
callback(node);
} else {
let unNode = this._fs.get(node.parent);
if (!unNode) return null;
if (!unNode) throw new Error(`Node does not exist under inode ${node.parent}`);
node = unNode;
childIndex[depthIndex] = 0;
@@ -271,12 +287,11 @@ export class FileSystem {
}
public static get instance(): FileSystem {
if(!FileSystem.#instance) {
if (!FileSystem.#instance) {
FileSystem.#instance = new FileSystem();
}
return FileSystem.instance;
}
}
+32
View File
@@ -0,0 +1,32 @@
export class MD5 {
private static encoder: TextEncoder = new TextEncoder();
public static hash(input: string) {
const uIntArr: Uint8Array<ArrayBuffer> = this.encoder.encode(input);
}
private pad(input: Uint8Array) {
const inputBitLength: number = input.length * 8;
const out: Uint8Array = new Uint8Array([...input, 0x80]);
const NBytes: number = (56 - (out.length % 64) + 64) % 64;
const zeroArray = new Uint8Array(NBytes);
const low = inputBitLength >>> 0;
const high = (inputBitLength / 0x100000000) >>> 0;
const lengthBytes = new Uint8Array([
low & 0xff,
(low >> 8) & 0xff,
(low >> 16) & 0xff,
(low >> 24) & 0xff,
high & 0xff,
(high >> 8) & 0xff,
(high >> 16) & 0xff,
(high >> 24) & 0xff
]);
return new Int8Array([...out, ...zeroArray, ...lengthBytes]);
}
}
+255
View File
@@ -0,0 +1,255 @@
import { FileSystem, type TreeNode } from '../filesystem/filesystem';
export enum SortNodeBy {
NAME = 'name',
INODE = 'inode',
SIZE = 'size',
EXTENSION = 'extension',
TYPE = 'type',
MTIME = 'modified',
ATIME = 'accessed',
CTIME = 'changed'
}
export class Sort {
public static nodeArraySort(
nodes: TreeNode[] | number[],
reverse: boolean = false,
sortBy: SortNodeBy = SortNodeBy.NAME
): TreeNode[] {
if (nodes.length === 0) {
console.warn('Tried to sort an empty node array!');
return [];
}
const parsedNodes: TreeNode[] = [];
if (typeof nodes[0] === 'number') {
for (const inode of nodes as number[]) {
const node = FileSystem.instance.getNodeByInode(inode);
parsedNodes.push(node);
}
Sort.nodeQSort(parsedNodes, reverse, sortBy, 0, parsedNodes.length - 1);
console.log(parsedNodes);
return parsedNodes;
} else {
Sort.nodeQSort(nodes as TreeNode[], reverse, sortBy, 0, nodes.length - 1);
console.log(nodes);
return nodes as TreeNode[];
}
}
private static nodeQSort(
array: TreeNode[],
reverse: boolean,
sortBy: SortNodeBy,
start: number,
end: number
) {
if (end <= start) return;
let pivot: number = this.nodePartition(array, reverse, sortBy, start, end);
this.nodeQSort(array, reverse, sortBy, start, pivot - 1);
this.nodeQSort(array, reverse, sortBy, pivot + 1, end);
}
private static nodePartition(
part: TreeNode[],
reverse: boolean,
sortBy: SortNodeBy,
start: number,
end: number
): number {
let pivot: TreeNode = part[end];
let i: number = start - 1;
for (let j = start; j <= end; j++) {
if (this.nodeCompareElements(part[j], pivot, sortBy, reverse) < 0) {
i++;
let temp = part[i];
part[i] = part[j];
part[j] = temp;
}
}
i++;
let temp = part[i];
part[i] = part[end];
part[end] = temp;
return i;
}
private static nodeCompareElements(
a: TreeNode,
b: TreeNode,
sortBy: SortNodeBy,
reverse: boolean
): number {
switch (sortBy) {
case SortNodeBy.NAME: {
const nameA: string = a.name.startsWith('.') ? a.name.slice(1) : a.name;
const nameB: string = b.name.startsWith('.') ? b.name.slice(1) : b.name;
const minLength = Math.min(nameA.length, nameB.length);
for (let i = 0; i < minLength; i++) {
const charCodeA = Posix.GetCharWeight(nameA[i]);
const charCodeB = Posix.GetCharWeight(nameB[i]);
if (charCodeA !== charCodeB) {
return reverse ? charCodeB - charCodeA : charCodeA - charCodeB;
}
}
return reverse ? nameB.length - nameA.length : nameA.length - nameB.length;
}
case SortNodeBy.MTIME:
case SortNodeBy.ATIME:
case SortNodeBy.CTIME: {
console.log(sortBy, 'sortby');
// The sortBy serves as the lookup key in the timestamps object.
// It works because the times in SortBy enum have assigned values matching the names of the keys in the TreeNode object
const timeA: number = a.timestamps[sortBy].getTime();
const timeB: number = b.timestamps[sortBy].getTime();
return reverse ? timeA - timeB : timeB - timeA;
}
case SortNodeBy.SIZE: {
return reverse ? a.size - b.size : b.size - a.size;
}
case SortNodeBy.EXTENSION: {
const extA: string = a.name.split('.').pop() ?? '';
const extB: string = b.name.split('.').pop() ?? '';
const minLength = Math.min(extA.length, extB.length);
for (let i = 0; i < minLength; i++) {
const charCodeA = extA.charCodeAt(i);
const charCodeB = extB.charCodeAt(i);
if (charCodeA !== charCodeB) {
return reverse ? charCodeB - charCodeA : charCodeA - charCodeB;
}
}
return reverse ? extB.length - extA.length : extA.length - extB.length;
}
case SortNodeBy.INODE: {
return reverse ? b.inode - a.inode : a.inode - b.inode;
}
case SortNodeBy.TYPE: {
return reverse ? b.type - a.type : a.type - b.type;
}
default:
throw new Error(`Sorting basis outside of the declared scope. - `);
}
}
}
class Posix {
private static readonly CharTable = {
// Space and punctuation (32-47)
' ': 32,
'!': 33,
'"': 34,
'#': 35,
$: 36,
'%': 37,
'&': 38,
"'": 39,
'(': 40,
')': 41,
'*': 42,
'+': 43,
',': 44,
'-': 45,
'.': 46,
'/': 47,
// Numbers 0-9 (48-57)
'0': 48,
'1': 49,
'2': 50,
'3': 51,
'4': 52,
'5': 53,
'6': 54,
'7': 55,
'8': 56,
'9': 57,
// More punctuation (58-64)
':': 58,
';': 59,
'<': 60,
'=': 61,
'>': 62,
'?': 63,
'@': 64,
// LETTERS - INTERLEAVED AaBbCc... (65-116)
A: 65,
a: 66,
B: 67,
b: 68,
C: 69,
c: 70,
D: 71,
d: 72,
E: 73,
e: 74,
F: 75,
f: 76,
G: 77,
g: 78,
H: 79,
h: 80,
I: 81,
i: 82,
J: 83,
j: 84,
K: 85,
k: 86,
L: 87,
l: 88,
M: 89,
m: 90,
N: 91,
n: 92,
O: 93,
o: 94,
P: 95,
p: 96,
Q: 97,
q: 98,
R: 99,
r: 100,
S: 101,
s: 102,
T: 103,
t: 104,
U: 105,
u: 106,
V: 107,
v: 108,
W: 109,
w: 110,
X: 111,
x: 112,
Y: 113,
y: 114,
Z: 115,
z: 116,
// Specials after letters (now 117-126)
'[': 117,
'\\': 118,
']': 119,
'^': 120,
_: 121,
'`': 122,
'{': 123,
'|': 124,
'}': 125,
'~': 126
} as const;
public static GetCharWeight(char: string): number {
return this.CharTable[char as keyof typeof this.CharTable];
}
}