a2800276/bencode.js — Issue #4: Keys as strings in bencoded dictionaries
Author: clarkf
Created: 2012-01-31 22:01:37+00:00
State: open

Hey, so, I've run into a slight issue with this portion of the doc:

> The exception to this is strings appearing as keys in bencoded dicts. These are decoded as Javascript Strings, as they should always be strings of (ascii) characters and if they weren't decoded as JS Strings, dict's couldn't be mapped to Javascript objects.

While this is technically true, it does present a problem. While communicating with a tracker, often times, the infohashes are returned as the dictionary keys. For example, a simple `scrape` response:

d5:filesd20:[info_hash]d8:completei23492e10:incompletei4544e10:downloadedi1024eeee

Where `[info_hash]` is a 20-byte, binary sha1sum that isn't necessarily well-suited to be a `String`. Say we decode that, either using `bncode.decode` or `new bncode.decoder/decode/result`. We'll get something along the lines of:

```javascript
{
"files": {
"[incorrect info_hash]": {
"complete": 23492,
"incomplete": 4544,
"downloaded": 1024
}
}
}
```
Where `[incorrect info_hash]` is a `String` with length 1. Obviously this is the fault of the `String`, but it's a relatively common use-case. Perhaps it might be wise to create a class for a `BDict` or something, that allows the use of `Buffer`s as keys?

```javascript
var data = "d5:dict5:valueee"
data = bncode.decode(data);
console.log(data.get(0)); // or "value"
console.log(data.key(0)); // or "dict"
```
Obviously this would add complexity to the library, but, I've been butting my head up against this problem for a few weeks now. Any thoughts/suggestions? I'd be more than willing to prepare a pull request with any guidance.