Skip to content

Instantly share code, notes, and snippets.

@duanebester
Created September 29, 2021 00:10
Show Gist options
  • Save duanebester/4f1f16801f732bb330ad59f5f74ece4c to your computer and use it in GitHub Desktop.
Save duanebester/4f1f16801f732bb330ad59f5f74ece4c to your computer and use it in GitHub Desktop.
BinF C-String helpers
(defn wr-cstring [view string]
(binf/wr-string view (str string "\0"))
view)
(defn rr-cstring [view]
(loop [index (binf/position view) acc []]
(let [b (binf/rr-u8 view)]
(if (zero? b)
(.toString
(.decode binf.string/decoder-utf-8
#?(:clj (ByteBuffer/wrap (byte-array acc))
:cljs (.from js/Uint8Array acc))))
(recur (inc index) (conj acc b))))))
@helins
Copy link

helins commented Sep 29, 2021

Neat!
I guess you could even optimize as such:

;; Avoids appending to string.
;;
(defn wr-cstring [view string]
  (-> view
      (binf/wr-string string)
      (binf/wr-b8 0))

And for reading, you can get a buffer in one go instead of having to create a vector. Something like:

(let [pos (binf/position view)]
  (loop []
    (if (zero? (binf/rr-u8 view))
      (binf/ra-buffer pos
                      (- (binf/position view)
                         pos
                         1))
      (recur))))
;;
;; Didn't try but should produce a buffer with all bytes between `pos` and the position right before 0.
;;
;; Returns a byte-array on the JVM, an ArrayBuffer in JS, so the rest of the example is good :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment