[racket] exception instead of EOF?

From: John Clements (clements at brinckerhoff.org)
Date: Mon Dec 26 11:06:47 EST 2011

On Dec 26, 2011, at 2:46 AM, Dmitry Pavlov wrote:

> Hello,
> 
> I would like to make read-byte and friends to
> throw an exception in case end of file is
> reached. That is, when I call read-byte,
> I know that the byte must be there, otherwise
> the input data is corrupt. I would prefer
> not to check the result of every read-byte
> call. What is the simplest way to achieve
> such a behavior?

I would just write a procedure that checks to see a byte is not an eof-object, and signals an error if required. Like this (including test cases):

#lang racket

(require rackunit)

;; given a stream, reads a byte, signalling 
;; an error at the end of the file.
(define (read-byte/exn input-stream)
  (define result (read-byte input-stream))
  (cond [(eof-object? result) 
         (error 'read-byte/exn "expected byte, got #<eof>")]
        [else result]))

(check-equal? (read-byte/exn (open-input-bytes #"ABC")) 65)
(check-exn exn:fail? 
           (lambda () (read-byte/exn (open-input-bytes #""))))


-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4624 bytes
Desc: not available
URL: <http://lists.racket-lang.org/users/archive/attachments/20111226/93d01ee8/attachment.p7s>

Posted on the users mailing list.