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

53 lines
1.6 KiB
Racket

8 years ago
#lang restructure/racket
(require racket/dict)
8 years ago
(provide (all-defined-out))
#|
approximates
https://github.com/mbutterick/restructure/blob/master/src/Struct.coffee
|#
(define-subclass RBase (RStruct [assocs (dictify)])
(field [key-index #f]
[fields (mhash)])
(for ([(k v) (in-dict assocs)])
8 years ago
(hash-set! fields k v))
8 years ago
8 years ago
(define/public-final (make-key-index! [fields assocs])
(set! key-index (map car fields)))
(make-key-index!)
(define/override (decode stream [parent #f] [length 0])
8 years ago
(define res (_setup stream parent length))
(_parseFields stream res fields)
#;(hash-set! (hash-ref res '_props) '_currentOffset (· stream pos))
8 years ago
(send this process res stream)
8 years ago
res)
8 years ago
8 years ago
(define/override (encode stream val [parent #f])
8 years ago
(send this preEncode val stream)
(for ([key (in-list key-index)])
8 years ago
(send (hash-ref fields key) encode stream (hash-ref val key))))
8 years ago
(define/public-final (_setup stream parent length)
8 years ago
(define res (mhasheq))
8 years ago
8 years ago
;; define hidden properties
#;(hash-set! res '_props
8 years ago
(mhasheq 'parent (mhasheq 'value parent)
'_startOffset (mhasheq 'value (· stream pos))
'_currentOffset (mhasheq 'value 0 'writable #t)
'_length (mhasheq 'value length)))
8 years ago
res)
8 years ago
(define/public-final (_parseFields stream res fields)
8 years ago
(for ([key (in-list key-index)])
(define dictvalue (dict-ref fields key))
8 years ago
(define val
(if (procedure? dictvalue)
(dictvalue res)
(send dictvalue decode stream res)))
8 years ago
(hash-set! res key val)))
8 years ago
)