|
| 1 | +var fs = require('fs') |
| 2 | +var path = require('path') |
| 3 | +var test = require('tape').test |
| 4 | +var bencode = require('..') |
| 5 | + |
| 6 | +var torrent = fs.readFileSync( |
| 7 | + path.join(__dirname, '..', 'benchmark', 'test.torrent') |
| 8 | +) |
| 9 | + |
| 10 | +test('encoding-length', function (t) { |
| 11 | + t.test('torrent', function (t) { |
| 12 | + var value = bencode.decode(torrent) |
| 13 | + var length = bencode.encodingLength(value) |
| 14 | + t.plan(1) |
| 15 | + t.equal(length, torrent.length) |
| 16 | + }) |
| 17 | + |
| 18 | + t.test('returns correct length for empty dictionaries', function (t) { |
| 19 | + t.plan(2) |
| 20 | + t.equal(bencode.encodingLength({}), 2) // de |
| 21 | + t.equal(bencode.encodingLength(new Map()), 2) // de |
| 22 | + }) |
| 23 | + |
| 24 | + t.test('returns correct length for dictionaries', function (t) { |
| 25 | + t.plan(2) |
| 26 | + var obj = { a: 1, b: 'str', c: { de: 'f' } } |
| 27 | + var map = new Map([ |
| 28 | + [ 'a', 1 ], |
| 29 | + [ 'b', 'str' ], |
| 30 | + [ 'c', { de: 'f' } ] |
| 31 | + ]) |
| 32 | + t.equal(bencode.encodingLength(obj), 28) // d1:ai1e1:b3:str1:cd2:de1:fee |
| 33 | + t.equal(bencode.encodingLength(map), 28) // d1:ai1e1:b3:str1:cd2:de1:fee |
| 34 | + }) |
| 35 | + |
| 36 | + t.test('returns correct length for empty lists', function (t) { |
| 37 | + t.plan(2) |
| 38 | + t.equal(bencode.encodingLength([]), 2) // le |
| 39 | + t.equal(bencode.encodingLength(new Set()), 2) // le |
| 40 | + }) |
| 41 | + |
| 42 | + t.test('returns correct length for lists', function (t) { |
| 43 | + t.plan(3) |
| 44 | + t.equal(bencode.encodingLength([1, 2, 3]), 11) // li1ei2ei3ee |
| 45 | + t.equal(bencode.encodingLength([1, 'string', [{ a: 1, b: 2 }]]), 29) // li1e6:stringld1:ai1e1:bi2eeee |
| 46 | + t.equal(bencode.encodingLength(new Set([1, 'string', [{ a: 1, b: 2 }]])), 29) // li1e6:stringld1:ai1e1:bi2eeee |
| 47 | + }) |
| 48 | + |
| 49 | + t.test('returns correct length for integers', function (t) { |
| 50 | + t.plan(2) |
| 51 | + t.equal(bencode.encodingLength(-0), 3) // i0e |
| 52 | + t.equal(bencode.encodingLength(-1), 4) // i-1e |
| 53 | + }) |
| 54 | + |
| 55 | + t.test('returns integer part length for floating point numbers', function (t) { |
| 56 | + t.plan(1) |
| 57 | + t.equal(bencode.encodingLength(100.25), 1 + 1 + 3) |
| 58 | + }) |
| 59 | + |
| 60 | + t.test('returns correct length for BigInts', function (t) { |
| 61 | + t.plan(1) |
| 62 | + // 2n ** 128n == 340282366920938463463374607431768211456 |
| 63 | + t.equal(bencode.encodingLength(340282366920938463463374607431768211456), 1 + 1 + 39) |
| 64 | + }) |
| 65 | + |
| 66 | + t.test('returns zero for undefined or null values', function (t) { |
| 67 | + t.plan(2) |
| 68 | + t.equal(bencode.encodingLength(null), 0) |
| 69 | + t.equal(bencode.encodingLength(undefined), 0) |
| 70 | + }) |
| 71 | +}) |
0 commit comments