Skip to content

Commit dd9b1cd

Browse files
lemireChALkeR
andauthored
fix: safe buffer alocation
* fixes issue 115 * fixing other case * Update src/index.ts Co-authored-by: Nikita Skovoroda <chalkerx@gmail.com> * added test --------- Co-authored-by: Nikita Skovoroda <chalkerx@gmail.com>
1 parent 139b8bd commit dd9b1cd

3 files changed

Lines changed: 25 additions & 6 deletions

File tree

src/encoding/ascii.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,11 @@ describe('ASCII', () => {
77
).toBe('ASCII');
88
});
99
});
10+
11+
describe('ASCII', () => {
12+
it('should return ASCII', () => {
13+
expect(
14+
chardet.detectFileSync(__dirname + '/../test/data/encodings/shortascii', { sampleSize: 32 }),
15+
).toBe('ASCII');
16+
});
17+
});

src/index.ts

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -117,10 +117,17 @@ export const detectFile = (
117117

118118
if (opts && opts.sampleSize) {
119119
fd = fs.openSync(filepath, 'r');
120-
const sample: Buffer = Buffer.allocUnsafe(opts.sampleSize);
121-
122-
fs.read(fd, sample, 0, opts.sampleSize, opts.offset, (err?: Error) => {
123-
handler(err, sample);
120+
let sample = Buffer.allocUnsafe(opts.sampleSize);
121+
122+
fs.read(fd, sample, 0, opts.sampleSize, opts.offset, (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => {
123+
if (err) {
124+
handler(err);
125+
} else {
126+
if (bytesRead < opts.sampleSize!) {
127+
sample = sample.subarray(0, bytesRead);
128+
}
129+
handler(null, sample);
130+
}
124131
});
125132
return;
126133
}
@@ -136,9 +143,12 @@ export const detectFileSync = (
136143

137144
if (opts && opts.sampleSize) {
138145
const fd = fs.openSync(filepath, 'r');
139-
const sample = Buffer.allocUnsafe(opts.sampleSize);
146+
let sample = Buffer.allocUnsafe(opts.sampleSize);
140147

141-
fs.readSync(fd, sample, 0, opts.sampleSize, opts.offset);
148+
const bytesRead = fs.readSync(fd, sample, 0, opts.sampleSize, opts.offset);
149+
if (bytesRead < opts.sampleSize) {
150+
sample = sample.subarray(0, bytesRead);
151+
}
142152
fs.closeSync(fd);
143153
return detect(sample);
144154
}

src/test/data/encodings/shortascii

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
short

0 commit comments

Comments
 (0)