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

47 lines
1.5 KiB
Racket

8 years ago
#lang restructure/racket
8 years ago
(require "number.rkt" "utils.rkt" "stream.rkt")
(provide (all-defined-out))
8 years ago
#|
approximates
https://github.com/mbutterick/restructure/blob/master/src/String.coffee
|#
8 years ago
(struct $codec (encoder decoder) #:transparent)
(define-subclass Streamcoder (String [strlen #f] [encoding 'ascii])
(field [codec (caseq encoding
[(latin-1 ascii) ($codec string->bytes/latin-1 bytes->string/latin-1)]
[(utf-8 utf8) ($codec string->bytes/utf-8 bytes->string/utf-8)])])
8 years ago
(define/augment (decode stream [parent #f])
8 years ago
(define count (if strlen
(resolveLength strlen stream parent)
8 years ago
(send stream length)))
(define bytes (send stream read count))
8 years ago
(($codec-decoder codec) bytes))
8 years ago
(define/augment (encode stream val [parent #f])
8 years ago
(define bytes (($codec-encoder codec) (format "~a" val)))
8 years ago
8 years ago
(when (Number? strlen) ;; length-prefixed string
(send strlen encode stream (bytes-length bytes)))
8 years ago
8 years ago
(send stream write bytes))
7 years ago
(define/override (size [str-in #f])
(define str (or str-in (make-string strlen #\x)))
8 years ago
(define es (+EncodeStream))
(encode es str)
(bytes-length (send es dump))))
8 years ago
(test-module
8 years ago
(require "stream.rkt")
(define stream (+DecodeStream #"\2BCDEF"))
(define S (+String uint8 'utf8))
8 years ago
(check-equal? (send S decode stream) "BC")
8 years ago
(define os (+EncodeStream))
8 years ago
(send S encode os "Mike")
8 years ago
(check-equal? (send os dump) #"\4Mike")
(check-equal? (send (+String) size "foobar") 6))