0.8.5.13:
[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 (defun write-line (string &optional (stream *standard-output*)
563                           &key (start 0) end)
564   (declare (type string string))
565   ;; FIXME: Why is there this difference between the treatments of the
566   ;; STREAM argument in WRITE-STRING and WRITE-LINE?
567   (let ((defaulted-stream (out-synonym-of stream)))
568     (%write-string string defaulted-stream start (%check-vector-sequence-bounds
569                                                   string start end))
570     (write-char #\newline defaulted-stream))
571   string)
572
573 (defun charpos (&optional (stream *standard-output*))
574   (with-out-stream stream (ansi-stream-misc :charpos) (stream-line-column)))
575
576 (defun line-length (&optional (stream *standard-output*))
577   (with-out-stream stream (ansi-stream-misc :line-length)
578                    (stream-line-length)))
579
580 (defun finish-output (&optional (stream *standard-output*))
581   (with-out-stream stream (ansi-stream-misc :finish-output)
582                    (stream-finish-output))
583   nil)
584
585 (defun force-output (&optional (stream *standard-output*))
586   (with-out-stream stream (ansi-stream-misc :force-output)
587                    (stream-force-output))
588   nil)
589
590 (defun clear-output (&optional (stream *standard-output*))
591   (with-out-stream stream (ansi-stream-misc :clear-output)
592                    (stream-force-output))
593   nil)
594
595 (defun write-byte (integer stream)
596   (with-out-stream stream (ansi-stream-bout integer)
597                    (stream-write-byte integer))
598   integer)
599 \f
600 ;;; This is called from ANSI-STREAM routines that encapsulate CLOS
601 ;;; streams to handle the misc routines and dispatch to the
602 ;;; appropriate Gray stream functions.
603 (defun stream-misc-dispatch (stream operation &optional arg1 arg2)
604   (declare (type fundamental-stream stream)
605            (ignore arg2))
606   (case operation
607     (:listen
608      ;; Return T if input available, :EOF for end-of-file, otherwise NIL.
609      (let ((char (stream-read-char-no-hang stream)))
610        (when (characterp char)
611          (stream-unread-char stream char))
612        char))
613     (:unread
614      (stream-unread-char stream arg1))
615     (:close
616      (close stream))
617     (:clear-input
618      (stream-clear-input stream))
619     (:force-output
620      (stream-force-output stream))
621     (:finish-output
622      (stream-finish-output stream))
623     (:element-type
624      (stream-element-type stream))
625     (:interactive-p
626      (interactive-stream-p stream))
627     (:line-length
628      (stream-line-length stream))
629     (:charpos
630      (stream-line-column stream))
631     (:file-length
632      (file-length stream))
633     (:file-position
634      (file-position stream arg1))))
635 \f
636 ;;;; broadcast streams
637
638 (defstruct (broadcast-stream (:include ansi-stream
639                                        (out #'broadcast-out)
640                                        (bout #'broadcast-bout)
641                                        (sout #'broadcast-sout)
642                                        (misc #'broadcast-misc))
643                              (:constructor %make-broadcast-stream
644                                            (&rest streams))
645                              (:copier nil))
646   ;; a list of all the streams we broadcast to
647   (streams () :type list :read-only t))
648
649 (defun make-broadcast-stream (&rest streams)
650   (dolist (stream streams)
651     (unless (or (and (synonym-stream-p stream)
652                      (output-stream-p (symbol-value
653                                        (synonym-stream-symbol stream))))
654                 (output-stream-p stream))
655       (error 'type-error
656              :datum stream
657              :expected-type '(satisfies output-stream-p))))
658   (apply #'%make-broadcast-stream streams))
659
660 (macrolet ((out-fun (fun method stream-method &rest args)
661              `(defun ,fun (stream ,@args)
662                 (dolist (stream (broadcast-stream-streams stream))
663                   (if (ansi-stream-p stream)
664                       (funcall (,method stream) stream ,@args)
665                       (,stream-method stream ,@args))))))
666   (out-fun broadcast-out ansi-stream-out stream-write-char char)
667   (out-fun broadcast-bout ansi-stream-bout stream-write-byte byte)
668   (out-fun broadcast-sout ansi-stream-sout stream-write-string
669            string start end))
670
671 (defun broadcast-misc (stream operation &optional arg1 arg2)
672   (let ((streams (broadcast-stream-streams stream)))
673     (case operation
674       (:charpos
675        (dolist (stream streams)
676          (let ((charpos (charpos stream)))
677            (if charpos (return charpos)))))
678       (:line-length
679        (let ((min nil))
680          (dolist (stream streams min)
681            (let ((res (line-length stream)))
682              (when res (setq min (if min (min res min) res)))))))
683       (:element-type
684        (let (res)
685          (dolist (stream streams (if (> (length res) 1) `(and ,@res) res))
686            (pushnew (stream-element-type stream) res :test #'equal))))
687       (:close)
688       (t
689        (let ((res nil))
690          (dolist (stream streams res)
691            (setq res
692                  (if (ansi-stream-p stream)
693                      (funcall (ansi-stream-misc stream) stream operation
694                               arg1 arg2)
695                      (stream-misc-dispatch stream operation arg1 arg2)))))))))
696 \f
697 ;;;; synonym streams
698
699 (defstruct (synonym-stream (:include ansi-stream
700                                      (in #'synonym-in)
701                                      (bin #'synonym-bin)
702                                      (n-bin #'synonym-n-bin)
703                                      (out #'synonym-out)
704                                      (bout #'synonym-bout)
705                                      (sout #'synonym-sout)
706                                      (misc #'synonym-misc))
707                            (:constructor make-synonym-stream (symbol))
708                            (:copier nil))
709   ;; This is the symbol, the value of which is the stream we are synonym to.
710   (symbol nil :type symbol :read-only t))
711 (def!method print-object ((x synonym-stream) stream)
712   (print-unreadable-object (x stream :type t :identity t)
713     (format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
714
715 ;;; The output simple output methods just call the corresponding method
716 ;;; in the synonymed stream.
717 (macrolet ((out-fun (name slot stream-method &rest args)
718              `(defun ,name (stream ,@args)
719                 (declare (optimize (safety 1)))
720                 (let ((syn (symbol-value (synonym-stream-symbol stream))))
721                   (if (ansi-stream-p syn)
722                       (funcall (,slot syn) syn ,@args)
723                       (,stream-method syn ,@args))))))
724   (out-fun synonym-out ansi-stream-out stream-write-char ch)
725   (out-fun synonym-bout ansi-stream-bout stream-write-byte n)
726   (out-fun synonym-sout ansi-stream-sout stream-write-string string start end))
727
728 ;;; For the input methods, we just call the corresponding function on the
729 ;;; synonymed stream. These functions deal with getting input out of
730 ;;; the In-Buffer if there is any.
731 (macrolet ((in-fun (name fun &rest args)
732              `(defun ,name (stream ,@args)
733                 (declare (optimize (safety 1)))
734                 (,fun (symbol-value (synonym-stream-symbol stream))
735                       ,@args))))
736   (in-fun synonym-in read-char eof-error-p eof-value)
737   (in-fun synonym-bin read-byte eof-error-p eof-value)
738   (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
739
740 (defun synonym-misc (stream operation &optional arg1 arg2)
741   (declare (optimize (safety 1)))
742   (let ((syn (symbol-value (synonym-stream-symbol stream))))
743     (if (ansi-stream-p syn)
744         ;; We have to special-case some operations which interact with
745         ;; the in-buffer of the wrapped stream, since just calling
746         ;; ANSI-STREAM-MISC on them
747         (case operation
748           (:listen (or (/= (the fixnum (ansi-stream-in-index syn))
749                            +ansi-stream-in-buffer-length+)
750                        (funcall (ansi-stream-misc syn) syn :listen)))
751           (:clear-input (clear-input syn))
752           (:unread (unread-char arg1 syn))
753           (t
754            (funcall (ansi-stream-misc syn) syn operation arg1 arg2)))
755         (stream-misc-dispatch syn operation arg1 arg2))))
756 \f
757 ;;;; two-way streams
758
759 (defstruct (two-way-stream
760             (:include ansi-stream
761                       (in #'two-way-in)
762                       (bin #'two-way-bin)
763                       (n-bin #'two-way-n-bin)
764                       (out #'two-way-out)
765                       (bout #'two-way-bout)
766                       (sout #'two-way-sout)
767                       (misc #'two-way-misc))
768             (:constructor %make-two-way-stream (input-stream output-stream))
769             (:copier nil))
770   (input-stream (missing-arg) :type stream :read-only t)
771   (output-stream (missing-arg) :type stream :read-only t))
772 (defprinter (two-way-stream) input-stream output-stream)
773
774 (defun make-two-way-stream (input-stream output-stream)
775   #!+sb-doc
776   "Return a bidirectional stream which gets its input from INPUT-STREAM and
777    sends its output to OUTPUT-STREAM."
778   ;; FIXME: This idiom of the-real-stream-of-a-possibly-synonym-stream
779   ;; should be encapsulated in a function, and used here and most of
780   ;; the other places that SYNONYM-STREAM-P appears.
781   (unless (or (and (synonym-stream-p output-stream)
782                    (output-stream-p (symbol-value
783                                      (synonym-stream-symbol output-stream))))
784               (output-stream-p output-stream))
785     (error 'type-error
786            :datum output-stream
787            :expected-type '(satisfies output-stream-p)))
788   (unless (or (and (synonym-stream-p input-stream)
789                    (input-stream-p (symbol-value
790                                     (synonym-stream-symbol input-stream))))
791               (input-stream-p input-stream))
792     (error 'type-error
793            :datum input-stream
794            :expected-type '(satisfies input-stream-p)))
795   (funcall #'%make-two-way-stream input-stream output-stream))
796
797 (macrolet ((out-fun (name slot stream-method &rest args)
798              `(defun ,name (stream ,@args)
799                 (let ((syn (two-way-stream-output-stream stream)))
800                   (if (ansi-stream-p syn)
801                       (funcall (,slot syn) syn ,@args)
802                       (,stream-method syn ,@args))))))
803   (out-fun two-way-out ansi-stream-out stream-write-char ch)
804   (out-fun two-way-bout ansi-stream-bout stream-write-byte n)
805   (out-fun two-way-sout ansi-stream-sout stream-write-string string start end))
806
807 (macrolet ((in-fun (name fun &rest args)
808              `(defun ,name (stream ,@args)
809                 (force-output (two-way-stream-output-stream stream))
810                 (,fun (two-way-stream-input-stream stream) ,@args))))
811   (in-fun two-way-in read-char eof-error-p eof-value)
812   (in-fun two-way-bin read-byte eof-error-p eof-value)
813   (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
814
815 (defun two-way-misc (stream operation &optional arg1 arg2)
816   (let* ((in (two-way-stream-input-stream stream))
817          (out (two-way-stream-output-stream stream))
818          (in-ansi-stream-p (ansi-stream-p in))
819          (out-ansi-stream-p (ansi-stream-p out)))
820     (case operation
821       (:listen
822        (if in-ansi-stream-p
823            (or (/= (the fixnum (ansi-stream-in-index in))
824                    +ansi-stream-in-buffer-length+)
825                (funcall (ansi-stream-misc in) in :listen))
826            (stream-listen in)))
827       ((:finish-output :force-output :clear-output)
828        (if out-ansi-stream-p
829            (funcall (ansi-stream-misc out) out operation arg1 arg2)
830            (stream-misc-dispatch out operation arg1 arg2)))
831       (:clear-input (clear-input in))
832       (:unread (unread-char arg1 in))
833       (:element-type
834        (let ((in-type (stream-element-type in))
835              (out-type (stream-element-type out)))
836          (if (equal in-type out-type)
837              in-type `(and ,in-type ,out-type))))
838       (:close
839        (set-closed-flame stream))
840       (t
841        (or (if in-ansi-stream-p
842                (funcall (ansi-stream-misc in) in operation arg1 arg2)
843                (stream-misc-dispatch in operation arg1 arg2))
844            (if out-ansi-stream-p
845                (funcall (ansi-stream-misc out) out operation arg1 arg2)
846                (stream-misc-dispatch out operation arg1 arg2)))))))
847 \f
848 ;;;; concatenated streams
849
850 (defstruct (concatenated-stream
851             (:include ansi-stream
852                       (in #'concatenated-in)
853                       (bin #'concatenated-bin)
854                       (n-bin #'concatenated-n-bin)
855                       (misc #'concatenated-misc))
856             (:constructor %make-concatenated-stream
857                           (&rest streams &aux (current streams)))
858             (:copier nil))
859   ;; The car of this is the substream we are reading from now.
860   current
861   ;; This is a list of all the substreams there ever were. We need to
862   ;; remember them so that we can close them.
863   ;;
864   ;; FIXME: ANSI says this is supposed to be the list of streams that
865   ;; we still have to read from. So either this needs to become a
866   ;; private member %STREAM (with CONCATENATED-STREAM-STREAMS a wrapper
867   ;; around it which discards closed files from the head of the list)
868   ;; or we need to update it as we run out of files.
869   (streams nil :type list :read-only t))
870 (def!method print-object ((x concatenated-stream) stream)
871   (print-unreadable-object (x stream :type t :identity t)
872     (format stream
873             ":STREAMS ~S"
874             (concatenated-stream-streams x))))
875
876 (defun make-concatenated-stream (&rest streams)
877   #!+sb-doc
878   "Return a stream which takes its input from each of the streams in turn,
879    going on to the next at EOF."
880   (dolist (stream streams)
881     (unless (or (and (synonym-stream-p stream)
882                      (input-stream-p (symbol-value
883                                       (synonym-stream-symbol stream))))
884                 (input-stream-p stream))
885       (error 'type-error
886              :datum stream
887              :expected-type '(satisfies input-stream-p))))
888   (apply #'%make-concatenated-stream streams))
889
890 (macrolet ((in-fun (name fun)
891              `(defun ,name (stream eof-error-p eof-value)
892                 (do ((current (concatenated-stream-current stream)
893                               (cdr current)))
894                     ((null current)
895                      (eof-or-lose stream eof-error-p eof-value))
896                   (let* ((stream (car current))
897                          (result (,fun stream nil nil)))
898                     (when result (return result)))
899                   (pop (concatenated-stream-current stream))))))
900   (in-fun concatenated-in read-char)
901   (in-fun concatenated-bin read-byte))
902
903 (defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
904   (do ((current (concatenated-stream-current stream) (cdr current))
905        (current-start start)
906        (remaining-bytes numbytes))
907       ((null current)
908        (if eof-errorp
909            (error 'end-of-file :stream stream)
910            (- numbytes remaining-bytes)))
911     (let* ((stream (car current))
912            (bytes-read (read-n-bytes stream buffer current-start
913                                      remaining-bytes nil)))
914       (incf current-start bytes-read)
915       (decf remaining-bytes bytes-read)
916       (when (zerop remaining-bytes) (return numbytes)))
917     (setf (concatenated-stream-current stream) (cdr current))))
918
919 (defun concatenated-misc (stream operation &optional arg1 arg2)
920   (let ((left (concatenated-stream-current stream)))
921     (when left
922       (let* ((current (car left)))
923         (case operation
924           (:listen
925            (loop
926              (let ((stuff (if (ansi-stream-p current)
927                               (funcall (ansi-stream-misc current) current
928                                        :listen)
929                               (stream-misc-dispatch current :listen))))
930                (cond ((eq stuff :eof)
931                       ;; Advance CURRENT, and try again.
932                       (pop (concatenated-stream-current stream))
933                       (setf current
934                             (car (concatenated-stream-current stream)))
935                       (unless current
936                         ;; No further streams. EOF.
937                         (return :eof)))
938                      (stuff
939                       ;; Stuff's available.
940                       (return t))
941                      (t
942                       ;; Nothing is available yet.
943                       (return nil))))))
944           (:clear-input (clear-input current))
945           (:unread (unread-char arg1 current))
946           (:close
947            (set-closed-flame stream))
948           (t
949            (if (ansi-stream-p current)
950                (funcall (ansi-stream-misc current) current operation arg1 arg2)
951                (stream-misc-dispatch current operation arg1 arg2))))))))
952 \f
953 ;;;; echo streams
954
955 (defstruct (echo-stream
956             (:include two-way-stream
957                       (in #'echo-in)
958                       (bin #'echo-bin)
959                       (misc #'echo-misc)
960                       (n-bin #'ill-bin))
961             (:constructor %make-echo-stream (input-stream output-stream))
962             (:copier nil))
963   unread-stuff)
964 (def!method print-object ((x echo-stream) stream)
965   (print-unreadable-object (x stream :type t :identity t)
966     (format stream
967             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
968             (two-way-stream-input-stream x)
969             (two-way-stream-output-stream x))))
970
971 (defun make-echo-stream (input-stream output-stream)
972   #!+sb-doc
973   "Return a bidirectional stream which gets its input from INPUT-STREAM and
974    sends its output to OUTPUT-STREAM. In addition, all input is echoed to
975    the output stream."
976   (unless (or (and (synonym-stream-p output-stream)
977                    (output-stream-p (symbol-value
978                                      (synonym-stream-symbol output-stream))))
979               (output-stream-p output-stream))
980     (error 'type-error
981            :datum output-stream
982            :expected-type '(satisfies output-stream-p)))
983   (unless (or (and (synonym-stream-p input-stream)
984                    (input-stream-p (symbol-value
985                                     (synonym-stream-symbol input-stream))))
986               (input-stream-p input-stream))
987     (error 'type-error
988            :datum input-stream
989            :expected-type '(satisfies input-stream-p)))
990   (funcall #'%make-echo-stream input-stream output-stream))
991
992 (macrolet ((in-fun (name fun out-slot stream-method &rest args)
993              `(defun ,name (stream ,@args)
994                 (or (pop (echo-stream-unread-stuff stream))
995                     (let* ((in (echo-stream-input-stream stream))
996                            (out (echo-stream-output-stream stream))
997                            (result (,fun in ,@args)))
998                       (if (ansi-stream-p out)
999                           (funcall (,out-slot out) out result)
1000                           (,stream-method out result))
1001                       result)))))
1002   (in-fun echo-in read-char ansi-stream-out stream-write-char
1003           eof-error-p eof-value)
1004   (in-fun echo-bin read-byte ansi-stream-bout stream-write-byte
1005           eof-error-p eof-value))
1006
1007 (defun echo-misc (stream operation &optional arg1 arg2)
1008   (let* ((in (two-way-stream-input-stream stream))
1009          (out (two-way-stream-output-stream stream)))
1010     (case operation
1011       (:listen
1012        (or (not (null (echo-stream-unread-stuff stream)))
1013            (if (ansi-stream-p in)
1014                (or (/= (the fixnum (ansi-stream-in-index in))
1015                        +ansi-stream-in-buffer-length+)
1016                    (funcall (ansi-stream-misc in) in :listen))
1017                (stream-misc-dispatch in :listen))))
1018       (:unread (push arg1 (echo-stream-unread-stuff stream)))
1019       (:element-type
1020        (let ((in-type (stream-element-type in))
1021              (out-type (stream-element-type out)))
1022          (if (equal in-type out-type)
1023              in-type `(and ,in-type ,out-type))))
1024       (:close
1025        (set-closed-flame stream))
1026       (:peek-char
1027        ;; For the special case of peeking into an echo-stream
1028        ;; arg1 is PEEK-TYPE, arg2 is (EOF-ERROR-P EOF-VALUE)
1029        ;; returns peeked-char, eof-value, or errors end-of-file
1030        ;;
1031        ;; Note: This code could be moved into PEEK-CHAR if desired.
1032        ;; I am unsure whether this belongs with echo-streams because it is
1033        ;; echo-stream specific, or PEEK-CHAR because it is peeking code.
1034        ;; -- mrd 2002-11-18
1035        ;;
1036        ;; UNREAD-CHAR-P indicates whether the current character was one
1037        ;; that was previously unread.  In that case, we need to ensure that
1038        ;; the semantics for UNREAD-CHAR are held; the character should
1039        ;; not be echoed again.
1040        (let ((unread-char-p nil))
1041          (flet ((outfn (c)
1042                   (unless unread-char-p
1043                     (if (ansi-stream-p out)
1044                         (funcall (ansi-stream-out out) out c)
1045                         ;; gray-stream
1046                         (stream-write-char out c))))
1047                 (infn ()
1048                   ;; Obtain input from unread buffer or input stream,
1049                   ;; and set the flag appropriately.
1050                   (cond ((not (null (echo-stream-unread-stuff stream)))
1051                          (setf unread-char-p t)
1052                          (pop (echo-stream-unread-stuff stream)))
1053                         (t
1054                          (setf unread-char-p nil)
1055                          (read-char in (first arg2) (second arg2))))))
1056            (generalized-peeking-mechanism
1057             arg1 (second arg2) char
1058             (infn)
1059             (unread-char char in)
1060             (outfn char)))))
1061       (t
1062        (or (if (ansi-stream-p in)
1063                (funcall (ansi-stream-misc in) in operation arg1 arg2)
1064                (stream-misc-dispatch in operation arg1 arg2))
1065            (if (ansi-stream-p out)
1066                (funcall (ansi-stream-misc out) out operation arg1 arg2)
1067                (stream-misc-dispatch out operation arg1 arg2)))))))
1068 \f
1069 ;;;; base STRING-STREAM stuff
1070
1071 (defstruct (string-stream
1072              (:include ansi-stream)
1073              (:constructor nil)
1074              (:copier nil))
1075   ;; FIXME: This type declaration is true, and will probably continue
1076   ;; to be true.  However, note well the comments in DEFTRANSFORM
1077   ;; REPLACE, implying that performance of REPLACE is somewhat
1078   ;; critical to performance of string streams.  If (VECTOR CHARACTER)
1079   ;; ever becomes different from (VECTOR BASE-CHAR), the transform
1080   ;; probably needs to be extended.
1081   (string (missing-arg) :type (vector character)))
1082 \f
1083 ;;;; STRING-INPUT-STREAM stuff
1084
1085 (defstruct (string-input-stream
1086              (:include string-stream
1087                        (in #'string-inch)
1088                        (bin #'ill-bin)
1089                        (n-bin #'string-stream-read-n-bytes)
1090                        (misc #'string-in-misc)
1091                        (string (missing-arg) :type simple-string))
1092              (:constructor internal-make-string-input-stream
1093                            (string current end))
1094              (:copier nil))
1095   (current (missing-arg) :type index)
1096   (end (missing-arg) :type index))
1097
1098 (defun string-inch (stream eof-error-p eof-value)
1099   (declare (type string-input-stream stream))
1100   (let ((string (string-input-stream-string stream))
1101         (index (string-input-stream-current stream)))
1102     (cond ((>= index (the index (string-input-stream-end stream)))
1103            (eof-or-lose stream eof-error-p eof-value))
1104           (t
1105            (setf (string-input-stream-current stream) (1+ index))
1106            (char string index)))))
1107
1108 (defun string-binch (stream eof-error-p eof-value)
1109   (declare (type string-input-stream stream))
1110   (let ((string (string-input-stream-string stream))
1111         (index (string-input-stream-current stream)))
1112     (cond ((>= index (the index (string-input-stream-end stream)))
1113            (eof-or-lose stream eof-error-p eof-value))
1114           (t
1115            (setf (string-input-stream-current stream) (1+ index))
1116            (char-code (char string index))))))
1117
1118 (defun string-stream-read-n-bytes (stream buffer start requested eof-error-p)
1119   (declare (type string-input-stream stream)
1120            (type index start requested))
1121   (let* ((string (string-input-stream-string stream))
1122          (index (string-input-stream-current stream))
1123          (available (- (string-input-stream-end stream) index))
1124          (copy (min available requested)))
1125     (declare (type simple-string string))
1126     (when (plusp copy)
1127       (setf (string-input-stream-current stream)
1128             (truly-the index (+ index copy)))
1129       (sb!sys:without-gcing
1130        (system-area-copy (vector-sap string)
1131                          (* index sb!vm:n-byte-bits)
1132                          (if (typep buffer 'system-area-pointer)
1133                              buffer
1134                              (vector-sap buffer))
1135                          (* start sb!vm:n-byte-bits)
1136                          (* copy sb!vm:n-byte-bits))))
1137     (if (and (> requested copy) eof-error-p)
1138         (error 'end-of-file :stream stream)
1139         copy)))
1140
1141 (defun string-in-misc (stream operation &optional arg1 arg2)
1142   (declare (type string-input-stream stream)
1143            (ignore arg2))
1144   (case operation
1145     (:file-position
1146      (if arg1
1147          (setf (string-input-stream-current stream)
1148                (case arg1
1149                  (:start 0)
1150                  (:end (string-input-stream-end stream))
1151                  ;; We allow moving position beyond EOF. Errors happen
1152                  ;; on read, not move -- or the user may extend the
1153                  ;; input string.
1154                  (t arg1)))
1155          (string-input-stream-current stream)))
1156     ;; According to ANSI: "Should signal an error of type type-error
1157     ;; if stream is not a stream associated with a file."
1158     ;; This is checked by FILE-LENGTH, so no need to do it here either.
1159     ;; (:file-length (length (string-input-stream-string stream)))
1160     (:unread (decf (string-input-stream-current stream)))
1161     (:listen (or (/= (the index (string-input-stream-current stream))
1162                      (the index (string-input-stream-end stream)))
1163                  :eof))
1164     (:element-type (array-element-type (string-input-stream-string stream)))))
1165
1166 (defun make-string-input-stream (string &optional (start 0) end)
1167   #!+sb-doc
1168   "Return an input stream which will supply the characters of STRING between
1169   START and END in order."
1170   (declare (type string string)
1171            (type index start)
1172            (type (or index null) end))
1173   (let ((end (%check-vector-sequence-bounds string start end)))
1174     (with-array-data ((string string) (start start) (end end))
1175       (internal-make-string-input-stream
1176        string ;; now simple
1177        start
1178        end))))
1179 \f
1180 ;;;; STRING-OUTPUT-STREAM stuff
1181
1182 (defstruct (string-output-stream
1183             (:include string-stream
1184                       (out #'string-ouch)
1185                       (sout #'string-sout)
1186                       (misc #'string-out-misc)
1187                       ;; The string we throw stuff in.
1188                       (string (missing-arg)
1189                               :type (simple-array character (*))))
1190             (:constructor make-string-output-stream 
1191                           (&key (element-type 'character)
1192                            &aux (string (make-string 40))))
1193             (:copier nil))
1194   ;; Index of the next location to use.
1195   (index 0 :type fixnum)
1196   ;; Index cache for string-output-stream-last-index
1197   (index-cache 0 :type fixnum)
1198   ;; Requested element type
1199   (element-type 'character))
1200
1201 #!+sb-doc
1202 (setf (fdocumentation 'make-string-output-stream 'function)
1203   "Return an output stream which will accumulate all output given it for
1204    the benefit of the function GET-OUTPUT-STREAM-STRING.")
1205
1206 (defun string-output-stream-last-index (stream)
1207   (max (string-output-stream-index stream)
1208        (string-output-stream-index-cache stream)))
1209
1210 (defun string-ouch (stream character)
1211   (let ((current (string-output-stream-index stream))
1212         (workspace (string-output-stream-string stream)))
1213     (declare (type (simple-array character (*)) workspace)
1214              (type fixnum current))
1215     (if (= current (the fixnum (length workspace)))
1216         (let ((new-workspace (make-string (* current 2))))
1217           (replace new-workspace workspace)
1218           (setf (aref new-workspace current) character
1219                 (string-output-stream-string stream) new-workspace))
1220         (setf (aref workspace current) character))
1221     (setf (string-output-stream-index stream) (1+ current))))
1222
1223 (defun string-sout (stream string start end)
1224   (declare (type simple-string string)
1225            (type fixnum start end))
1226   (let* ((string (coerce string '(simple-array character (*))))
1227          (current (string-output-stream-index stream))
1228          (length (- end start))
1229          (dst-end (+ length current))
1230          (workspace (string-output-stream-string stream)))
1231     (declare (type (simple-array character (*)) workspace string)
1232              (type fixnum current length dst-end))
1233     (if (> dst-end (the fixnum (length workspace)))
1234         (let ((new-workspace (make-string (+ (* current 2) length))))
1235           (replace new-workspace workspace :end2 current)
1236           (replace new-workspace string
1237                    :start1 current :end1 dst-end
1238                    :start2 start :end2 end)
1239           (setf (string-output-stream-string stream) new-workspace))
1240         (replace workspace string
1241                  :start1 current :end1 dst-end
1242                  :start2 start :end2 end))
1243     (setf (string-output-stream-index stream) dst-end)))
1244
1245 (defun string-out-misc (stream operation &optional arg1 arg2)
1246   (declare (ignore arg2))
1247   (case operation
1248     (:file-position
1249      (if arg1
1250          (let ((end (string-output-stream-last-index stream)))
1251            (setf (string-output-stream-index-cache stream) end
1252                  (string-output-stream-index stream)
1253                  (case arg1
1254                    (:start 0)
1255                    (:end end)
1256                    (t
1257                     ;; We allow moving beyond the end of stream,
1258                     ;; implicitly extending the output stream.
1259                     (let ((buffer (string-output-stream-string stream)))
1260                       (when (> arg1 (length buffer))
1261                         (setf (string-output-stream-string stream)
1262                               (make-string
1263                                arg1 :element-type (array-element-type buffer))
1264                               (subseq (string-output-stream-string stream)
1265                                       0 end)
1266                               (subseq buffer 0 end))))
1267                       arg1))))
1268          (string-output-stream-index stream)))
1269     (:charpos
1270      (do ((index (1- (the fixnum (string-output-stream-index stream)))
1271                  (1- index))
1272           (count 0 (1+ count))
1273           (string (string-output-stream-string stream)))
1274          ((< index 0) count)
1275        (declare (type (simple-array character (*)) string)
1276                 (type fixnum index count))
1277        (if (char= (schar string index) #\newline)
1278            (return count))))
1279     (:element-type (array-element-type (string-output-stream-string stream)))))
1280
1281 ;;; Return a string of all the characters sent to a stream made by
1282 ;;; MAKE-STRING-OUTPUT-STREAM since the last call to this function.
1283 (defun get-output-stream-string (stream)
1284   (declare (type string-output-stream stream))
1285   (let* ((length (string-output-stream-last-index stream))
1286          (element-type (string-output-stream-element-type stream))
1287          (result 
1288           (case element-type
1289             ;; Overwhelmingly common case; can be inlined.
1290             ((character) (make-string length))
1291             (t (make-string length :element-type element-type)))))
1292     ;; For the benefit of the REPLACE transform, let's do this, so
1293     ;; that the common case isn't ludicrously expensive.
1294     (etypecase result 
1295       ((simple-array character (*)) 
1296        (replace result (string-output-stream-string stream)))
1297       ((simple-array nil (*))
1298        (replace result (string-output-stream-string stream))))
1299     (setf (string-output-stream-index stream) 0
1300           (string-output-stream-index-cache stream) 0)
1301     result))
1302
1303 ;;; Dump the characters buffer up in IN-STREAM to OUT-STREAM as
1304 ;;; GET-OUTPUT-STREAM-STRING would return them.
1305 (defun dump-output-stream-string (in-stream out-stream)
1306   (%write-string (string-output-stream-string in-stream)
1307                  out-stream
1308                  0
1309                  (string-output-stream-last-index in-stream))
1310   (setf (string-output-stream-index in-stream) 0
1311         (string-output-stream-index-cache in-stream) 0))
1312 \f
1313 ;;;; fill-pointer streams
1314
1315 ;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
1316 ;;; the CLM, but they are required for the implementation of
1317 ;;; WITH-OUTPUT-TO-STRING.
1318
1319 (deftype string-with-fill-pointer ()
1320   '(and (vector character)
1321         (satisfies array-has-fill-pointer-p)))
1322
1323 (defstruct (fill-pointer-output-stream
1324             (:include string-stream
1325                       (out #'fill-pointer-ouch)
1326                       (sout #'fill-pointer-sout)
1327                       (misc #'fill-pointer-misc)
1328                       ;; a string with a fill pointer where we stuff
1329                       ;; the stuff we write
1330                       (string (missing-arg)
1331                               :type string-with-fill-pointer
1332                               :read-only t))
1333             (:constructor make-fill-pointer-output-stream (string))
1334             (:copier nil)))
1335
1336 (defun fill-pointer-ouch (stream character)
1337   (let* ((buffer (fill-pointer-output-stream-string stream))
1338          (current (fill-pointer buffer))
1339          (current+1 (1+ current)))
1340     (declare (fixnum current))
1341     (with-array-data ((workspace buffer) (start) (end))
1342       (declare (type (simple-array character (*)) workspace))
1343       (let ((offset-current (+ start current)))
1344         (declare (fixnum offset-current))
1345         (if (= offset-current end)
1346             (let* ((new-length (1+ (* current 2)))
1347                    (new-workspace (make-string new-length)))
1348               (declare (simple-string new-workspace))
1349               (%byte-blt workspace start
1350                          new-workspace 0 current)
1351               (setf workspace new-workspace
1352                     offset-current current)
1353               (set-array-header buffer workspace new-length
1354                                 current+1 0 new-length nil))
1355             (setf (fill-pointer buffer) current+1))
1356         (setf (schar workspace offset-current) character)))
1357     current+1))
1358
1359 (defun fill-pointer-sout (stream string start end)
1360   (declare (simple-string string) (fixnum start end))
1361   (let* ((string (if (typep string '(simple-array character (*)))
1362                      string
1363                      (coerce string '(simple-array character (*)))))
1364          (buffer (fill-pointer-output-stream-string stream))
1365          (current (fill-pointer buffer))
1366          (string-len (- end start))
1367          (dst-end (+ string-len current)))
1368     (declare (fixnum current dst-end string-len))
1369     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1370       (declare (type (simple-array character (*)) workspace))
1371       (let ((offset-dst-end (+ dst-start dst-end))
1372             (offset-current (+ dst-start current)))
1373         (declare (fixnum offset-dst-end offset-current))
1374         (if (> offset-dst-end dst-length)
1375             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1376                    (new-workspace (make-string new-length)))
1377               (declare (type (simple-array character (*)) new-workspace))
1378               (%byte-blt workspace dst-start
1379                          new-workspace 0 current)
1380               (setf workspace new-workspace)
1381               (setf offset-current current)
1382               (setf offset-dst-end dst-end)
1383               (set-array-header buffer
1384                                 workspace
1385                                 new-length
1386                                 dst-end
1387                                 0
1388                                 new-length
1389                                 nil))
1390             (setf (fill-pointer buffer) dst-end))
1391         (%byte-blt string start
1392                    workspace offset-current offset-dst-end)))
1393     dst-end))
1394
1395 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1396   (declare (ignore arg1 arg2))
1397   (case operation
1398     (:file-position
1399      (let ((buffer (fill-pointer-output-stream-string stream)))
1400        (if arg1
1401            (setf (fill-pointer buffer)
1402                  (case arg1
1403                    (:start 0)
1404                    ;; Fill-pointer is always at fill-pointer we will
1405                    ;; make :END move to the end of the actual string.
1406                    (:end (array-total-size buffer))
1407                    ;; We allow moving beyond the end of string if the
1408                    ;; string is adjustable.
1409                    (t (when (>= arg1 (array-total-size buffer))
1410                         (if (adjustable-array-p buffer)
1411                             (adjust-array buffer arg1)
1412                             (error "Cannot move FILE-POSITION beyond the end ~
1413                                     of WITH-OUTPUT-TO-STRING stream ~
1414                                     constructed with non-adjustable string.")))
1415                       arg1)))
1416            (fill-pointer buffer))))
1417     (:charpos
1418      (let* ((buffer (fill-pointer-output-stream-string stream))
1419             (current (fill-pointer buffer)))
1420        (with-array-data ((string buffer) (start) (end current))
1421          (declare (simple-string string) (ignore start))
1422          (let ((found (position #\newline string :test #'char=
1423                                 :end end :from-end t)))
1424            (if found
1425                (- end (the fixnum found))
1426                current)))))
1427      (:element-type (array-element-type
1428                      (fill-pointer-output-stream-string stream)))))
1429 \f
1430 ;;;; indenting streams
1431
1432 (defstruct (indenting-stream (:include ansi-stream
1433                                        (out #'indenting-out)
1434                                        (sout #'indenting-sout)
1435                                        (misc #'indenting-misc))
1436                              (:constructor make-indenting-stream (stream))
1437                              (:copier nil))
1438   ;; the stream we're based on
1439   stream
1440   ;; how much we indent on each line
1441   (indentation 0))
1442
1443 #!+sb-doc
1444 (setf (fdocumentation 'make-indenting-stream 'function)
1445  "Return an output stream which indents its output by some amount.")
1446
1447 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1448 ;;; output on the given STREAM based on the specified SUB-STREAM.
1449 (defmacro indenting-indent (stream sub-stream)
1450   ;; KLUDGE: bare magic number 60
1451   `(do ((i 0 (+ i 60))
1452         (indentation (indenting-stream-indentation ,stream)))
1453        ((>= i indentation))
1454      (%write-string
1455       "                                                     "
1456       ,sub-stream
1457       0
1458       (min 60 (- indentation i)))))
1459
1460 ;;; INDENTING-OUT writes a character to an indenting stream.
1461 (defun indenting-out (stream char)
1462   (let ((sub-stream (indenting-stream-stream stream)))
1463     (write-char char sub-stream)
1464     (if (char= char #\newline)
1465         (indenting-indent stream sub-stream))))
1466
1467 ;;; INDENTING-SOUT writes a string to an indenting stream.
1468 (defun indenting-sout (stream string start end)
1469   (declare (simple-string string) (fixnum start end))
1470   (do ((i start)
1471        (sub-stream (indenting-stream-stream stream)))
1472       ((= i end))
1473     (let ((newline (position #\newline string :start i :end end)))
1474       (cond (newline
1475              (%write-string string sub-stream i (1+ newline))
1476              (indenting-indent stream sub-stream)
1477              (setq i (+ newline 1)))
1478             (t
1479              (%write-string string sub-stream i end)
1480              (setq i end))))))
1481
1482 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1483 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1484 ;;; the base stream minus the stream's indentation.
1485 (defun indenting-misc (stream operation &optional arg1 arg2)
1486   (let ((sub-stream (indenting-stream-stream stream)))
1487     (if (ansi-stream-p sub-stream)
1488         (let ((method (ansi-stream-misc sub-stream)))
1489           (case operation
1490             (:line-length
1491              (let ((line-length (funcall method sub-stream operation)))
1492                (if line-length
1493                    (- line-length (indenting-stream-indentation stream)))))
1494             (:charpos
1495              (let ((charpos (funcall method sub-stream operation)))
1496                (if charpos
1497                    (- charpos (indenting-stream-indentation stream)))))
1498             (t
1499              (funcall method sub-stream operation arg1 arg2))))
1500         ;; must be Gray streams FUNDAMENTAL-STREAM
1501         (case operation
1502           (:line-length
1503            (let ((line-length (stream-line-length sub-stream)))
1504              (if line-length
1505                  (- line-length (indenting-stream-indentation stream)))))
1506           (:charpos
1507            (let ((charpos (stream-line-column sub-stream)))
1508              (if charpos
1509                  (- charpos (indenting-stream-indentation stream)))))
1510           (t
1511            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1512
1513 (declaim (maybe-inline read-char unread-char read-byte listen))
1514 \f
1515 ;;;; case frobbing streams, used by FORMAT ~(...~)
1516
1517 (defstruct (case-frob-stream
1518             (:include ansi-stream
1519                       (misc #'case-frob-misc))
1520             (:constructor %make-case-frob-stream (target out sout))
1521             (:copier nil))
1522   (target (missing-arg) :type stream))
1523
1524 (defun make-case-frob-stream (target kind)
1525   #!+sb-doc
1526   "Return a stream that sends all output to the stream TARGET, but modifies
1527    the case of letters, depending on KIND, which should be one of:
1528      :upcase - convert to upper case.
1529      :downcase - convert to lower case.
1530      :capitalize - convert the first letter of words to upper case and the
1531         rest of the word to lower case.
1532      :capitalize-first - convert the first letter of the first word to upper
1533         case and everything else to lower case."
1534   (declare (type stream target)
1535            (type (member :upcase :downcase :capitalize :capitalize-first)
1536                  kind)
1537            (values stream))
1538   (if (case-frob-stream-p target)
1539       ;; If we are going to be writing to a stream that already does
1540       ;; case frobbing, why bother frobbing the case just so it can
1541       ;; frob it again?
1542       target
1543       (multiple-value-bind (out sout)
1544           (ecase kind
1545             (:upcase
1546              (values #'case-frob-upcase-out
1547                      #'case-frob-upcase-sout))
1548             (:downcase
1549              (values #'case-frob-downcase-out
1550                      #'case-frob-downcase-sout))
1551             (:capitalize
1552              (values #'case-frob-capitalize-out
1553                      #'case-frob-capitalize-sout))
1554             (:capitalize-first
1555              (values #'case-frob-capitalize-first-out
1556                      #'case-frob-capitalize-first-sout)))
1557         (%make-case-frob-stream target out sout))))
1558
1559 (defun case-frob-misc (stream op &optional arg1 arg2)
1560   (declare (type case-frob-stream stream))
1561   (case op
1562     (:close)
1563     (t
1564      (let ((target (case-frob-stream-target stream)))
1565        (if (ansi-stream-p target)
1566            (funcall (ansi-stream-misc target) target op arg1 arg2)
1567            (stream-misc-dispatch target op arg1 arg2))))))
1568
1569 (defun case-frob-upcase-out (stream char)
1570   (declare (type case-frob-stream stream)
1571            (type base-char char))
1572   (let ((target (case-frob-stream-target stream))
1573         (char (char-upcase char)))
1574     (if (ansi-stream-p target)
1575         (funcall (ansi-stream-out target) target char)
1576         (stream-write-char target char))))
1577
1578 (defun case-frob-upcase-sout (stream str start end)
1579   (declare (type case-frob-stream stream)
1580            (type simple-base-string str)
1581            (type index start)
1582            (type (or index null) end))
1583   (let* ((target (case-frob-stream-target stream))
1584          (len (length str))
1585          (end (or end len))
1586          (string (if (and (zerop start) (= len end))
1587                      (string-upcase str)
1588                      (nstring-upcase (subseq str start end))))
1589          (string-len (- end start)))
1590     (if (ansi-stream-p target)
1591         (funcall (ansi-stream-sout target) target string 0 string-len)
1592         (stream-write-string target string 0 string-len))))
1593
1594 (defun case-frob-downcase-out (stream char)
1595   (declare (type case-frob-stream stream)
1596            (type base-char char))
1597   (let ((target (case-frob-stream-target stream))
1598         (char (char-downcase char)))
1599     (if (ansi-stream-p target)
1600         (funcall (ansi-stream-out target) target char)
1601         (stream-write-char target char))))
1602
1603 (defun case-frob-downcase-sout (stream str start end)
1604   (declare (type case-frob-stream stream)
1605            (type simple-base-string str)
1606            (type index start)
1607            (type (or index null) end))
1608   (let* ((target (case-frob-stream-target stream))
1609          (len (length str))
1610          (end (or end len))
1611          (string (if (and (zerop start) (= len end))
1612                      (string-downcase str)
1613                      (nstring-downcase (subseq str start end))))
1614          (string-len (- end start)))
1615     (if (ansi-stream-p target)
1616         (funcall (ansi-stream-sout target) target string 0 string-len)
1617         (stream-write-string target string 0 string-len))))
1618
1619 (defun case-frob-capitalize-out (stream char)
1620   (declare (type case-frob-stream stream)
1621            (type base-char char))
1622   (let ((target (case-frob-stream-target stream)))
1623     (cond ((alphanumericp char)
1624            (let ((char (char-upcase char)))
1625              (if (ansi-stream-p target)
1626                  (funcall (ansi-stream-out target) target char)
1627                  (stream-write-char target char)))
1628            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1629            (setf (case-frob-stream-sout stream)
1630                  #'case-frob-capitalize-aux-sout))
1631           (t
1632            (if (ansi-stream-p target)
1633                (funcall (ansi-stream-out target) target char)
1634                (stream-write-char target char))))))
1635
1636 (defun case-frob-capitalize-sout (stream str start end)
1637   (declare (type case-frob-stream stream)
1638            (type simple-base-string str)
1639            (type index start)
1640            (type (or index null) end))
1641   (let* ((target (case-frob-stream-target stream))
1642          (str (subseq str start end))
1643          (len (length str))
1644          (inside-word nil))
1645     (dotimes (i len)
1646       (let ((char (schar str i)))
1647         (cond ((not (alphanumericp char))
1648                (setf inside-word nil))
1649               (inside-word
1650                (setf (schar str i) (char-downcase char)))
1651               (t
1652                (setf inside-word t)
1653                (setf (schar str i) (char-upcase char))))))
1654     (when inside-word
1655       (setf (case-frob-stream-out stream)
1656             #'case-frob-capitalize-aux-out)
1657       (setf (case-frob-stream-sout stream)
1658             #'case-frob-capitalize-aux-sout))
1659     (if (ansi-stream-p target)
1660         (funcall (ansi-stream-sout target) target str 0 len)
1661         (stream-write-string target str 0 len))))
1662
1663 (defun case-frob-capitalize-aux-out (stream char)
1664   (declare (type case-frob-stream stream)
1665            (type base-char char))
1666   (let ((target (case-frob-stream-target stream)))
1667     (cond ((alphanumericp char)
1668            (let ((char (char-downcase char)))
1669              (if (ansi-stream-p target)
1670                  (funcall (ansi-stream-out target) target char)
1671                  (stream-write-char target char))))
1672           (t
1673            (if (ansi-stream-p target)
1674                (funcall (ansi-stream-out target) target char)
1675                (stream-write-char target char))
1676            (setf (case-frob-stream-out stream)
1677                  #'case-frob-capitalize-out)
1678            (setf (case-frob-stream-sout stream)
1679                  #'case-frob-capitalize-sout)))))
1680
1681 (defun case-frob-capitalize-aux-sout (stream str start end)
1682   (declare (type case-frob-stream stream)
1683            (type simple-base-string str)
1684            (type index start)
1685            (type (or index null) end))
1686   (let* ((target (case-frob-stream-target stream))
1687          (str (subseq str start end))
1688          (len (length str))
1689          (inside-word t))
1690     (dotimes (i len)
1691       (let ((char (schar str i)))
1692         (cond ((not (alphanumericp char))
1693                (setf inside-word nil))
1694               (inside-word
1695                (setf (schar str i) (char-downcase char)))
1696               (t
1697                (setf inside-word t)
1698                (setf (schar str i) (char-upcase char))))))
1699     (unless inside-word
1700       (setf (case-frob-stream-out stream)
1701             #'case-frob-capitalize-out)
1702       (setf (case-frob-stream-sout stream)
1703             #'case-frob-capitalize-sout))
1704     (if (ansi-stream-p target)
1705         (funcall (ansi-stream-sout target) target str 0 len)
1706         (stream-write-string target str 0 len))))
1707
1708 (defun case-frob-capitalize-first-out (stream char)
1709   (declare (type case-frob-stream stream)
1710            (type base-char char))
1711   (let ((target (case-frob-stream-target stream)))
1712     (cond ((alphanumericp char)
1713            (let ((char (char-upcase char)))
1714              (if (ansi-stream-p target)
1715                  (funcall (ansi-stream-out target) target char)
1716                  (stream-write-char target char)))
1717            (setf (case-frob-stream-out stream)
1718                  #'case-frob-downcase-out)
1719            (setf (case-frob-stream-sout stream)
1720                  #'case-frob-downcase-sout))
1721           (t
1722            (if (ansi-stream-p target)
1723                (funcall (ansi-stream-out target) target char)
1724                (stream-write-char target char))))))
1725
1726 (defun case-frob-capitalize-first-sout (stream str start end)
1727   (declare (type case-frob-stream stream)
1728            (type simple-base-string str)
1729            (type index start)
1730            (type (or index null) end))
1731   (let* ((target (case-frob-stream-target stream))
1732          (str (subseq str start end))
1733          (len (length str)))
1734     (dotimes (i len)
1735       (let ((char (schar str i)))
1736         (when (alphanumericp char)
1737           (setf (schar str i) (char-upcase char))
1738           (do ((i (1+ i) (1+ i)))
1739               ((= i len))
1740             (setf (schar str i) (char-downcase (schar str i))))
1741           (setf (case-frob-stream-out stream)
1742                 #'case-frob-downcase-out)
1743           (setf (case-frob-stream-sout stream)
1744                 #'case-frob-downcase-sout)
1745           (return))))
1746     (if (ansi-stream-p target)
1747         (funcall (ansi-stream-sout target) target str 0 len)
1748         (stream-write-string target str 0 len))))
1749 \f
1750 ;;;; READ-SEQUENCE
1751
1752 (defun read-sequence (seq stream &key (start 0) end)
1753   #!+sb-doc
1754   "Destructively modify SEQ by reading elements from STREAM.
1755   That part of SEQ bounded by START and END is destructively modified by
1756   copying successive elements into it from STREAM. If the end of file
1757   for STREAM is reached before copying all elements of the subsequence,
1758   then the extra elements near the end of sequence are not updated, and
1759   the index of the next element is returned."
1760   (declare (type sequence seq)
1761            (type stream stream)
1762            (type index start)
1763            (type sequence-end end)
1764            (values index))
1765   (if (ansi-stream-p stream)
1766       (ansi-stream-read-sequence seq stream start end)
1767       ;; must be Gray streams FUNDAMENTAL-STREAM
1768       (stream-read-sequence stream seq start end)))
1769
1770 (defun ansi-stream-read-sequence (seq stream start %end)
1771   (declare (type sequence seq)
1772            (type ansi-stream stream)
1773            (type index start)
1774            (type sequence-end %end)
1775            (values index))
1776   (let ((end (or %end (length seq))))
1777     (declare (type index end))
1778     (etypecase seq
1779       (list
1780        (let ((read-function
1781               (if (subtypep (stream-element-type stream) 'character)
1782                   #'read-char
1783                   #'read-byte)))
1784          (do ((rem (nthcdr start seq) (rest rem))
1785               (i start (1+ i)))
1786              ((or (endp rem) (>= i end)) i)
1787            (declare (type list rem)
1788                     (type index i))
1789            (let ((el (funcall read-function stream nil :eof)))
1790              (when (eq el :eof)
1791                (return i))
1792              (setf (first rem) el)))))
1793       (vector
1794        (with-array-data ((data seq) (offset-start start) (offset-end end))
1795          (typecase data
1796            ((or (simple-array (unsigned-byte 8) (*))
1797                 (simple-array (signed-byte 8) (*))
1798                 simple-string)
1799             (let* ((numbytes (- end start))
1800                    (bytes-read (sb!sys:read-n-bytes stream
1801                                                     data
1802                                                     offset-start
1803                                                     numbytes
1804                                                     nil)))
1805               (if (< bytes-read numbytes)
1806                   (+ start bytes-read)
1807                   end)))
1808            (t
1809             (let ((read-function
1810                    (if (subtypep (stream-element-type stream) 'character)
1811                        #'read-char
1812                        #'read-byte)))
1813               (do ((i offset-start (1+ i)))
1814                   ((>= i offset-end) end)
1815                 (declare (type index i))
1816                 (let ((el (funcall read-function stream nil :eof)))
1817                   (when (eq el :eof)
1818                     (return (+ start (- i offset-start))))
1819                   (setf (aref data i) el)))))))))))
1820 \f
1821 ;;;; WRITE-SEQUENCE
1822
1823 (defun write-sequence (seq stream &key (start 0) (end nil))
1824   #!+sb-doc
1825   "Write the elements of SEQ bounded by START and END to STREAM."
1826   (declare (type sequence seq)
1827            (type stream stream)
1828            (type index start)
1829            (type sequence-end end)
1830            (values sequence))
1831   (if (ansi-stream-p stream)
1832       (ansi-stream-write-sequence seq stream start end)
1833       ;; must be Gray-streams FUNDAMENTAL-STREAM
1834       (stream-write-sequence stream seq start end)))
1835
1836 (defun ansi-stream-write-sequence (seq stream start %end)
1837   (declare (type sequence seq)
1838            (type ansi-stream stream)
1839            (type index start)
1840            (type sequence-end %end)
1841            (values sequence))
1842   (let ((end (or %end (length seq))))
1843     (declare (type index end))
1844     (etypecase seq
1845       (list
1846        (let ((write-function
1847               (if (subtypep (stream-element-type stream) 'character)
1848                   #'write-char
1849                   #'write-byte)))
1850          (do ((rem (nthcdr start seq) (rest rem))
1851               (i start (1+ i)))
1852              ((or (endp rem) (>= i end)) seq)
1853            (declare (type list rem)
1854                     (type index i))
1855            (funcall write-function (first rem) stream))))
1856       (string
1857        (%write-string seq stream start end))
1858       (vector
1859        (let ((write-function
1860               (if (subtypep (stream-element-type stream) 'character)
1861                   #'write-char
1862                   #'write-byte)))
1863          (do ((i start (1+ i)))
1864              ((>= i end) seq)
1865            (declare (type index i))
1866            (funcall write-function (aref seq i) stream)))))))
1867 \f
1868 ;;;; etc.
1869
1870 ;;; (These were inline throughout this file, but that's not appropriate
1871 ;;; globally.)
1872 (declaim (maybe-inline read-char unread-char read-byte listen))