PageRenderTime 56ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/src/skyway/encodings.clj

https://github.com/burke/skyway
Clojure | 66 lines | 48 code | 11 blank | 7 comment | 0 complexity | c4d5a3d5d18a2c5c59cc222ea3a55583 MD5 | raw file
  1. ;; Copyright (c) James Reeves. All rights reserved.
  2. ;; The use and distribution terms for this software are covered by the Eclipse
  3. ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which
  4. ;; can be found in the file epl-v10.html at the root of this distribution. By
  5. ;; using this software in any fashion, you are agreeing to be bound by the
  6. ;; terms of this license. You must not remove this notice, or any other, from
  7. ;; this software.
  8. (ns skyway.encodings
  9. "Functions for encoding data."
  10. (:use skyway.str-utils)
  11. (:use clojure.contrib.duck-streams)
  12. (:import java.net.URLEncoder)
  13. (:import java.net.URLDecoder)
  14. (:import org.apache.commons.codec.binary.Base64)
  15. (:import org.apache.commons.codec.binary.Hex))
  16. (defn urlencode
  17. "Encode a urlencoded string using the default encoding."
  18. [s]
  19. (URLEncoder/encode (str* s) *default-encoding*))
  20. (defn urldecode
  21. "Decode a urlencoded string using the default encoding."
  22. [s]
  23. (URLDecoder/decode s *default-encoding*))
  24. (defn base64-encode-bytes
  25. "Encode an array of bytes into a base64 encoded string."
  26. [unencoded]
  27. (String. (Base64/encodeBase64 unencoded)))
  28. (defn base64-encode
  29. [unencoded]
  30. "Encode a string using base64."
  31. (base64-encode-bytes (.getBytes unencoded)))
  32. (defn base64-decode-bytes
  33. "Decode a string using base64 into an array of bytes."
  34. [encoded]
  35. (Base64/decodeBase64 (.getBytes encoded)))
  36. (defn base64-decode
  37. "Decode a string using base64."
  38. [encoded]
  39. (String. (base64-decode-bytes encoded)))
  40. (defn marshal
  41. "Serialize a Clojure object in a base64-encoded string."
  42. [data]
  43. (base64-encode (pr-str data)))
  44. (defn unmarshal
  45. "Unserialize a Clojure object from a base64-encoded string."
  46. [marshaled]
  47. (read-string (base64-decode marshaled)))
  48. (defn decode-hex
  49. "Converts a string of hex into it's corresponding byte array."
  50. [s]
  51. (Hex/decodeHex (.toCharArray s)))
  52. (defn encode-hex
  53. "Converts a byte array into it's corresponding hex String."
  54. [array]
  55. (String. (Hex/encodeHex array)))