-
Notifications
You must be signed in to change notification settings - Fork 11
/
bencode.js
137 lines (128 loc) · 3.62 KB
/
bencode.js
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
exports.encode = function encode(s){
var type = typeof s, result, i, sLen, prop, props;
if (type === 'number') {
return 'i' + s + 'e';
}
else
if (type === 'string') {
return s.length + ':' + s;
}
else
if (type === 'object') {
if (s) {
if (s instanceof Array) {
result = 'l';
for (i = 0, sLen = s.length; i < sLen; i += 1) {
result += encode(s[i]);
}
return result + 'e';
}
else {
result = 'd';
props = [];
for (prop in s) {
if (s.hasOwnProperty(prop)) {
props.push(prop);
}
}
props.sort();
for (i = 0, sLen = props.length; i < sLen; i += 1) {
prop = props[i];
result += encode(prop) + encode(s[prop]);
}
return result + 'e';
}
}
throw "unexpected null";
}
else {
throw "unexpected type " + type;
}
};
function checkedIndexOf(s, c){
var result = s.indexOf(c);
if (result < 0) {
throw "expected a " + c;
}
return result;
}
function decodeInt(s){
s = s.substring(1);
var e = checkedIndexOf(s, 'e');
return [parseInt(s.substring(0, e), 10), s.substring(e + 1)];
}
function decodeString(s){
var e = checkedIndexOf(s, ':'), len = parseInt(s.substring(0, e), 10), startOfString = e + 1, endOfString = startOfString + len;
return [s.substring(startOfString, endOfString), s.substring(endOfString)];
}
// Predeclaration to make jslint happy.
var decode2;
function decodeList(s){
s = s.substring(1);
var a = [], s2;
while (true) {
if (s.length === 0) {
throw "end of input while looking for 'e'";
}
if (s.charAt(0) === 'e') {
return [a, s.substring(1)];
}
else {
s2 = decode2(s);
a.push(s2[0]);
s = s2[1];
}
}
}
function decodeDictionary(s){
s = s.substring(1);
var a = {}, s2, k;
while (true) {
if (s.length === 0) {
throw "end of input while looking for 'e'";
}
if (s.charAt(0) === 'e') {
return [a, s.substring(1)];
}
else {
s2 = decode2(s);
k = s2[0];
s = s2[1];
s2 = decode2(s);
a[k] = s2[0];
s = s2[1];
}
}
}
function decode2(s){
if ('string' !== typeof s || s.length < 1) {
throw "expected a non-empty string";
}
var c = s.charAt(0);
if (c === 'i') {
return decodeInt(s);
}
else
if (c >= '0' && c <= '9') {
return decodeString(s);
}
else
if (c === 'l') {
return decodeList(s);
}
else
if (c === 'd') {
return decodeDictionary(s);
}
else {
throw "unexpected character " + c;
}
}
exports.decode2 = decode2;
exports.decode = function decode(s){
var result = decode2(s), leftOver = result[1];
if (leftOver !== '') {
throw "'characters left over at end of decode: '" + leftOver + "'";
}
return result[0];
};