-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread.ts
96 lines (54 loc) · 2.31 KB
/
read.ts
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
import { existsSync } from "https://deno.land/[email protected]/fs/mod.ts";
import { readLines } from "https://deno.land/[email protected]/io/mod.ts";
/** Read a file into lines */
const fileToLines = async ( filename: string ): Promise<string[]> => {
let lines: string[] = [];
if ( existsSync( filename ) ) {
const file = await Deno.open( filename );
for await ( const line of readLines( file ) )
lines = [ ...lines, line ];
Deno.close( file.rid );
} else
console.log( filename, "does not exist." );
return lines;
};
const getOffset = ( line: string ): number | typeof NaN => {
const hexOffset = line.match( /^[\da-fA-F]+/ );
if ( hexOffset )
return parseInt( hexOffset[ 0 ], 16 );
return NaN;
};
const linesToFrames = ( lines: string[] ): number[][] => {
let frames: number[][] = [];
let frame: number[] = [];
lines.forEach( ( line, lineNumber ) => {
const offset = getOffset( line );
if ( isNaN( offset ) ) {
console.log( "Line", lineNumber + 1, "has no valid offset." );
return [];
}
if ( lineNumber === 0 && offset !== 0 ) {
console.log( "Line 1 does not begin with a null offset." );
return [];
}
const hex = line.match( /^[0-9a-fA-F]+ +([0-9a-fA-F]{2}( [0-9a-fA-F]{2})*)/ );
if ( hex === null ) {
console.log( "Line", lineNumber + 1, "has no valid hexadecimal data." );
return [];
}
const bytes = hex[ 1 ].split( " " ).map( hex => parseInt( hex, 16 ) );
if ( lines[ lineNumber + 1 ] && getOffset( lines[ lineNumber + 1 ] ) !== 0 ) {
const bytesToRead = getOffset( lines[ lineNumber + 1 ] ) - offset;
if ( bytesToRead > bytes.length )
console.log( "Line", lineNumber + 1, "is iscomplete." );
frame = [ ...frame, ...bytes.slice( 0, bytesToRead ) ];
} else
frame = [ ...frame, ...bytes ];
if ( lineNumber === lines.length - 1 || getOffset( lines[ lineNumber + 1 ] ) === 0 ) {
frames = [ ...frames, frame ];
frame = [];
}
} );
return frames;
}
export const fileToFrames = async ( filename: string ) => linesToFrames( await fileToLines( filename ) );