taoensso / nippy

The fastest serialization library for Clojure
https://www.taoensso.com/nippy
Eclipse Public License 1.0
1.04k stars 60 forks source link

Quick Question about custom types #149

Closed Outrovurt closed 2 years ago

Outrovurt commented 2 years ago

The following example given for extending nippy for custom types only works if (:data x) is a string:

(nippy/extend-freeze MyType :my-type/foo ; A unique (namespaced) type identifier
  [x data-output]
  (.writeUTF data-output (:data x)))

Q: If I want to serialize any other Clojure built-in here, is the correct approach to use freeze-to-string? For example:

(deftype MyType [some-map])
(extend-freeze
   MyType ::MyType
   [x data-out]
   (.writeUTF data-out-stream
              (nippy/freeze-to-string (.-some-map x))))

I can't find anything obvious in the documentation as to how to pass non-string values to the .writeUTF method.

ptaoussanis commented 2 years ago

Hi @Outrovurt,

The following example given for extending nippy for custom types only works if (:data x) is a string:

Correct

Q: If I want to serialize any other Clojure built-in here

Most built-in Clojure types should already have an appropriate implementation out-the-box. You can use nippy/freeze-to-out! to do a type-appropriate freeze within a custom freezer.

In most cases if someone is writing a custom freezer, it's because they want to write directly against a DataOutput using its API.

Hope that helps!

Outrovurt commented 2 years ago

Thanks a lot, that is exactly what I was looking for and it works perfectly! It also produces a reasonably smaller output than freeze-to-string, so I'm very happy. :-)