This repository has been archived by the owner on Aug 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
util.js
69 lines (60 loc) · 1.64 KB
/
util.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
61
62
63
64
65
66
67
68
69
'use strict'
const {
PBNode
} = require('./dag')
const DAGLink = require('./dag-link/dagLink')
const DAGNode = require('./dag-node/dagNode')
const { serializeDAGNode, serializeDAGNodeLike } = require('./serialize')
const genCid = require('./genCid')
/**
* @typedef {import('./types').DAGLinkLike} DAGLinkLike
*/
/**
* Calculate the CID of the binary blob
*
* @param {Uint8Array} binaryBlob - Encoded IPLD Node
* @param {import('./genCid').GenCIDOptions} [userOptions] - Options to create the CID
*/
const cid = (binaryBlob, userOptions) => {
return genCid.cid(binaryBlob, userOptions)
}
/**
* Serialize internal representation into a binary PB block
*
* @param {DAGNode | { Data?: Uint8Array, Links?: (DAGLink | DAGLinkLike)[]}} node
*/
const serialize = (node) => {
if (node instanceof DAGNode) {
return serializeDAGNode(node)
} else {
return serializeDAGNodeLike(node.Data, node.Links)
}
}
/**
* Deserialize PB block into the internal representation.
*
* @param {Uint8Array} buffer - Binary representation of a PB block
*/
const deserialize = (buffer) => {
const message = PBNode.decode(buffer)
const pbn = PBNode.toObject(message, {
defaults: false,
arrays: true,
longs: Number,
objects: false
})
/** @type {DAGLink[]} */
const links = pbn.Links.map((/** @type {DAGLinkLike} */ link) => {
// @ts-ignore
return new DAGLink(link.Name, link.Tsize, link.Hash)
})
const data = pbn.Data == null ? new Uint8Array(0) : pbn.Data
return new DAGNode(data, links, buffer.byteLength)
}
module.exports = {
codec: genCid.codec,
defaultHashAlg: genCid.defaultHashAlg,
serialize,
deserialize,
cid
}