fifo-buffer
v1.0.0
Published
A fast FIFO implementation purely based on Node Buffers
Downloads
24
Readme
fifo.js
A simple fifo buffer for node-buffers. Excellent for handling encapsulated binary data in a TCP/IP stream. I encountered many situations where I needed to decode an embedded packet structure from a socket stream.
Installation
As npm for Node.js:
$ npm install fifo-buffer
Example
Some console interaction:
> FIFO=require('./fifo.js')
[Function: FIFOBuffer]
> b = new FIFO()
FIFOBuffer {
buffer: <Buffer 00 00 00 00 00 00 00 00 00 ... >,
high: 1048576,
tail: 0,
head: 0 }
> b.enq(Buffer.from([1,2,3,4]))
true
> b.enq(Buffer.from([5,6,7,8]))
true
> b.deq(2)
<Buffer 01 02>
> b.deq(2)
<Buffer 03 04>
> b.deq(2)
<Buffer 05 06>
> b.deq(2)
<Buffer 07 08>
> b.deq(2)
null
> b.enq(Buffer.from([1,2,3,4]))
true
> b.peek(2)
<Buffer 01 02>
> b.peek(2)
<Buffer 01 02>
> b.peek(5)
null
> b.size
4
>
A sample interface to extract a packet within a TCP/IP stream. Assuming socket is configured to provide a buffer on "data". The encapsulated packet simply begins with a 4 byte header containing its length.
var FIFO = require('fifo-buffer');
var fifo = new FIFO();
// ... assuming socket setup and connected:
socket.on("data", (data) => {
if (!fifo.enq(data))
throw "No more space in FIFO!";
let temp_buf;
while (temp_buf = fifo.peek(4)) { // as long as there are 4 bytes in fifo (our header)
let psize = temp_buf.readUInt32BE(); // we only deq complete packets so the first 4 bytes must be the length of the incoming packet.
if (fifo.size < psize + 4)
break; // incomplete packet, try again next time we receive data.
// EITHER remove header and give remaining packet to some handler:
fifo.deq(4); // trash 4 byte Header
handleCompleteEncapsulatedPacket(fifo.deq(psize));
// OR leave header in place:
handleCompleteEncapsulatedPacket(fifo.deq(psize + 4));
}
});
API
FIFOBuffer()
Initializes a new empty FIFOBuffer
with the default capacity (1MByte).
FIFOBuffer(capacity)
Initializes a new empty FIFOBuffer
with the given capacity
.
FIFOBuffer#deq(n)
Dequeues the oldest n bytes of the FIFO buffer and returns a copy.
Returns null
when the buffer has less bytes available.
FIFOBuffer#enq(buffer)
Enqueues the buffer
at the end and returns true
when there was enough space.
When the buffer is full the method returns false
.
FIFOBuffer#peek(n)
Copies the oldest n bytes of the FIFO buffer. Does not change the state.
Returns null
when the buffer has less bytes available.
FIFOBuffer#size
Returns the current size of the FIFO.
Testing
As npm package:
$ npm test
Licence
ISC