Permalink
Browse files

add fmt-size fn. allow uppercase characters in pack's fmt string

  • Loading branch information...
1 parent 4d96d3f commit 48798ada7f48495157fee190ed660f781ecae670 @geoffsalmon committed Dec 30, 2011
Showing with 44 additions and 7 deletions.
  1. +26 −7 src/bytebuffer/buff.clj
  2. +18 −0 test/bytebuffer/buff_test.clj
View
33 src/bytebuffer/buff.clj
@@ -165,16 +165,35 @@ consumes the bytes in the given buffer."
(.position buff (+ (.position buff) len)) ; advance the actual buffer
rdbuf
))
- )
+ )
+
+(defn fmt-size [fmt]
+ (reduce (fn [acc f]
+ (+ acc
+ (condp = f
+ \b 1
+ \B 1
+ \s 2
+ \S 2
+ \i 4
+ \I 4
+ \l 8
+ \L 8
+ (throw (IllegalArgumentException. (str "Unknown format symbol \"" fmt \")))
+ ))) 0 fmt))
(defn- pack-one [buff fmt val]
(condp = fmt
- \b (put-byte buff val)
- \s (put-short buff val)
- \i (put-int buff val)
- \l (put-long buff val)
- (throw (IllegalArgumentException. (str "Unknown format symbol \"" fmt \")))
- ))
+ \b (put-byte buff val)
+ \B (put-byte buff val)
+ \s (put-short buff val)
+ \S (put-short buff val)
+ \i (put-int buff val)
+ \I (put-int buff val)
+ \l (put-long buff val)
+ \L (put-long buff val)
+ (throw (IllegalArgumentException. (str "Unknown format symbol \"" fmt \")))
+ ))
(defn pack
"Puts one or more numbers for vals into buff using field sizes
View
18 test/bytebuffer/buff_test.clj
@@ -206,3 +206,21 @@ filled callin the Java put* methods"
(is (= [14 15] (unpack buff "bb")))
)
))
+
+(deftest test-fmt-size
+ (is (= 0 (fmt-size "")))
+ (let [fmts "bBsSiIlL"
+ rand-fmt (fn [n] (apply str (for [i (range n)] (rand-nth fmts))))
+ buf (byte-buffer 100)
+ ;; compare fmt-size result against resulting position after
+ ;; packing zeroes into a buffer
+ test (fn [fmt]
+ (.clear buf)
+ (apply pack buf fmt (repeat (.length fmt) 0))
+ (is (= (.position buf) (fmt-size fmt))))]
+ ;; test all single letter fmt strings
+ (doseq [fmt fmts]
+ (test (str fmt)))
+ ;; test random fmt strings of length >= 2
+ (doseq [i (range 20)]
+ (test (rand-fmt (+ 2 (rand-int 10)))))))

0 comments on commit 48798ad

Please sign in to comment.