Created
July 30, 2017 21:09
-
-
Save camdez/108968382449b7c3a957daecb1aa500a to your computer and use it in GitHub Desktop.
Experimenting with extending Transit to truncate Doubles and Floats
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 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