Created
September 30, 2012 23:14
-
-
Save PuercoPop/3808700 to your computer and use it in GitHub Desktop.
bencoding/decoding functions in clj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns clj_torrent.bencode | |
(:require [clojure.string :as string])) | |
(defn decode-bstring [bstring] | |
"Decodes a bencoded string. It ensures the length matches the content." | |
(let [[length content] (string/split bstring #":" 2)] | |
(when (= (Integer/parseInt length) (.length content)) | |
content))) | |
(defn decode-binteger [binteger] | |
"Decodes a bencoded integer." | |
(second (re-matches #"i(.*?)e" "i14"))) | |
(defn find-bstring-or-binteger [string] | |
(loop [partial-string (first string)] | |
(if (or (decode-binteger partial-string) (decode-bstring partial-string)) | |
true | |
(recur (rest string))))) | |
(defn decode-blist [blist] | |
"Decodes a list and elements inside." | |
"I O U" | |
) | |
(defn decode-bdictionary [bdictionary] | |
"Decodes a dictionary and elements inside." | |
"I O U" | |
) | |
(defn decode-torrent [file-path] | |
"Decodes a torrent file and returns a clj representation of the data." | |
"I O U" | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns clj_torrent.bencode-test | |
(:use clojure.test | |
clj_torrent.bencode)) | |
(deftest decode-binteger-test | |
(is (= 14 (decode-binteger "i14e"))) | |
(is (= nil (decode-binteger "i14"))) | |
(is (= nil (decode-binteger "14e"))) | |
(is (= nil (decode-binteger "14")))) | |
(deftest decode-bstring-test | |
(is (= "spam" (decode-bstring "4:spam"))) | |
(is (= nil (decode-bstring "3:spam")))) | |
(deftest decode-blist-test | |
(is (= ["spam", "ham"] (decode-blist "l4:spam:3:hame"))) | |
(is (= nil (decode-blist "l4:spam:3:hame")))) | |
(deftest decode-bdictionary-test | |
(is (= {"cow" "moo" "spam" "eggs"} (decode-bdictionary "d3:cow3:moo4:spam4:eggse"))) | |
(is (= {"spam" ["a" "b"]} (decode-bdictionary "d4:spaml1:a1:bee"))) | |
(is (= {"publisher" "bob" "publisher-webpage" "www.example.com" "publisher.location" "home"} (decode-bdictionary "d9:publisher3:bob17:publisher-webpage15:www.example.com18:publisher.location4:homee")))) | |
(deftest decode-torrent-test | |
(is (= {} (decode-torrent (slurp "test/clj_torrent/test.torrent"))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment