Source

clj-digest / src / digest.clj

Diff from to

src/digest.clj

 ; Default buffer size for reading
 (def ^:dynamic *buffer-size* 1024)
 
-; Why on earth is java.io.byte-array-type private?
-(def ByteArray (type (make-array Byte/TYPE 0)))
-
 (defn- read-some 
   "Read some data from reader. Return [data size] if there's more to read,
   otherwise nil."
         padding (apply str (repeat (- size (count sig)) "0"))]
     (str padding sig)))
 
-(defmulti digest
-  "Returns digest for input with given algorithm."
-  (fn [algorithm message] (class message)))
+(defprotocol Digestible
+  (-digest [message algorithm]))
 
-(defmethod digest String [algorithm message]
-  (digest algorithm (.getBytes message)))
+(extend-protocol Digestible
+  (class (make-array Byte/TYPE 0))
+  (-digest  [message algorithm]
+    (-digest [message] algorithm))
+  
+  java.util.Collection
+  ;; Code "borrowed" from 
+  ;; * http://www.holygoat.co.uk/blog/entry/2009-03-26-1
+  ;; * http://www.rgagnon.com/javadetails/java-0416.html 
+  (-digest [message algorithm]
+    (let [algo (MessageDigest/getInstance algorithm)]
+      (.reset algo)
+      (doseq [chunk message] (.update algo chunk))
+      (signature algo)))
 
-(defmethod digest ByteArray [algorithm message]
-  (digest algorithm [message]))
+  String
+  (-digest [message algorithm]
+    (-digest [(.getBytes message)] algorithm))
+  
+  
 
-(defmethod digest File [algorithm file]
-  (digest algorithm (FileInputStream. file)))
+  InputStream
+  (-digest [reader algorithm]
+    (-digest (byte-seq reader) algorithm))
+  
+  File
+  (-digest [file algorithm]
+    (-digest (FileInputStream. file) algorithm))
 
-(defmethod digest InputStream [algorithm reader]
-  (digest algorithm (byte-seq reader)))
+  nil
+  (-digest [message algorithm]
+    nil))
 
-; Code "borrowed" from 
-; * http://www.holygoat.co.uk/blog/entry/2009-03-26-1
-; * http://www.rgagnon.com/javadetails/java-0416.html 
-(defmethod digest :default [algorithm chunks]
-  (let [algo (MessageDigest/getInstance algorithm)]
-    (.reset algo)
-    (dorun (map #(.update algo %) chunks))
-    (signature algo)))
+(defn digest
+  "Returns digest for message with given algorithm."
+  [algorithm message]
+  (-digest message algorithm))
 
 (defn algorithms []
   "List support digest algorithms."
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.