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