Here’s something I’ve wasted a couple of days on to get right; a BEncoding utility class that encodes/decodes data to and from bencoded bytes, written in Objective-C, as specified in the BitTorrent Specification.

I don’t think I’ll have time to write an entire bittorrent client, but at least here’s a GPL’d class you could use in your own client or tool :) If you want to use this in a commercial product, then please contact me and I’ll be happy to provide you with an appropriately licensed version.

Instructions

It’s pretty straight forward. If you have a bencoded byte array in a NSData object called data, you can retrieve a pointer to the decoded object(s) by calling [BEncoding objectFromEncodedData:data].

It will deserialise NSDictionary, NSArray, NSNumber and NSData objects from a given bencoded byte array, and will of course handle nested objects, so an encoded array can have each entry holding a dictionary, which in turn holds string keys and number values.

Strings are always returned as NSData objects, except when they are used as keys to NSDictionary objects. Its up to you to convert the NSData to an NSString, as there is no hint that a given byte string is actually a string and not a chunk of binary data. The exception to this is that any NSString used as a key is decoded as a UTF8 string.

If you have an NSString, NSData, NSNumber, NSArray or NSDictionary, you can serialise them to a bencoded byte array by calling [BEncoding encodedDataFromObject:object]. NSStrings are encoded as UTF8 strings. Collections of course recursively encode their contents. Unsupported types are ignored.

Notes

This is an exercise in using Obj-C Foundation types for doing as much of the heavy lifting as possible. It may not be as efficient as an equivalent C implementation, however for Obj-C programmers, it might be ‘good enough’. If you have any patches that improve performance or fixes a bug, mail them to be and I’ll check them out.

Download: BEncoding-1.0.0.zip