Skip to content

Commit 82eb789

Browse files
committed
feat: add read method.
- Add read method to get the byte at the position in the buffer. - Add test cases for read method.
1 parent 235ca41 commit 82eb789

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

src/dynamicBuffer.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,31 @@ export class DynamicBuffer {
185185
return count;
186186
}
187187

188+
/**
189+
* Reads and returns a byte at the position `offset` in this buffer.
190+
*
191+
* ```js
192+
* buf.append('Hello world');
193+
* console.log(buf.read(0));
194+
* // 72
195+
* ```
196+
*
197+
* @param offset Number of bytes to skip before starting to read, and the offset must satisfy
198+
* between 0 and `this.length - `, default `0`.
199+
* @returns The byte at the position in the buffer.
200+
*/
201+
read(offset: number = 0) {
202+
if (!this.buffer || offset < 0 || offset >= this.used) {
203+
throw new RangeError(`The value of "offset" is out of range. It must be >= 0 and <= ${
204+
this.used - 1
205+
}. Received ${
206+
offset
207+
}`);
208+
}
209+
210+
return this.buffer[offset];
211+
}
212+
188213
/**
189214
* Copies the buffer data onto a new `Buffer` instance without unused parts.
190215
*

test/read.spec.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import assert from 'assert';
2+
import { constants } from 'buffer';
3+
import { describe, it } from 'mocha';
4+
5+
import { DynamicBuffer } from '../src';
6+
7+
describe('Read tests', () => {
8+
it('Test read without parameter', () => {
9+
const buffer = new DynamicBuffer();
10+
const str = 'Hello world';
11+
12+
buffer.append(str);
13+
14+
assert.equal(buffer.read(), str.charCodeAt(0));
15+
});
16+
17+
it('Test read with legal ranges', () => {
18+
const buffer = new DynamicBuffer();
19+
const str = 'Hello world';
20+
21+
buffer.append(str);
22+
23+
for (let i = 0; i < str.length; i += 1) {
24+
assert.equal(buffer.read(i), str.charCodeAt(i));
25+
}
26+
});
27+
28+
it('Test read with a negative offset', () => {
29+
const buffer = new DynamicBuffer();
30+
31+
buffer.append('Hello world');
32+
33+
assert.throws(() => {
34+
buffer.read(-1);
35+
});
36+
});
37+
38+
it('Test read with a offset larger than buffer length', () => {
39+
const buffer = new DynamicBuffer();
40+
41+
buffer.append('Hello world');
42+
43+
assert.throws(() => {
44+
buffer.read(buffer.length + 1);
45+
});
46+
});
47+
});

0 commit comments

Comments
 (0)