I want to create a wrapper class for byte arrays so that I can use them as keys in fastutil's Object2LongAVLTreeMap. I have created a wrapper like this:
(deftype Bytes [^bytes ba]
Comparable
(compareTo
[this other]
(let [m (alength ^bytes (.ba this))
n (alength ^bytes (.ba other))
l (min m n)]
(loop [i 0]
(if (< i l)
(let [a (aget ^bytes (.ba ^Bytes this) i)
b (aget ^bytes (.ba ^Bytes other) i)
d (compare a b)]
(if (zero? d)
(recur (inc i))
d))
(compare m n))))))
The wrapper needs to implement Comparable for the insertions in the AVL Tree.
I am looking for feedback regarding my overall approach and my implementation of compareTo. I will be inserting lots of entries into the tree so I don't want to be creating unnecessary objects, etc. during the comparison.
EDIT: I believe the code above has a bug. See my comment below.
(compare a b)compares two (signed) bytes. For example, ifais(unchecked-byte 0xFF)andbis(unchecked-byte 0x00)), it returns-1rather than1. In my case, this caused the byte arrays to be inserted incorrectly in the AVL tree. A solution is to setato(bit-and (aget ba i) 0xFF)andbto(bit-and (aget ^bytes (.ba ^Bytes o) i) 0xFF). \$\endgroup\$