Repository navigation
Expand file tree
/
Copy pathdecode.js
More file actions
110 lines (72 loc) · 1.83 KB
/
Copy pathdecode.js
File metadata and controls
110 lines (72 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
* Decodes bencoded data.
*
* @param {Buffer} data
* @param {String} encoding
* @return {Object|Array|Buffer|String|Number}
*/
function decode( data, encoding ) {
decode.position = 0
decode.encoding = encoding || null
decode.data = !( data instanceof Buffer )
? new Buffer( data )
: data
return decode.next()
}
decode.position = 0
decode.data = null
decode.encoding = null
decode.next = function() {
switch( decode.data[decode.position] ) {
case 0x64: return decode.dictionary(); break
case 0x6C: return decode.list(); break
case 0x69: return decode.integer(); break
default: return decode.bytes(); break
}
}
decode.find = function( chr ) {
var i = decode.position
var c = decode.data.length
var d = decode.data
while( i < c ) {
if( d[i] === chr )
return i
i++
}
return -1
}
decode.dictionary = function() {
decode.position++
var dict = {}
while( decode.data[decode.position] !== 0x65 ) {
dict[ decode.bytes() ] = decode.next()
}
decode.position++
return dict
}
decode.list = function() {
decode.position++
var lst = []
while( decode.data[decode.position] !== 0x65 ) {
lst.push( decode.next() )
}
decode.position++
return lst
}
decode.integer = function() {
var end = decode.find( 0x65 )
var number = decode.data.toString('ascii', decode.position+1, end )
decode.position += end + 1 - decode.position
return parseInt( number )
}
decode.bytes = function() {
var sep = decode.find( 0x3A )
var length = parseInt(decode.data.toString('ascii', decode.position, sep ), 10)
var end = ++sep + length
decode.position += end - decode.position
return decode.encoding
? decode.data.toString(decode.encoding, sep, end )
: decode.data.slice( sep, end )
}
// Expose
module.exports = decode