Skip to content

Commit

Permalink
encodeing works
Browse files Browse the repository at this point in the history
  • Loading branch information
Mark Schmale committed Aug 2, 2010
1 parent 93c6001 commit 0c3ff65
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
72 changes: 71 additions & 1 deletion bencode.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
/*
* ----------------------------------------------------------------------------
* node-bencode v0.1.0
* <[email protected]> wrote this file. As long as you retain this notice
* you can do whatever you want with this stuff. If we meet some day, and you
* think this stuff is worth it, you can buy me a beer in return. Mark Schmale
* ----------------------------------------------------------------------------
*/
var sys = require('sys');

/**
* decodes a bencoded string
*/
exports.decode = function decode(str) {
var arr = str.split('');

Expand Down Expand Up @@ -89,5 +100,64 @@ exports.decode = function decode(str) {
return data;
}

return next(0);
return next(0).ret;
}

exports.encode = function encode(data) {
/* sys.puts(sys.inspect(typeof(data)));
sys.puts(sys.inspect(is_array(data)));*/

function encode_string(data) {
return data.length + ":" + data;
}

function encode_integer(data) {
return "i" + data + "e";
}

function encode_list(data) {
var max = data.length;
var i = 0;
var str = "l";
for(i=0;i<max;i++) {
str = str + encode(data[i]);
}
str = str + "e";
return str;
}

function encode_dict(data) {
var str = "d";
for(var key in data) {
str = str + encode_string(key) + encode(data[key]);
}
str = str + "e";
return str;
}

/** helper **/
function is_array(obj) {
return obj.constructor == Array;
}

var str = "";

switch(typeof(data)) {
case 'object':
if(is_array(data) === true) {
str = encode_list(data);
} else {
str = encode_dict(data);
}
break;

case 'number':
str = encode_integer(data);
break;

case 'string':
str = encode_string(data);
break;
}
return str;
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{ "name": "bencode",
"description": "a bencode de/encoder",
"version": "0.0.1",
"version": "0.1.0",
"author": "Mark Schmale <[email protected]",
"directories": { "/": "./" },
"main": "./bencode",
Expand Down

0 comments on commit 0c3ff65

Please sign in to comment.