~williewillus/racket-rfc8949

13bfcb3acf01723c61aaab17a050398343699bad — Vincent Lee 3 years ago 39ea6cb
Custom serializer support (untested/undocumented)
2 files changed, 18 insertions(+), 4 deletions(-)

M encode.rkt
M scribblings/manual.scrbl
M encode.rkt => encode.rkt +17 -3
@@ 1,8 1,12 @@
#lang racket/base

(require racket/undefined
(require racket/generic
         racket/undefined
         "common.rkt")
(provide cbor-write)
(provide cbor-write
         gen:cbor-custom-write
         cbor-custom-write?
         cbor-write-proc)

(define u8-max #xFF)
(define u16-max #xFFFF)


@@ 115,6 119,15 @@
        (write-byte (combine 7 24) out)
        (write-byte inner out))))

(define-generics cbor-custom-write
  (cbor-write-proc cbor-custom-write))

(define (cbor-write-custom-impl config v out)
  (define ser (cbor-write-proc v))
  (unless (cbor-tag? ser)
    (error "Custom CBOR write implementation must return a cbor-tag?"))
  (cbor-write-tag config ser out))

(define (cbor-write config v [out (current-output-port)])
  (cond
    [(and (exact-integer? v) (<= 0 v u64-max))


@@ 133,8 146,9 @@
    [(vector? v) (cbor-write-vector config v out)]
    [(hash? v) (cbor-write-map config v out)]
    [(sequence? v) (cbor-write-seq config v out)]
    [(cbor-tag? v) (cbor-write-tag config v out)] ; todo handle interpreted values
    [(cbor-tag? v) (cbor-write-tag config v out)]
    [(cbor-simple-value? v) (cbor-write-simple-value v out)]
    [(cbor-custom-write? v) (cbor-write-custom-impl config v out)]
    [else (error "Don't know how to write" v)]))

(module* test #f

M scribblings/manual.scrbl => scribblings/manual.scrbl +1 -1
@@ 70,7 70,7 @@ Equivalent to @racket[(or/c (integer-in 0 19) (integer-in 32 255))].

@defstruct[cbor-tag ([number cbor-valid-tag-number?] [content any/c])]{
Raw representation of a CBOR tag with tag number @racket[number] and tag content
@racket[content].
@racket[content]. @racket[content] must be serializable by @racket[cbor-write].
}

@defstruct[cbor-simple-value ([inner cbor-unassigned-simple-value?])]{