Skip to content

Loading…

Default field value support #7

Closed
wants to merge 1 commit into from

3 participants

@ibodrov

Patch to add default field value support.

Example:

(defcodec example {:a :int32 :b (default :int32 7)})
(encode example {:a 4})
(decode example *1) => {:a 4 :b 7}

Also, it works with nested types:

(defcodec example {:a :int32 :b (default (repeated :int32 :prefix :none) [1 2 3])})
(encode example {:a 4})
(decode example *1) => {:a 4 :b [1 2 3]}

@jamiei

Default field value support would be great.

@ztellman
Owner

Sorry for the delay on this, I've been travelling. I'm not opposed to this, but as far as I can tell your use-case can be handled by compile-frame and appropriate pre-encoder/post-decoder functions. Is there a reason you chose to not go this route?

@ibodrov

Because i totally missed pre-encoder/post-decoder in compile-frame definition. :-)
My bad, sorry.

This means, (default frame value) can be implemented in simple macro like this: (defmacro default [frame value] '(compile-frame ~frame #(or % ~value)), right?

@ztellman
Owner

Shouldn't have to be a macro, a function will suffice. Also, it might make more sense to have a top-level compile-frame that merges in a default map, rather than having it be per-value.

@ztellman ztellman closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Mar 25, 2012
  1. @ibodrov
Showing with 42 additions and 0 deletions.
  1. +13 −0 src/gloss/core.clj
  2. +29 −0 test/gloss/test/core.clj
View
13 src/gloss/core.clj
@@ -267,3 +267,16 @@
(codecs/wrap-prefixed-sequence
(or (compile-frame (:prefix options)) (:int32 primitive-codecs))
codec))))
+
+(defn default
+ [frame default-value]
+ (let [codec (compile-frame frame)]
+ (reify
+ Reader
+ (read-bytes [_ b]
+ (read-bytes codec b))
+ Writer
+ (sizeof [_]
+ (sizeof codec))
+ (write-bytes [_ buf vs]
+ (write-bytes codec buf (or vs default-value))))))
View
29 test/gloss/test/core.clj
@@ -298,3 +298,32 @@
dec)
(string :utf-8 :suffix ","))
"abc"))
+
+(deftest test-default-values
+ (letfn [(test-default [codec before after]
+ (is= (decode codec (encode codec before))
+ after))]
+ (test-default {:a :byte :b (default :byte 7)}
+ {:a 3}
+ {:a 3 :b 7})
+ (let [complex {:a :byte :b (default (repeated :int32 :prefix :none) [1 2 3])}]
+ (test-default complex
+ {:a 5}
+ {:a 5 :b [1 2 3]})
+ (test-default complex
+ {:a 8 :b [4 5 6]}
+ {:a 8 :b [4 5 6]}))
+ (let [complex-str {:a :byte :b (default (string :utf-8) "def")}]
+ (test-default complex-str
+ {:a 9}
+ {:a 9 :b "def"})
+ (test-default complex-str
+ {:a 9 :b "string"}
+ {:a 9 :b "string"}))
+ (let [plain-str (default (string :utf-8) "def")]
+ (test-default plain-str
+ nil
+ "def")
+ (test-default plain-str
+ "string"
+ "string"))))
Something went wrong with that request. Please try again.