Skip to content

Commit

Permalink
efficient u8a-style slice() & ensure byte arrays have clean-bounds
Browse files Browse the repository at this point in the history
  • Loading branch information
rvagg committed Jan 9, 2021
1 parent 136ee99 commit c97a9cc
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
4 changes: 2 additions & 2 deletions lib/2bytes.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Token, Type } from './token.js'
import { assertEnoughData } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'
import { compare, fromString, slice } from './byte-utils.js'

function toToken (data, pos, prefix, length) {
assertEnoughData(data, pos, prefix + length)
const buf = data.subarray(pos + prefix, pos + prefix + length)
const buf = slice(data, pos + prefix, pos + prefix + length)
return new Token(Type.bytes, buf, prefix + length)
}

Expand Down
4 changes: 2 additions & 2 deletions lib/bl.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat } from './byte-utils.js'
import { alloc, concat, slice } from './byte-utils.js'

const defaultChunkSize = 1024

Expand Down Expand Up @@ -151,7 +151,7 @@ class Bl {
this._initReuseChunk = null
this.chunks = []
} else {
byts = Uint8Array.prototype.slice.call(this.chunks[0], 0, this.cursor)
byts = slice(this.chunks[0], 0, this.cursor)
}
} else {
byts = concat(this.chunks, this.cursor)
Expand Down
12 changes: 12 additions & 0 deletions lib/byte-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ export const fromArray = (arr) => {
return Uint8Array.from(arr)
}

export const slice = useBuffer
? (bytes, start, end) => {
if (isBuffer(bytes)) {
return new Uint8Array(bytes.subarray(start, end))
}
return bytes.slice(start, end)
}
/* c8 ignore next 3 */
: (bytes, start, end) => {
return bytes.slice(start, end)
}

export const concat = useBuffer
? (chunks, length) => {
// might get a stray plain Array here
Expand Down

0 comments on commit c97a9cc

Please sign in to comment.