|
| 1 | +/* eslint-disable required-modules */ |
| 2 | +'use strict'; |
| 3 | +const { Duplex } = require('stream'); |
| 4 | +const assert = require('assert'); |
| 5 | + |
| 6 | +const kCallback = Symbol('Callback'); |
| 7 | +const kOtherSide = Symbol('Other'); |
| 8 | + |
| 9 | +class DuplexSocket extends Duplex { |
| 10 | + constructor() { |
| 11 | + super(); |
| 12 | + this[kCallback] = null; |
| 13 | + this[kOtherSide] = null; |
| 14 | + } |
| 15 | + |
| 16 | + _read() { |
| 17 | + const callback = this[kCallback]; |
| 18 | + if (callback) { |
| 19 | + this[kCallback] = null; |
| 20 | + callback(); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + _write(chunk, encoding, callback) { |
| 25 | + assert.notStrictEqual(this[kOtherSide], null); |
| 26 | + assert.strictEqual(this[kOtherSide][kCallback], null); |
| 27 | + this[kOtherSide][kCallback] = callback; |
| 28 | + this[kOtherSide].push(chunk); |
| 29 | + } |
| 30 | + |
| 31 | + _final(callback) { |
| 32 | + this[kOtherSide].on('end', callback); |
| 33 | + this[kOtherSide].push(null); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function makeDuplexPair() { |
| 38 | + const clientSide = new DuplexSocket(); |
| 39 | + const serverSide = new DuplexSocket(); |
| 40 | + clientSide[kOtherSide] = serverSide; |
| 41 | + serverSide[kOtherSide] = clientSide; |
| 42 | + return { clientSide, serverSide }; |
| 43 | +} |
| 44 | + |
| 45 | +module.exports = makeDuplexPair; |
0 commit comments