Skip to content

Commit efa2762

Browse files
committed
feat: get byte from buffer by index.
1 parent 7352588 commit efa2762

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/dynamicBuffer.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ export class DynamicBuffer {
8787
*/
8888
private used: number;
8989

90+
// eslint-disable-next-line no-undef
91+
[index: number]: number | undefined;
92+
9093
/**
9194
* Create a DynamicBuffer with default settings.
9295
*
@@ -187,6 +190,20 @@ export class DynamicBuffer {
187190
if (data) {
188191
this.append(data);
189192
}
193+
194+
// eslint-disable-next-line no-constructor-return
195+
return new Proxy(this, {
196+
get: (target: this, p: string | symbol, receiver: any) => {
197+
if (Reflect.has(target, p)) {
198+
return Reflect.get(target, p, receiver);
199+
}
200+
if (Number(p) >= 0) {
201+
return Reflect.apply(Reflect.get(target, 'read', receiver), target, [Number(p)]);
202+
}
203+
204+
return Reflect.get(target, p, receiver);
205+
},
206+
});
190207
}
191208

192209
/**

test/read.spec.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,35 @@ import { describe, it } from 'mocha';
33

44
import { DynamicBuffer } from '../src';
55

6+
describe('Get by index tests', () => {
7+
it('Test getting by index with legal ranges', () => {
8+
const buffer = new DynamicBuffer();
9+
const str = 'Hello world';
10+
11+
buffer.append(str);
12+
13+
for (let i = 0; i < str.length; i += 1) {
14+
assert.equal(buffer[i], str.charCodeAt(i));
15+
}
16+
});
17+
18+
it('Test getting by index with a negative offset', () => {
19+
const buffer = new DynamicBuffer();
20+
21+
buffer.append('Hello world');
22+
23+
assert.equal(buffer[-1], undefined);
24+
});
25+
26+
it('Test getting by index with a offset larger than buffer length', () => {
27+
const buffer = new DynamicBuffer();
28+
29+
buffer.append('Hello world');
30+
31+
assert.equal(buffer[buffer.length + 1], undefined);
32+
});
33+
});
34+
635
describe('Read tests', () => {
736
it('Test read without parameter', () => {
837
const buffer = new DynamicBuffer();

0 commit comments

Comments
 (0)