|
| 1 | +import { expect } from 'aegir/chai' |
| 2 | +import { encode } from 'cborg' |
| 3 | +import map from 'it-map' |
| 4 | +import { pair } from 'it-pair' |
| 5 | +import toBuffer from 'it-to-buffer' |
| 6 | +import * as varint from 'uint8-varint' |
| 7 | +import { concat as uint8ArrayConcat } from 'uint8arrays/concat' |
| 8 | +import { cborStream } from '../src/index.js' |
| 9 | +import type { CBORStream } from '../src/index.js' |
| 10 | + |
| 11 | +/* eslint-env mocha */ |
| 12 | +/* eslint-disable max-nested-callbacks */ |
| 13 | + |
| 14 | +describe('it-cbor-stream', () => { |
| 15 | + let w: CBORStream<any> |
| 16 | + |
| 17 | + beforeEach(async () => { |
| 18 | + w = cborStream(pair<Uint8Array>()) |
| 19 | + }) |
| 20 | + |
| 21 | + it('unwraps underlying stream', () => { |
| 22 | + const stream = pair<Uint8Array>() |
| 23 | + const w = cborStream(stream) |
| 24 | + |
| 25 | + expect(w.unwrap()).to.equal(stream) |
| 26 | + }) |
| 27 | + |
| 28 | + it('encode/decode', async () => { |
| 29 | + const input = { |
| 30 | + foo: 'bar' |
| 31 | + } |
| 32 | + |
| 33 | + void w.write(input) |
| 34 | + |
| 35 | + const output = await w.read() |
| 36 | + |
| 37 | + expect(output).to.deep.equal(input) |
| 38 | + }) |
| 39 | + |
| 40 | + it('reads remaining data from unwrapped stream in one buffer', async () => { |
| 41 | + const message = { |
| 42 | + foo: 'bar' |
| 43 | + } |
| 44 | + const messageBuf = encode(message) |
| 45 | + const extraData = Uint8Array.from([0, 1, 2, 3, 4, 5]) |
| 46 | + |
| 47 | + const w = cborStream({ |
| 48 | + source: (async function * () { |
| 49 | + yield uint8ArrayConcat([ |
| 50 | + varint.encode(messageBuf.byteLength), |
| 51 | + messageBuf, |
| 52 | + extraData |
| 53 | + ]) |
| 54 | + }()), |
| 55 | + sink: async () => {} |
| 56 | + }) |
| 57 | + |
| 58 | + const read = await w.read() |
| 59 | + expect(read).to.deep.equal(message) |
| 60 | + |
| 61 | + const rest = await toBuffer(map(w.unwrap().source, (buf) => buf.subarray())) |
| 62 | + expect(rest).to.equalBytes(extraData) |
| 63 | + }) |
| 64 | + |
| 65 | + it('reads remaining data from unwrapped stream in multiple buffers', async () => { |
| 66 | + const message = { |
| 67 | + foo: 'bar' |
| 68 | + } |
| 69 | + const messageBuf = encode(message) |
| 70 | + const extraData = Uint8Array.from([0, 1, 2, 3, 4, 5]) |
| 71 | + |
| 72 | + const w = cborStream({ |
| 73 | + source: (async function * () { |
| 74 | + yield varint.encode(messageBuf.byteLength) |
| 75 | + yield messageBuf |
| 76 | + yield extraData |
| 77 | + }()), |
| 78 | + sink: async () => {} |
| 79 | + }) |
| 80 | + |
| 81 | + const read = await w.read() |
| 82 | + expect(read).to.deep.equal(message) |
| 83 | + |
| 84 | + const rest = await toBuffer(map(w.unwrap().source, (buf) => buf.subarray())) |
| 85 | + expect(rest).to.equalBytes(extraData) |
| 86 | + }) |
| 87 | +}) |
0 commit comments