Skip to content

Commit

Permalink
fix: swap bl for uint8arraylist (#21)
Browse files Browse the repository at this point in the history
`bl` brings the buffer polyfill, node streams deps and a bunch of
other stuff, and has a big API that we don't really use any of.

Swap for the `uint8arraylist` module which only really concentrates
on appending byte arrays, slicing them and consuming bytes from them.

BREAKING CHANGE: where `BufferList`s were returned, now `Uint8ArrayList`s are
  • Loading branch information
achingbrain authored Feb 16, 2022
1 parent 68a8d54 commit a836df3
Show file tree
Hide file tree
Showing 13 changed files with 107 additions and 95 deletions.
2 changes: 1 addition & 1 deletion .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ updates:
directory: "/"
schedule:
interval: daily
time: "04:00"
time: "10:00"
open-pull-requests-limit: 10
23 changes: 3 additions & 20 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,21 +1,4 @@
The MIT License (MIT)
This project is dual licensed under MIT and Apache-2.0.

Copyright (c) 2016 Friedel Ziegelmayer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
MIT: https://www.opensource.org/licenses/mit
Apache-2.0: https://www.apache.org/licenses/license-2.0
5 changes: 5 additions & 0 deletions LICENSE-APACHE
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
19 changes: 19 additions & 0 deletions LICENSE-MIT
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ await pipe(
lp.encode(),
async source => {
for await (const chunk of source) {
encoded.push(chunk.slice()) // (.slice converts BufferList to Buffer)
encoded.push(chunk.slice()) // (.slice converts Uint8ArrayList to Uint8Array)
}
}
)
Expand All @@ -42,7 +42,7 @@ await pipe(
lp.decode(),
async source => {
for await (const chunk of source) {
decoded.push(chunk.slice()) // (.slice converts BufferList to Buffer)
decoded.push(chunk.slice()) // (.slice converts Uint8ArrayList to Uint8Array)
}
}
)
Expand Down Expand Up @@ -80,28 +80,28 @@ import {
- The following additional length encoders are available:
- **int32BE** - `const { int32BEEncode } = require('it-length-prefixed')`

Returns a [transform](https://gist.github.com/alanshaw/591dc7dd54e4f99338a347ef568d6ee9#transform-it) that yields [`BufferList`](https://www.npmjs.com/package/bl) objects. All messages will be prefixed with a length, determined by the `lengthEncoder` function.
Returns a [transform](https://gist.github.com/alanshaw/591dc7dd54e4f99338a347ef568d6ee9#transform-it) that yields [`Uint8ArrayList`](https://www.npmjs.com/package/uint8arraylist) objects. All messages will be prefixed with a length, determined by the `lengthEncoder` function.

### `encode.single(chunk, [opts])`

- `chunk: Buffer|BufferList` chunk to encode
- `chunk: Buffer|Uint8ArrayList` chunk to encode
- `opts: Object`, optional
- `lengthEncoder: Function`: See description above. Note that this encoder will _not_ be passed a `target` or `offset` and so will need to allocate a buffer to write to.

Returns a `BufferList` containing the encoded chunk.
Returns a `Uint8ArrayList` containing the encoded chunk.

### `decode([opts])`

- `opts: Object`, optional
- `maxLengthLength`: If provided, will not decode messages whose length section exceeds the size specified, if omitted will use the default of 147 bytes.
- `maxDataLength`: If provided, will not decode messages whose data section exceeds the size specified, if omitted will use the default of 4MB.
- `onLength(len: Number)`: Called for every length prefix that is decoded from the stream
- `onData(data: BufferList)`: Called for every chunk of data that is decoded from the stream
- `lengthDecoder: Function`: A function that decodes the length that prefixes each message. By default this is a [`varint`](https://www.npmjs.com/package/varint) decoder. It is passed some `data` to decode which is a [`BufferList`](https://www.npmjs.com/package/bl). The function should decode the length, set the `lengthDecoder.bytes` value (the number of bytes read) and return the length. If the length cannot be decoded, the function should throw a `RangeError`.
- `onData(data: Uint8ArrayList)`: Called for every chunk of data that is decoded from the stream
- `lengthDecoder: Function`: A function that decodes the length that prefixes each message. By default this is a [`varint`](https://www.npmjs.com/package/varint) decoder. It is passed some `data` to decode which is a [`Uint8ArrayList`](https://www.npmjs.com/package/uint8arraylist). The function should decode the length, set the `lengthDecoder.bytes` value (the number of bytes read) and return the length. If the length cannot be decoded, the function should throw a `RangeError`.
- The following additional length decoders are available:
- **int32BE** - `const { int32BEDecode } = require('it-length-prefixed')`

Returns a [transform](https://gist.github.com/alanshaw/591dc7dd54e4f99338a347ef568d6ee9#transform-it) that yields [`BufferList`](https://www.npmjs.com/package/bl) objects.
Returns a [transform](https://gist.github.com/alanshaw/591dc7dd54e4f99338a347ef568d6ee9#transform-it) that yields [`Uint8ArrayList`](https://www.npmjs.com/package/uint8arraylist) objects.

### `decode.fromReader(reader, [opts])`

Expand All @@ -111,10 +111,10 @@ Behaves like `decode` except it only reads the exact number of bytes needed for
- `opts: Object`, optional
- `maxLengthLength`: If provided, will not decode messages whose length section exceeds the size specified, if omitted will use the default of 147 bytes.
- `maxDataLength`: If provided, will not decode messages whose data section exceeds the size specified, if omitted will use the default of 4MB.
- `onData(data: BufferList)`: Called for every chunk of data that is decoded from the stream
- `onData(data: Uint8ArrayList)`: Called for every chunk of data that is decoded from the stream
- `lengthEncoder: Function`: See description above.

Returns a [transform](https://gist.github.com/alanshaw/591dc7dd54e4f99338a347ef568d6ee9#transform-it) that yields [`BufferList`](https://www.npmjs.com/package/bl) objects.
Returns a [transform](https://gist.github.com/alanshaw/591dc7dd54e4f99338a347ef568d6ee9#transform-it) that yields [`Uint8ArrayList`](https://www.npmjs.com/package/uint8arraylist) objects.

## Contribute

Expand Down
61 changes: 34 additions & 27 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,41 @@
"name": "it-length-prefixed",
"version": "6.0.1",
"description": "Streaming length prefixed buffers with async iterables",
"author": "Alan Shaw",
"license": "Apache-2.0 OR MIT",
"homepage": "https://github.com/alanshaw/it-length-prefixed#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/alanshaw/it-length-prefixed.git"
},
"bugs": {
"url": "https://github.com/alanshaw/it-length-prefixed/issues"
},
"keywords": [
"async",
"iterable",
"iterator",
"length-prefixed",
"length-prefixed-stream",
"varint"
],
"engines": {
"node": ">=16.0.0",
"npm": ">=7.0.0"
},
"type": "module",
"types": "./dist/src/index.d.ts",
"typesVersions": {
"*": {
"*": [
"*",
"*/index",
"dist/*",
"dist/*/index",
"dist/src/*",
"dist/src/*/index"
],
"src/*": [
"*",
"dist/*",
"dist/src/*",
"dist/src/*/index"
]
Expand All @@ -26,11 +52,11 @@
".": {
"import": "./dist/src/index.js"
},
"./encode": {
"import": "./dist/src/encode.js"
},
"./decode": {
"import": "./dist/src/decode.js"
},
"./encode": {
"import": "./dist/src/encode.js"
}
},
"eslintConfig": {
Expand Down Expand Up @@ -134,42 +160,23 @@
"test:electron-main": "npm run test -- -t electron-main",
"release": "semantic-release"
},
"repository": {
"type": "git",
"url": "git+https://github.com/alanshaw/it-length-prefixed.git"
},
"keywords": [
"varint",
"async",
"iterable",
"iterator",
"length-prefixed-stream",
"length-prefixed"
],
"author": "Alan Shaw",
"license": "MIT",
"bugs": {
"url": "https://github.com/alanshaw/it-length-prefixed/issues"
},
"homepage": "https://github.com/alanshaw/it-length-prefixed#readme",
"dependencies": {
"bl": "^5.0.0",
"err-code": "^3.0.1",
"it-stream-types": "^1.0.4",
"uint8arraylist": "^1.2.0",
"varint": "^6.0.0"
},
"devDependencies": {
"@types/bl": "^5.0.1",
"@types/varint": "^6.0.0",
"aegir": "^36.1.3",
"iso-random-stream": "^2.0.0",
"it-all": "^1.0.6",
"it-block": "^4.0.0",
"it-block": "^5.0.0",
"it-foreach": "^0.1.1",
"it-map": "^1.0.6",
"it-pipe": "^2.0.2",
"it-pushable": "^2.0.1",
"it-reader": "^4.0.1",
"it-reader": "^5.0.0",
"p-defer": "^4.0.0",
"random-int": "^3.0.0",
"uint8arrays": "^3.0.0"
Expand Down
35 changes: 17 additions & 18 deletions src/decode.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import BufferList from 'bl/BufferList.js'
import { Uint8ArrayList } from 'uint8arraylist'
import { varintDecode } from './varint-decode.js'
import errCode from 'err-code'
import type { LengthDecoderFunction } from './varint-decode.js'
Expand All @@ -19,22 +19,22 @@ export interface DecoderOptions {

export interface ReadResult {
mode: string
chunk?: BufferList
buffer: BufferList
chunk?: Uint8ArrayList
buffer: Uint8ArrayList
state?: ReadState
data?: BufferList
data?: Uint8ArrayList
}

interface ReadHandler {
(chunk: BufferList, buffer: BufferList, state?: ReadState, options?: DecoderOptions): ReadResult
(chunk: Uint8ArrayList, buffer: Uint8ArrayList, state?: ReadState, options?: DecoderOptions): ReadResult
}

// Maximum length of the length section of the message
export const MAX_LENGTH_LENGTH = 8 // Varint.encode(Number.MAX_SAFE_INTEGER).length
// Maximum length of the data section of the message
export const MAX_DATA_LENGTH = 1024 * 1024 * 4

const empty = new BufferList([])
const empty = new Uint8ArrayList()
const ReadModes = { LENGTH: 'readLength', DATA: 'readData' }

const ReadHandlers: Record<string, ReadHandler> = {
Expand All @@ -44,7 +44,7 @@ const ReadHandlers: Record<string, ReadHandler> = {
const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH

// console.log(ReadModes.LENGTH, chunk.length)
buffer = buffer.append(chunk)
buffer.append(chunk)

let dataLength
try {
Expand All @@ -63,8 +63,8 @@ const ReadHandlers: Record<string, ReadHandler> = {
throw errCode(new Error('message data too long'), 'ERR_MSG_DATA_TOO_LONG')
}

chunk = buffer.shallowSlice(lengthDecoder.bytes)
buffer = new BufferList()
chunk = buffer.subarray(lengthDecoder.bytes)
buffer = new Uint8ArrayList()

if (options?.onLength != null) {
options.onLength(dataLength)
Expand All @@ -78,7 +78,7 @@ const ReadHandlers: Record<string, ReadHandler> = {
},

[ReadModes.DATA]: (chunk, buffer, state, options?) => {
buffer = buffer.append(chunk)
buffer.append(chunk)

if (state == null) {
throw new Error('state is required')
Expand All @@ -89,24 +89,23 @@ const ReadHandlers: Record<string, ReadHandler> = {
}

const { dataLength } = state
const data = buffer.shallowSlice(0, dataLength)
const data = buffer.subarray(0, dataLength)

const nextChunk = buffer.length > dataLength ? buffer.shallowSlice(dataLength) : undefined
buffer = new BufferList()
const nextChunk = buffer.length > dataLength ? buffer.subarray(dataLength) : undefined
buffer = new Uint8ArrayList()

return { mode: ReadModes.LENGTH, chunk: nextChunk, buffer, state: undefined, data }
}
}

export function decode (options?: DecoderOptions): Transform<BufferList | Uint8Array, Uint8Array> {
const decoder = async function * (source: Source<BufferList | Uint8Array>): Source<Uint8Array> {
let buffer = new BufferList()
export function decode (options?: DecoderOptions): Transform<Uint8ArrayList | Uint8Array, Uint8Array> {
const decoder = async function * (source: Source<Uint8ArrayList | Uint8Array>): Source<Uint8Array> {
let buffer = new Uint8ArrayList()
let mode = ReadModes.LENGTH // current parsing mode
let state: ReadState | undefined // accumulated state for the current mode

for await (const chunk of source) {
// @ts-expect-error bl types are broken
let nextChunk: BufferList | undefined = new BufferList(chunk)
let nextChunk: Uint8ArrayList | undefined = new Uint8ArrayList(chunk)

// Each chunk may contain multiple messages - keep calling handler for the
// current parsing mode until all handlers have consumed the chunk.
Expand Down
11 changes: 5 additions & 6 deletions src/encode.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import BufferList from 'bl/BufferList.js'
import { Uint8ArrayList } from 'uint8arraylist'
import { varintEncode } from './varint-encode.js'
import { concat as uint8ArrayConcat } from 'uint8arrays'
import type { LengthEncoderFunction } from './varint-encode.js'
Expand All @@ -13,13 +13,13 @@ interface EncoderOptions {
export const MIN_POOL_SIZE = 8 // Varint.encode(Number.MAX_SAFE_INTEGER).length
export const DEFAULT_POOL_SIZE = 10 * 1024

export function encode (options?: EncoderOptions): Transform<BufferList | Uint8Array, Uint8Array> {
export function encode (options?: EncoderOptions): Transform<Uint8ArrayList | Uint8Array, Uint8Array> {
options = options ?? {}

const poolSize = Math.max(options.poolSize ?? DEFAULT_POOL_SIZE, options.minPoolSize ?? MIN_POOL_SIZE)
const encodeLength = options.lengthEncoder ?? varintEncode

const encoder = async function * (source: Source<BufferList | Uint8Array>): Source<Uint8Array> {
const encoder = async function * (source: Source<Uint8ArrayList | Uint8Array>): Source<Uint8Array> {
let pool = new Uint8Array(poolSize)
let poolOffset = 0

Expand All @@ -40,9 +40,8 @@ export function encode (options?: EncoderOptions): Transform<BufferList | Uint8A
return encoder
}

encode.single = (chunk: BufferList | Uint8Array, options?: EncoderOptions) => {
encode.single = (chunk: Uint8ArrayList | Uint8Array, options?: EncoderOptions) => {
options = options ?? {}
const encodeLength = options.lengthEncoder ?? varintEncode
// @ts-expect-error bl types are broken
return new BufferList([encodeLength(chunk.length), chunk.slice()])
return new Uint8ArrayList(...[encodeLength(chunk.length), chunk.slice()])
}
2 changes: 1 addition & 1 deletion src/int32BE-encode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { LengthEncoderFunction } from './varint-encode.js'
export const int32BEEncode: LengthEncoderFunction = (value, target, offset) => {
target = target ?? allocUnsafe(4)
const view = new DataView(target.buffer, target.byteOffset, target.byteLength)
view.setInt32(offset, value, false)
view.setInt32(offset ?? 0, value, false)
return target
}
int32BEEncode.bytes = 4 // Always because fixed length
5 changes: 3 additions & 2 deletions src/varint-encode.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import varint from 'varint'

export interface LengthEncoderFunction {
(value: number, target: Uint8Array, offset: number): Uint8Array
(value: number, target?: Uint8Array, offset?: number): Uint8Array
bytes: number
}

/**
* Encode the passed length `value` to the `target` buffer at the given `offset`
*/
export const varintEncode: LengthEncoderFunction = (value, target, offset) => {
export const varintEncode: LengthEncoderFunction = (value, target?, offset?) => {
// @ts-expect-error target can be undefined
const ret = varint.encode(value, target, offset)
varintEncode.bytes = varint.encode.bytes
// If no target, create Buffer from returned array
Expand Down
Loading

0 comments on commit a836df3

Please sign in to comment.