Skip to content

Commit

Permalink
fix: ensure Uint8Array type is returned by default (#31)
Browse files Browse the repository at this point in the history
If a buffer isn't passed a `Uint8Array` will be allocated, but if
you type the return value it overrides the default generic type
so break them out into method overloads.
  • Loading branch information
achingbrain committed Aug 16, 2023
1 parent 747c0b4 commit 4bed840
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,9 @@ export function decodeUint8ArrayList (buf: Uint8ArrayList, offset: number): numb
throw new RangeError('Could not decode varint')
}

export function encode (value: number): Uint8Array
export function encode (value: number, buf: Uint8Array, offset?: number): Uint8Array
export function encode (value: number, buf: Uint8ArrayList, offset?: number): Uint8ArrayList
export function encode <T extends Uint8Array | Uint8ArrayList = Uint8Array> (value: number, buf?: T, offset: number = 0): T {
if (buf == null) {
buf = allocUnsafe(encodingLength(value)) as T
Expand Down
6 changes: 6 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,12 @@ describe('uint8-varint', () => {
}).to.throw(RangeError)
})

it('should encode to Uint8Array by default', () => {
const buf: ArrayLike<number> = varint.encode(1234)

expect(buf).to.equalBytes([0xD2, 0x09])
})

function randint (range: number): number {
return Math.floor(Math.random() * range)
}
Expand Down

0 comments on commit 4bed840

Please sign in to comment.