~williewillus/racket-rfc8949

5a83fd33afc0f44f5061c8c203a799ebe0faf411 — Alwinfy 3 years ago e35d8c9
Make read-n-bytes performant (tm)
1 files changed, 11 insertions(+), 19 deletions(-)

M decode.rkt
M decode.rkt => decode.rkt +11 -19
@@ 11,15 11,13 @@
      res
      (error "Unexpected EOF")))

; read n bytes from port into buf. n is inferred from the length of buf
(define (read-n-bytes buf port)
  (define n (bytes-length buf))
  (let loop ([cur 0])
    (if (= cur n)
        buf
        (begin
          (bytes-set! buf cur (expect-byte port))
          (loop (add1 cur))))))
; read exactly n bytes, or throw
(define (read-n-bytes n port)
  (let* ([bytes (read-bytes n port)]
         [len   (if (eof-object? bytes) 0 (bytes-length bytes))])
    (if (= len n)
      bytes
      (error "Unexpected EOF: Expected ~a bytes, got ~a" n len))))

(define (read-argument port major additional)
  (if (< additional 24)


@@ 78,8 76,7 @@
                            (lambda () (cbor-read config port)) ; TODO disallow indefinites in the chunks, and also check that they are actually bytestrings
                            (lambda (strs)
                              (bytes->immutable-bytes (apply bytes-append (reverse strs)))))
      (let ([buf (make-bytes payload-len)])
        (bytes->immutable-bytes (read-n-bytes buf port)))))
      (bytes->immutable-bytes (read-n-bytes payload-len port))))

(define (cbor-read-string config port additional)
  (define payload-len (read-argument port 3 additional))


@@ 88,8 85,7 @@
                            (lambda () (cbor-read config port)) ; TODO disallow indefinites in the chunks, and also check that they are actually strings
                            (lambda (strs)
                              (apply string-append-immutable (reverse strs))))
      (let ([buf (make-bytes payload-len)])
        (read-n-bytes buf port)
      (let ([buf (read-n-bytes payload-len port)])
        (string->immutable-string (bytes->string/utf-8 buf)))))

(define (cbor-read-list config port additional)


@@ 173,13 169,9 @@
                       (arithmetic-shift (expect-byte port) 8)
                       (expect-byte port)))]
        [(26)
         (define buf (bytes 0 0 0 0))
         (read-n-bytes buf port)
         (floating-point-bytes->real buf #t)]
         (floating-point-bytes->real (read-n-bytes 4 port) #t)]
        [(27)
         (define buf (bytes 0 0 0 0 0 0 0 0))
         (read-n-bytes buf port)
         (floating-point-bytes->real buf #t)]
         (floating-point-bytes->real (read-n-bytes 8 port) #t)]
        [(28 29 30) (error "Additional information ~a is reserved in major type 7" additional)]
        [(31) (error "Unexpected break code")]))) ; We handle break explicitly in deserialization of lists of things, so it should never appear here.