Created
June 29, 2015 17:12
-
-
Save drbobbeaty/c6c42e2970ec07c6c381 to your computer and use it in GitHub Desktop.
Quick and easy Base-64 encoding and decoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
:dependencies [[base64-clj "0.1.1"]] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns project.util | |
(:require [[base64-clj.core :as b64]])) | |
(defn b64-encode | |
"Function for a safe base-64 encode that handels nils as well as converts | |
any non-string argument to it's string equivalent and then encodes that. | |
It's also smart enough to take a sequence of things and encode each, | |
individually - returning a sequence of encoded values." | |
[s] | |
(cond | |
(nil? s) nil | |
(string? s) (b64/encode s) | |
(coll? s) (map b64-encode s) | |
:else (b64-encode (pr-str s)))) | |
(defn b64-decode | |
"Function to safely attempt to do a base64 decoding of the argument - assuming | |
it's a correct fit for the decoding. It's got to be a string, and it's got to | |
have a length that's divisible by 4. If it's invalid, this function will just | |
return `nil`." | |
[s] | |
(cond | |
(string? s) (let [len (count s)] | |
(when (and (pos? len) (zero? (unchecked-remainder-int len 4))) | |
(b64/decode s))) | |
(coll? s) (map b64-decode s) | |
:else nil)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment