Skip to content

Commit

Permalink
feat: added utils.js from js-libp2p-floodsub
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikerah committed Apr 16, 2019
1 parent 1d04874 commit d83e357
Showing 1 changed file with 95 additions and 0 deletions.
95 changes: 95 additions & 0 deletions src/utils.js
@@ -0,0 +1,95 @@
'use strict'

const crypto = require('libp2p-crypto')
const bs58 = require('bs58')

exports = module.exports

/**
* Generatea random sequence number.
*
* @returns {Buffer}
* @private
*/
exports.randomSeqno = () => {
return crypto.randomBytes(20)
}

/**
* Generate a message id, based on the `from` and `seqno`.
*
* @param {string} from
* @param {Buffer} seqno
* @returns {string}
* @private
*/
exports.msgId = (from, seqno) => {
return from + seqno.toString('hex')
}

/**
* Check if any member of the first set is also a member
* of the second set.
*
* @param {Set|Array} a
* @param {Set|Array} b
* @returns {boolean}
* @private
*/
exports.anyMatch = (a, b) => {
let bHas
if (Array.isArray(b)) {
bHas = (val) => b.indexOf(val) > -1
} else {
bHas = (val) => b.has(val)
}

for (let val of a) {
if (bHas(val)) {
return true
}
}

return false
}

/**
* Make everything an array.
*
* @param {any} maybeArray
* @returns {Array}
* @private
*/
exports.ensureArray = (maybeArray) => {
if (!Array.isArray(maybeArray)) {
return [maybeArray]
}

return maybeArray
}

exports.normalizeInRpcMessages = (messages) => {
if (!messages) {
return messages
}
return messages.map((msg) => {
const m = Object.assign({}, msg)
if (Buffer.isBuffer(msg.from)) {
m.from = bs58.encode(msg.from)
}
return m
})
}

exports.normalizeOutRpcMessages = (messages) => {
if (!messages) {
return messages
}
return messages.map((msg) => {
const m = Object.assign({}, msg)
if (typeof msg.from === 'string' || msg.from instanceof String) {
m.from = bs58.decode(msg.from)
}
return m
})
}

0 comments on commit d83e357

Please sign in to comment.