From 31efbd7aaadc546c16388584fafa47b9d22856c5 Mon Sep 17 00:00:00 2001 From: Matthew Butterick Date: Sun, 16 Jun 2019 08:35:04 -0700 Subject: [PATCH] bitfield examples & error check --- xenomorph/xenomorph/bitfield.rkt | 6 ++++++ xenomorph/xenomorph/scribblings/xenomorph.scrbl | 14 +++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/xenomorph/xenomorph/bitfield.rkt b/xenomorph/xenomorph/bitfield.rkt index fbf5323b..c3f36149 100644 --- a/xenomorph/xenomorph/bitfield.rkt +++ b/xenomorph/xenomorph/bitfield.rkt @@ -35,6 +35,12 @@ https://github.com/mbutterick/restructure/blob/master/src/Bitfield.coffee flag-hash) (define/augment (x:encode flag-hash port [parent #f]) + (define invalid-flags + (for/list ([flag (in-hash-keys flag-hash)] + #:unless (member flag @flags)) + flag)) + (unless (null? invalid-flags) + (raise-argument-error 'encode (format "valid flag name ~v" @flags) invalid-flags)) (define bit-int (for/sum ([(flag idx) (in-indexed @flags)] #:when (and flag (hash-ref flag-hash flag #f))) (arithmetic-shift 1 idx))) diff --git a/xenomorph/xenomorph/scribblings/xenomorph.scrbl b/xenomorph/xenomorph/scribblings/xenomorph.scrbl index 32891dc7..9735b4ef 100644 --- a/xenomorph/xenomorph/scribblings/xenomorph.scrbl +++ b/xenomorph/xenomorph/scribblings/xenomorph.scrbl @@ -1486,7 +1486,8 @@ Generate an instance of @racket[x:pointer%] (or a subclass of @racket[x:pointer% @defthing[x:pointer-type-key symbol? #:value 'x:ptr-type] @defthing[x:length-key symbol? #:value 'x:length] @defthing[x:val-key symbol? #:value 'x:val])]{ -Housekeeping. + +Private fields used for pointer housekeeping. There is no reason to mess with these. } @@ -1558,6 +1559,17 @@ Generate an instance of @racket[x:bitfield%] (or a subclass of @racket[x:bitfiel @racket[pre-encode-proc] and @racket[post-decode-proc] control the pre-encoding and post-decoding procedures, respectively. Each takes as input the value to be processed and returns a new value. @racket[base-class] controls the class used for instantiation of the new object. + +@examples[#:eval my-eval +(define flags (x:bitfield uint8 '(alpha bravo charlie delta echo))) +(define vals (hasheq + 'alpha #true + 'charlie #true + 'echo #true)) +(encode flags vals #f) +(decode flags #"\25") +] + }