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