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