-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFtzReader.js
102 lines (82 loc) · 2.21 KB
/
FtzReader.js
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
const fs = require('fs');
const FASTTEXT_VERSION = 12;
const FASTTEXT_FILEFORMAT_MAGIC_INT32 = 793712314;
class FtzReader {
constructor(modelFile) {
this.position = 0;
this.modelFile = modelFile;
}
open(callback) {
fs.readFile(this.modelFile, (err, buffer) => {
if (err) {
return callback(err);
}
this.buffer = buffer;
callback(null, this.isValid(this.readInt32(), this.readInt32()));
});
}
isValid(magicNumber, fileVersion) {
return magicNumber === FASTTEXT_FILEFORMAT_MAGIC_INT32 && fileVersion === FASTTEXT_VERSION;
}
readUInt8() {
const value = this.buffer.readUInt8(this.position);
this.position++;
return value;
}
readInt32() {
const value = this.buffer.readInt32LE(this.position);
this.position+=4;
return value;
}
readUint32() {
const value = this.buffer.readUInt32LE(this.position);
this.position+=4;
return value;
}
readFloat() {
const value = this.buffer.readFloatLE(this.position);
this.position+=4;
return value;
}
readInt64() {
let low = this.readInt32();
let high = this.readInt32();
return (high * 4294967296) + low;
}
readDouble() {
const value = this.buffer.readDoubleLE(this.position);
this.position+=8;
return value;
}
readString() {
let word = '';
while (this.buffer[this.position] != 0) {
word += String.fromCharCode(this.buffer[this.position]);
this.position++;
}
// Move past null terminator
this.position++;
return word;
}
readUInt8TypedArray(length) {
const data = new Uint8Array(length);
this.buffer.copy(data, 0, this.position, this.position + length);
this.position+=length;
return data;
}
readUInt32TypedArray(length) {
const output = new Uint32Array(length);
for (let i = 0; i < length; i++) {
output[i] = this.readUint32();
}
return output;
}
readFloat32TypedArray(length) {
const output = new Float32Array(length);
for (let i = 0; i < length; i++) {
output[i] = this.readFloat();
}
return output;
}
}
module.exports = FtzReader;