Files
2026-03-09 23:09:46 -04:00

102 lines
2.7 KiB
Clojure

(ns binary
"Erlang :binary module — binary data operations.
In CljElixir: (binary/split data pattern), (binary/part data pos len), etc.
Efficient binary search, split, and manipulation.")
(defn split
"Splits binary by pattern. Returns list of parts.
(binary/split \"a,b,c\" \",\") ;=> [\"a\" \"b,c\"]
(binary/split \"a,b,c\" \",\" [:global]) ;=> [\"a\" \"b\" \"c\"]"
([subject pattern])
([subject pattern opts]))
(defn part
"Extracts a part of a binary.
(binary/part \"hello\" 1 3) ;=> \"ell\"
(binary/part \"hello\" {1 3}) ;=> \"ell\""
([subject pos-len])
([subject pos len]))
(defn match
"Finds the first/all occurrences of pattern in binary.
(binary/match \"hello world\" \"world\") ;=> {6 5}
(binary/match \"abcabc\" \"a\" [:global]) ;=> [... all positions ...]"
([subject pattern])
([subject pattern opts]))
(defn matches
"Returns all matches (like match with :global).
(binary/matches \"abcabc\" \"a\") ;=> [{0 1} {3 1}]"
([subject pattern])
([subject pattern opts]))
(defn replace
"Replaces pattern in binary.
(binary/replace \"hello\" \"l\" \"L\" [:global]) ;=> \"heLLo\""
([subject pattern replacement])
([subject pattern replacement opts]))
(defn at
"Returns the byte at position.
(binary/at \"hello\" 0) ;=> 104"
[subject position])
(defn first
"Returns the first byte.
(binary/first \"hello\") ;=> 104"
[subject])
(defn last
"Returns the last byte.
(binary/last \"hello\") ;=> 111"
[subject])
(defn bin-to-list
"Converts binary to list of bytes.
(binary/bin-to-list \"hello\") ;=> [104 101 108 108 111]"
([subject])
([subject pos-len])
([subject pos len]))
(defn list-to-bin
"Converts byte list to binary.
(binary/list-to-bin [104 101 108 108 111]) ;=> \"hello\""
[byte-list])
(defn copy
"Copies a binary, optionally repeating it.
(binary/copy \"ab\" 3) ;=> \"ababab\""
([subject])
([subject n]))
(defn decode-unsigned
"Decodes an unsigned integer from binary.
(binary/decode-unsigned <<0 0 0 42>>) ;=> 42"
([subject])
([subject endianness]))
(defn encode-unsigned
"Encodes an unsigned integer to binary.
(binary/encode-unsigned 42) ;=> <<42>>"
([value])
([value endianness]))
(defn longest-common-prefix
"Returns the length of the longest common prefix of binaries.
(binary/longest-common-prefix [\"abc\" \"abd\"]) ;=> 2"
[binaries])
(defn longest-common-suffix
"Returns the length of the longest common suffix."
[binaries])
(defn compile-pattern
"Pre-compiles a search pattern for repeated use.
(let [pat (binary/compile-pattern \",\")] (binary/split data pat))"
[pattern])
(defn referenced-byte-size
"Returns the size of the referenced binary (before sub-binary optimization)."
[binary])