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