Skip to content

Add support for large integers#44

Merged
jhermsmeier merged 1 commit into
masterfrom
bignum-support
Aug 25, 2016
Merged

Add support for large integers#44
jhermsmeier merged 1 commit into
masterfrom
bignum-support

Conversation

@jhermsmeier
Copy link
Copy Markdown
Contributor

[WIP]: Adds support for large 2^53+ integers via bignumber.js as proposed in #35.
Not sure this is the best way of doing it – been thinking about a way to hook certain types or define custom ones, similiar to the mechanic msgpack uses – which I'll attempt to explore as well.

Closes #35

@fanatid
Copy link
Copy Markdown

fanatid commented Mar 28, 2016

Why not use indutny/bn.js?

@jhermsmeier
Copy link
Copy Markdown
Contributor Author

Why not use indutny/bn.js?

I might, after I have explored what else I had in mind, and once I get to the benchmarks on this one, if this one happens. With a type hook system this won't even be necessary, because people would be able to choose their own way of parsing types, if need be.

@jhermsmeier
Copy link
Copy Markdown
Contributor Author

jhermsmeier commented Aug 25, 2016

So... it's been a while, but I got around to trying out that idea I had, which is basically a middleware-style way of adding support for other types, i.e.:

var assert = require('assert')
var Bencode = require('./index')
var BigNumber = require('bignumber.js')
// OR var BigNumber = require('bn.js')

// The current API still works as before,
// but can't have any new types added to it globally,
// to avoid trashing other things using it (in deduplicated bundles, for example)
Bencode.encode({ something: 'with a value' })
Bencode.decode( buffer )

// Create a new instance of Bencode (which uses it's own set of encoder/decoder),
var bignumBencode = new Bencode()

// Register a type check, encode & decode function for a new type
bignumBencode.use('bignumber', 'number', {
  check: function (value) {
    return value instanceof BigNumber
  },
  encode: function (buffers, data) {
    buffers.push(new Buffer('i' + data.toString(10) + 'e'))
  },
  decode: function () {
    var end = this.find(0x65)
    var number = this.data.toString('ascii', this.position + 1, end)
    this.position += end + 1 - this.position
    return new BigNumber(number, 10)
  }
})

// Profit
var value = new BigNumber('1234567890123456789', 10)
var encoded = bignumBencode.encode(value)
var decoded = bignumBencode.decode(encoded)

assert.deepEqual( value, decoded )

It has added some complexity, but the benchmarks surprisingly still show pretty much the same numbers, if not even better ones. I still need to add tests for this though.
What do you think?

@themasch
Copy link
Copy Markdown
Contributor

"Branch protection options saved"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants