-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbencoder.js
More file actions
129 lines (101 loc) · 3.02 KB
/
bencoder.js
File metadata and controls
129 lines (101 loc) · 3.02 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class BencodeParser {
constructor(data) {
this.data = data;
this.position = 0;
}
// DECODING LOGIC
parse() {
return this.parseValue();
}
parseValue() {
const character = this.data[this.position];
if (character === 'i') {
return this.parseInteger();
}
else if (character === 'l') {
return this.parseList();
}
else if (character === 'd') {
return this.parseDictionary();
}
else if (character >= '0' && character <= '9') {
return this.parseString();
}
throw new Error(`Invalid Bencode format at position ${this.position}: unexpected character '${character}'`);
}
parseInteger(){
this.position++;
let numStr = "";
while(this.data[this.position] !== 'e') {
numStr += this.data[this.position++];
}
this.position++;
return parseInt(numStr, 10);
}
parseString() {
let lengthStr = "";
while (this.data[this.position] !== ":") {
lengthStr += this.data[this.position];
this.position++;
}
this.position++;
const length = parseInt(lengthStr, 10);
const str = this.data.substr(this.position, length);
this.position += length;
return str;
}
parseList() {
this.position++;
const list = [];
while (this.data[this.position] !== "e") {
list.push(this.parseValue());
}
this.position++;
return list;
}
parseDictionary() {
this.position++;
const ditionary = {};
while (this.data[this.position] !== "e") {
const key = this.parseString();
const value = this.parseValue();
ditionary[key] = value;
}
this.position++;
return ditionary;
}
// DECODING FUNCTIONALITY IN JAVASCRIPT
static decode(bencodedString) {
const parser = new BencodeParser(bencodedString);
return parser.parse();
}
// ENCODING FUNCTIONALITY IN JAVASCRIPT
static encode(value) {
if (typeof value === 'number') {
return `i${value}e`
}
if (typeof value === 'string') {
return `${value.length}:${value}`;
}
if (Array.isArray(value)) {
let result = 'l';
for (let item of value) {
result += BencodeParser.encode(item);
}
result += 'e';
return result;
}
else if (typeof value === 'object') {
let result = 'd';
const keys = Object.keys(value).sort();
for (let key of keys) {
result += BencodeParser.encode(key);
result += BencodeParser.encode(value[key]);
}
result += 'e';
return result;
}
throw new Error("Unable to encode value of type " + typeof value);
}
}
export default BencodeParser;