buffer.js for precise control over packet reading

This commit is contained in:
Tony Garnock-Jones 2018-11-29 17:13:30 +00:00
parent 7c70fa74fe
commit e0fe54e61b
2 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1,68 @@
//---------------------------------------------------------------------------
// @syndicate-lang/driver-streams-node, Stream support for Syndicate/js
// Copyright (C) 2016-2018 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//---------------------------------------------------------------------------
import { currentFacet, Observe, genUuid, Bytes, List } from "@syndicate-lang/core";
const S = activate require("./streams");
message type PacketRequest(id, size);
export {
PacketRequest,
};
export function spawnBufferStream() {
const id = genUuid('buffer-stream');
spawn named id {
stop on retracted Observe(S.Duplex(id));
assert S.Duplex(id);
assert S.StreamInfo(id, 'Duplex', null);
field this.buffer = Bytes();
field this.queue = List();
on message S.Push(id, $chunk, $ack) {
this.buffer = Bytes.concat([this.buffer, chunk]);
if (ack !== null) send ack;
}
stop on message S.Close(id, $ack) {
if (ack !== null) send ack;
}
on message PacketRequest(id, $size) {
if (size === 0) {
// Signal to terminate.
currentFacet().stop(() => { send S.Data(id, this.buffer); });
} else {
this.queue = this.queue.push(size);
}
}
dataflow {
if (!this.queue.isEmpty()) {
const expected = this.queue.first();
if (this.buffer.size >= expected) {
send S.Data(id, this.buffer.slice(0, expected));
this.buffer = this.buffer.slice(expected);
this.queue = this.queue.shift();
}
}
}
}
return id;
}

View File

@ -20,3 +20,4 @@
Object.assign(module.exports, activate require('./streams.js'));
Object.assign(module.exports, activate require('./net.js'));
Object.assign(module.exports, activate require('./subprocess.js'));
Object.assign(module.exports, activate require('./buffer.js'));