compact-encoding
Advanced tools
Comparing version 2.0.0 to 2.1.0
38
index.js
@@ -40,2 +40,16 @@ const LE = (new Uint8Array(new Uint16Array([255]).buffer))[0] === 0xff | ||
exports.uint16 = { | ||
preencode (state, n) { | ||
state.end += 2 | ||
}, | ||
encode (state, n) { | ||
state.buffer[state.start++] = n | ||
state.buffer[state.start++] = n >>> 8 | ||
}, | ||
decode (state) { | ||
if (state.end - state.start < 2) throw new Error('Out of bounds') | ||
return state.buffer[state.start++] + state.buffer[state.start++] * 256 | ||
} | ||
} | ||
exports.buffer = { | ||
@@ -181,2 +195,14 @@ preencode (state, b) { | ||
exports.none = { | ||
preencode (state, m) { | ||
// do nothing | ||
}, | ||
encode (state, m) { | ||
// do nothing | ||
}, | ||
decode (state) { | ||
return null | ||
} | ||
} | ||
exports.fixed = fixed | ||
@@ -186,2 +212,14 @@ exports.array = array | ||
exports.encode = function (enc, m) { | ||
const state = { start: 0, end: 0, buffer: null } | ||
enc.preencode(state, m) | ||
state.buffer = Buffer.allocUnsafe(state.end) | ||
enc.encode(state, m) | ||
return state.buffer | ||
} | ||
exports.decode = function (enc, buffer) { | ||
return enc.decode({ start: 0, end: buffer.byteLength, buffer }) | ||
} | ||
function from (enc) { | ||
@@ -188,0 +226,0 @@ if (enc.preencode) return enc |
{ | ||
"name": "compact-encoding", | ||
"version": "2.0.0", | ||
"version": "2.1.0", | ||
"description": "A series of compact encoding schemes for building small and fast parsers and serializers", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -58,2 +58,12 @@ # compact-encoding | ||
## Helpers | ||
If you are just encoding to a buffer or decoding from one you can use the `encode` and `decode` helpers | ||
to reduce your boilerplate | ||
``` js | ||
const buf = cenc.encode(cenc.bool, true) | ||
const bool = cenc.decode(cenc.bool, buf) | ||
``` | ||
## Bundled encodings | ||
@@ -66,2 +76,3 @@ | ||
* `cenc.int` - Encodes an int using [compact-uint](https://github.com/mafintosh/compact-uint) as a signed int using ZigZag encoding. | ||
* `cenc.uint16` - Encodes a fixed size uint16 (useful for things like ports) | ||
* `cenc.buffer` - Encodes a buffer with it's length uint prefixed. When decoding an empty buf, null is returned. | ||
@@ -68,0 +79,0 @@ * `cenc.raw` - Pass through encodes a buffer - ie a basic copy. |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
22797
526
90