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