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

46 lines
1.5 KiB
Racket

6 years ago
#lang racket/base
(require "base.rkt" racket/class racket/match)
6 years ago
(provide (all-defined-out))
6 years ago
#|
approximates
https://github.com/mbutterick/restructure/blob/master/src/Optional.coffee
|#
6 years ago
(define x:optional%
(class xenobase%
6 years ago
(super-new)
6 years ago
(init-field [(@type type)] [(@condition condition)])
6 years ago
6 years ago
(unless (xenomorphic-type? @type)
6 years ago
(raise-argument-error 'x:optional"xenomorphic type" @type))
6 years ago
(define (resolve-condition parent)
6 years ago
(match @condition
[(? procedure? proc) (proc parent)]
[val val]))
6 years ago
(define/augment (decode port parent)
6 years ago
(when (resolve-condition parent)
(send @type decode port parent)))
6 years ago
(define/augment (encode val port [parent #f])
6 years ago
(when (resolve-condition parent)
(send @type encode val port parent)))
6 years ago
(define/augment (size [val #f] [parent #f])
(if (resolve-condition parent) (send @type size val parent) 0))))
6 years ago
6 years ago
(define no-val (gensym))
6 years ago
(define (x:optional [type-arg #f] [cond-arg no-val]
6 years ago
#:type [type-kwarg #f]
6 years ago
#:condition [cond-kwarg no-val]
#:pre-encode [pre-proc #f]
#:post-decode [post-proc #f])
6 years ago
(define type (or type-arg type-kwarg))
(define condition (cond
[(and (eq? cond-arg no-val) (eq? cond-kwarg no-val)) #true]
[(not (eq? cond-arg no-val)) cond-arg]
[(not (eq? cond-kwarg no-val)) cond-kwarg]))
6 years ago
(new (generate-subclass x:optional% pre-proc post-proc) [type type] [condition condition]))