Skip to content

# Fix issue #19: Allow empty collection to byte array conversion #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/clj_commons/byte_streams.clj
Original file line number Diff line number Diff line change
Expand Up @@ -513,10 +513,16 @@
(recur))))
(.toByteArray out)))

#_(let [ary (Utils/byteArray 0)]
(def-conversion ^{:cost 0} [::nil byte-array-type]
[src options]
ary))
(def-conversion ^{:cost 0} [::nil byte-array-type]
[src options]
(clojure.core/byte-array 0))

(def-conversion ^{:cost 0.5} [clojure.lang.IPersistentCollection byte-array-type]
[coll options]
(if (empty? coll)
(clojure.core/byte-array 0)
(throw (IllegalArgumentException.
(str "Don't know how to convert non-empty " (class coll) " into " byte-array-type)))))

(def-conversion ^{:cost 2} [#'proto/ByteSource byte-array-type]
[src options]
Expand Down
19 changes: 18 additions & 1 deletion test/clj_commons/byte_streams_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
[clj-commons.byte-streams :refer [bytes= compare-bytes conversion-path convert dev-null possible-conversions seq-of stream-of to-byte-array to-byte-buffer to-byte-buffers to-input-stream to-string transfer vector-of] :as bs]
[clojure.test :refer :all]
[clojure.java.io :as io]
[clj-commons.primitive-math :as p])
[clj-commons.primitive-math :as p]
[clojure.set :as set])
(:refer-clojure
:exclude [vector-of])
(:import
Expand Down Expand Up @@ -240,5 +241,21 @@
(is (= (aget bb-array i) 0)))
(is (= (aget bb-array size) val)))))))))

(deftest test-empty-collections
(testing "Empty vector to byte array conversion"
(let [result (to-byte-array [])]
(is (instance? (Class/forName "[B") result))
(is (= 0 (alength result)))))

(testing "Empty list to byte array conversion"
(let [result (to-byte-array '())]
(is (instance? (Class/forName "[B") result))
(is (= 0 (alength result)))))

(testing "Empty seq to byte array conversion"
(let [result (to-byte-array (seq []))]
(is (instance? (Class/forName "[B") result))
(is (= 0 (alength result))))))