Skip to content

Commit 0c3ff65

Browse files
author
Mark Schmale
committed
encodeing works
1 parent 93c6001 commit 0c3ff65

File tree

2 files changed

+72
-2
lines changed

2 files changed

+72
-2
lines changed

bencode.js

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
1+
/*
2+
* ----------------------------------------------------------------------------
3+
* node-bencode v0.1.0
4+
* <[email protected]> wrote this file. As long as you retain this notice
5+
* you can do whatever you want with this stuff. If we meet some day, and you
6+
* think this stuff is worth it, you can buy me a beer in return. Mark Schmale
7+
* ----------------------------------------------------------------------------
8+
*/
19
var sys = require('sys');
210

11+
/**
12+
* decodes a bencoded string
13+
*/
314
exports.decode = function decode(str) {
415
var arr = str.split('');
516

@@ -89,5 +100,64 @@ exports.decode = function decode(str) {
89100
return data;
90101
}
91102

92-
return next(0);
103+
return next(0).ret;
104+
}
105+
106+
exports.encode = function encode(data) {
107+
/* sys.puts(sys.inspect(typeof(data)));
108+
sys.puts(sys.inspect(is_array(data)));*/
109+
110+
function encode_string(data) {
111+
return data.length + ":" + data;
112+
}
113+
114+
function encode_integer(data) {
115+
return "i" + data + "e";
116+
}
117+
118+
function encode_list(data) {
119+
var max = data.length;
120+
var i = 0;
121+
var str = "l";
122+
for(i=0;i<max;i++) {
123+
str = str + encode(data[i]);
124+
}
125+
str = str + "e";
126+
return str;
127+
}
128+
129+
function encode_dict(data) {
130+
var str = "d";
131+
for(var key in data) {
132+
str = str + encode_string(key) + encode(data[key]);
133+
}
134+
str = str + "e";
135+
return str;
136+
}
137+
138+
/** helper **/
139+
function is_array(obj) {
140+
return obj.constructor == Array;
141+
}
142+
143+
var str = "";
144+
145+
switch(typeof(data)) {
146+
case 'object':
147+
if(is_array(data) === true) {
148+
str = encode_list(data);
149+
} else {
150+
str = encode_dict(data);
151+
}
152+
break;
153+
154+
case 'number':
155+
str = encode_integer(data);
156+
break;
157+
158+
case 'string':
159+
str = encode_string(data);
160+
break;
161+
}
162+
return str;
93163
}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{ "name": "bencode",
22
"description": "a bencode de/encoder",
3-
"version": "0.0.1",
3+
"version": "0.1.0",
44
"author": "Mark Schmale <[email protected]",
55
"directories": { "/": "./" },
66
"main": "./bencode",

0 commit comments

Comments
 (0)