enum done

main
Matthew Butterick 6 years ago
parent e46d7271d5
commit ec946a275f

@ -0,0 +1,32 @@
#lang racket/base
(require "helper.rkt" racket/list)
(provide (all-defined-out))
#|
approximates
https://github.com/mbutterick/restructure/blob/master/src/Enum.coffee
|#
(define (xenum-decode xe [port-arg (current-input-port)] #:parent [parent #f])
(define port (->input-port port-arg))
(define index (decode (xenum-type xe) port))
(or (list-ref (xenum-options xe) index) index))
(define (xenum-size xe [val #f] [parent #f]) (size (xenum-type xe)))
(define (xenum-encode xe val [port-arg (current-output-port)] #:parent [parent #f])
(define port (if (output-port? port-arg) port-arg (open-output-bytes)))
(define index (index-of (xenum-options xe) val))
(unless index
(raise-argument-error 'Enum:encode "valid option" val))
(encode (xenum-type xe) index port)
(unless port-arg (get-output-bytes port)))
(struct xenum (type options) #:transparent
#:methods gen:xenomorphic
[(define decode xenum-decode)
(define encode xenum-encode)
(define size xenum-size)])
(define (+xenum type [options null])
(xenum type options))

@ -0,0 +1,36 @@
#lang racket/base
(require rackunit
sugar/unstable/dict
"../helper.rkt"
"../number.rkt"
"../enum.rkt")
#|
approximates
https://github.com/mbutterick/restructure/blob/master/test/Enum.coffee
|#
(define e (+xenum uint8 '("foo" "bar" "baz")))
(test-case
"should have the right size"
(check-equal? (size e) 1))
(test-case
"decode should decode"
(parameterize ([current-input-port (open-input-bytes (bytes 1 2 0))])
(check-equal? (decode e) "bar")
(check-equal? (decode e) "baz")
(check-equal? (decode e) "foo")))
(test-case
"encode should encode"
(parameterize ([current-output-port (open-output-bytes)])
(encode e "bar")
(encode e "baz")
(encode e "foo")
(check-equal? (dump (current-output-port)) (bytes 1 2 0))))
(test-case
"should throw on unknown option"
(check-exn exn:fail:contract? (λ () (encode e "unknown" (open-output-bytes)))))

@ -3,7 +3,7 @@
(require "array-test.rkt"
"bitfield-test.rkt"
"buffer-test.rkt"
;"enum-test.rkt"
"enum-test.rkt"
;"lazy-array-test.rkt"
"number-test.rkt"
;"optional-test.rkt"

Loading…
Cancel
Save