Skip to content

Commit

Permalink
feat: codecs table + impl
Browse files Browse the repository at this point in the history
  • Loading branch information
daviddias committed Sep 25, 2016
1 parent ef92d54 commit bd02c0c
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 0 deletions.
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "multicodec-packed",
"version": "0.0.0",
"description": "JavaScript implementation of the multicodec-packed specification",
"main": "src/index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/multiformats/js-multicodec-packed.git"
},
"keywords": [
"IPFS",
"multiformats",
"multicodec",
"binary",
"packed",
"the",
"data!"
],
"author": "David Dias <daviddias@ipfs.io>",
"license": "MIT",
"bugs": {
"url": "https://github.com/multiformats/js-multicodec-packed/issues"
},
"homepage": "https://github.com/multiformats/js-multicodec-packed#readme",
"dependencies": {
"varint": "^4.0.1"
}
}
20 changes: 20 additions & 0 deletions src/base-table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const varint = require('varint')

exports = module.exports

// Miscellaneous
exports.raw = varintBuf(0) // 0x00

// Multiformats
exports.multicodec = varintBuf(64) // 0x40
exports.multihash = varintBuf(65) // 0x41
exports.multiaddr = varintBuf(66) // 0x42

// Serialization formats
exports.protobuf = varintBuf(80) // 0x50
exports.cbor = varintBuf(81) // 0x51
exports.rlp = varintBuf(96) // 0x60

function varintBuf (n) {
return new Buffer(varint.encode(n))
}
36 changes: 36 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict'

const table = require('./base-table')
const varint = require('varint')

exports = module.exports

exports.addPrefix = (multicodecStrOrCode, data) => {
let pfx

if (Buffer.isBuffer(multicodecStrOrCode)) {
pfx = multicodecStrOrCode
} else {
if (table[multicodecStrOrCode]) {
pfx = table[multicodecStrOrCode]
} else {
throw new Error('multicodec not recognized')
}
}
return Buffer.concat([pfx, data])
}

exports.rmPrefix = (data) => {
varint.decode(data)
return data.slice(varint.decode.bytes)
}

exports.getMulticodec = (prefixedData) => {
const code = new Buffer(varint.decode(prefixedData))
Object.keys(table)
.forEach((multicodec) => {
if (Buffer.isEqual(code, table[multicodec])) {
return multicodec
}
})
}
Empty file added test/multicodec.spec.js
Empty file.

0 comments on commit bd02c0c

Please sign in to comment.