This repository has been archived by the owner on Mar 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (56 loc) · 1.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const assert = require('assert')
const Buffer = require('safe-buffer').Buffer
const leb128 = require('leb128').unsigned
const Pipe = require('buffer-pipe')
module.exports = class Capability {
/**
* creates a new capability given the path of the process creating it and a "tag"
* @param {Array<Buffer>} path
* @param {Integer} tag
*/
constructor (path, tag = 0, funIndex = 0) {
if (!Array.isArray(path)) {
path = [path]
}
this.version = 0
this.path = path
this.tag = tag
}
/**
* Serializes the capability
* @returns {Buffer}
*/
serialize () {
return Buffer.concat([
leb128.encode(this.version),
leb128.encode(this.path.length),
Buffer.concat(this.path),
leb128.encode(this.tag)
])
}
/**
* Deserializes a Buffer and returns a new instance of `Capability`
* @param {Buffer} raw
* @returns {Object}
*/
static deserialize (raw) {
const p = new Pipe(raw)
return Capability.deserializeFromPipe(p)
}
/**
* Deserializes a capability from a buffer-pipe and returns a new instance of `Capability`
* @param {Pipe} p
* @returns {Object}
*/
static deserializeFromPipe (p) {
const version = leb128.readBn(p).toNumber()
assert.equal(version, 0, 'version should be 0')
let numOfSegments = leb128.readBn(p).toNumber()
const path = []
while (numOfSegments--) {
path.push(p.read(20))
}
const tag = leb128.readBn(p).toNumber()
return new Capability(path, tag)
}
}