node/deps/npm/node_modules/minipass-sized/index.js
Myles Borins 2e54524955
deps: update npm to 7.0.0-rc.3
PR-URL: https://github.com/nodejs/node/pull/35474
Reviewed-By: Ruy Adorno <ruyadorno@github.com>
Reviewed-By: Ujjwal Sharma <ryzokuken@disroot.org>
Reviewed-By: Ben Coe <bencoe@gmail.com>
Reviewed-By: Geoffrey Booth <webmaster@geoffreybooth.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Shelley Vohr <codebytere@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
2020-10-07 09:59:49 -04:00

67 lines
1.7 KiB
JavaScript

const Minipass = require('minipass')
class SizeError extends Error {
constructor (found, expect) {
super(`Bad data size: expected ${expect} bytes, but got ${found}`)
this.expect = expect
this.found = found
this.code = 'EBADSIZE'
Error.captureStackTrace(this, this.constructor)
}
get name () {
return 'SizeError'
}
}
class MinipassSized extends Minipass {
constructor (options = {}) {
super(options)
if (options.objectMode)
throw new TypeError(`${
this.constructor.name
} streams only work with string and buffer data`)
this.found = 0
this.expect = options.size
if (typeof this.expect !== 'number' ||
this.expect > Number.MAX_SAFE_INTEGER ||
isNaN(this.expect) ||
this.expect < 0 ||
!isFinite(this.expect) ||
this.expect !== Math.floor(this.expect))
throw new Error('invalid expected size: ' + this.expect)
}
write (chunk, encoding, cb) {
const buffer = Buffer.isBuffer(chunk) ? chunk
: typeof chunk === 'string' ?
Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8')
: chunk
if (!Buffer.isBuffer(buffer)) {
this.emit('error', new TypeError(`${
this.constructor.name
} streams only work with string and buffer data`))
return false
}
this.found += buffer.length
if (this.found > this.expect)
this.emit('error', new SizeError(this.found, this.expect))
return super.write(chunk, encoding, cb)
}
emit (ev, ...data) {
if (ev === 'end') {
if (this.found !== this.expect)
this.emit('error', new SizeError(this.found, this.expect))
}
return super.emit(ev, ...data)
}
}
MinipassSized.SizeError = SizeError
module.exports = MinipassSized