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/pitfall/restructure/bitfield.rkt

45 lines
1.5 KiB
Racket

7 years ago
#lang restructure/racket
7 years ago
(require "stream.rkt")
(provide (all-defined-out))
7 years ago
#|
approximates
https://github.com/mbutterick/restructure/blob/master/src/Bitfield.coffee
|#
7 years ago
(define-subclass Streamcoder (Bitfield type [flags empty])
7 years ago
(unless (andmap (λ (f) (or (key? f) (not f))) flags)
(raise-argument-error 'Bitfield "list of keys" flags))
7 years ago
7 years ago
(define/augment (decode stream . _)
(define flag-hash (mhasheq))
(for* ([val (in-value (send type decode stream))]
[(flag i) (in-indexed flags)]
#:when flag)
7 years ago
(hash-set! flag-hash flag (bitwise-bit-set? val i)))
7 years ago
flag-hash)
7 years ago
7 years ago
(define/override (size . _) (send type size))
7 years ago
(define/augment (encode stream flag-hash [ctx #f])
7 years ago
(define bitfield-integer (for/sum ([(flag i) (in-indexed flags)]
#:when (and flag (ref flag-hash flag)))
(arithmetic-shift 1 i)))
(send type encode stream bitfield-integer)))
7 years ago
(test-module
7 years ago
(require "number.rkt" "stream.rkt")
(define bfer (+Bitfield uint16be '(bold italic underline #f shadow condensed extended)))
7 years ago
(define bf (send bfer decode (+DecodeStream #"\0\25")))
7 years ago
(check-equal? (length (ref-keys bf)) 6) ; omits #f flag
(check-true (ref bf 'bold))
(check-true (ref bf 'underline))
(check-true (ref bf 'shadow))
(check-false (ref bf 'italic))
(check-false (ref bf 'condensed))
(check-false (ref bf 'extended))
7 years ago
7 years ago
(define os (+EncodeStream))
7 years ago
(send bfer encode os bf)
(check-equal? (send os dump) #"\0\25"))