Skip to content

Instantly share code, notes, and snippets.

@camdez
Created July 30, 2017 21:09
Show Gist options
  • Save camdez/108968382449b7c3a957daecb1aa500a to your computer and use it in GitHub Desktop.
Save camdez/108968382449b7c3a957daecb1aa500a to your computer and use it in GitHub Desktop.
Experimenting with extending Transit to truncate Doubles and Floats
(ns transit-ex-test.core
(:gen-class)
(:require [cognitect.transit :as transit])
(:import [java.io ByteArrayOutputStream]
[com.cognitect.transit.impl
WriteHandlers
WriteHandlers$DoubleWriteHandler
WriteHandlers$FloatWriteHandler]))
(defn truncate-double [^Double d]
(if (or (.isNaN d) (#{Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY} d))
d
(-> d (* 100) Math/round (/ 100) double)))
(def double-write-handler
(proxy [WriteHandlers$DoubleWriteHandler] []
(rep [^Double d]
(truncate-double d))))
(defn truncate-float [^Float d]
(if (or (.isNaN d) (#{Float/POSITIVE_INFINITY Float/NEGATIVE_INFINITY} d))
d
(-> d (* 100) Math/round (/ 100) float)))
(def float-write-handler
(proxy [WriteHandlers$FloatWriteHandler] []
(rep [^Float d]
(truncate-float d))))
(let [out (ByteArrayOutputStream. 4096)
writer (transit/writer out :json
{:handlers
{Double double-write-handler
Float float-write-handler}})]
(transit/write writer {:double Math/PI
:double-inf Double/POSITIVE_INFINITY
:float (float Math/PI)
:float-inf Float/NEGATIVE_INFINITY})
(.toString out))
;; => "[\"^ \",\"~:double\",3.14,\"~:double-inf\",\"~zInfinity\",\"~:float\",3.14,\"~:float-inf\",\"~z-Infinity\"]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment