Skip to content

Commit 2419962

Browse files
committed
Merge branch 'master' of github.com:ztellman/byte-streams
2 parents b41c922 + 8b4bd90 commit 2419962

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/byte_streams.clj

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -895,7 +895,20 @@
895895
(p/int->uint (.getInt b (p/+ idx b-offset))))]
896896
(if (p/== 0 cmp)
897897
(recur (p/+ idx 4))
898-
(p/* sign cmp)))))]
898+
;; Use (if (pos? cmp) 1 -1) to ensure that the
899+
;; sign of the value x returned by cmp-bufs (and
900+
;; compare-bytes) is not modified when Clojure's
901+
;; comparator infrastructure calls (.intValue
902+
;; x). The intValue method truncates a Java
903+
;; Long's most significant 32 bits away, which
904+
;; in some cases changes the sign of the result,
905+
;; and thus the direction of the comparison
906+
;; result. Such code is not needed when
907+
;; comparing individual bytes below, because the
908+
;; subtraction result fits within the least
909+
;; significant 9 bits, and (.intValue x) never
910+
;; changes the sign.
911+
(p/* sign (if (pos? cmp) 1 -1))))))]
899912
(if (p/== 0 (long cmp))
900913
(let [limit' (.remaining a)]
901914
(loop [idx limit]

test/byte_streams_test.clj

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,9 @@
138138
(is (bytes= text-bytes (-> text-bytes to-string to-byte-array)))
139139
(is (bytes= text-bytes (-> text-bytes to-input-stream to-string to-byte-array)))
140140
(is (bytes= text-bytes (-> text-bytes (to-input-stream {:chunk-size 128}) to-string to-byte-array)))))
141+
142+
(deftest compare-bytes-former-bug
143+
(let [bx (convert (byte-array [0x00 0x00 0x00 0x01]) java.nio.ByteBuffer)
144+
by (convert (byte-array [0x80 0x00 0x00 0x01]) java.nio.ByteBuffer)]
145+
(is (= [bx by] (sort compare-bytes [bx by])))
146+
(is (= [bx by] (sort compare-bytes [by bx])))))

0 commit comments

Comments
 (0)