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/enum.rkt

40 lines
1.4 KiB
Racket

#lang racket/base
(require racket/class racket/match "base.rkt" racket/list)
6 years ago
(provide (all-defined-out))
6 years ago
#|
approximates
https://github.com/mbutterick/restructure/blob/master/src/Enum.coffee
|#
6 years ago
(define x:enum%
(class x:base%
6 years ago
(super-new)
6 years ago
(init-field [(@type type)] [(@values values)])
(unless (xenomorphic-type? @type)
6 years ago
(raise-argument-error 'x:enum "xenomorphic type" @type))
6 years ago
(unless (list? @values)
6 years ago
(raise-argument-error 'x:enum "list of values" @values))
6 years ago
(define/augment (decode port parent)
(define index (send @type decode port parent))
6 years ago
(or (list-ref @values index) index))
6 years ago
(define/augment (encode val port [parent #f])
6 years ago
(match (index-of @values val)
[(? values idx) (send @type encode idx port parent)]
6 years ago
[_ (raise-argument-error 'x:enum-encode "valid option" val)]))
6 years ago
(define/augment (size [val #f] [parent #f])
(send @type size val parent))))
6 years ago
(define (x:enum [type-arg #f] [values-arg #f]
6 years ago
#:type [type-kwarg #f]
6 years ago
#:values [values-kwarg #f]
#:pre-encode [pre-proc #f]
#:post-decode [post-proc #f]
#:base-class [base-class x:enum%])
6 years ago
(define type (or type-arg type-kwarg))
(define values (or values-arg values-kwarg))
(new (generate-subclass base-class pre-proc post-proc) [type type] [values values]))