|
| 1 | +/* globals BigInt */ |
| 2 | +'use strict'; |
| 3 | + |
| 4 | +const BSON = require('../register-bson'); |
| 5 | + |
| 6 | +describe('BSON BigInt Support', function () { |
| 7 | + before(function () { |
| 8 | + try { |
| 9 | + BigInt(0); |
| 10 | + } catch (_) { |
| 11 | + this.skip('JS VM does not support BigInt'); |
| 12 | + } |
| 13 | + }); |
| 14 | + it('Should serialize an int that fits in int32', function () { |
| 15 | + const testDoc = { b: BigInt(32) }; |
| 16 | + expect(() => BSON.serialize(testDoc)).to.throw(TypeError); |
| 17 | + |
| 18 | + // const serializedDoc = BSON.serialize(testDoc); |
| 19 | + // // prettier-ignore |
| 20 | + // const resultBuffer = Buffer.from([0x0C, 0x00, 0x00, 0x00, 0x10, 0x62, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00]); |
| 21 | + // const resultDoc = BSON.deserialize(serializedDoc); |
| 22 | + // expect(Array.from(serializedDoc)).to.have.members(Array.from(resultBuffer)); |
| 23 | + // expect(BigInt(resultDoc.b)).to.equal(testDoc.b); |
| 24 | + }); |
| 25 | + |
| 26 | + it('Should serialize an int that fits in int64', function () { |
| 27 | + const testDoc = { b: BigInt(0x1ffffffff) }; |
| 28 | + expect(() => BSON.serialize(testDoc)).to.throw(TypeError); |
| 29 | + |
| 30 | + // const serializedDoc = BSON.serialize(testDoc); |
| 31 | + // // prettier-ignore |
| 32 | + // const resultBuffer = Buffer.from([0x10, 0x00, 0x00, 0x00, 0x12, 0x62, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00]); |
| 33 | + // const resultDoc = BSON.deserialize(serializedDoc); |
| 34 | + // expect(Array.from(serializedDoc)).to.have.members(Array.from(resultBuffer)); |
| 35 | + // expect(BigInt(resultDoc.b)).to.equal(testDoc.b); |
| 36 | + }); |
| 37 | + |
| 38 | + it('Should serialize an int that fits in decimal128', function () { |
| 39 | + const testDoc = { b: BigInt('9223372036854776001') }; // int64 max + 1 |
| 40 | + expect(() => BSON.serialize(testDoc)).to.throw(TypeError); |
| 41 | + |
| 42 | + // const serializedDoc = BSON.serialize(testDoc); |
| 43 | + // // prettier-ignore |
| 44 | + // const resultBuffer = Buffer.from([0x18, 0x00, 0x00, 0x00, 0x13, 0x62, 0x00, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x30, 0x00]); |
| 45 | + // const resultDoc = BSON.deserialize(serializedDoc); |
| 46 | + // expect(Array.from(serializedDoc)).to.have.members(Array.from(resultBuffer)); |
| 47 | + // expect(resultDoc.b._bsontype).to.equal('Decimal128'); |
| 48 | + // expect(BigInt(resultDoc.b.toString())).to.equal(testDoc.b); |
| 49 | + }); |
| 50 | + |
| 51 | + it('Should throw if BigInt is too large to serialize', function () { |
| 52 | + const testDoc = { |
| 53 | + b: BigInt('9'.repeat(35)) |
| 54 | + }; // decimal 128 can only encode 34 digits of precision |
| 55 | + expect(() => BSON.serialize(testDoc)).to.throw(TypeError); |
| 56 | + // expect(() => BSON.serialize(testDoc)).to.throw(); |
| 57 | + }); |
| 58 | +}); |
0 commit comments