Next Previous Up Top Contents Index

15.2 An illustrative example of user defined streams

15.2.4 Stream input

The following definition for thestream-read-char reads a character from the stream. If the character read is a#\Line-Separator, then the method returns#\Newline, otherwise the character read is returned. It also returns:eof at the end of the file.

(defmethod stream:stream-read-char ((stream unicode-ls-stream))
  (let ((char (read-char (ls-stream-file-stream stream) 
               nil :eof)))
    (if (eq char #\Line-Separator)
        #\Newline
      char)))

There is no need to define a new method forstream-read-line as the default method usesstream-read-char repeatedly to read a line, and our implementation ofstream-read-char ensures that this will work.

stream-read-char

Generic Function

stream-read-char stream

Package:stream
The generic functionstream-read-char reads one item from stream. The item read is either a character or the end of file symbol:eof if the stream is at the end of a file. Every subclass offundamental-character-input-stream must define a method for this function.

We also need to make sure that if a#\Newline is unread, it is unread as a#\Line-Separator. The following code uses the Common Lisp file stream functionunread-char to achieve this.

(defmethod stream:stream-unread-char ((stream unicode-ls-stream)
                                      char)
  (unread-char (if (eq char #\Newline) #\Line-Separator char)
               (ls-stream-file-stream stream)))

stream-unread-char

Generic Function

stream-unread-char stream

Package:stream
The generic functionstream-unread-char undoes the last call tostream-read-char, as inunread-char. Every subclass offundamental-character-input-stream must define a method for this function.

Finally, although the default methods forstream-listen andstream-clear-input would work for our stream, it is faster to use the functions provided byfile-stream, using our accessor,ls-stream-file-stream.

(defmethod stream:stream-listen ((stream unicode-ls-stream))
  (listen (ls-stream-file-stream stream)))

(defmethod stream:stream-clear-input ((stream unicode-ls-stream)) (clear-input (ls-stream-file-stream stream)))

stream-clear-input

Generic Function

stream-clear-input stream

Package:stream
The generic functionstream-clear-input implementsclear-input. The default method is defined onfundamental-input-stream and does nothing.
stream-listen

Generic Function

stream-listen stream

Package:stream
The generic functionstream-listen is used bylisten and returnst if there is input available. The default method usesstream-read-char-no-hang andstream-unread-char. Most streams should define their own method as this is usually trivial and more efficient than the method provided.

LispWorks User Guide - 14 Oct 1998

Next Previous Up Top Contents Index

Generated with Harlequin WebMaker