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