b09bacf785706ef4b43ff35a916e7d01ea536f46
[sbcl.git] / src / code / stream.lisp
1 ;;;; os-independent stream functions
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 (deftype string-stream ()
15   '(or string-input-stream string-output-stream
16        fill-pointer-output-stream))
17
18 ;;;; standard streams
19
20 ;;; The initialization of these streams is performed by
21 ;;; STREAM-COLD-INIT-OR-RESET.
22 (defvar *terminal-io* () #!+sb-doc "Terminal I/O stream.")
23 (defvar *standard-input* () #!+sb-doc "Default input stream.")
24 (defvar *standard-output* () #!+sb-doc "Default output stream.")
25 (defvar *error-output* () #!+sb-doc "Error output stream.")
26 (defvar *query-io* () #!+sb-doc "Query I/O stream.")
27 (defvar *trace-output* () #!+sb-doc "Trace output stream.")
28 (defvar *debug-io* () #!+sb-doc "Interactive debugging stream.")
29
30 (defun ill-in (stream &rest ignore)
31   (declare (ignore ignore))
32   (error 'simple-type-error
33          :datum stream
34          :expected-type '(satisfies input-stream-p)
35          :format-control "~S is not a character input stream."
36          :format-arguments (list stream)))
37 (defun ill-out (stream &rest ignore)
38   (declare (ignore ignore))
39   (error 'simple-type-error
40          :datum stream
41          :expected-type '(satisfies output-stream-p)
42          :format-control "~S is not a character output stream."
43          :format-arguments (list stream)))
44 (defun ill-bin (stream &rest ignore)
45   (declare (ignore ignore))
46   (error 'simple-type-error
47          :datum stream
48          :expected-type '(satisfies input-stream-p)
49          :format-control "~S is not a binary input stream."
50          :format-arguments (list stream)))
51 (defun ill-bout (stream &rest ignore)
52   (declare (ignore ignore))
53   (error 'simple-type-error
54          :datum stream
55          :expected-type '(satisfies output-stream-p)
56          :format-control "~S is not a binary output stream."
57          :format-arguments (list stream)))
58 (defun closed-flame (stream &rest ignore)
59   (declare (ignore ignore))
60   (error "~S is closed." stream))
61 (defun do-nothing (&rest ignore)
62   (declare (ignore ignore)))
63 \f
64 ;;; HOW THE STREAM STRUCTURE IS USED:
65 ;;;
66 ;;; Many of the slots of the stream structure contain functions
67 ;;; which are called to perform some operation on the stream. Closed
68 ;;; streams have #'CLOSED-FLAME in all of their function slots. If
69 ;;; one side of an I/O or echo stream is closed, the whole stream is
70 ;;; considered closed. The functions in the operation slots take
71 ;;; arguments as follows:
72 ;;;
73 ;;; In:                 Stream, Eof-Errorp, Eof-Value
74 ;;; Bin:                Stream, Eof-Errorp, Eof-Value
75 ;;; N-Bin:              Stream, Buffer, Start, Numbytes, Eof-Errorp
76 ;;; Out:                Stream, Character
77 ;;; Bout:               Stream, Integer
78 ;;; Sout:               Stream, String, Start, End
79 ;;; Misc:               Stream, Operation, &Optional Arg1, Arg2
80 ;;;
81 ;;; In order to save space, some of the less common stream operations
82 ;;; are handled by just one function, the MISC method. This function
83 ;;; is passed a keyword which indicates the operation to perform.
84 ;;; The following keywords are used:
85 ;;;  :listen            - Return the following values:
86 ;;;                          t if any input waiting.
87 ;;;                          :eof if at eof.
88 ;;;                          nil if no input is available and not at eof.
89 ;;;  :unread            - Unread the character Arg.
90 ;;;  :close             - Do any stream specific stuff to close the stream.
91 ;;;                       The methods are set to closed-flame by the close
92 ;;;                       function, so that need not be done by this
93 ;;;                       function.
94 ;;;  :clear-input       - Clear any unread input
95 ;;;  :finish-output,
96 ;;;  :force-output      - Cause output to happen
97 ;;;  :clear-output      - Clear any undone output
98 ;;;  :element-type      - Return the type of element the stream deals with.
99 ;;;  :line-length       - Return the length of a line of output.
100 ;;;  :charpos           - Return current output position on the line.
101 ;;;  :file-length       - Return the file length of a file stream.
102 ;;;  :file-position     - Return or change the current position of a
103 ;;;                       file stream.
104 ;;;  :file-name         - Return the name of an associated file.
105 ;;;  :interactive-p     - Is this an interactive device?
106 ;;;
107 ;;; In order to do almost anything useful, it is necessary to
108 ;;; define a new type of structure that includes stream, so that the
109 ;;; stream can have some state information.
110 ;;;
111 ;;; THE STREAM IN-BUFFER:
112 ;;;
113 ;;; The IN-BUFFER in the stream holds characters or bytes that
114 ;;; are ready to be read by some input function. If there is any
115 ;;; stuff in the IN-BUFFER, then the reading function can use it
116 ;;; without calling any stream method. Any stream may put stuff in
117 ;;; the IN-BUFFER, and may also assume that any input in the IN-BUFFER
118 ;;; has been consumed before any in-method is called. If a text
119 ;;; stream has in IN-BUFFER, then the first character should not be
120 ;;; used to buffer normal input so that it is free for unreading into.
121 ;;;
122 ;;; The IN-BUFFER slot is a vector +IN-BUFFER-LENGTH+ long. The
123 ;;; IN-INDEX is the index in the IN-BUFFER of the first available
124 ;;; object. The available objects are thus between IN-INDEX and the
125 ;;; length of the IN-BUFFER.
126 ;;;
127 ;;; When this buffer is only accessed by the normal stream
128 ;;; functions, the number of function calls is halved, thus
129 ;;; potentially doubling the speed of simple operations. If the
130 ;;; FAST-READ-CHAR and FAST-READ-BYTE macros are used, nearly all
131 ;;; function call overhead is removed, vastly speeding up these
132 ;;; important operations.
133 ;;;
134 ;;; If a stream does not have an IN-BUFFER, then the IN-BUFFER slot
135 ;;; must be nil, and the IN-INDEX must be +IN-BUFFER-LENGTH+. These are
136 ;;; the default values for the slots.
137 \f
138 ;;; stream manipulation functions
139
140 (defun input-stream-p (stream)
141   (declare (type stream stream))
142
143   #!+high-security
144   (when (synonym-stream-p stream)
145     (setf stream
146           (symbol-value (synonym-stream-symbol stream))))
147
148   (and (lisp-stream-p stream)
149        (not (eq (lisp-stream-in stream) #'closed-flame))
150        ;;; KLUDGE: It's probably not good to have EQ tests on function
151        ;;; values like this. What if someone's redefined the function?
152        ;;; Is there a better way? (Perhaps just VALID-FOR-INPUT and
153        ;;; VALID-FOR-OUTPUT flags? -- WHN 19990902
154        (or (not (eq (lisp-stream-in stream) #'ill-in))
155            (not (eq (lisp-stream-bin stream) #'ill-bin)))))
156
157 (defun output-stream-p (stream)
158   (declare (type stream stream))
159
160   #!+high-security
161   (when (synonym-stream-p stream)
162     (setf stream (symbol-value
163                   (synonym-stream-symbol stream))))
164
165   (and (lisp-stream-p stream)
166        (not (eq (lisp-stream-in stream) #'closed-flame))
167        (or (not (eq (lisp-stream-out stream) #'ill-out))
168            (not (eq (lisp-stream-bout stream) #'ill-bout)))))
169
170 (defun open-stream-p (stream)
171   (declare (type stream stream))
172   (not (eq (lisp-stream-in stream) #'closed-flame)))
173
174 (defun stream-element-type (stream)
175   (declare (type stream stream))
176   (funcall (lisp-stream-misc stream) stream :element-type))
177
178 (defun interactive-stream-p (stream)
179   (declare (type stream stream))
180   (funcall (lisp-stream-misc stream) stream :interactive-p))
181
182 (defun open-stream-p (stream)
183   (declare (type stream stream))
184   (not (eq (lisp-stream-in stream) #'closed-flame)))
185
186 (defun close (stream &key abort)
187   (declare (type stream stream))
188   (when (open-stream-p stream)
189     (funcall (lisp-stream-misc stream) stream :close abort))
190   t)
191
192 (defun set-closed-flame (stream)
193   (setf (lisp-stream-in stream) #'closed-flame)
194   (setf (lisp-stream-bin stream) #'closed-flame)
195   (setf (lisp-stream-n-bin stream) #'closed-flame)
196   (setf (lisp-stream-in stream) #'closed-flame)
197   (setf (lisp-stream-out stream) #'closed-flame)
198   (setf (lisp-stream-bout stream) #'closed-flame)
199   (setf (lisp-stream-sout stream) #'closed-flame)
200   (setf (lisp-stream-misc stream) #'closed-flame))
201 \f
202 ;;;; file position and file length
203
204 ;;; Call the misc method with the :file-position operation.
205 (defun file-position (stream &optional position)
206   (declare (type stream stream))
207   (declare (type (or index (member nil :start :end)) position))
208   (cond
209    (position
210     (setf (lisp-stream-in-index stream) +in-buffer-length+)
211     (funcall (lisp-stream-misc stream) stream :file-position position))
212    (t
213     (let ((res (funcall (lisp-stream-misc stream) stream :file-position nil)))
214       (when res
215         (- res (- +in-buffer-length+ (lisp-stream-in-index stream))))))))
216
217 ;;; declaration test functions
218
219 #!+high-security
220 (defun stream-associated-with-file (stream)
221   #!+sb-doc
222   "Tests if the stream is associated with a file"
223   (or (typep stream 'file-stream)
224       (and (synonym-stream-p stream)
225            (typep (symbol-value (synonym-stream-symbol stream))
226                   'file-stream))))
227
228 ;;; Like File-Position, only use :file-length.
229 (defun file-length (stream)
230   (declare (type (or file-stream synonym-stream) stream))
231
232   #!+high-security
233   (check-type-var stream '(satisfies stream-associated-with-file)
234                   "a stream associated with a file")
235
236   (funcall (lisp-stream-misc stream) stream :file-length))
237 \f
238 ;;;; input functions
239
240 (defun read-line (&optional (stream *standard-input*) (eof-error-p t) eof-value
241                             recursive-p)
242   (declare (ignore recursive-p))
243   (let ((stream (in-synonym-of stream)))
244     (if (lisp-stream-p stream)
245         (prepare-for-fast-read-char stream
246           (let ((res (make-string 80))
247                 (len 80)
248                 (index 0))
249             (loop
250              (let ((ch (fast-read-char nil nil)))
251                (cond (ch
252                       (when (char= ch #\newline)
253                         (done-with-fast-read-char)
254                         (return (values (shrink-vector res index) nil)))
255                       (when (= index len)
256                         (setq len (* len 2))
257                         (let ((new (make-string len)))
258                           (replace new res)
259                           (setq res new)))
260                       (setf (schar res index) ch)
261                       (incf index))
262                      ((zerop index)
263                       (done-with-fast-read-char)
264                       (return (values (eof-or-lose stream
265                                                    eof-error-p
266                                                    eof-value)
267                                       t)))
268                      ;; Since FAST-READ-CHAR already hit the eof char, we
269                      ;; shouldn't do another READ-CHAR.
270                      (t
271                       (done-with-fast-read-char)
272                       (return (values (shrink-vector res index) t))))))))
273         ;; must be Gray streams FUNDAMENTAL-STREAM
274         (multiple-value-bind (string eof) (stream-read-line stream)
275           (if (and eof (zerop (length string)))
276               (values (eof-or-lose stream eof-error-p eof-value) t)
277               (values string eof))))))
278
279 ;;; We proclaim them INLINE here, then proclaim them MAYBE-INLINE at EOF,
280 ;;; so, except in this file, they are not inline by default, but they can be.
281 #!-sb-fluid (declaim (inline read-char unread-char read-byte listen))
282
283 (defun read-char (&optional (stream *standard-input*)
284                             (eof-error-p t)
285                             eof-value
286                             recursive-p)
287   (declare (ignore recursive-p))
288   (let ((stream (in-synonym-of stream)))
289     (if (lisp-stream-p stream)
290         (prepare-for-fast-read-char stream
291           (prog1
292               (fast-read-char eof-error-p eof-value)
293             (done-with-fast-read-char)))
294         ;; must be Gray streams FUNDAMENTAL-STREAM
295         (let ((char (stream-read-char stream)))
296           (if (eq char :eof)
297               (eof-or-lose stream eof-error-p eof-value)
298               char)))))
299
300 (defun unread-char (character &optional (stream *standard-input*))
301   (let ((stream (in-synonym-of stream)))
302     (if (lisp-stream-p stream)
303         (let ((index (1- (lisp-stream-in-index stream)))
304               (buffer (lisp-stream-in-buffer stream)))
305           (declare (fixnum index))
306           (when (minusp index) (error "Nothing to unread."))
307           (cond (buffer
308                  (setf (aref buffer index) (char-code character))
309                  (setf (lisp-stream-in-index stream) index))
310                 (t
311                  (funcall (lisp-stream-misc stream) stream
312                           :unread character))))
313         ;; must be Gray streams FUNDAMENTAL-STREAM
314         (stream-unread-char stream character)))
315   nil)
316
317 (defun peek-char (&optional (peek-type nil)
318                             (stream *standard-input*)
319                             (eof-error-p t)
320                             eof-value recursive-p)
321   (declare (ignore recursive-p))
322   (let ((stream (in-synonym-of stream)))
323     (if (lisp-stream-p stream)
324         (let ((char (read-char stream eof-error-p eof-value)))
325           (cond ((eq char eof-value) char)
326                 ((characterp peek-type)
327                  (do ((char char (read-char stream eof-error-p eof-value)))
328                      ((or (eq char eof-value) (char= char peek-type))
329                       (unless (eq char eof-value)
330                         (unread-char char stream))
331                       char)))
332                 ((eq peek-type t)
333                  (do ((char char (read-char stream eof-error-p eof-value)))
334                      ((or (eq char eof-value) (not (whitespace-char-p char)))
335                       (unless (eq char eof-value)
336                         (unread-char char stream))
337                       char)))
338                 (t
339                  (unread-char char stream)
340                  char)))
341         ;; must be Gray streams FUNDAMENTAL-STREAM
342         (cond ((characterp peek-type)
343                (do ((char (stream-read-char stream) (stream-read-char stream)))
344                    ((or (eq char :eof) (char= char peek-type))
345                     (cond ((eq char :eof)
346                            (eof-or-lose stream eof-error-p eof-value))
347                           (t
348                            (stream-unread-char stream char)
349                            char)))))
350               ((eq peek-type t)
351                (do ((char (stream-read-char stream) (stream-read-char stream)))
352                    ((or (eq char :eof) (not (whitespace-char-p char)))
353                     (cond ((eq char :eof)
354                            (eof-or-lose stream eof-error-p eof-value))
355                           (t
356                            (stream-unread-char stream char)
357                            char)))))
358               (t
359                (let ((char (stream-peek-char stream)))
360                  (if (eq char :eof)
361                      (eof-or-lose stream eof-error-p eof-value)
362                      char)))))))
363
364 (defun listen (&optional (stream *standard-input*))
365   (let ((stream (in-synonym-of stream)))
366     (if (lisp-stream-p stream)
367         (or (/= (the fixnum (lisp-stream-in-index stream)) +in-buffer-length+)
368             ;; Test for T explicitly since misc methods return :EOF sometimes.
369             (eq (funcall (lisp-stream-misc stream) stream :listen) t))
370         ;; Fall through to Gray streams FUNDAMENTAL-STREAM case.
371         (stream-listen stream))))
372
373 (defun read-char-no-hang (&optional (stream *standard-input*)
374                                     (eof-error-p t)
375                                     eof-value
376                                     recursive-p)
377   (declare (ignore recursive-p))
378   (let ((stream (in-synonym-of stream)))
379     (if (lisp-stream-p stream)
380         (if (funcall (lisp-stream-misc stream) stream :listen)
381             ;; On T or :EOF get READ-CHAR to do the work.
382             (read-char stream eof-error-p eof-value)
383             nil)
384         ;; must be Gray streams FUNDAMENTAL-STREAM
385         (let ((char (stream-read-char-no-hang stream)))
386           (if (eq char :eof)
387               (eof-or-lose stream eof-error-p eof-value)
388               char)))))
389
390 (defun clear-input (&optional (stream *standard-input*))
391   (let ((stream (in-synonym-of stream)))
392     (cond ((lisp-stream-p stream)
393            (setf (lisp-stream-in-index stream) +in-buffer-length+)
394            (funcall (lisp-stream-misc stream) stream :clear-input))
395           (t
396            (stream-clear-input stream))))
397   nil)
398 \f
399 (declaim (maybe-inline read-byte))
400 (defun read-byte (stream &optional (eof-error-p t) eof-value)
401   (let ((stream (in-synonym-of stream)))
402     (if (lisp-stream-p stream)
403         (prepare-for-fast-read-byte stream
404           (prog1
405               (fast-read-byte eof-error-p eof-value t)
406             (done-with-fast-read-byte)))
407         ;; must be Gray streams FUNDAMENTAL-STREAM
408         (let ((char (stream-read-byte stream)))
409           (if (eq char :eof)
410               (eof-or-lose stream eof-error-p eof-value)
411               char)))))
412
413 ;;; Read NUMBYTES bytes into BUFFER beginning at START, and return the
414 ;;; number of bytes read.
415 ;;;
416 ;;; Note: CMU CL's version of this had a special interpretation of
417 ;;; EOF-ERROR-P which SBCL does not have. (In the EOF-ERROR-P=NIL
418 ;;; case, CMU CL's version would return as soon as any data became
419 ;;; available.) This could be useful behavior for things like pipes in
420 ;;; some cases, but it wasn't being used in SBCL, so it was dropped.
421 ;;; If we ever need it, it could be added later as a new variant N-BIN
422 ;;; method (perhaps N-BIN-ASAP?) or something.
423 (defun read-n-bytes (stream buffer start numbytes &optional (eof-error-p t))
424   (declare (type lisp-stream stream)
425            (type index numbytes start)
426            (type (or (simple-array * (*)) system-area-pointer) buffer))
427   (let* ((stream (in-synonym-of stream lisp-stream))
428          (in-buffer (lisp-stream-in-buffer stream))
429          (index (lisp-stream-in-index stream))
430          (num-buffered (- +in-buffer-length+ index)))
431     (declare (fixnum index num-buffered))
432     (cond
433      ((not in-buffer)
434       (funcall (lisp-stream-n-bin stream)
435                stream
436                buffer
437                start
438                numbytes
439                eof-error-p))
440      ((<= numbytes num-buffered)
441       (%primitive sb!c:byte-blt
442                   in-buffer
443                   index
444                   buffer
445                   start
446                   (+ start numbytes))
447       (setf (lisp-stream-in-index stream) (+ index numbytes))
448       numbytes)
449      (t
450       (let ((end (+ start num-buffered)))
451         (%primitive sb!c:byte-blt in-buffer index buffer start end)
452         (setf (lisp-stream-in-index stream) +in-buffer-length+)
453         (+ (funcall (lisp-stream-n-bin stream)
454                     stream
455                     buffer
456                     end
457                     (- numbytes num-buffered)
458                     eof-error-p)
459            num-buffered))))))
460
461 ;;; the amount of space we leave at the start of the in-buffer for
462 ;;; unreading
463 ;;;
464 ;;; (It's 4 instead of 1 to allow word-aligned copies.)
465 (defconstant +in-buffer-extra+ 4) ; FIXME: should be symbolic constant
466
467 ;;; This function is called by the FAST-READ-CHAR expansion to refill
468 ;;; the IN-BUFFER for text streams. There is definitely an IN-BUFFER,
469 ;;; and hence must be an N-BIN method.
470 (defun fast-read-char-refill (stream eof-error-p eof-value)
471   (let* ((ibuf (lisp-stream-in-buffer stream))
472          (count (funcall (lisp-stream-n-bin stream)
473                          stream
474                          ibuf
475                          +in-buffer-extra+
476                          (- +in-buffer-length+ +in-buffer-extra+)
477                          nil))
478          (start (- +in-buffer-length+ count)))
479     (declare (type index start count))
480     (cond ((zerop count)
481            (setf (lisp-stream-in-index stream) +in-buffer-length+)
482            (funcall (lisp-stream-in stream) stream eof-error-p eof-value))
483           (t
484            (when (/= start +in-buffer-extra+)
485              (bit-bash-copy ibuf (+ (* +in-buffer-extra+ sb!vm:byte-bits)
486                                     (* sb!vm:vector-data-offset
487                                        sb!vm:word-bits))
488                             ibuf (+ (the index (* start sb!vm:byte-bits))
489                                     (* sb!vm:vector-data-offset
490                                        sb!vm:word-bits))
491                             (* count sb!vm:byte-bits)))
492            (setf (lisp-stream-in-index stream) (1+ start))
493            (code-char (aref ibuf start))))))
494
495 ;;; This is similar to FAST-READ-CHAR-REFILL, but we don't have to
496 ;;; leave room for unreading.
497 (defun fast-read-byte-refill (stream eof-error-p eof-value)
498   (let* ((ibuf (lisp-stream-in-buffer stream))
499          (count (funcall (lisp-stream-n-bin stream) stream
500                          ibuf 0 +in-buffer-length+
501                          nil))
502          (start (- +in-buffer-length+ count)))
503     (declare (type index start count))
504     (cond ((zerop count)
505            (setf (lisp-stream-in-index stream) +in-buffer-length+)
506            (funcall (lisp-stream-bin stream) stream eof-error-p eof-value))
507           (t
508            (unless (zerop start)
509              (bit-bash-copy ibuf (* sb!vm:vector-data-offset sb!vm:word-bits)
510                             ibuf (+ (the index (* start sb!vm:byte-bits))
511                                     (* sb!vm:vector-data-offset
512                                        sb!vm:word-bits))
513                             (* count sb!vm:byte-bits)))
514            (setf (lisp-stream-in-index stream) (1+ start))
515            (aref ibuf start)))))
516 \f
517 ;;; output functions
518
519 (defun write-char (character &optional (stream *standard-output*))
520   (with-out-stream stream (lisp-stream-out character)
521                    (stream-write-char character))
522   character)
523
524 (defun terpri (&optional (stream *standard-output*))
525   (with-out-stream stream (lisp-stream-out #\newline) (stream-terpri))
526   nil)
527
528 (defun fresh-line (&optional (stream *standard-output*))
529   (let ((stream (out-synonym-of stream)))
530     (if (lisp-stream-p stream)
531         (when (/= (or (charpos stream) 1) 0)
532           (funcall (lisp-stream-out stream) stream #\newline)
533           t)
534         ;; must be Gray streams FUNDAMENTAL-STREAM
535         (stream-fresh-line stream))))
536
537 (defun write-string (string &optional (stream *standard-output*)
538                             &key (start 0) (end (length (the vector string))))
539
540   ;; FIXME: These SETFs don't look right to me. Looking at the
541   ;; definition of "bounding indices" in the glossary of the ANSI
542   ;; spec, and extrapolating from the behavior of other operations
543   ;; when their operands are the wrong type, it seems that it would be
544   ;; more correct to essentially
545   ;;    (AVER (<= 0 START END (LENGTH STRING)))
546   ;; instead of modifying the incorrect values.
547   #!+high-security
548   (setf end (min end (length (the vector string))))
549   #!+high-security
550   (setf start (max start 0))
551
552   ;; FIXME: And I'd just signal a non-continuable error..
553   #!+high-security
554   (when (< end start)
555       (cerror "Continue with switched start and end ~S <-> ~S"
556               "Write-string: start (~S) and end (~S) exchanged."
557               start end string)
558       (rotatef start end))
559
560   (write-string* string stream start end))
561
562 (defun write-string* (string &optional (stream *standard-output*)
563                              (start 0) (end (length (the vector string))))
564   (declare (fixnum start end))
565   (let ((stream (out-synonym-of stream)))
566     (cond ((lisp-stream-p stream)
567            (if (array-header-p string)
568                (with-array-data ((data string) (offset-start start)
569                                  (offset-end end))
570                  (funcall (lisp-stream-sout stream)
571                           stream data offset-start offset-end))
572                (funcall (lisp-stream-sout stream) stream string start end))
573            string)
574           (t ; must be Gray streams FUNDAMENTAL-STREAM
575            (stream-write-string stream string start end)))))
576
577 (defun write-line (string &optional (stream *standard-output*)
578                           &key (start 0) (end (length string)))
579   (write-line* string stream start end))
580
581 (defun write-line* (string &optional (stream *standard-output*)
582                            (start 0) (end (length string)))
583   (declare (fixnum start end))
584   (let ((stream (out-synonym-of stream)))
585     (cond ((lisp-stream-p stream)
586            (if (array-header-p string)
587                (with-array-data ((data string) (offset-start start)
588                                  (offset-end end))
589                  (with-out-stream stream (lisp-stream-sout data offset-start
590                                                            offset-end)))
591                (with-out-stream stream (lisp-stream-sout string start end)))
592            (funcall (lisp-stream-out stream) stream #\newline))
593           (t ; must be Gray streams FUNDAMENTAL-STREAM
594            (stream-write-string stream string start end)
595            (stream-write-char stream #\Newline)))
596     string))
597
598 (defun charpos (&optional (stream *standard-output*))
599   (with-out-stream stream (lisp-stream-misc :charpos) (stream-line-column)))
600
601 (defun line-length (&optional (stream *standard-output*))
602   (with-out-stream stream (lisp-stream-misc :line-length)
603                    (stream-line-length)))
604
605 (defun finish-output (&optional (stream *standard-output*))
606   (with-out-stream stream (lisp-stream-misc :finish-output)
607                    (stream-finish-output))
608   nil)
609
610 (defun force-output (&optional (stream *standard-output*))
611   (with-out-stream stream (lisp-stream-misc :force-output)
612                    (stream-force-output))
613   nil)
614
615 (defun clear-output (&optional (stream *standard-output*))
616   (with-out-stream stream (lisp-stream-misc :clear-output)
617                    (stream-force-output))
618   nil)
619
620 (defun write-byte (integer stream)
621   (with-out-stream stream (lisp-stream-bout integer)
622                    (stream-write-byte integer))
623   integer)
624 \f
625 ;;; This is called from LISP-STREAM routines that encapsulate CLOS
626 ;;; streams to handle the misc routines and dispatch to the
627 ;;; appropriate Gray stream functions.
628 (defun stream-misc-dispatch (stream operation &optional arg1 arg2)
629   (declare (type fundamental-stream stream)
630            (ignore arg2))
631   (case operation
632     (:listen
633      ;; Return T if input available, :EOF for end-of-file, otherwise NIL.
634      (let ((char (stream-read-char-no-hang stream)))
635        (when (characterp char)
636          (stream-unread-char stream char))
637        char))
638     (:unread
639      (stream-unread-char stream arg1))
640     (:close
641      (close stream))
642     (:clear-input
643      (stream-clear-input stream))
644     (:force-output
645      (stream-force-output stream))
646     (:finish-output
647      (stream-finish-output stream))
648     (:element-type
649      (stream-element-type stream))
650     (:interactive-p
651      (interactive-stream-p stream))
652     (:line-length
653      (stream-line-length stream))
654     (:charpos
655      (stream-line-column stream))
656     (:file-length
657      (file-length stream))
658     (:file-position
659      (file-position stream arg1))))
660 \f
661 ;;;; broadcast streams
662
663 (defstruct (broadcast-stream (:include lisp-stream
664                                        (out #'broadcast-out)
665                                        (bout #'broadcast-bout)
666                                        (sout #'broadcast-sout)
667                                        (misc #'broadcast-misc))
668                              (:constructor #!-high-security-support
669                                            make-broadcast-stream
670                                            #!+high-security-support
671                                            %make-broadcast-stream (&rest
672                                                                    streams))
673                              (:copier nil))
674   ;; a list of all the streams we broadcast to
675   (streams () :type list :read-only t))
676
677 #!+high-security-support
678 (defun make-broadcast-stream (&rest streams)
679   (dolist (stream streams)
680     (unless (or (and (synonym-stream-p stream)
681                      (output-stream-p (symbol-value
682                                        (synonym-stream-symbol stream))))
683                 (output-stream-p stream))
684       (error 'type-error
685              :datum stream
686              :expected-type '(satisfies output-stream-p))))
687   (apply #'%make-broadcast-stream streams))
688
689 (macrolet ((out-fun (fun method stream-method &rest args)
690              `(defun ,fun (stream ,@args)
691                 (dolist (stream (broadcast-stream-streams stream))
692                   (if (lisp-stream-p stream)
693                       (funcall (,method stream) stream ,@args)
694                       (,stream-method stream ,@args))))))
695   (out-fun broadcast-out lisp-stream-out stream-write-char char)
696   (out-fun broadcast-bout lisp-stream-bout stream-write-byte byte)
697   (out-fun broadcast-sout lisp-stream-sout stream-write-string
698            string start end))
699
700 (defun broadcast-misc (stream operation &optional arg1 arg2)
701   (let ((streams (broadcast-stream-streams stream)))
702     (case operation
703       (:charpos
704        (dolist (stream streams)
705          (let ((charpos (charpos stream)))
706            (if charpos (return charpos)))))
707       (:line-length
708        (let ((min nil))
709          (dolist (stream streams min)
710            (let ((res (line-length stream)))
711              (when res (setq min (if min (min res min) res)))))))
712       (:element-type
713        (let (res)
714          (dolist (stream streams (if (> (length res) 1) `(and ,@res) res))
715            (pushnew (stream-element-type stream) res :test #'equal))))
716       (:close)
717       (t
718        (let ((res nil))
719          (dolist (stream streams res)
720            (setq res
721                  (if (lisp-stream-p stream)
722                      (funcall (lisp-stream-misc stream) stream operation
723                               arg1 arg2)
724                      (stream-misc-dispatch stream operation arg1 arg2)))))))))
725 \f
726 ;;;; synonym streams
727
728 (defstruct (synonym-stream (:include lisp-stream
729                                      (in #'synonym-in)
730                                      (bin #'synonym-bin)
731                                      (n-bin #'synonym-n-bin)
732                                      (out #'synonym-out)
733                                      (bout #'synonym-bout)
734                                      (sout #'synonym-sout)
735                                      (misc #'synonym-misc))
736                            (:constructor make-synonym-stream (symbol))
737                            (:copier nil))
738   ;; This is the symbol, the value of which is the stream we are synonym to.
739   (symbol nil :type symbol :read-only t))
740 (def!method print-object ((x synonym-stream) stream)
741   (print-unreadable-object (x stream :type t :identity t)
742     (format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
743
744 ;;; The output simple output methods just call the corresponding method
745 ;;; in the synonymed stream.
746 (macrolet ((out-fun (name slot stream-method &rest args)
747              `(defun ,name (stream ,@args)
748                 (declare (optimize (safety 1)))
749                 (let ((syn (symbol-value (synonym-stream-symbol stream))))
750                   (if (lisp-stream-p syn)
751                       (funcall (,slot syn) syn ,@args)
752                       (,stream-method syn ,@args))))))
753   (out-fun synonym-out lisp-stream-out stream-write-char ch)
754   (out-fun synonym-bout lisp-stream-bout stream-write-byte n)
755   (out-fun synonym-sout lisp-stream-sout stream-write-string string start end))
756
757 ;;; For the input methods, we just call the corresponding function on the
758 ;;; synonymed stream. These functions deal with getting input out of
759 ;;; the In-Buffer if there is any.
760 (macrolet ((in-fun (name fun &rest args)
761              `(defun ,name (stream ,@args)
762                 (declare (optimize (safety 1)))
763                 (,fun (symbol-value (synonym-stream-symbol stream))
764                       ,@args))))
765   (in-fun synonym-in read-char eof-error-p eof-value)
766   (in-fun synonym-bin read-byte eof-error-p eof-value)
767   (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
768
769 ;;; We have to special-case the operations which could look at stuff in
770 ;;; the in-buffer.
771 (defun synonym-misc (stream operation &optional arg1 arg2)
772   (declare (optimize (safety 1)))
773   (let ((syn (symbol-value (synonym-stream-symbol stream))))
774     (if (lisp-stream-p syn)
775         (case operation
776           (:listen (or (/= (the fixnum (lisp-stream-in-index syn))
777                            +in-buffer-length+)
778                        (funcall (lisp-stream-misc syn) syn :listen)))
779           (t
780            (funcall (lisp-stream-misc syn) syn operation arg1 arg2)))
781         (stream-misc-dispatch syn operation arg1 arg2))))
782 \f
783 ;;;; two-way streams
784
785 (defstruct (two-way-stream
786             (:include lisp-stream
787                       (in #'two-way-in)
788                       (bin #'two-way-bin)
789                       (n-bin #'two-way-n-bin)
790                       (out #'two-way-out)
791                       (bout #'two-way-bout)
792                       (sout #'two-way-sout)
793                       (misc #'two-way-misc))
794             (:constructor #!-high-security-support
795                           make-two-way-stream
796                           #!+high-security-support
797                           %make-two-way-stream (input-stream output-stream))
798             (:copier nil))
799   (input-stream (required-argument) :type stream :read-only t)
800   (output-stream (required-argument) :type stream :read-only t))
801 (def!method print-object ((x two-way-stream) stream)
802   (print-unreadable-object (x stream :type t :identity t)
803     (format stream
804             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
805             (two-way-stream-input-stream x)
806             (two-way-stream-output-stream x))))
807
808 #!-high-security-support
809 (setf (fdocumentation 'make-two-way-stream 'function)
810   "Returns a bidirectional stream which gets its input from Input-Stream and
811    sends its output to Output-Stream.")
812 #!+high-security-support
813 (defun make-two-way-stream (input-stream output-stream)
814   #!+sb-doc
815   "Returns a bidirectional stream which gets its input from Input-Stream and
816    sends its output to Output-Stream."
817   ;; FIXME: This idiom of the-real-stream-of-a-possibly-synonym-stream
818   ;; should be encapsulated in a function, and used here and most of
819   ;; the other places that SYNONYM-STREAM-P appears.
820   (unless (or (and (synonym-stream-p output-stream)
821                    (output-stream-p (symbol-value
822                                      (synonym-stream-symbol output-stream))))
823               (output-stream-p output-stream))
824     (error 'type-error
825            :datum output-stream
826            :expected-type '(satisfies output-stream-p)))
827   (unless (or (and (synonym-stream-p input-stream)
828                    (input-stream-p (symbol-value
829                                     (synonym-stream-symbol input-stream))))
830               (input-stream-p input-stream))
831     (error 'type-error
832            :datum input-stream
833            :expected-type '(satisfies input-stream-p)))
834   (funcall #'%make-two-way-stream input-stream output-stream))
835
836 (macrolet ((out-fun (name slot stream-method &rest args)
837              `(defun ,name (stream ,@args)
838                 (let ((syn (two-way-stream-output-stream stream)))
839                   (if (lisp-stream-p syn)
840                       (funcall (,slot syn) syn ,@args)
841                       (,stream-method syn ,@args))))))
842   (out-fun two-way-out lisp-stream-out stream-write-char ch)
843   (out-fun two-way-bout lisp-stream-bout stream-write-byte n)
844   (out-fun two-way-sout lisp-stream-sout stream-write-string string start end))
845
846 (macrolet ((in-fun (name fun &rest args)
847              `(defun ,name (stream ,@args)
848                 (force-output (two-way-stream-output-stream stream))
849                 (,fun (two-way-stream-input-stream stream) ,@args))))
850   (in-fun two-way-in read-char eof-error-p eof-value)
851   (in-fun two-way-bin read-byte eof-error-p eof-value)
852   (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
853
854 (defun two-way-misc (stream operation &optional arg1 arg2)
855   (let* ((in (two-way-stream-input-stream stream))
856          (out (two-way-stream-output-stream stream))
857          (in-lisp-stream-p (lisp-stream-p in))
858          (out-lisp-stream-p (lisp-stream-p out)))
859     (case operation
860       (:listen
861        (if in-lisp-stream-p
862            (or (/= (the fixnum (lisp-stream-in-index in)) +in-buffer-length+)
863                (funcall (lisp-stream-misc in) in :listen))
864            (stream-listen in)))
865       ((:finish-output :force-output :clear-output)
866        (if out-lisp-stream-p
867            (funcall (lisp-stream-misc out) out operation arg1 arg2)
868            (stream-misc-dispatch out operation arg1 arg2)))
869       ((:clear-input :unread)
870        (if in-lisp-stream-p
871            (funcall (lisp-stream-misc in) in operation arg1 arg2)
872            (stream-misc-dispatch in operation arg1 arg2)))
873       (:element-type
874        (let ((in-type (stream-element-type in))
875              (out-type (stream-element-type out)))
876          (if (equal in-type out-type)
877              in-type `(and ,in-type ,out-type))))
878       (:close
879        (set-closed-flame stream))
880       (t
881        (or (if in-lisp-stream-p
882                (funcall (lisp-stream-misc in) in operation arg1 arg2)
883                (stream-misc-dispatch in operation arg1 arg2))
884            (if out-lisp-stream-p
885                (funcall (lisp-stream-misc out) out operation arg1 arg2)
886                (stream-misc-dispatch out operation arg1 arg2)))))))
887 \f
888 ;;;; concatenated streams
889
890 (defstruct (concatenated-stream
891             (:include lisp-stream
892                       (in #'concatenated-in)
893                       (bin #'concatenated-bin)
894                       (n-bin #'concatenated-n-bin)
895                       (misc #'concatenated-misc))
896             (:constructor
897              #!-high-security-support make-concatenated-stream
898              #!+high-security-support %make-concatenated-stream
899                  (&rest streams &aux (current streams)))
900             (:copier nil))
901   ;; The car of this is the substream we are reading from now.
902   current
903   ;; This is a list of all the substreams there ever were. We need to
904   ;; remember them so that we can close them.
905   ;;
906   ;; FIXME: ANSI says this is supposed to be the list of streams that
907   ;; we still have to read from. So either this needs to become a
908   ;; private member %STREAM (with CONCATENATED-STREAM-STREAMS a wrapper
909   ;; around it which discards closed files from the head of the list)
910   ;; or we need to update it as we run out of files.
911   (streams nil :type list :read-only t))
912 (def!method print-object ((x concatenated-stream) stream)
913   (print-unreadable-object (x stream :type t :identity t)
914     (format stream
915             ":STREAMS ~S"
916             (concatenated-stream-streams x))))
917
918 #!-high-security-support
919 (setf (fdocumentation 'make-concatenated-stream 'function)
920   "Returns a stream which takes its input from each of the Streams in turn,
921    going on to the next at EOF.")
922
923 #!+high-security-support
924 (defun make-concatenated-stream (&rest streams)
925   #!+sb-doc
926   "Returns a stream which takes its input from each of the Streams in turn,
927    going on to the next at EOF."
928   (dolist (stream streams)
929     (unless (or (and (synonym-stream-p stream)
930                      (input-stream-p (symbol-value
931                                       (synonym-stream-symbol stream))))
932                 (input-stream-p stream))
933       (error 'type-error
934              :datum stream
935              :expected-type '(satisfies input-stream-p))))
936   (apply #'%make-concatenated-stream streams))
937
938 (macrolet ((in-fun (name fun)
939              `(defun ,name (stream eof-error-p eof-value)
940                 (do ((current (concatenated-stream-current stream)
941                               (cdr current)))
942                     ((null current)
943                      (eof-or-lose stream eof-error-p eof-value))
944                   (let* ((stream (car current))
945                          (result (,fun stream nil nil)))
946                     (when result (return result)))
947                   (setf (concatenated-stream-current stream) current)))))
948   (in-fun concatenated-in read-char)
949   (in-fun concatenated-bin read-byte))
950
951 (defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
952   (do ((current (concatenated-stream-current stream) (cdr current))
953        (current-start start)
954        (remaining-bytes numbytes))
955       ((null current)
956        (if eof-errorp
957            (error 'end-of-file :stream stream)
958            (- numbytes remaining-bytes)))
959     (let* ((stream (car current))
960            (bytes-read (read-n-bytes stream buffer current-start
961                                      remaining-bytes nil)))
962       (incf current-start bytes-read)
963       (decf remaining-bytes bytes-read)
964       (when (zerop remaining-bytes) (return numbytes)))
965     (setf (concatenated-stream-current stream) (cdr current))))
966
967 (defun concatenated-misc (stream operation &optional arg1 arg2)
968   (let ((left (concatenated-stream-current stream)))
969     (when left
970       (let* ((current (car left)))
971         (case operation
972           (:listen
973            (loop
974              (let ((stuff (if (lisp-stream-p current)
975                               (funcall (lisp-stream-misc current) current
976                                        :listen)
977                               (stream-misc-dispatch current :listen))))
978                (cond ((eq stuff :eof)
979                       ;; Advance CURRENT, and try again.
980                       (pop (concatenated-stream-current stream))
981                       (setf current
982                             (car (concatenated-stream-current stream)))
983                       (unless current
984                         ;; No further streams. EOF.
985                         (return :eof)))
986                      (stuff
987                       ;; Stuff's available.
988                       (return t))
989                      (t
990                       ;; Nothing is available yet.
991                       (return nil))))))
992           (:close
993            (set-closed-flame stream))
994           (t
995            (if (lisp-stream-p current)
996                (funcall (lisp-stream-misc current) current operation arg1 arg2)
997                (stream-misc-dispatch current operation arg1 arg2))))))))
998 \f
999 ;;;; echo streams
1000
1001 (defstruct (echo-stream
1002             (:include two-way-stream
1003                       (in #'echo-in)
1004                       (bin #'echo-bin)
1005                       (misc #'echo-misc)
1006                       (n-bin #'ill-bin))
1007             (:constructor make-echo-stream (input-stream output-stream))
1008             (:copier nil))
1009   unread-stuff)
1010 (def!method print-object ((x echo-stream) stream)
1011   (print-unreadable-object (x stream :type t :identity t)
1012     (format stream
1013             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
1014             (two-way-stream-input-stream x)
1015             (two-way-stream-output-stream x))))
1016
1017 (macrolet ((in-fun (name fun out-slot stream-method &rest args)
1018              `(defun ,name (stream ,@args)
1019                 (or (pop (echo-stream-unread-stuff stream))
1020                     (let* ((in (echo-stream-input-stream stream))
1021                            (out (echo-stream-output-stream stream))
1022                            (result (,fun in ,@args)))
1023                       (if (lisp-stream-p out)
1024                           (funcall (,out-slot out) out result)
1025                           (,stream-method out result))
1026                       result)))))
1027   (in-fun echo-in read-char lisp-stream-out stream-write-char
1028           eof-error-p eof-value)
1029   (in-fun echo-bin read-byte lisp-stream-bout stream-write-byte
1030           eof-error-p eof-value))
1031
1032 (defun echo-misc (stream operation &optional arg1 arg2)
1033   (let* ((in (two-way-stream-input-stream stream))
1034          (out (two-way-stream-output-stream stream)))
1035     (case operation
1036       (:listen
1037        (or (not (null (echo-stream-unread-stuff stream)))
1038            (if (lisp-stream-p in)
1039                (or (/= (the fixnum (lisp-stream-in-index in))
1040                        +in-buffer-length+)
1041                    (funcall (lisp-stream-misc in) in :listen))
1042                (stream-misc-dispatch in :listen))))
1043       (:unread (push arg1 (echo-stream-unread-stuff stream)))
1044       (:element-type
1045        (let ((in-type (stream-element-type in))
1046              (out-type (stream-element-type out)))
1047          (if (equal in-type out-type)
1048              in-type `(and ,in-type ,out-type))))
1049       (:close
1050        (set-closed-flame stream))
1051       (t
1052        (or (if (lisp-stream-p in)
1053                (funcall (lisp-stream-misc in) in operation arg1 arg2)
1054                (stream-misc-dispatch in operation arg1 arg2))
1055            (if (lisp-stream-p out)
1056                (funcall (lisp-stream-misc out) out operation arg1 arg2)
1057                (stream-misc-dispatch out operation arg1 arg2)))))))
1058
1059 #!+sb-doc
1060 (setf (fdocumentation 'make-echo-stream 'function)
1061   "Returns a bidirectional stream which gets its input from Input-Stream and
1062    sends its output to Output-Stream. In addition, all input is echoed to
1063    the output stream")
1064 \f
1065 ;;;; string input streams
1066
1067 (defstruct (string-input-stream
1068              (:include lisp-stream
1069                        (in #'string-inch)
1070                        (bin #'string-binch)
1071                        (n-bin #'string-stream-read-n-bytes)
1072                        (misc #'string-in-misc))
1073              (:constructor internal-make-string-input-stream
1074                            (string current end))
1075              (:copier nil))
1076   (string nil :type simple-string)
1077   (current nil :type index)
1078   (end nil :type index))
1079
1080 (defun string-inch (stream eof-error-p eof-value)
1081   (let ((string (string-input-stream-string stream))
1082         (index (string-input-stream-current stream)))
1083     (declare (simple-string string) (fixnum index))
1084     (cond ((= index (the index (string-input-stream-end stream)))
1085            (eof-or-lose stream eof-error-p eof-value))
1086           (t
1087            (setf (string-input-stream-current stream) (1+ index))
1088            (aref string index)))))
1089
1090 (defun string-binch (stream eof-error-p eof-value)
1091   (let ((string (string-input-stream-string stream))
1092         (index (string-input-stream-current stream)))
1093     (declare (simple-string string)
1094              (type index index))
1095     (cond ((= index (the index (string-input-stream-end stream)))
1096            (eof-or-lose stream eof-error-p eof-value))
1097           (t
1098            (setf (string-input-stream-current stream) (1+ index))
1099            (char-code (aref string index))))))
1100
1101 (defun string-stream-read-n-bytes (stream buffer start requested eof-error-p)
1102   (declare (type string-input-stream stream)
1103            (type index start requested))
1104   (let* ((string (string-input-stream-string stream))
1105          (index (string-input-stream-current stream))
1106          (available (- (string-input-stream-end stream) index))
1107          (copy (min available requested)))
1108     (declare (simple-string string)
1109              (type index index available copy))
1110     (when (plusp copy)
1111       (setf (string-input-stream-current stream)
1112             (truly-the index (+ index copy)))
1113       (sb!sys:without-gcing
1114        (system-area-copy (vector-sap string)
1115                          (* index sb!vm:byte-bits)
1116                          (if (typep buffer 'system-area-pointer)
1117                              buffer
1118                              (vector-sap buffer))
1119                          (* start sb!vm:byte-bits)
1120                          (* copy sb!vm:byte-bits))))
1121     (if (and (> requested copy) eof-error-p)
1122         (error 'end-of-file :stream stream)
1123         copy)))
1124
1125 (defun string-in-misc (stream operation &optional arg1 arg2)
1126   (declare (ignore arg2))
1127   (case operation
1128     (:file-position
1129      (if arg1
1130          (setf (string-input-stream-current stream) arg1)
1131          (string-input-stream-current stream)))
1132     (:file-length (length (string-input-stream-string stream)))
1133     (:unread (decf (string-input-stream-current stream)))
1134     (:listen (or (/= (the fixnum (string-input-stream-current stream))
1135                      (the fixnum (string-input-stream-end stream)))
1136                  :eof))
1137     (:element-type 'base-char)))
1138
1139 (defun make-string-input-stream (string &optional
1140                                         (start 0) (end (length string)))
1141   #!+sb-doc
1142   "Returns an input stream which will supply the characters of String between
1143   Start and End in order."
1144   (declare (type string string)
1145            (type index start)
1146            (type (or index null) end))
1147
1148   #!+high-security
1149   (when (> end (length string))
1150     (cerror "Continue with end changed from ~S to ~S"
1151             "Write-string: end (~S) is larger then the length of the string (~S)"
1152             end (1- (length string))))
1153
1154   (internal-make-string-input-stream (coerce string 'simple-string)
1155                                      start end))
1156 \f
1157 ;;;; string output streams
1158
1159 (defstruct (string-output-stream
1160             (:include lisp-stream
1161                       (out #'string-ouch)
1162                       (sout #'string-sout)
1163                       (misc #'string-out-misc))
1164             (:constructor make-string-output-stream ())
1165             (:copier nil))
1166   ;; The string we throw stuff in.
1167   (string (make-string 40) :type simple-string)
1168   ;; Index of the next location to use.
1169   (index 0 :type fixnum))
1170
1171 #!+sb-doc
1172 (setf (fdocumentation 'make-string-output-stream 'function)
1173   "Returns an Output stream which will accumulate all output given it for
1174    the benefit of the function Get-Output-Stream-String.")
1175
1176 (defun string-ouch (stream character)
1177   (let ((current (string-output-stream-index stream))
1178         (workspace (string-output-stream-string stream)))
1179     (declare (simple-string workspace) (fixnum current))
1180     (if (= current (the fixnum (length workspace)))
1181         (let ((new-workspace (make-string (* current 2))))
1182           (replace new-workspace workspace)
1183           (setf (aref new-workspace current) character)
1184           (setf (string-output-stream-string stream) new-workspace))
1185         (setf (aref workspace current) character))
1186     (setf (string-output-stream-index stream) (1+ current))))
1187
1188 (defun string-sout (stream string start end)
1189   (declare (simple-string string) (fixnum start end))
1190   (let* ((current (string-output-stream-index stream))
1191          (length (- end start))
1192          (dst-end (+ length current))
1193          (workspace (string-output-stream-string stream)))
1194     (declare (simple-string workspace)
1195              (fixnum current length dst-end))
1196     (if (> dst-end (the fixnum (length workspace)))
1197         (let ((new-workspace (make-string (+ (* current 2) length))))
1198           (replace new-workspace workspace :end2 current)
1199           (replace new-workspace string
1200                    :start1 current :end1 dst-end
1201                    :start2 start :end2 end)
1202           (setf (string-output-stream-string stream) new-workspace))
1203         (replace workspace string
1204                  :start1 current :end1 dst-end
1205                  :start2 start :end2 end))
1206     (setf (string-output-stream-index stream) dst-end)))
1207
1208 (defun string-out-misc (stream operation &optional arg1 arg2)
1209   (declare (ignore arg2))
1210   (case operation
1211     (:file-position
1212      (if (null arg1)
1213          (string-output-stream-index stream)))
1214     (:charpos
1215      (do ((index (1- (the fixnum (string-output-stream-index stream)))
1216                  (1- index))
1217           (count 0 (1+ count))
1218           (string (string-output-stream-string stream)))
1219          ((< index 0) count)
1220        (declare (simple-string string)
1221                 (fixnum index count))
1222        (if (char= (schar string index) #\newline)
1223            (return count))))
1224     (:element-type 'base-char)))
1225
1226 ;;; Return a string of all the characters sent to a stream made by
1227 ;;; MAKE-STRING-OUTPUT-STREAM since the last call to this function.
1228 (defun get-output-stream-string (stream)
1229   (declare (type string-output-stream stream))
1230   (let* ((length (string-output-stream-index stream))
1231          (result (make-string length)))
1232     (replace result (string-output-stream-string stream))
1233     (setf (string-output-stream-index stream) 0)
1234     result))
1235
1236 ;;; Dump the characters buffer up in IN-STREAM to OUT-STREAM as
1237 ;;; GET-OUTPUT-STREAM-STRING would return them.
1238 (defun dump-output-stream-string (in-stream out-stream)
1239   (write-string* (string-output-stream-string in-stream) out-stream
1240                  0 (string-output-stream-index in-stream))
1241   (setf (string-output-stream-index in-stream) 0))
1242 \f
1243 ;;;; fill-pointer streams
1244
1245 ;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
1246 ;;; the CLM, but they are required for the implementation of
1247 ;;; WITH-OUTPUT-TO-STRING.
1248
1249 (defstruct (fill-pointer-output-stream
1250             (:include lisp-stream
1251                       (out #'fill-pointer-ouch)
1252                       (sout #'fill-pointer-sout)
1253                       (misc #'fill-pointer-misc))
1254             (:constructor make-fill-pointer-output-stream (string))
1255             (:copier nil))
1256   ;; the string we throw stuff in
1257   string)
1258
1259 (defun fill-pointer-ouch (stream character)
1260   (let* ((buffer (fill-pointer-output-stream-string stream))
1261          (current (fill-pointer buffer))
1262          (current+1 (1+ current)))
1263     (declare (fixnum current))
1264     (with-array-data ((workspace buffer) (start) (end))
1265       (declare (simple-string workspace))
1266       (let ((offset-current (+ start current)))
1267         (declare (fixnum offset-current))
1268         (if (= offset-current end)
1269             (let* ((new-length (* current 2))
1270                    (new-workspace (make-string new-length)))
1271               (declare (simple-string new-workspace))
1272               (%primitive sb!c:byte-blt
1273                           workspace
1274                           start
1275                           new-workspace
1276                           0
1277                           current)
1278               (setf workspace new-workspace)
1279               (setf offset-current current)
1280               (set-array-header buffer workspace new-length
1281                                 current+1 0 new-length nil))
1282             (setf (fill-pointer buffer) current+1))
1283         (setf (schar workspace offset-current) character)))
1284     current+1))
1285
1286 (defun fill-pointer-sout (stream string start end)
1287   (declare (simple-string string) (fixnum start end))
1288   (let* ((buffer (fill-pointer-output-stream-string stream))
1289          (current (fill-pointer buffer))
1290          (string-len (- end start))
1291          (dst-end (+ string-len current)))
1292     (declare (fixnum current dst-end string-len))
1293     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1294       (declare (simple-string workspace))
1295       (let ((offset-dst-end (+ dst-start dst-end))
1296             (offset-current (+ dst-start current)))
1297         (declare (fixnum offset-dst-end offset-current))
1298         (if (> offset-dst-end dst-length)
1299             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1300                    (new-workspace (make-string new-length)))
1301               (declare (simple-string new-workspace))
1302               (%primitive sb!c:byte-blt
1303                           workspace
1304                           dst-start
1305                           new-workspace
1306                           0
1307                           current)
1308               (setf workspace new-workspace)
1309               (setf offset-current current)
1310               (setf offset-dst-end dst-end)
1311               (set-array-header buffer
1312                                 workspace
1313                                 new-length
1314                                 dst-end
1315                                 0
1316                                 new-length
1317                                 nil))
1318             (setf (fill-pointer buffer) dst-end))
1319         (%primitive sb!c:byte-blt
1320                     string
1321                     start
1322                     workspace
1323                     offset-current
1324                     offset-dst-end)))
1325     dst-end))
1326
1327 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1328   (declare (ignore arg1 arg2))
1329   (case operation
1330     (:charpos
1331      (let* ((buffer (fill-pointer-output-stream-string stream))
1332             (current (fill-pointer buffer)))
1333        (with-array-data ((string buffer) (start) (end current))
1334          (declare (simple-string string) (ignore start))
1335          (let ((found (position #\newline string :test #'char=
1336                                 :end end :from-end t)))
1337            (if found
1338                (- end (the fixnum found))
1339                current)))))
1340      (:element-type 'base-char)))
1341 \f
1342 ;;;; indenting streams
1343
1344 (defstruct (indenting-stream (:include lisp-stream
1345                                        (out #'indenting-out)
1346                                        (sout #'indenting-sout)
1347                                        (misc #'indenting-misc))
1348                              (:constructor make-indenting-stream (stream))
1349                              (:copier nil))
1350   ;; the stream we're based on
1351   stream
1352   ;; how much we indent on each line
1353   (indentation 0))
1354
1355 #!+sb-doc
1356 (setf (fdocumentation 'make-indenting-stream 'function)
1357  "Returns an output stream which indents its output by some amount.")
1358
1359 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1360 ;;; output on the given STREAM based on the specified SUB-STREAM.
1361 (defmacro indenting-indent (stream sub-stream)
1362   ;; KLUDGE: bare magic number 60
1363   `(do ((i 0 (+ i 60))
1364         (indentation (indenting-stream-indentation ,stream)))
1365        ((>= i indentation))
1366      (write-string*
1367       "                                                     "
1368       ,sub-stream 0 (min 60 (- indentation i)))))
1369
1370 ;;; INDENTING-OUT writes a character to an indenting stream.
1371 (defun indenting-out (stream char)
1372   (let ((sub-stream (indenting-stream-stream stream)))
1373     (write-char char sub-stream)
1374     (if (char= char #\newline)
1375         (indenting-indent stream sub-stream))))
1376
1377 ;;; INDENTING-SOUT writes a string to an indenting stream.
1378 (defun indenting-sout (stream string start end)
1379   (declare (simple-string string) (fixnum start end))
1380   (do ((i start)
1381        (sub-stream (indenting-stream-stream stream)))
1382       ((= i end))
1383     (let ((newline (position #\newline string :start i :end end)))
1384       (cond (newline
1385              (write-string* string sub-stream i (1+ newline))
1386              (indenting-indent stream sub-stream)
1387              (setq i (+ newline 1)))
1388             (t
1389              (write-string* string sub-stream i end)
1390              (setq i end))))))
1391
1392 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1393 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1394 ;;; the base stream minus the stream's indentation.
1395 (defun indenting-misc (stream operation &optional arg1 arg2)
1396   (let ((sub-stream (indenting-stream-stream stream)))
1397     (if (lisp-stream-p sub-stream)
1398         (let ((method (lisp-stream-misc sub-stream)))
1399           (case operation
1400             (:line-length
1401              (let ((line-length (funcall method sub-stream operation)))
1402                (if line-length
1403                    (- line-length (indenting-stream-indentation stream)))))
1404             (:charpos
1405              (let ((charpos (funcall method sub-stream operation)))
1406                (if charpos
1407                    (- charpos (indenting-stream-indentation stream)))))
1408             (t
1409              (funcall method sub-stream operation arg1 arg2))))
1410         ;; must be Gray streams FUNDAMENTAL-STREAM
1411         (case operation
1412           (:line-length
1413            (let ((line-length (stream-line-length sub-stream)))
1414              (if line-length
1415                  (- line-length (indenting-stream-indentation stream)))))
1416           (:charpos
1417            (let ((charpos (stream-line-column sub-stream)))
1418              (if charpos
1419                  (- charpos (indenting-stream-indentation stream)))))
1420           (t
1421            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1422
1423 (declaim (maybe-inline read-char unread-char read-byte listen))
1424 \f
1425 ;;;; case frobbing streams, used by FORMAT ~(...~)
1426
1427 (defstruct (case-frob-stream
1428             (:include lisp-stream
1429                       (:misc #'case-frob-misc))
1430             (:constructor %make-case-frob-stream (target out sout))
1431             (:copier nil))
1432   (target (required-argument) :type stream))
1433
1434 (defun make-case-frob-stream (target kind)
1435   #!+sb-doc
1436   "Returns a stream that sends all output to the stream TARGET, but modifies
1437    the case of letters, depending on KIND, which should be one of:
1438      :upcase - convert to upper case.
1439      :downcase - convert to lower case.
1440      :capitalize - convert the first letter of words to upper case and the
1441         rest of the word to lower case.
1442      :capitalize-first - convert the first letter of the first word to upper
1443         case and everything else to lower case."
1444   (declare (type stream target)
1445            (type (member :upcase :downcase :capitalize :capitalize-first)
1446                  kind)
1447            (values stream))
1448   (if (case-frob-stream-p target)
1449       ;; If we are going to be writing to a stream that already does
1450       ;; case frobbing, why bother frobbing the case just so it can
1451       ;; frob it again?
1452       target
1453       (multiple-value-bind (out sout)
1454           (ecase kind
1455             (:upcase
1456              (values #'case-frob-upcase-out
1457                      #'case-frob-upcase-sout))
1458             (:downcase
1459              (values #'case-frob-downcase-out
1460                      #'case-frob-downcase-sout))
1461             (:capitalize
1462              (values #'case-frob-capitalize-out
1463                      #'case-frob-capitalize-sout))
1464             (:capitalize-first
1465              (values #'case-frob-capitalize-first-out
1466                      #'case-frob-capitalize-first-sout)))
1467         (%make-case-frob-stream target out sout))))
1468
1469 (defun case-frob-misc (stream op &optional arg1 arg2)
1470   (declare (type case-frob-stream stream))
1471   (case op
1472     (:close)
1473     (t
1474      (let ((target (case-frob-stream-target stream)))
1475        (if (lisp-stream-p target)
1476            (funcall (lisp-stream-misc target) target op arg1 arg2)
1477            (stream-misc-dispatch target op arg1 arg2))))))
1478
1479 (defun case-frob-upcase-out (stream char)
1480   (declare (type case-frob-stream stream)
1481            (type base-char char))
1482   (let ((target (case-frob-stream-target stream))
1483         (char (char-upcase char)))
1484     (if (lisp-stream-p target)
1485         (funcall (lisp-stream-out target) target char)
1486         (stream-write-char target char))))
1487
1488 (defun case-frob-upcase-sout (stream str start end)
1489   (declare (type case-frob-stream stream)
1490            (type simple-base-string str)
1491            (type index start)
1492            (type (or index null) end))
1493   (let* ((target (case-frob-stream-target stream))
1494          (len (length str))
1495          (end (or end len))
1496          (string (if (and (zerop start) (= len end))
1497                      (string-upcase str)
1498                      (nstring-upcase (subseq str start end))))
1499          (string-len (- end start)))
1500     (if (lisp-stream-p target)
1501         (funcall (lisp-stream-sout target) target string 0 string-len)
1502         (stream-write-string target string 0 string-len))))
1503
1504 (defun case-frob-downcase-out (stream char)
1505   (declare (type case-frob-stream stream)
1506            (type base-char char))
1507   (let ((target (case-frob-stream-target stream))
1508         (char (char-downcase char)))
1509     (if (lisp-stream-p target)
1510         (funcall (lisp-stream-out target) target char)
1511         (stream-write-char target char))))
1512
1513 (defun case-frob-downcase-sout (stream str start end)
1514   (declare (type case-frob-stream stream)
1515            (type simple-base-string str)
1516            (type index start)
1517            (type (or index null) end))
1518   (let* ((target (case-frob-stream-target stream))
1519          (len (length str))
1520          (end (or end len))
1521          (string (if (and (zerop start) (= len end))
1522                      (string-downcase str)
1523                      (nstring-downcase (subseq str start end))))
1524          (string-len (- end start)))
1525     (if (lisp-stream-p target)
1526         (funcall (lisp-stream-sout target) target string 0 string-len)
1527         (stream-write-string target string 0 string-len))))
1528
1529 (defun case-frob-capitalize-out (stream char)
1530   (declare (type case-frob-stream stream)
1531            (type base-char char))
1532   (let ((target (case-frob-stream-target stream)))
1533     (cond ((alphanumericp char)
1534            (let ((char (char-upcase char)))
1535              (if (lisp-stream-p target)
1536                  (funcall (lisp-stream-out target) target char)
1537                  (stream-write-char target char)))
1538            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1539            (setf (case-frob-stream-sout stream)
1540                  #'case-frob-capitalize-aux-sout))
1541           (t
1542            (if (lisp-stream-p target)
1543                (funcall (lisp-stream-out target) target char)
1544                (stream-write-char target char))))))
1545
1546 (defun case-frob-capitalize-sout (stream str start end)
1547   (declare (type case-frob-stream stream)
1548            (type simple-base-string str)
1549            (type index start)
1550            (type (or index null) end))
1551   (let* ((target (case-frob-stream-target stream))
1552          (str (subseq str start end))
1553          (len (length str))
1554          (inside-word nil))
1555     (dotimes (i len)
1556       (let ((char (schar str i)))
1557         (cond ((not (alphanumericp char))
1558                (setf inside-word nil))
1559               (inside-word
1560                (setf (schar str i) (char-downcase char)))
1561               (t
1562                (setf inside-word t)
1563                (setf (schar str i) (char-upcase char))))))
1564     (when inside-word
1565       (setf (case-frob-stream-out stream)
1566             #'case-frob-capitalize-aux-out)
1567       (setf (case-frob-stream-sout stream)
1568             #'case-frob-capitalize-aux-sout))
1569     (if (lisp-stream-p target)
1570         (funcall (lisp-stream-sout target) target str 0 len)
1571         (stream-write-string target str 0 len))))
1572
1573 (defun case-frob-capitalize-aux-out (stream char)
1574   (declare (type case-frob-stream stream)
1575            (type base-char char))
1576   (let ((target (case-frob-stream-target stream)))
1577     (cond ((alphanumericp char)
1578            (let ((char (char-downcase char)))
1579              (if (lisp-stream-p target)
1580                  (funcall (lisp-stream-out target) target char)
1581                  (stream-write-char target char))))
1582           (t
1583            (if (lisp-stream-p target)
1584                (funcall (lisp-stream-out target) target char)
1585                (stream-write-char target char))
1586            (setf (case-frob-stream-out stream)
1587                  #'case-frob-capitalize-out)
1588            (setf (case-frob-stream-sout stream)
1589                  #'case-frob-capitalize-sout)))))
1590
1591 (defun case-frob-capitalize-aux-sout (stream str start end)
1592   (declare (type case-frob-stream stream)
1593            (type simple-base-string str)
1594            (type index start)
1595            (type (or index null) end))
1596   (let* ((target (case-frob-stream-target stream))
1597          (str (subseq str start end))
1598          (len (length str))
1599          (inside-word t))
1600     (dotimes (i len)
1601       (let ((char (schar str i)))
1602         (cond ((not (alphanumericp char))
1603                (setf inside-word nil))
1604               (inside-word
1605                (setf (schar str i) (char-downcase char)))
1606               (t
1607                (setf inside-word t)
1608                (setf (schar str i) (char-upcase char))))))
1609     (unless inside-word
1610       (setf (case-frob-stream-out stream)
1611             #'case-frob-capitalize-out)
1612       (setf (case-frob-stream-sout stream)
1613             #'case-frob-capitalize-sout))
1614     (if (lisp-stream-p target)
1615         (funcall (lisp-stream-sout target) target str 0 len)
1616         (stream-write-string target str 0 len))))
1617
1618 (defun case-frob-capitalize-first-out (stream char)
1619   (declare (type case-frob-stream stream)
1620            (type base-char char))
1621   (let ((target (case-frob-stream-target stream)))
1622     (cond ((alphanumericp char)
1623            (let ((char (char-upcase char)))
1624              (if (lisp-stream-p target)
1625                  (funcall (lisp-stream-out target) target char)
1626                  (stream-write-char target char)))
1627            (setf (case-frob-stream-out stream)
1628                  #'case-frob-downcase-out)
1629            (setf (case-frob-stream-sout stream)
1630                  #'case-frob-downcase-sout))
1631           (t
1632            (if (lisp-stream-p target)
1633                (funcall (lisp-stream-out target) target char)
1634                (stream-write-char target char))))))
1635
1636 (defun case-frob-capitalize-first-sout (stream str start end)
1637   (declare (type case-frob-stream stream)
1638            (type simple-base-string str)
1639            (type index start)
1640            (type (or index null) end))
1641   (let* ((target (case-frob-stream-target stream))
1642          (str (subseq str start end))
1643          (len (length str)))
1644     (dotimes (i len)
1645       (let ((char (schar str i)))
1646         (when (alphanumericp char)
1647           (setf (schar str i) (char-upcase char))
1648           (do ((i (1+ i) (1+ i)))
1649               ((= i len))
1650             (setf (schar str i) (char-downcase (schar str i))))
1651           (setf (case-frob-stream-out stream)
1652                 #'case-frob-downcase-out)
1653           (setf (case-frob-stream-sout stream)
1654                 #'case-frob-downcase-sout)
1655           (return))))
1656     (if (lisp-stream-p target)
1657         (funcall (lisp-stream-sout target) target str 0 len)
1658         (stream-write-string target str 0 len))))
1659 \f
1660 ;;;; stream commands
1661
1662 (defstruct (stream-command (:constructor make-stream-command
1663                                          (name &optional args))
1664                            (:copier nil))
1665   (name nil :type symbol)
1666   (args nil :type list))
1667 (def!method print-object ((obj stream-command) str)
1668   (print-unreadable-object (obj str :type t :identity t)
1669     (prin1 (stream-command-name obj) str)))
1670
1671 ;;; Take a stream and wait for text or a command to appear on it. If
1672 ;;; text appears before a command, return NIL, otherwise return a
1673 ;;; command.
1674 ;;;
1675 ;;; We can't simply call the stream's misc method because NIL is an
1676 ;;; ambiguous return value: does it mean text arrived, or does it mean
1677 ;;; the stream's misc method had no :GET-COMMAND implementation? We
1678 ;;; can't return NIL until there is text input. We don't need to loop
1679 ;;; because any stream implementing :GET-COMMAND would wait until it
1680 ;;; had some input. If the LISTEN fails, then we have some stream we
1681 ;;; must wait on.
1682 (defun get-stream-command (stream)
1683   (let ((cmdp (funcall (lisp-stream-misc stream) stream :get-command)))
1684     (cond (cmdp)
1685           ((listen stream)
1686            nil)
1687           (t
1688            ;; This waits for input and returns NIL when it arrives.
1689            (unread-char (read-char stream) stream)))))
1690 \f
1691 (defun read-sequence (seq stream &key (start 0) (end nil))
1692   #!+sb-doc
1693   "Destructively modify SEQ by reading elements from STREAM.
1694   That part of SEQ bounded by START and END is destructively modified by
1695   copying successive elements into it from STREAM. If the end of file
1696   for STREAM is reached before copying all elements of the subsequence,
1697   then the extra elements near the end of sequence are not updated, and
1698   the index of the next element is returned."
1699   (declare (type sequence seq)
1700            (type stream stream)
1701            (type index start)
1702            (type sequence-end end)
1703            (values index))
1704   (let ((end (or end (length seq))))
1705     (declare (type index end))
1706     (etypecase seq
1707       (list
1708        (let ((read-function
1709               (if (subtypep (stream-element-type stream) 'character)
1710                   #'read-char
1711                   #'read-byte)))
1712          (do ((rem (nthcdr start seq) (rest rem))
1713               (i start (1+ i)))
1714              ((or (endp rem) (>= i end)) i)
1715            (declare (type list rem)
1716                     (type index i))
1717            (let ((el (funcall read-function stream nil :eof)))
1718              (when (eq el :eof)
1719                (return i))
1720              (setf (first rem) el)))))
1721       (vector
1722        (with-array-data ((data seq) (offset-start start) (offset-end end))
1723          (typecase data
1724            ((or (simple-array (unsigned-byte 8) (*))
1725                 (simple-array (signed-byte 8) (*))
1726                 simple-string)
1727             (let* ((numbytes (- end start))
1728                    (bytes-read (sb!sys:read-n-bytes stream
1729                                                     data
1730                                                     offset-start
1731                                                     numbytes
1732                                                     nil)))
1733               (if (< bytes-read numbytes)
1734                   (+ start bytes-read)
1735                   end)))
1736            (t
1737             (let ((read-function
1738                    (if (subtypep (stream-element-type stream) 'character)
1739                        #'read-char
1740                        #'read-byte)))
1741               (do ((i offset-start (1+ i)))
1742                   ((>= i offset-end) end)
1743                 (declare (type index i))
1744                 (let ((el (funcall read-function stream nil :eof)))
1745                   (when (eq el :eof)
1746                     (return (+ start (- i offset-start))))
1747                   (setf (aref data i) el)))))))))))
1748
1749 (defun write-sequence (seq stream &key (start 0) (end nil))
1750   #!+sb-doc
1751   "Write the elements of SEQ bounded by START and END to STREAM."
1752   (declare (type sequence seq)
1753            (type stream stream)
1754            (type index start)
1755            (type sequence-end end)
1756            (values sequence))
1757   (let ((end (or end (length seq))))
1758     (declare (type index start end))
1759     (etypecase seq
1760       (list
1761        (let ((write-function
1762               (if (subtypep (stream-element-type stream) 'character)
1763                   #'write-char
1764                   #'write-byte)))
1765          (do ((rem (nthcdr start seq) (rest rem))
1766               (i start (1+ i)))
1767              ((or (endp rem) (>= i end)) seq)
1768            (declare (type list rem)
1769                     (type index i))
1770            (funcall write-function (first rem) stream))))
1771       (string
1772        (write-string* seq stream start end))
1773       (vector
1774        (let ((write-function
1775               (if (subtypep (stream-element-type stream) 'character)
1776                   #'write-char
1777                   #'write-byte)))
1778          (do ((i start (1+ i)))
1779              ((>= i end) seq)
1780            (declare (type index i))
1781            (funcall write-function (aref seq i) stream)))))))
1782
1783 ;;; (These were inline throughout this file, but that's not appropriate
1784 ;;; globally.)
1785 (declaim (maybe-inline read-char unread-char read-byte listen))