Skip to content

Commit

Permalink
Unslab announcer record + use unslabEncode helper (#192)
Browse files Browse the repository at this point in the history
* Unslab announcer record

* Use encodeUnslab helper
  • Loading branch information
HDegroote authored Sep 19, 2024
1 parent f86e26c commit 24ac01a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
3 changes: 2 additions & 1 deletion lib/announcer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
Expand All @@ -17,7 +18,7 @@ module.exports = class Announcer {
this.relayAddresses = []
this.stopped = false
this.suspended = false
this.record = c.encode(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
this.online = new Signal()

this._refreshing = false
Expand Down
16 changes: 16 additions & 0 deletions lib/encode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab (enc, m) {
// Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
// Makes sense to put in compact-encoding when we need it in other modules too
const state = cenc.state()
enc.preencode(state, m)
state.buffer = b4a.allocUnsafeSlow(state.end)
enc.encode(state, m)
return state.buffer
}

module.exports = {
encodeUnslab
}
6 changes: 3 additions & 3 deletions lib/persistent.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

Expand Down Expand Up @@ -124,7 +125,7 @@ module.exports = class Persistent {

const k = b4a.toString(req.target, 'hex')
const announceSelf = b4a.equals(TMP, req.target)
const record = unslab(c.encode(m.peer, peer))
const record = encodeUnslab(m.peer, peer)

if (announceSelf) {
this.dht._router.set(k, {
Expand Down Expand Up @@ -196,8 +197,7 @@ module.exports = class Persistent {
}
}

const entry = c.encode(m.mutableGetResponse, { seq, value, signature })
this.mutables.set(k, unslab(entry))
this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
req.reply(null)
}

Expand Down

0 comments on commit 24ac01a

Please sign in to comment.