Skip to content

A general purpose bencode decoder written in Swift 3

License

Notifications You must be signed in to change notification settings

VFK/SwiftyBencode

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SwiftyBencode GitHub release Build Status

A general purpose bencode decoder written in Swift 3

Usage

Bencode.decode(data: Data) throws -> BencodeResult

BencodeResult

BencodeResult.integer -> Int?
BencodeResult.string -> String?
BencodeResult.list -> [BencodeResult]?
BencodeResult.dictionary -> [String: BencodeResult]?

// hexadecimal representation of swift Data.
BencodeResult.hexString -> String? // Data(bytes: [0, 1, 127, 128, 255]) -> 00017f80ff

Decoding torrent file

import Bencode

let url: URL = <path to torrent file>
let data = try! Data(contentsOf: url!)

do {
  let result = try Bencode.decode(data: data)

  if let announce = result.dictionary?["announce"]?.string {
    print(announce)
  }

  if let announceList = result.dictionary?["announce"]?.list {
    // announceList is [BencodeResult]
    for item in announceList {
      print(item.string!)
    }
  }

  if let creationDate = result.dictionary?["creation date"]?.integer {
    print(creationDate)
  }

} catch BencodeDecodeError.invalidFormat {

} catch {

}

Installation

Swift Package Manager

import PackageDescription

let package = Package(
  <...>
  dependencies: [
    .Package(url: "https://github.com/VFK/SwiftyBencode.git", majorVersion: 0, minor: 2)
  ]
  <...>
)