Skip to content

Commit 616b1a5

Browse files
santi-mirtargos
authored andcommitted
feat: decode text
1 parent 49a2df9 commit 616b1a5

File tree

4 files changed

+31
-7
lines changed

4 files changed

+31
-7
lines changed

src/IOBuffer.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { decode, encode } from './utf8';
1+
import { decode, encode } from './text';
22

33
const defaultByteLength = 1024 * 8;
44

@@ -366,6 +366,15 @@ export class IOBuffer {
366366
return decode(this.readBytes(n));
367367
}
368368

369+
/**
370+
* Read the next `n` bytes, return a string decoded with `encoding` and move pointer
371+
* forward by `n` bytes.
372+
* If no encoding is passed, the function is equivalent to @see {@link IOBuffer#readUtf8}
373+
*/
374+
public decodeText(n = 1, encoding = 'utf-8'): string {
375+
return decode(this.readBytes(n), encoding);
376+
}
377+
369378
/**
370379
* Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer
371380
* forward by 1 byte.

src/__tests__/read.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,4 +114,21 @@ describe('read data', () => {
114114
theBuffer.seek(1);
115115
expect(theBuffer.readUtf8()).toBe('4');
116116
});
117+
118+
it('decodeText', () => {
119+
const theBuffer = new IOBuffer(
120+
Buffer.from([
121+
42, 0x34, 0x32, 0xe2, 0x82, 0xac, 42, 0x72, 0x75, 0x6e, 0x21, 0xcf,
122+
0x79, 0x6f, 0x73, 0x65, 0x6d, 0x69, 0x74, 0x65,
123+
]),
124+
);
125+
expect(theBuffer.readByte()).toBe(42);
126+
const strE1 = theBuffer.decodeText(5);
127+
expect(strE1).toBe('42€');
128+
expect(theBuffer.readByte()).toBe(42);
129+
const strE2 = theBuffer.decodeText(4, 'windows-1251');
130+
expect(strE2).toBe('run!');
131+
expect(theBuffer.decodeText(1, 'windows-1251')).toBe('П');
132+
expect(theBuffer.decodeText(8, 'ISO-8859-2')).toBe('yosemite');
133+
});
117134
});
Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
// eslint-disable-next-line import/no-unassigned-import
22
import './text-encoding-polyfill';
33

4-
const decoder = new TextDecoder('utf-8');
5-
6-
export function decode(bytes: Uint8Array): string {
4+
export function decode(bytes: Uint8Array, encoding = 'utf8'): string {
5+
const decoder = new TextDecoder(encoding);
76
return decoder.decode(bytes);
87
}
98

src/utf8.ts renamed to src/text.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import { TextDecoder, TextEncoder } from 'util';
22

3-
const decoder = new TextDecoder('utf-8');
4-
5-
export function decode(bytes: Uint8Array): string {
3+
export function decode(bytes: Uint8Array, encoding = 'utf8'): string {
4+
const decoder = new TextDecoder(encoding);
65
return decoder.decode(bytes);
76
}
87

0 commit comments

Comments
 (0)