You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
typesetting/xenomorph/xenomorph/bitfield.rkt

58 lines
2.2 KiB
Racket

#lang racket/base
6 years ago
(require "helper.rkt" racket/dict sugar/unstable/dict)
6 years ago
(provide (all-defined-out))
6 years ago
#|
approximates
https://github.com/mbutterick/restructure/blob/master/src/Bitfield.coffee
|#
6 years ago
(define/post-decode (xbitfield-decode xb [port-arg (current-input-port)] #:parent [parent #f])
(define port (->input-port port-arg))
(parameterize ([current-input-port port])
6 years ago
(define flag-hash (mhasheq))
6 years ago
(define val (xdecode (xbitfield-type xb)))
6 years ago
(for ([(flag i) (in-indexed (xbitfield-flags xb))]
#:when flag)
6 years ago
(hash-set! flag-hash flag (bitwise-bit-set? val i)))
6 years ago
flag-hash))
6 years ago
6 years ago
(define/pre-encode (xbitfield-encode xb flag-hash [port-arg (current-output-port)] #:parent [parent #f])
(define port (if (output-port? port-arg) port-arg (open-output-bytes)))
(parameterize ([current-output-port port])
(define bit-int (for/sum ([(flag i) (in-indexed (xbitfield-flags xb))]
#:when (and flag (dict-ref flag-hash flag #f)))
(arithmetic-shift 1 i)))
(encode (xbitfield-type xb) bit-int)
(unless port-arg (get-output-bytes port))))
6 years ago
6 years ago
(define (xbitfield-size xb [val #f] #:parent [parent #f])
(size (xbitfield-type xb)))
6 years ago
6 years ago
(struct xbitfield xbase (type flags) #:transparent
#:methods gen:xenomorphic
[(define decode xbitfield-decode)
6 years ago
(define xdecode xbitfield-decode)
6 years ago
(define encode xbitfield-encode)
(define size xbitfield-size)])
6 years ago
6 years ago
(define (+xbitfield [type-arg #f] [flag-arg #f]
#:type [type-kwarg #f] #:flags [flag-kwarg #f])
(define type (or type-arg type-kwarg))
(define flags (or flag-arg flag-kwarg null))
(unless (andmap (λ (f) (or (symbol? f) (not f))) flags)
(raise-argument-error '+xbitfield "list of symbols" flags))
(xbitfield type flags))
6 years ago
6 years ago
(module+ test
(require rackunit "number.rkt")
(define bfer (+xbitfield uint16be '(bold italic underline #f shadow condensed extended)))
(define bf (decode bfer #"\0\25"))
(check-equal? (length (dict-keys bf)) 6) ; omits #f flag
(check-true (dict-ref bf 'bold))
(check-true (dict-ref bf 'underline))
(check-true (dict-ref bf 'shadow))
(check-false (dict-ref bf 'italic))
(check-false (dict-ref bf 'condensed))
(check-false (dict-ref bf 'extended))
(check-equal? (encode bfer bf #f) #"\0\25"))