Commits

Meikel Brandmeyer committed 71cbc87

Write binary data verbatim to a byte string

Comments (0)

Files changed (2)

src/main/clojure/clojure/tools/nrepl/bencode.clj

   (:import
     java.io.InputStream
     java.io.OutputStream
-    java.io.PushbackInputStream))
+    java.io.PushbackInputStream
+    clojure.lang.RT))
 
 ;; # Motivation
 ;;
 
 (defmulti write-bencode
   "Write the given thing to the output stream. “Thing” means here a
-  string, map, sequence or integer."
+  string, map, sequence or integer. Alternatively an ByteArray may
+  be provided whose contents are written as a bytestring."
   (fn [_output thing]
     (cond
+      (instance? (RT/classForName "[B") thing) :bytes
       (string? thing) :string
       (map? thing)    :map
       ;; Check for various sequency things. Yes. This is tedious. But as long
           (instance? Long thing))
       :integer)))
 
-;; The following methods should be pretty straight-forward. For strings
-;; we simply write the string as a netstring without trailing comma.
+;; The following methods should be pretty straight-forward.
+;;
+;; The easiest case is of course when we already have a byte array.
+;; We can simply pass it on to the underlying machinery.
+
+(defmethod write-bencode :bytes
+  [output bytes]
+  (write-netstring* output bytes))
+
+;; For strings we simply write the string as a netstring without
+;; trailing comma after encoding the string as UTF-8 bytes.
 
 (defmethod write-bencode :string
   [output string]

src/test/clojure/clojure/tools/nrepl/bencode_test.clj

     "Hällö, Würld!"  "16:Hällö, Würld!,"
     "Здравей, Свят!" "25:Здравей, Свят!,"))
 
+(deftest test-byte-array-writing
+  (are [x y] (= (>output (>bytes x) :writer write-bencode) y)
+    ""               "0:"
+    "Hello, World!"  "13:Hello, World!"
+    "Hällö, Würld!"  "16:Hällö, Würld!"
+    "Здравей, Свят!" "25:Здравей, Свят!"))
+
 (deftest test-string-writing
   (are [x y] (= (>output x :writer write-bencode) y)
     ""               "0:"