Skip to content

Add support for maps as keys (pathwise) #34

Description

@Frozenlock

Clojurians are used to be able to use pretty much anything as keys, including maps.

Codax is almost there, but lacks support for maps.

I came up with a simple encoder/decoder that leverages Nippy:

(ns my-ns
  (:require [codax.core :as c]
            [taoensso.nippy :as nippy])
  (:import (java.util Base64)))

;; Simply encoding bytes to strings (String. bytes) causes the data to
;; be corrupted after a round trip in Codax.  Encoding in b64 solves
;; this.

(defn bytes-to-base64 [bytes]
  (let [encoder (Base64/getEncoder)]
    (.encodeToString encoder bytes)))

(defn base64-to-bytes [base64-string]
  (let [decoder (Base64/getDecoder)]
    (.decode decoder base64-string)))

(c/defpathtype [0x71
                clojure.lang.PersistentHashMap
                clojure.lang.PersistentArrayMap
                clojure.lang.PersistentTreeMap]
  (fn map-encoder [m]
    (bytes-to-base64 (nippy/freeze m)))

  (fn map-decoder [s]
    (nippy/thaw (base64-to-bytes s))))

Nippy also automatically handles keys ordering:

(let [encoding1 (:encoding (c/check-path-encoding {{:a 1, :b 2} "map1"}))
      encoding2 (:encoding (c/check-path-encoding {{:b 2, :a 1} "map1"}))]
  (= encoding1 encoding2))

;=> true

Could something like this be added to Codax?
Could it leverage other types defined for pathwise?

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions