export function bind_sendPacketStream(wstream) :: const pkt_hdr_1 = Buffer.from @# 0 const pkt_hdr_3 = Buffer.from @# 254, 0, 0 const pkt_hdr_5 = Buffer.from @# 255, 0, 0, 0, 0 let p_drain = null, on_drain :: let p = new Promise @ resolve => :: wstream.on @ 'drain', _drained wstream.once @ 'error', shutdown wstream.once @ 'close', shutdown function shutdown() :: if null !== wstream :: wstream.off @ 'drain', _drained wstream.end() wstream = null resolve() return @[] send_packed, p function send_packed(d_pkt) :: if null === wstream :: // blackhole extra packets return Promise.resolve(false) d_pkt = Buffer.from(d_pkt) let len = d_pkt.byteLength let pkt_hdr if len < 254 :: ; (pkt_hdr = pkt_hdr_1).writeUInt8 @ len, 0 else if len < 65536 :: ; (pkt_hdr = pkt_hdr_3).writeUInt16BE @ len, 1 else :: ; (pkt_hdr = pkt_hdr_5).writeUInt32BE @ len, 1 let s_pkt = Buffer.concat @# pkt_hdr, d_pkt if wstream.write(s_pkt) :: return true // sent immediate, no backpressure promise // backpressure as promise for next drain event return next_drain() function next_drain() :: if null === p_drain :: p_drain = new Promise @ resolve => :: on_drain = resolve return p_drain function _drained() :: p_drain = null if null !== on_drain :: on_drain(true) on_drain = null