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