Files: 94b5daa6362ac3c9f4a4c781894a73ad2c5160c5 / utils.js
1181 bytesRaw
1 | const { FunctionRef, ModuleRef, generateActorId, getType } = require('./') |
2 | |
3 | const actorRefToId = ref => ref.reduce((parent, curr) => generateActorId({ parent, nonce: curr }), null) |
4 | |
5 | const toHex = arg => Buffer.isBuffer(arg) ? `0x${arg.toString('hex')}` : arg |
6 | |
7 | const fromHex = arg => typeof arg !== 'string' ? arg : Buffer.from(arg.slice(0, 2) === '0x' ? arg.slice(2) : arg, 'hex') |
8 | |
9 | const toJSON = (arg, includeOptional = true) => { |
10 | switch (getType(arg)) { |
11 | case 'elem': |
12 | return arg.map(a => toJSON(a, includeOptional)) |
13 | case 'id': |
14 | case 'func': |
15 | case 'mod': |
16 | return arg.toJSON(includeOptional) |
17 | case 'link': |
18 | return { |
19 | '@Link': { |
20 | '/': toJSON(arg['/'], includeOptional) |
21 | } |
22 | } |
23 | case 'data': |
24 | default: |
25 | return toHex(arg) |
26 | } |
27 | } |
28 | |
29 | const fromJSON = arg => { |
30 | if (typeof arg === 'object') { |
31 | if (Array.isArray(arg)) { |
32 | return arg.map(fromJSON) |
33 | } |
34 | |
35 | if (arg['@FunctionRef']) { |
36 | return FunctionRef.fromJSON(arg) |
37 | } else if (arg['@ModuleRef']) { |
38 | return ModuleRef.fromJSON(arg) |
39 | } |
40 | } |
41 | |
42 | return fromHex(arg) |
43 | } |
44 | |
45 | module.exports = { |
46 | actorRefToId, |
47 | toJSON, |
48 | fromJSON, |
49 | toHex, |
50 | fromHex |
51 | } |
52 |
Built with git-ssb-web