Skip to content
Snippets Groups Projects
stream.lisp 58.5 KiB
Newer Older
ram's avatar
ram committed
;;;
;;; **********************************************************************
;;; This code was written as part of the CMU Common Lisp project at
;;; Carnegie Mellon University, and has been placed in the public domain.
;;;
(ext:file-comment
  "$Header: /Volumes/share2/src/cmucl/cvs2git/cvsroot/src/code/stream.lisp,v 1.31 1998/05/05 00:12:14 dtc Exp $")
ram's avatar
ram committed
;;; **********************************************************************
;;;
;;; Stream functions for Spice Lisp.
;;; Written by Skef Wholey and Rob MacLachlan.
;;;
;;; This file contains the OS-independent stream functions.
ram's avatar
ram committed
;;;
ram's avatar
ram committed

(export '(broadcast-stream make-broadcast-stream broadcast-stream-streams 
	  synonym-stream make-synonym-stream synonym-stream-symbol
	  concatenated-stream make-concatenated-stream
	  concatenated-stream-streams
	  two-way-stream make-two-way-stream two-way-stream-input-stream
	  two-way-stream-output-stream
	  echo-stream make-echo-stream echo-stream-input-stream
	  echo-stream-output-stream
	  make-string-input-stream make-string-output-stream
ram's avatar
ram committed
	  get-output-stream-string stream-element-type input-stream-p
	  output-stream-p open-stream-p interactive-stream-p
	  open-stream-p close read-line read-char
ram's avatar
ram committed
	  unread-char peek-char listen read-char-no-hang clear-input read-byte
	  write-char write-string write-line terpri fresh-line
	  finish-output force-output clear-output write-byte
          stream streamp string-stream
	  *standard-input* *standard-output*
ram's avatar
ram committed
          *error-output* *query-io* *debug-io* *terminal-io* *trace-output*))

(in-package "SYSTEM")
ram's avatar
ram committed
(export '(make-indenting-stream read-n-bytes))

(in-package "EXT")

(export '(get-stream-command
	  stream-command stream-command-p stream-command-name 
	  stream-command-args make-stream-command make-case-frob-stream))

(in-package "LISP")
ram's avatar
ram committed

(deftype string-stream ()
  '(or string-input-stream string-output-stream
       fill-pointer-output-stream))

ram's avatar
ram committed
;;;; Standard streams:
;;;
;;; The initialization of these streams is performed by Stream-Init,
;;; which lives in the file of machine-specific stream functions.
;;;
(defvar *terminal-io* () "Terminal I/O stream.")
(defvar *standard-input* () "Default input stream.")
(defvar *standard-output* () "Default output stream.")
(defvar *error-output* () "Error output stream.")
(defvar *query-io* () "Query I/O stream.")
(defvar *trace-output* () "Trace output stream.")
(defvar *debug-io* () "Interactive debugging stream.")

(defun ill-in (stream &rest ignore)
  (declare (ignore ignore))
  (error "~S is not a character input stream." stream))
(defun ill-out (stream &rest ignore)
  (declare (ignore ignore))
  (error "~S is not a character output stream." stream))
(defun ill-bin (stream &rest ignore)
  (declare (ignore ignore))
  (error "~S is not a binary input stream." stream))
(defun ill-bout (stream &rest ignore)
  (declare (ignore ignore))
  (error "~S is not a binary output stream." stream))
(defun closed-flame (stream &rest ignore)
  (declare (ignore ignore))
  (error "~S is closed." stream))
(defun do-nothing (&rest ignore)
  (declare (ignore ignore)))

(defun %print-stream (structure stream d)
  (declare (ignore d structure))
  (write-string "#<Bare Stream>" stream))

;;; HOW THE STREAM STRUCTURE IS USED:
;;;
;;;    Many of the slots of the stream structure contain functions
;;; which are called to perform some operation on the stream.  Closed
;;; streams have #'Closed-Flame in all of their function slots.  If
;;; one side of an I/O or echo stream is closed, the whole stream is
;;; considered closed.  The functions in the operation slots take
;;; arguments as follows:
;;;
;;; In:			Stream, Eof-Errorp, Eof-Value
;;; Bin:		Stream, Eof-Errorp, Eof-Value
;;; N-Bin:		Stream, Buffer, Start, Numbytes, Eof-Errorp
;;; Out:		Stream, Character
;;; Bout:		Stream, Integer
;;; Sout:		Stream, String, Start, End
;;; Misc:		Stream, Operation, &Optional Arg1, Arg2
;;;
;;;    In order to save space, some of the less common stream operations
;;; are handled by just one function, the Misc method.  This function
;;; is passed a keyword which indicates the operation to perform.
;;; The following keywords are used:
;;;  :listen 		- Return the following values:
;;; 			     t if any input waiting.
;;; 			     :eof if at eof.
;;; 			     nil if no input is available and not at eof.
ram's avatar
ram committed
;;;  :unread		- Unread the character Arg.
;;;  :close		- Do any stream specific stuff to close the stream.
;;;			  The methods are set to closed-flame by the close
;;;			  function, so that need not be done by this
;;;			  function.
;;;  :clear-input 	- Clear any unread input
;;;  :finish-output,
;;;  :force-output	- Cause output to happen
;;;  :clear-output	- Clear any undone output
;;;  :element-type 	- Return the type of element the stream deals wit<h.
ram's avatar
ram committed
;;;  :line-length	- Return the length of a line of output.
;;;  :charpos		- Return current output position on the line.
;;;  :file-length	- Return the file length of a file stream.
;;;  :file-position	- Return or change the current position of a file stream.
;;;  :file-name		- Return the name of an associated file.
;;;  :interactive-p     - Is this an interactive device?
ram's avatar
ram committed
;;;
;;;    In order to do almost anything useful, it is necessary to
;;; define a new type of structure that includes stream, so that the
;;; stream can have some state information.
;;;
;;; THE STREAM IN-BUFFER:
;;;
;;;    The In-Buffer in the stream holds characters or bytes that
;;; are ready to be read by some input function.  If there is any
;;; stuff in the In-Buffer, then the reading function can use it
;;; without calling any stream method.  Any stream may put stuff in
;;; the In-Buffer, and may also assume that any input in the In-Buffer
;;; has been consumed before any in-method is called.  If a text
;;; stream has in In-Buffer, then the first character should not be
;;; used to buffer normal input so that it is free for unreading into.
;;;
;;;    The In-Buffer slot is a vector In-Buffer-Length long.  The
;;; In-Index is the index in the In-Buffer of the first available
;;; object.  The available objects are thus between In-Index and the
;;; length of the In-Buffer.
;;;
;;;    When this buffer is only accessed by the normal stream
;;; functions, the number of function calls is halved, thus
;;; potentially doubling the speed of simple operations.  If the
;;; Fast-Read-Char and Fast-Read-Byte macros are used, nearly all
;;; function call overhead is removed, vastly speeding up these
;;; important operations.
;;;
;;;    If a stream does not have an In-Buffer, then the In-Buffer slot
;;; must be nil, and the In-Index must be In-Buffer-Length.  These are
;;; the default values for the slots. 
ram's avatar
ram committed

;;; Stream manipulation functions.

(defun input-stream-p (stream)
  "Returns non-nil if the given Stream can perform input operations."
dtc's avatar
dtc committed
  (and (lisp-stream-p stream)
       (not (eq (lisp-stream-in stream) #'closed-flame))
       (or (not (eq (lisp-stream-in stream) #'ill-in))
	   (not (eq (lisp-stream-bin stream) #'ill-bin)))))
ram's avatar
ram committed

(defun output-stream-p (stream)
  "Returns non-nil if the given Stream can perform output operations."
dtc's avatar
dtc committed
  (and (lisp-stream-p stream)
       (not (eq (lisp-stream-in stream) #'closed-flame))
       (or (not (eq (lisp-stream-out stream) #'ill-out))
	   (not (eq (lisp-stream-bout stream) #'ill-bout)))))
ram's avatar
ram committed

(defun open-stream-p (stream)
  "Return true if Stream is not closed."
  (declare (type stream stream))
dtc's avatar
dtc committed
  (not (eq (lisp-stream-in stream) #'closed-flame)))
ram's avatar
ram committed
(defun stream-element-type (stream)
  "Returns a type specifier for the kind of object returned by the Stream."
  (declare (type stream stream))
dtc's avatar
dtc committed
  (funcall (lisp-stream-misc stream) stream :element-type))
ram's avatar
ram committed

(defun interactive-stream-p (stream)
  "Return true if Stream does I/O on a terminal or other interactive device."
  (declare (type stream stream))
dtc's avatar
dtc committed
  (funcall (lisp-stream-misc stream) stream :interactive-p))
(defun open-stream-p (stream)
  "Return true if and only if STREAM has not been closed."
  (declare (type stream stream))
dtc's avatar
dtc committed
  (not (eq (lisp-stream-in stream) #'closed-flame)))
ram's avatar
ram committed
(defun close (stream &key abort)
  "Closes the given Stream.  No more I/O may be performed, but inquiries
  may still be made.  If :Abort is non-nil, an attempt is made to clean
  up the side effects of having created the stream."
  (declare (type stream stream))
  (when (open-stream-p stream)
dtc's avatar
dtc committed
    (funcall (lisp-stream-misc stream) stream :close abort))
ram's avatar
ram committed
  t)

(defun set-closed-flame (stream)
dtc's avatar
dtc committed
  (setf (lisp-stream-in stream) #'closed-flame)
  (setf (lisp-stream-bin stream) #'closed-flame)
  (setf (lisp-stream-n-bin stream) #'closed-flame)
  (setf (lisp-stream-in stream) #'closed-flame)
  (setf (lisp-stream-out stream) #'closed-flame)
  (setf (lisp-stream-bout stream) #'closed-flame)
  (setf (lisp-stream-sout stream) #'closed-flame)
  (setf (lisp-stream-misc stream) #'closed-flame))


;;;; File position and file length.

;;; File-Position  --  Public
;;;
;;;    Call the misc method with the :file-position operation.
;;;
(defun file-position (stream &optional position)
  "With one argument returns the current position within the file
   File-Stream is open to.  If the second argument is supplied, then
   this becomes the new file position.  The second argument may also
   be :start or :end for the start and end of the file, respectively."
  (declare (stream stream)
	   (type (or index (member nil :start :end)) position))
  (cond
   (position
dtc's avatar
dtc committed
    (setf (lisp-stream-in-index stream) in-buffer-length)
    (funcall (lisp-stream-misc stream) stream :file-position position))
dtc's avatar
dtc committed
    (let ((res (funcall (lisp-stream-misc stream) stream :file-position nil)))
      (when res (- res (- in-buffer-length (lisp-stream-in-index stream))))))))


;;; File-Length  --  Public
;;;
;;;    Like File-Position, only use :file-length.
;;;
(defun file-length (stream)
  "This function returns the length of the file that File-Stream is open to."
  (declare (stream stream))
dtc's avatar
dtc committed
  (funcall (lisp-stream-misc stream) stream :file-length))
ram's avatar
ram committed

;;; Input functions:

(defun read-line (&optional (stream *standard-input*) (eof-errorp t) eof-value
			    recursive-p)
  "Returns a line of text read from the Stream as a string, discarding the
  newline character."
  (declare (ignore recursive-p))
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (prepare-for-fast-read-char stream
         (let ((res (make-string 80))
	       (len 80)
	       (index 0))
	   (loop
	    (let ((ch (fast-read-char nil nil)))
	      (cond (ch
		     (when (char= ch #\newline)
		       (done-with-fast-read-char)
		       (return (values (shrink-vector res index) nil)))
		     (when (= index len)
		       (setq len (* len 2))
		       (let ((new (make-string len)))
			 (replace new res)
			 (setq res new)))
		     (setf (schar res index) ch)
		     (incf index))
		    ((zerop index)
		     (done-with-fast-read-char)
		     (return (values (eof-or-lose stream eof-errorp eof-value)
				     t)))
		    ;; since fast-read-char hit already the eof char, we
		    ;; shouldn't do another read-char
		    (t
		     (done-with-fast-read-char)
		     (return (values (shrink-vector res index) t)))))))))
      (fundamental-stream
       (multiple-value-bind (string eof)
	   (stream-read-line stream)
	 (if (and eof (zerop (length string)))
	     (values (eof-or-lose stream eof-errorp eof-value) t)
	     (values string eof)))))))
ram's avatar
ram committed
;;; We proclaim them inline here, then proclaim them notinline at EOF,
;;; so, except in this file, they are not inline by default, but they can be.
;;;
(proclaim '(inline read-char unread-char read-byte listen))
(defun read-char (&optional (stream *standard-input*) (eof-errorp t) eof-value
			    recursive-p)
  "Inputs a character from Stream and returns it."
  (declare (ignore recursive-p))
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (prepare-for-fast-read-char stream
         (prog1
	     (fast-read-char eof-errorp eof-value)
	   (done-with-fast-read-char))))
      (fundamental-stream
       (let ((char (stream-read-char stream)))
	 (if (eq char :eof)
	     (eof-or-lose stream eof-errorp eof-value)
	     char))))))
ram's avatar
ram committed

(defun unread-char (character &optional (stream *standard-input*))
  "Puts the Character back on the front of the input Stream."
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (let ((index (1- (lisp-stream-in-index stream)))
	     (buffer (lisp-stream-in-buffer stream)))
	 (declare (fixnum index))
	 (when (minusp index) (error "Nothing to unread."))
	 (cond (buffer
		(setf (aref buffer index) (char-code character))
		(setf (lisp-stream-in-index stream) index))
	       (t
		(funcall (lisp-stream-misc stream) stream 
			 :unread character)))))
      (fundamental-stream
       (stream-unread-char stream character))))
ram's avatar
ram committed
  nil)

(defun peek-char (&optional (peek-type nil) (stream *standard-input*)
			    (eof-errorp t) eof-value recursive-p)
  "Peeks at the next character in the input Stream.  See manual for details."
  (declare (ignore recursive-p))
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (let ((char (read-char stream eof-errorp eof-value)))
	 (cond ((eq char eof-value) char)
	       ((characterp peek-type)
		(do ((char char (read-char stream eof-errorp eof-value)))
		    ((or (eq char eof-value) (char= char peek-type))
		     (unless (eq char eof-value)
		       (unread-char char stream))
		     char)))
	       ((eq peek-type t)
		(do ((char char (read-char stream eof-errorp eof-value)))
		    ((or (eq char eof-value) (not (whitespace-char-p char)))
		     (unless (eq char eof-value)
		       (unread-char char stream))
		     char)))
	       (t
		(unread-char char stream)
		char))))
      (fundamental-stream
       (cond ((characterp peek-type)
	      (do ((char (stream-read-char stream) (stream-read-char stream)))
		  ((or (eq char :eof) (char= char peek-type))
		   (cond ((eq char :eof)
			  (eof-or-lose stream eof-errorp eof-value))
			 (t
			  (stream-unread-char stream char)
			  char)))))
	     ((eq peek-type t)
	      (do ((char (stream-read-char stream) (stream-read-char stream)))
		  ((or (eq char :eof) (not (whitespace-char-p char)))
		   (cond ((eq char :eof)
			  (eof-or-lose stream eof-errorp eof-value))
			 (t
			  (stream-unread-char stream char)
			  char)))))
	     (t
	      (let ((char (stream-peek-char stream)))
		(if (eq char :eof)
		    (eof-or-lose stream eof-errorp eof-value)
		    char))))))))
ram's avatar
ram committed

(defun listen (&optional (stream *standard-input*))
  "Returns T if a character is availible on the given Stream."
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (or (/= (the fixnum (lisp-stream-in-index stream)) in-buffer-length)
	   ;; Test for t explicitly since misc methods return :eof sometimes.
	   (eq (funcall (lisp-stream-misc stream) stream :listen) t)))
      (fundamental-stream
       (stream-listen stream)))))
ram's avatar
ram committed

(defun read-char-no-hang (&optional (stream *standard-input*)
				    (eof-errorp t) eof-value recursive-p)
  "Returns the next character from the Stream if one is availible, or nil."
  (declare (ignore recursive-p))
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (if (funcall (lisp-stream-misc stream) stream :listen)
	   ;; On t or :eof get READ-CHAR to do the work.
	   (read-char stream eof-errorp eof-value)
	   nil))
      (fundamental-stream
       (let ((char (stream-read-char-no-hang stream)))
	 (if (eq char :eof)
	     (eof-or-lose stream eof-errorp eof-value)
	     char))))))

ram's avatar
ram committed

(defun clear-input (&optional (stream *standard-input*))
  "Clears any buffered input associated with the Stream."
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (setf (lisp-stream-in-index stream) in-buffer-length)
       (funcall (lisp-stream-misc stream) stream :clear-input))
      (fundamental-stream
       (stream-clear-input stream))))
  nil)
ram's avatar
ram committed

(defun read-byte (stream &optional (eof-errorp t) eof-value)
  "Returns the next byte of the Stream."
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (prepare-for-fast-read-byte stream
         (prog1
	     (fast-read-byte eof-errorp eof-value t)
	   (done-with-fast-read-byte))))
      (fundamental-stream
       (let ((char (stream-read-byte stream)))
	 (if (eq char :eof)
	     (eof-or-lose stream eof-errorp eof-value)
	     char))))))
ram's avatar
ram committed

(defun read-n-bytes (stream buffer start numbytes &optional (eof-errorp t))
  "Reads Numbytes bytes into the Buffer starting at Start, returning the number
   of bytes read.
   -- If EOF-ERROR-P is true, an END-OF-FILE condition is signalled if
      end-of-file is encountered before Count bytes have been read.
   -- If EOF-ERROR-P is false, READ-N-BYTES reads as much data is currently
      available (up to count bytes.)  On pipes or similar devices, this
      function returns as soon as any adata is available, even if the amount
      read is less than Count and eof has not been hit."
dtc's avatar
dtc committed
  (declare (type lisp-stream stream)
	   (type index numbytes start)
	   (type (or (simple-array * (*)) system-area-pointer) buffer))
dtc's avatar
dtc committed
  (let* ((stream (stream-synonym-of stream lisp-stream))
	 (in-buffer (lisp-stream-in-buffer stream))
	 (index (lisp-stream-in-index stream))
ram's avatar
ram committed
	 (num-buffered (- in-buffer-length index)))
    (declare (fixnum index num-buffered))
    (cond
dtc's avatar
dtc committed
      (funcall (lisp-stream-n-bin stream) stream buffer start numbytes eof-errorp))
ram's avatar
ram committed
     ((<= numbytes num-buffered)
      (%primitive byte-blt in-buffer index buffer start (+ start numbytes))
dtc's avatar
dtc committed
      (setf (lisp-stream-in-index stream) (+ index numbytes))
ram's avatar
ram committed
      numbytes)
     (t
      (let ((end (+ start num-buffered)))
	(%primitive byte-blt in-buffer index buffer start end)
dtc's avatar
dtc committed
	(setf (lisp-stream-in-index stream) in-buffer-length)
	(+ (funcall (lisp-stream-n-bin stream) stream buffer end
		    (- numbytes num-buffered)
		    eof-errorp)
ram's avatar
ram committed
	   num-buffered))))))


;;; Amount of space we leave at the start of the in-buffer for unreading.  4
;;; instead of 1 to allow word-aligned copies.
;;;
(defconstant in-buffer-extra 4)

;;; FAST-READ-CHAR-REFILL  --  Interface
;;;
;;;    This function is called by the fast-read-char expansion to refill the
;;; in-buffer for text streams.  There is definitely an in-buffer, and hence
;;; myst be an n-bin method.
;;;
(defun fast-read-char-refill (stream eof-errorp eof-value)
dtc's avatar
dtc committed
  (let* ((ibuf (lisp-stream-in-buffer stream))
	 (count (funcall (lisp-stream-n-bin stream) stream
			 ibuf in-buffer-extra
			 (- in-buffer-length in-buffer-extra)
			 nil))
	 (start (- in-buffer-length count)))
    (declare (type index start count))
    (cond ((zerop count)
dtc's avatar
dtc committed
	   (setf (lisp-stream-in-index stream) in-buffer-length)
	   (funcall (lisp-stream-in stream) stream eof-errorp eof-value))
	  (t
	   (when (/= start in-buffer-extra)
	     (bit-bash-copy ibuf (+ (* in-buffer-extra vm:byte-bits)
				    (* vm:vector-data-offset vm:word-bits))
			    ibuf (+ (the index (* start vm:byte-bits))
				    (* vm:vector-data-offset vm:word-bits))
			    (* count vm:byte-bits)))
dtc's avatar
dtc committed
	   (setf (lisp-stream-in-index stream) (1+ start))
	   (code-char (aref ibuf start))))))


;;; FAST-READ-BYTE-REFILL  --  Interface
;;;
;;;    Similar to FAST-READ-CHAR-REFILL, but we don't have to leave room for
;;; unreading.
;;;
(defun fast-read-byte-refill (stream eof-errorp eof-value)
dtc's avatar
dtc committed
  (let* ((ibuf (lisp-stream-in-buffer stream))
	 (count (funcall (lisp-stream-n-bin stream) stream
			 ibuf 0 in-buffer-length
			 nil))
	 (start (- in-buffer-length count)))
    (declare (type index start count))
    (cond ((zerop count)
dtc's avatar
dtc committed
	   (setf (lisp-stream-in-index stream) in-buffer-length)
	   (funcall (lisp-stream-bin stream) stream eof-errorp eof-value))
	  (t
	   (unless (zerop start)
	     (bit-bash-copy ibuf (* vm:vector-data-offset vm:word-bits)
			    ibuf (+ (the index (* start vm:byte-bits))
				    (* vm:vector-data-offset vm:word-bits))
			    (* count vm:byte-bits)))
dtc's avatar
dtc committed
	   (setf (lisp-stream-in-index stream) (1+ start))
	   (aref ibuf start)))))
  
ram's avatar
ram committed

;;; Output functions:

(defun write-char (character &optional (stream *standard-output*))
  "Outputs the Character to the Stream."
dtc's avatar
dtc committed
  (with-stream stream (lisp-stream-out character)
	       (stream-write-char character))
ram's avatar
ram committed
  character)

(defun terpri (&optional (stream *standard-output*))
  "Outputs a new line to the Stream."
dtc's avatar
dtc committed
  (with-stream stream (lisp-stream-out #\newline) (stream-terpri))
ram's avatar
ram committed
  nil)

(defun fresh-line (&optional (stream *standard-output*))
  "Outputs a new line to the Stream if it is not positioned at the begining of
   a line.  Returns T if it output a new line, nil otherwise."
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (when (/= (or (charpos stream) 1) 0)
	 (funcall (lisp-stream-out stream) stream #\newline)
	 t))
      (fundamental-stream
       (stream-fresh-line stream)))))
ram's avatar
ram committed

(defun write-string (string &optional (stream *standard-output*)
			    &key (start 0) (end (length (the vector string))))
  "Outputs the String to the given Stream."
  (write-string* string stream start end))

(defun write-string* (string &optional (stream *standard-output*)
			     (start 0) (end (length (the vector string))))
  (declare (fixnum start end))
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (if (array-header-p string)
	   (with-array-data ((data string) (offset-start start)
			     (offset-end end))
	     (funcall (lisp-stream-sout stream)
		      stream data offset-start offset-end))
	   (funcall (lisp-stream-sout stream) stream string start end))
       string)
      (fundamental-stream
       (stream-write-string stream string start end)))))
ram's avatar
ram committed

(defun write-line (string &optional (stream *standard-output*)
			  &key (start 0) (end (length string)))
  "Outputs the String to the given Stream, followed by a newline character."
  (write-line* string stream start end))

(defun write-line* (string &optional (stream *standard-output*)
			   (start 0) (end (length string)))
  (declare (fixnum start end))
dtc's avatar
dtc committed
  (let ((stream (stream-synonym-of stream)))
    (etypecase stream
      (lisp-stream
       (if (array-header-p string)
	   (with-array-data ((data string) (offset-start start)
			     (offset-end end))
	     (with-stream stream (lisp-stream-sout data offset-start
						   offset-end)))
	   (with-stream stream (lisp-stream-sout string start end)))
       (funcall (lisp-stream-out stream) stream #\newline))
      (fundamental-stream
       (stream-write-string stream string start end)
       (stream-write-char stream #\Newline)))
    string))
ram's avatar
ram committed

(defun charpos (&optional (stream *standard-output*))
  "Returns the number of characters on the current line of output of the given
  Stream, or Nil if that information is not availible."
dtc's avatar
dtc committed
  (with-stream stream (lisp-stream-misc :charpos) (stream-line-column)))
ram's avatar
ram committed

(defun line-length (&optional (stream *standard-output*))
  "Returns the number of characters that will fit on a line of output on the
  given Stream, or Nil if that information is not available."
dtc's avatar
dtc committed
  (with-stream stream (lisp-stream-misc :line-length) (stream-line-length)))
ram's avatar
ram committed

(defun finish-output (&optional (stream *standard-output*))
dtc's avatar
dtc committed
  "Attempts to ensure that all output sent to the Stream has reached its
ram's avatar
ram committed
   destination, and only then returns."
dtc's avatar
dtc committed
  (with-stream stream (lisp-stream-misc :finish-output) (stream-finish-output))
ram's avatar
ram committed
  nil)

(defun force-output (&optional (stream *standard-output*))
  "Attempts to force any buffered output to be sent."
dtc's avatar
dtc committed
  (with-stream stream (lisp-stream-misc :force-output) (stream-force-output))
ram's avatar
ram committed
  nil)

(defun clear-output (&optional (stream *standard-output*))
  "Clears the given output Stream."
dtc's avatar
dtc committed
  (with-stream stream (lisp-stream-misc :clear-output) (stream-force-output))
ram's avatar
ram committed
  nil)

(defun write-byte (integer stream)
  "Outputs the Integer to the binary Stream."
dtc's avatar
dtc committed
  (with-stream stream (lisp-stream-bout integer) (stream-write-byte))
ram's avatar
ram committed
  integer)

;;;; Broadcast streams:

dtc's avatar
dtc committed
(defstruct (broadcast-stream (:include lisp-stream
ram's avatar
ram committed
				       (out #'broadcast-out)
				       (bout #'broadcast-bout)
				       (sout #'broadcast-sout)
				       (misc #'broadcast-misc))
			     (:print-function %print-broadcast-stream)
			     (:constructor make-broadcast-stream (&rest streams)))
  ;; This is a list of all the streams we broadcast to.
  (streams () :type list :read-only t))
ram's avatar
ram committed

(setf (documentation 'make-broadcast-stream 'function)
 "Returns an ouput stream which sends its output to all of the given streams.")

(defun %print-broadcast-stream (s stream d)
  (declare (ignore s d))
  (write-string "#<Broadcast Stream>" stream))

(macrolet ((out-fun (fun method &rest args)
	     `(defun ,fun (stream ,@args)
		(dolist (stream (broadcast-stream-streams stream))
		  (funcall (,method stream) stream ,@args)))))
dtc's avatar
dtc committed
  (out-fun broadcast-out lisp-stream-out char)
  (out-fun broadcast-bout lisp-stream-bout byte)
  (out-fun broadcast-sout lisp-stream-sout string start end))
ram's avatar
ram committed

(defun broadcast-misc (stream operation &optional arg1 arg2)
  (let ((streams (broadcast-stream-streams stream)))
    (case operation
      (:charpos
       (dolist (stream streams)
dtc's avatar
dtc committed
	 (let ((charpos (funcall (lisp-stream-misc stream) stream :charpos)))
ram's avatar
ram committed
	   (if charpos (return charpos)))))
      (:line-length
       (let ((min nil))
	 (dolist (stream streams min)
dtc's avatar
dtc committed
	   (let ((res (funcall (lisp-stream-misc stream) stream :line-length)))
ram's avatar
ram committed
	     (when res (setq min (if min (min res min) res)))))))
      (:element-type
       (let (res)
	 (dolist (stream streams (if (> (length res) 1) `(and ,@res) res))
dtc's avatar
dtc committed
	   (pushnew (funcall (lisp-stream-misc stream) stream :element-type) res
ram's avatar
ram committed
		    :test #'equal))))
ram's avatar
ram committed
      (t
       (let ((res nil))
	 (dolist (stream streams res)
dtc's avatar
dtc committed
	   (setq res (funcall (lisp-stream-misc stream) stream operation
ram's avatar
ram committed
			      arg1 arg2))))))))

;;;; Synonym Streams:

dtc's avatar
dtc committed
(defstruct (synonym-stream (:include lisp-stream
ram's avatar
ram committed
				     (in #'synonym-in)
				     (bin #'synonym-bin)
				     (n-bin #'synonym-n-bin)
				     (out #'synonym-out)
				     (bout #'synonym-bout)
				     (sout #'synonym-sout)
				     (misc #'synonym-misc))
			   (:print-function %print-synonym-stream)
			   (:constructor make-synonym-stream (symbol)))
  ;; This is the symbol, the value of which is the stream we are synonym to.
  (symbol nil :type symbol :read-only t))
ram's avatar
ram committed

(defun %print-synonym-stream (s stream d)
  (declare (ignore d))
  (format stream "#<Synonym Stream to ~S>" (synonym-stream-symbol s)))

(setf (documentation 'make-synonym-stream 'function)
  "Returns a stream which performs its operations on the stream which is the
   value of the dynamic variable named by Symbol.")

;;; The output simple output methods just call the corresponding method
;;; in the synonymed stream.
;;;
(macrolet ((out-fun (name slot &rest args)
	     `(defun ,name (stream ,@args)
ram's avatar
ram committed
		(let ((syn (symbol-value (synonym-stream-symbol stream))))
		  (funcall (,slot syn) syn ,@args)))))
dtc's avatar
dtc committed
  (out-fun synonym-out lisp-stream-out ch)
  (out-fun synonym-bout lisp-stream-bout n)
  (out-fun synonym-sout lisp-stream-sout string start end))
ram's avatar
ram committed


;;; Bind synonym stream to this so that SPIO can turn on the right frob in
;;; the icon when we are in a terminal input wait.
;;;
(defvar *previous-stream* nil)

;;; For the input methods, we just call the corresponding function on the
;;; synonymed stream.  These functions deal with getting input out of
;;; the In-Buffer if there is any.
;;;
(macrolet ((in-fun (name fun &rest args)
	     `(defun ,name (stream ,@args)
ram's avatar
ram committed
		(let ((*previous-stream* stream))
		  (,fun (symbol-value (synonym-stream-symbol stream)) ,@args)))))
  (in-fun synonym-in read-char eof-errorp eof-value)
  (in-fun synonym-bin read-byte eof-errorp eof-value)
  (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-errorp))


;;; Synonym-Misc  --  Internal
;;;
;;;    We have to special-case the operations which could look at stuff in
;;; the in-buffer.
;;;
(defun synonym-misc (stream operation &optional arg1 arg2)
ram's avatar
ram committed
  (let ((syn (symbol-value (synonym-stream-symbol stream)))
	(*previous-stream* stream))
    (case operation
dtc's avatar
dtc committed
      (:listen (or (/= (the fixnum (lisp-stream-in-index syn)) in-buffer-length)
		   (funcall (lisp-stream-misc syn) syn :listen)))
ram's avatar
ram committed
      (t
dtc's avatar
dtc committed
       (funcall (lisp-stream-misc syn) syn operation arg1 arg2)))))
ram's avatar
ram committed

;;;; Two-Way streams:

(defstruct (two-way-stream
dtc's avatar
dtc committed
	    (:include lisp-stream
ram's avatar
ram committed
		      (in #'two-way-in)
		      (bin #'two-way-bin)
		      (n-bin #'two-way-n-bin)
		      (out #'two-way-out)
		      (bout #'two-way-bout)
		      (sout #'two-way-sout)
		      (misc #'two-way-misc))
	    (:print-function %print-two-way-stream)
	    (:constructor make-two-way-stream (input-stream output-stream)))
  ;; We read from this stream...
  (input-stream (required-argument) :type stream :read-only t)
ram's avatar
ram committed
  ;; And write to this one
  (output-stream (required-argument) :type stream :read-only t))
ram's avatar
ram committed

(defun %print-two-way-stream (s stream d)
  (declare (ignore d))
  (format stream "#<Two-Way Stream, Input = ~S, Output = ~S>"
	  (two-way-stream-input-stream s)
	  (two-way-stream-output-stream s)))

(setf (documentation 'make-two-way-stream 'function)
  "Returns a bidirectional stream which gets its input from Input-Stream and
   sends its output to Output-Stream.")

(macrolet ((out-fun (name slot &rest args)
	     `(defun ,name (stream ,@args)
		(let ((syn (two-way-stream-output-stream stream)))
		  (funcall (,slot syn) syn ,@args)))))
dtc's avatar
dtc committed
  (out-fun two-way-out lisp-stream-out ch)
  (out-fun two-way-bout lisp-stream-bout n)
  (out-fun two-way-sout lisp-stream-sout string start end))
ram's avatar
ram committed

(macrolet ((in-fun (name fun &rest args)
	     `(defun ,name (stream ,@args)
		(force-output (two-way-stream-output-stream stream))
ram's avatar
ram committed
		(,fun (two-way-stream-input-stream stream) ,@args))))
  (in-fun two-way-in read-char eof-errorp eof-value)
  (in-fun two-way-bin read-byte eof-errorp eof-value)
  (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-errorp))

(defun two-way-misc (stream operation &optional arg1 arg2)
  (let* ((in (two-way-stream-input-stream stream))
dtc's avatar
dtc committed
	 (in-method (lisp-stream-misc in))
ram's avatar
ram committed
	 (out (two-way-stream-output-stream stream))
dtc's avatar
dtc committed
	 (out-method (lisp-stream-misc out)))
ram's avatar
ram committed
    (case operation
dtc's avatar
dtc committed
      (:listen (or (/= (the fixnum (lisp-stream-in-index in)) in-buffer-length)
ram's avatar
ram committed
		   (funcall in-method in :listen)))
      ((:finish-output :force-output :clear-output)
       (funcall out-method out operation arg1 arg2))
      ((:clear-input :unread)
       (funcall in-method in operation arg1 arg2))
      (:element-type
       (let ((in-type (funcall in-method in :element-type))
	     (out-type (funcall out-method out :element-type)))
	 (if (equal in-type out-type)
	     in-type `(and ,in-type ,out-type))))
      (:close 
       (set-closed-flame stream))
      (t
       (or (funcall in-method in operation arg1 arg2)
	   (funcall out-method out operation arg1 arg2))))))

;;;; Concatenated Streams:

(defstruct (concatenated-stream
dtc's avatar
dtc committed
	    (:include lisp-stream
ram's avatar
ram committed
		      (in #'concatenated-in)
		      (bin #'concatenated-bin)
		      (misc #'concatenated-misc))
	    (:print-function %print-concatenated-stream)
	    (:constructor
	     make-concatenated-stream (&rest streams &aux (current streams))))
  ;; The car of this is the stream we are reading from now.
  current
  ;; This is a list of all the streams.  We need to remember them so that
  ;; we can close them.
  (streams nil :type list :read-only t))
ram's avatar
ram committed

(defun %print-concatenated-stream (s stream d)
  (declare (ignore d))
  (format stream "#<Concatenated Stream, Streams = ~S>"
	  (concatenated-stream-streams s)))

(setf (documentation 'make-concatenated-stream 'function)
  "Returns a stream which takes its input from each of the Streams in turn,
   going on to the next at EOF.")

(macrolet ((in-fun (name fun)
	     `(defun ,name (stream eof-errorp eof-value)
		(do ((current (concatenated-stream-current stream) (cdr current)))
		    ((null current)
		     (eof-or-lose stream eof-errorp eof-value))
		  (let* ((stream (car current))
			 (result (,fun stream nil nil)))
		    (when result (return result)))
		  (setf (concatenated-stream-current stream) current)))))
  (in-fun concatenated-in read-char)
  (in-fun concatenated-bin read-byte))

(defun concatenated-misc (stream operation &optional arg1 arg2)
  (let ((left (concatenated-stream-current stream)))
    (when left
      (let* ((current (car left))
dtc's avatar
dtc committed
	     (misc (lisp-stream-misc current)))
	(case operation
	  (:listen
	   (loop
	     (let ((stuff (funcall misc current :listen)))
	       (cond ((eq stuff :eof)
		      ;; Advance current, and try again.
		      (pop (concatenated-stream-current stream))
		      (setf current
			    (car (concatenated-stream-current stream)))
		      (unless current
			;; No further streams.  EOF.
			(return :eof))
dtc's avatar
dtc committed
		      (setf misc (lisp-stream-misc current)))
		     (stuff
		      ;; Stuff's available.
		      (return t))
		     (t
		      ;; Nothing available yet.
		      (return nil))))))
	  (:close
	   (set-closed-flame stream))
	  (t
	   (funcall misc current operation arg1 arg2)))))))
ram's avatar
ram committed

;;;; Echo Streams:

(defstruct (echo-stream
	    (:include two-way-stream
		      (in #'echo-in)
		      (bin #'echo-bin)
		      (misc #'echo-misc)
		      (n-bin #'ill-bin))
	    (:print-function %print-echo-stream)
	    (:constructor make-echo-stream (input-stream output-stream)))
  unread-stuff)
ram's avatar
ram committed


(macrolet ((in-fun (name fun out-slot &rest args)
	     `(defun ,name (stream ,@args)
		(or (pop (echo-stream-unread-stuff stream))
		    (let* ((in (echo-stream-input-stream stream))
			   (out (echo-stream-output-stream stream))
			   (result (,fun in ,@args)))
		      (funcall (,out-slot out) out result)
		      result)))))
dtc's avatar
dtc committed
  (in-fun echo-in read-char lisp-stream-out eof-errorp eof-value)
  (in-fun echo-bin read-byte lisp-stream-bout eof-errorp eof-value))
ram's avatar
ram committed

(defun echo-misc (stream operation &optional arg1 arg2)
  (let* ((in (two-way-stream-input-stream stream))
dtc's avatar
dtc committed
	 (in-method (lisp-stream-misc in))
ram's avatar
ram committed
	 (out (two-way-stream-output-stream stream))
dtc's avatar
dtc committed
	 (out-method (lisp-stream-misc out)))
ram's avatar
ram committed
    (case operation
      (:listen (or (not (null (echo-stream-unread-stuff stream)))
dtc's avatar
dtc committed
		   (/= (the fixnum (lisp-stream-in-index in)) in-buffer-length)
ram's avatar
ram committed
		   (funcall in-method in :listen)))
      (:unread (push arg1 (echo-stream-unread-stuff stream)))
ram's avatar
ram committed
      (:element-type
       (let ((in-type (funcall in-method in :element-type))
	     (out-type (funcall out-method out :element-type)))
	 (if (equal in-type out-type)
	     in-type `(and ,in-type ,out-type))))
      (:close
       (set-closed-flame stream))
      (t
       (or (funcall in-method in operation arg1 arg2)
	   (funcall out-method out operation arg1 arg2))))))

(defun %print-echo-stream (s stream d)
  (declare (ignore d))
  (format stream "#<Echo Stream, Input = ~S, Output = ~S>"
	  (two-way-stream-input-stream s)
	  (two-way-stream-output-stream s)))

(setf (documentation 'make-echo-stream 'function)
  "Returns a bidirectional stream which gets its input from Input-Stream and
   sends its output to Output-Stream.  In addition, all input is echoed to
   the output stream")

;;;; String Input Streams:

(defstruct (string-input-stream
dtc's avatar
dtc committed
	     (:include lisp-stream
		       (in #'string-inch)
		       (bin #'string-binch)
		       (n-bin #'string-stream-read-n-bytes)
		       (misc #'string-in-misc))
	     (:print-function %print-string-input-stream)
					;(:constructor nil)
	     (:constructor internal-make-string-input-stream
			   (string current end)))
ram's avatar
ram committed
  (string nil :type simple-string)
  (current nil :type index)
  (end nil :type index))
ram's avatar
ram committed

(defun %print-string-input-stream (s stream d)
  (declare (ignore s d))
  (write-string "#<String-Input Stream>" stream))
  
(defun string-inch (stream eof-errorp eof-value)
  (let ((string (string-input-stream-string stream))
	(index (string-input-stream-current stream)))
    (declare (simple-string string) (fixnum index))
    (cond ((= index (the index (string-input-stream-end stream)))
ram's avatar
ram committed
	   (eof-or-lose stream eof-errorp eof-value))
	  (t
	   (setf (string-input-stream-current stream) (1+ index))
	   (aref string index)))))

(defun string-binch (stream eof-errorp eof-value)
  (let ((string (string-input-stream-string stream))
	(index (string-input-stream-current stream)))
    (declare (simple-string string)
	     (type index index))
    (cond ((= index (the index (string-input-stream-end stream)))
	   (eof-or-lose stream eof-errorp eof-value))
	  (t
	   (setf (string-input-stream-current stream) (1+ index))
	   (char-code (aref string index))))))

(defun string-stream-read-n-bytes (stream buffer start requested eof-errorp)
  (declare (type string-input-stream stream)
	   (type index start requested))
  (let* ((string (string-input-stream-string stream))
	 (index (string-input-stream-current stream))
	 (available (- (string-input-stream-end stream) index))
	 (copy (min available requested)))
    (declare (simple-string string)
	     (type index index available copy))
    (when (plusp copy)
      (setf (string-input-stream-current stream)
	    (truly-the index (+ index copy)))
      (system:without-gcing
       (system-area-copy (vector-sap string)
			 (* index vm:byte-bits)
			 (if (typep buffer 'system-area-pointer)
			     buffer
			     (vector-sap buffer))
			 (* start vm:byte-bits)
			 (* copy vm:byte-bits))))
    (if (and (> requested copy) eof-errorp)
	(error 'end-of-file :stream stream)
	copy)))