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