-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilebuf.js
87 lines (77 loc) · 2.12 KB
/
filebuf.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
/**
* Asynchronous buffer with writeback support
*
* @constructor
* @param {string} filename Name of the file to download
* @param {boolean} writeback Allow writeback
* @param {number|undefined} size
*/
function AsyncNodeJSBuffer(filename, writeback, size) {
this.fs = require("fs");
this.filename = filename;
this.writeback = writeback;
this.byteLength = size || this.fs.statSync(filename).size;
this.fd = 0;
this.onload = undefined;
this.onprogress = undefined;
}
AsyncNodeJSBuffer.prototype.load = function() {
this.fs.open(this.filename, this.writeback ? "r+" : "r", (error, fd) => {
if (error) {
throw new Error("Cannot load: " + this.filename + ". " + error);
} else {
this.fd = fd;
this.onload && this.onload(Object.create(null));
}
});
}
AsyncNodeJSBuffer.prototype.destroy = function() {
this.fs.close(this.fd, error => {
if (error) {
throw new Error("Cannot close: " + this.filename + ". " + error);
}
});
}
/**
* @param {number} offset
* @param {number} len
* @param {function(!Uint8Array)} fn
*/
AsyncNodeJSBuffer.prototype.get = function(offset, len, fn) {
const buffer = new Uint8Array(len);
this.fs.read(this.fd, buffer, 0, len, offset, (error, bytesRead, buffer) => {
if (error) {
throw new Error("Cannot read: " + this.filename + ". " + error);
} else {
fn(buffer);
}
});
}
/**
* @param {number} start
* @param {!Uint8Array} data
* @param {function()} fn
*/
AsyncNodeJSBuffer.prototype.set = function(start, data, fn) {
if (!this.writeback)
return;
console.assert(start + data.byteLength <= this.byteLength);
this.fs.write(this.fd, data, 0, data.byteLength, start, (error, bytesWritten, data) => {
if (error) {
throw new Error("Cannot write: " + this.filename + ". " + error);
} else {
fn();
}
});
};
AsyncNodeJSBuffer.prototype.get_buffer = function(fn) {
fn();
};
AsyncNodeJSBuffer.prototype.get_state = function() {
// All changes should be written to disk
return [];
};
AsyncNodeJSBuffer.prototype.set_state = function(state) {
return;
};
exports.AsyncNodeJSBuffer = AsyncNodeJSBuffer;