Skip to content

Commit

Permalink
feat(decode): add decodeFromReader method
Browse files Browse the repository at this point in the history
  • Loading branch information
dignifiedquire committed Aug 8, 2016
1 parent 193c832 commit 729dc2e
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 42 deletions.
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@
},
"homepage": "https://github.com/dignifiedquire/pull-length-prefixed#readme",
"dependencies": {
"pull-reader": "^1.2.5",
"pull-reader": "^1.2.8",
"safe-buffer": "^5.0.1",
"varint": "^4.0.0"
"varint": "^4.0.1"
},
"devDependencies": {
"aegir": "^3.2.0",
"aegir": "^6.0.0",
"chai": "^3.5.0",
"pull-pushable": "^2.0.0",
"pull-stream": "^3.4.2"
"pull-pushable": "^2.0.1",
"pull-stream": "^3.4.3"
}
}
77 changes: 42 additions & 35 deletions src/decode.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,54 +4,61 @@ const varint = require('varint')
const Reader = require('pull-reader')
const Buffer = require('safe-buffer').Buffer

module.exports = decode
exports.decode = decode
exports.decodeFromReader = decodeFromReader

const MSB = 0x80
const isEndByte = (byte) => !(byte & MSB)

function decode () {
let ended = false
let reader = new Reader()
let first = true

return (read) => (end, cb) => {
reader(read)
if (end) return reader.abort(end, cb)
if (ended) return cb(ended)

let rawMsgSize = []
if (first) readByte()

// 1. Read the varint
function readByte () {
first = false
reader.read(1, (err, byte) => {
if (err) {
ended = err
return cb(ended)
}

rawMsgSize.push(byte)
if (byte && !isEndByte(byte[0])) {
readByte()
} else {
readMessage()
}
})
}

function readMessage () {
const msgSize = varint.decode(Buffer.concat(rawMsgSize))
decodeFromReader(reader, (err, msg) => {
if (err) {
ended = err
return cb(ended)
}

cb(null, msg)
})
}
}

function decodeFromReader (reader, cb) {
let rawMsgSize = []
if (rawMsgSize.length === 0) readByte()

// 1. Read the varint
function readByte () {
reader.read(1, (err, byte) => {
if (err) {
return cb(err)
}

rawMsgSize.push(byte)
if (byte && !isEndByte(byte[0])) {
readByte()
} else {
readMessage()
}
})
}

function readMessage () {
const msgSize = varint.decode(Buffer.concat(rawMsgSize))
reader.read(msgSize, (err, msg) => {
if (err) {
return cb(err)
}

rawMsgSize = []
reader.read(msgSize, (err, msg) => {
if (err) {
ended = err
return cb(ended)
}

first = true
cb(null, msg)
})
}
cb(null, msg)
})
}
}
5 changes: 3 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
'use strict'

const encode = require('./encode')
const decode = require('./decode')
const d = require('./decode')

exports.encode = encode
exports.decode = decode
exports.decode = d.decode
exports.decodeFromReader = d.decodeFromReader

0 comments on commit 729dc2e

Please sign in to comment.