stringage
parent
c18859eb4b
commit
13c2be37db
@ -0,0 +1,16 @@
|
||||
#lang restructure/racket
|
||||
(require "decodestream.rkt" "encodestream.rkt")
|
||||
(provide RStreamcoder)
|
||||
|
||||
(define-subclass RBase (RStreamcoder)
|
||||
|
||||
(define/overment (decode stream . args)
|
||||
(unless (is-a? stream RDecodeStream)
|
||||
(raise-argument-error 'decode "RDecodeStream" stream))
|
||||
(inner (void) decode stream . args))
|
||||
|
||||
(define/overment (encode stream . args)
|
||||
(when stream
|
||||
(unless (is-a? stream REncodeStream)
|
||||
(raise-argument-error 'encode "REncodeStream" stream)))
|
||||
(inner (void) encode stream . args)))
|
@ -0,0 +1,38 @@
|
||||
#lang restructure/racket
|
||||
(require "number.rkt" "utils.rkt" "streamcoder.rkt")
|
||||
(provide RString)
|
||||
|
||||
#|
|
||||
approximates
|
||||
https://github.com/mbutterick/restructure/blob/master/src/String.coffee
|
||||
|#
|
||||
|
||||
(define-subclass RStreamcoder (RString [length #f] [encoding 'ascii])
|
||||
(field [_codec (caseq encoding
|
||||
[(latin-1) (cons string->bytes/latin-1 bytes->string/latin-1)]
|
||||
[(ascii utf-8 utf8)(cons string->bytes/utf-8 bytes->string/utf-8)])])
|
||||
|
||||
(define/augment (decode stream [parent #f])
|
||||
(define count (if length
|
||||
(resolveLength length stream parent)
|
||||
(send stream length)))
|
||||
(define bytes (send stream read count))
|
||||
((cdr _codec) bytes))
|
||||
|
||||
(define/augment (encode stream val [parent #f])
|
||||
(define bytes ((car _codec) val))
|
||||
|
||||
(when (is-a? length Number) ;; length-prefixed string
|
||||
(send length encode stream (bytes-length bytes)))
|
||||
|
||||
(send stream write bytes)))
|
||||
|
||||
|
||||
(test-module
|
||||
(require "decodestream.rkt" "encodestream.rkt")
|
||||
(define stream (make-object RDecodeStream #"\2BCDEF"))
|
||||
(define S (make-object RString uint8 'utf8))
|
||||
(check-equal? (send S decode stream) "BC")
|
||||
(define os (make-object REncodeStream))
|
||||
(send S encode os "Mike")
|
||||
(check-equal? (send os dump) #"\4Mike"))
|
@ -0,0 +1,11 @@
|
||||
#lang restructure/racket
|
||||
(provide (all-defined-out))
|
||||
(require "number.rkt")
|
||||
|
||||
(define (resolveLength length stream parent)
|
||||
(cond
|
||||
[(number? length) length]
|
||||
[(procedure? length) (length parent)]
|
||||
[(and parent (string? length) (· parent length))]
|
||||
[(and stream (is-a? length Number) (send length decode stream))]
|
||||
[else (raise-argument-error 'resolveLength "fixed-size item" length)]))
|
Loading…
Reference in New Issue