diff --git a/pitfall/restructure/bitfield-test.rkt b/pitfall/restructure/bitfield-test.rkt new file mode 100644 index 00000000..f1091570 --- /dev/null +++ b/pitfall/restructure/bitfield-test.rkt @@ -0,0 +1,53 @@ +#lang restructure/racket +(require "bitfield.rkt" "number.rkt" "stream.rkt" "buffer.rkt" rackunit racket/match) + +#| +approximates +https://github.com/mbutterick/restructure/blob/master/test/Bitfield.coffee +|# + +;describe 'Bitfield', -> +; bitfield = new Bitfield uint8, ['Jack', 'Kack', 'Lack', 'Mack', 'Nack', 'Oack', 'Pack', 'Quack'] +; JACK = 1 << 0 +; KACK = 1 << 1 +; LACK = 1 << 2 +; MACK = 1 << 3 +; NACK = 1 << 4 +; OACK = 1 << 5 +; PACK = 1 << 6 +; QUACK = 1 << 7 + +(define bitfield (+Bitfield uint8 '(Jack Kack Lack Mack Nack Oack Pack Quack))) +(match-define (list JACK KACK LACK MACK NACK OACK PACK QUACK) + (map (curry arithmetic-shift 1) (range 8))) + +; +; it 'should have the right size', -> +; bitfield.size().should.equal 1 + +(check-equal? (send bitfield size) 1) + +; +; it 'should decode', -> +; stream = new DecodeStream new Buffer [JACK | MACK | PACK | NACK | QUACK] +; bitfield.decode(stream).should.deep.equal +; Jack: yes, Kack: no, Lack: no, Mack: yes, Nack: yes, Oack: no, Pack: yes, Quack: yes + +(let ([stream (+DecodeStream (+Buffer (list (bitwise-ior JACK MACK PACK NACK QUACK))))]) + (for/and ([(k v) (in-hash (send bitfield decode stream))]) + (check-equal? v (hash-ref #hash((Quack . #t) (Nack . #t) (Lack . #f) (Oack . #f) (Pack . #t) (Mack . #t) (Jack . #t) (Kack . #f)) k)))) + + +; +; it 'should encode', (done) -> +; stream = new EncodeStream +; stream.pipe concat (buf) -> +; buf.should.deep.equal new Buffer [JACK | MACK | PACK | NACK | QUACK] +; done() +; +; bitfield.encode stream, Jack: yes, Kack: no, Lack: no, Mack: yes, Nack: yes, Oack: no, Pack: yes, Quack: yes + +(let ([stream (+EncodeStream)]) + (define h #hash((Quack . #t) (Nack . #t) (Lack . #f) (Oack . #f) (Pack . #t) (Mack . #t) (Jack . #t) (Kack . #f))) + (send bitfield encode stream h) + (check-equal? (send stream dump) (+Buffer (list (bitwise-ior JACK MACK PACK NACK QUACK))))) diff --git a/pitfall/restructure/bitfield.rkt b/pitfall/restructure/bitfield.rkt index b7ed5bba..325692cf 100644 --- a/pitfall/restructure/bitfield.rkt +++ b/pitfall/restructure/bitfield.rkt @@ -19,7 +19,7 @@ https://github.com/mbutterick/restructure/blob/master/src/Bitfield.coffee (define/override (size . args) (send type size)) - (define/augment (encode stream flag-hash) + (define/augment (encode stream flag-hash [ctx #f]) (define bitfield-int (for/sum ([(flag i) (in-indexed flags)] #:when (and flag (hash-ref flag-hash flag))) (expt 2 i)))