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