Created
August 7, 2013 02:12
-
-
Save favila/6170632 to your computer and use it in GitHub Desktop.
Encode and Decode java.lang.Long as a web-safe, identically-sortable Base64 string.
I.e., the Long and the string will both sort exactly the same way, and none of
the characters of the string ever need to be escaped in a web context (e.g. in html,
in xml, in any part of a url). Requires net.iharder.Base64 class which is Public Domain.
See http:/…
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 b64longs | |
"Encode and Decode java.lang.Long as a web-safe, identically-sortable Base64 string. | |
I.e., the Long and the string will both sort exactly the same way, and none of | |
the characters of the string ever need to be escaped in a web context (e.g. in html, | |
in xml, in any part of a url). | |
Requires net.iharder.Base64 class which is Public Domain. | |
See http://iharder.sourceforge.net/current/java/base64/ | |
Add this as a leinigen dependency. | |
[net.iharder/base64 \"2.3.8\"] | |
Example usage: | |
(long->b64s 19234) | |
; => \"--------Hm7=\" | |
(b64s->long \"--------Hm7=\") | |
; => 19234" | |
(:import java.nio.ByteBuffer | |
net.iharder.Base64)) | |
(defn long->b64s | |
"Return the string representation of a long in the ordered variant of Base64. | |
The Base64 replacement table used is both web-safe and has the same lexical | |
sorting as the bytes converted." | |
[i] | |
(Base64/encodeBytes | |
(.. (ByteBuffer/allocate (/ Long/SIZE 8)) | |
(putLong i) (array)) | |
Base64/ORDERED)) | |
(defn b64s->long | |
"Return the long int represented by an ordered-Base64-encoded string." | |
[s] | |
(-> (.getBytes s "US-ASCII") | |
(Base64/decode 0 12 Base64/ORDERED) | |
(ByteBuffer/wrap) | |
(.getLong))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment