0.6.12.2:
[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       (%primitive sb!c:byte-blt
459                   in-buffer
460                   index
461                   buffer
462                   start
463                   (+ start numbytes))
464       (setf (lisp-stream-in-index stream) (+ index numbytes))
465       numbytes)
466      (t
467       (let ((end (+ start num-buffered)))
468         (%primitive sb!c:byte-blt in-buffer index buffer start end)
469         (setf (lisp-stream-in-index stream) +in-buffer-length+)
470         (+ (funcall (lisp-stream-n-bin stream)
471                     stream
472                     buffer
473                     end
474                     (- numbytes num-buffered)
475                     eof-error-p)
476            num-buffered))))))
477
478 ;;; the amount of space we leave at the start of the in-buffer for
479 ;;; unreading
480 ;;;
481 ;;; (It's 4 instead of 1 to allow word-aligned copies.)
482 (defconstant +in-buffer-extra+ 4) ; FIXME: should be symbolic constant
483
484 ;;; This function is called by the FAST-READ-CHAR expansion to refill
485 ;;; the IN-BUFFER for text streams. There is definitely an IN-BUFFER,
486 ;;; and hence must be an N-BIN method.
487 (defun fast-read-char-refill (stream eof-error-p eof-value)
488   (let* ((ibuf (lisp-stream-in-buffer stream))
489          (count (funcall (lisp-stream-n-bin stream)
490                          stream
491                          ibuf
492                          +in-buffer-extra+
493                          (- +in-buffer-length+ +in-buffer-extra+)
494                          nil))
495          (start (- +in-buffer-length+ count)))
496     (declare (type index start count))
497     (cond ((zerop count)
498            (setf (lisp-stream-in-index stream) +in-buffer-length+)
499            (funcall (lisp-stream-in stream) stream eof-error-p eof-value))
500           (t
501            (when (/= start +in-buffer-extra+)
502              (bit-bash-copy ibuf (+ (* +in-buffer-extra+ sb!vm:byte-bits)
503                                     (* sb!vm:vector-data-offset
504                                        sb!vm:word-bits))
505                             ibuf (+ (the index (* start sb!vm:byte-bits))
506                                     (* sb!vm:vector-data-offset
507                                        sb!vm:word-bits))
508                             (* count sb!vm:byte-bits)))
509            (setf (lisp-stream-in-index stream) (1+ start))
510            (code-char (aref ibuf start))))))
511
512 ;;; This is similar to FAST-READ-CHAR-REFILL, but we don't have to
513 ;;; leave room for unreading.
514 (defun fast-read-byte-refill (stream eof-error-p eof-value)
515   (let* ((ibuf (lisp-stream-in-buffer stream))
516          (count (funcall (lisp-stream-n-bin stream) stream
517                          ibuf 0 +in-buffer-length+
518                          nil))
519          (start (- +in-buffer-length+ count)))
520     (declare (type index start count))
521     (cond ((zerop count)
522            (setf (lisp-stream-in-index stream) +in-buffer-length+)
523            (funcall (lisp-stream-bin stream) stream eof-error-p eof-value))
524           (t
525            (unless (zerop start)
526              (bit-bash-copy ibuf (* sb!vm:vector-data-offset sb!vm:word-bits)
527                             ibuf (+ (the index (* start sb!vm:byte-bits))
528                                     (* sb!vm:vector-data-offset
529                                        sb!vm:word-bits))
530                             (* count sb!vm:byte-bits)))
531            (setf (lisp-stream-in-index stream) (1+ start))
532            (aref ibuf start)))))
533 \f
534 ;;; output functions
535
536 (defun write-char (character &optional (stream *standard-output*))
537   (with-out-stream stream (lisp-stream-out character)
538                    (stream-write-char character))
539   character)
540
541 (defun terpri (&optional (stream *standard-output*))
542   (with-out-stream stream (lisp-stream-out #\newline) (stream-terpri))
543   nil)
544
545 (defun fresh-line (&optional (stream *standard-output*))
546   (let ((stream (out-synonym-of stream)))
547     (if (lisp-stream-p stream)
548         (when (/= (or (charpos stream) 1) 0)
549           (funcall (lisp-stream-out stream) stream #\newline)
550           t)
551         ;; must be Gray streams FUNDAMENTAL-STREAM
552         (stream-fresh-line stream))))
553
554 (defun write-string (string &optional (stream *standard-output*)
555                             &key (start 0) (end (length (the vector string))))
556
557   ;; FIXME: These SETFs don't look right to me. Looking at the
558   ;; definition of "bounding indices" in the glossary of the ANSI
559   ;; spec, and extrapolating from the behavior of other operations
560   ;; when their operands are the wrong type, it seems that it would be
561   ;; more correct to essentially
562   ;;    (AVER (<= 0 START END (LENGTH STRING)))
563   ;; instead of modifying the incorrect values.
564   #!+high-security
565   (setf end (min end (length (the vector string))))
566   #!+high-security
567   (setf start (max start 0))
568
569   ;; FIXME: And I'd just signal a non-continuable error..
570   #!+high-security
571   (when (< end start)
572       (cerror "Continue with switched start and end ~S <-> ~S"
573               "Write-string: start (~S) and end (~S) exchanged."
574               start end string)
575       (rotatef start end))
576
577   (write-string* string stream start end))
578
579 (defun write-string* (string &optional (stream *standard-output*)
580                              (start 0) (end (length (the vector string))))
581   (declare (fixnum start end))
582   (let ((stream (out-synonym-of stream)))
583     (cond ((lisp-stream-p stream)
584            (if (array-header-p string)
585                (with-array-data ((data string) (offset-start start)
586                                  (offset-end end))
587                  (funcall (lisp-stream-sout stream)
588                           stream data offset-start offset-end))
589                (funcall (lisp-stream-sout stream) stream string start end))
590            string)
591           (t ; must be Gray streams FUNDAMENTAL-STREAM
592            (stream-write-string stream string start end)))))
593
594 (defun write-line (string &optional (stream *standard-output*)
595                           &key (start 0) (end (length string)))
596   (write-line* string stream start end))
597
598 (defun write-line* (string &optional (stream *standard-output*)
599                            (start 0) (end (length string)))
600   (declare (fixnum start end))
601   (let ((stream (out-synonym-of stream)))
602     (cond ((lisp-stream-p stream)
603            (if (array-header-p string)
604                (with-array-data ((data string) (offset-start start)
605                                  (offset-end end))
606                  (with-out-stream stream (lisp-stream-sout data offset-start
607                                                            offset-end)))
608                (with-out-stream stream (lisp-stream-sout string start end)))
609            (funcall (lisp-stream-out stream) stream #\newline))
610           (t ; must be Gray streams FUNDAMENTAL-STREAM
611            (stream-write-string stream string start end)
612            (stream-write-char stream #\Newline)))
613     string))
614
615 (defun charpos (&optional (stream *standard-output*))
616   (with-out-stream stream (lisp-stream-misc :charpos) (stream-line-column)))
617
618 (defun line-length (&optional (stream *standard-output*))
619   (with-out-stream stream (lisp-stream-misc :line-length)
620                    (stream-line-length)))
621
622 (defun finish-output (&optional (stream *standard-output*))
623   (with-out-stream stream (lisp-stream-misc :finish-output)
624                    (stream-finish-output))
625   nil)
626
627 (defun force-output (&optional (stream *standard-output*))
628   (with-out-stream stream (lisp-stream-misc :force-output)
629                    (stream-force-output))
630   nil)
631
632 (defun clear-output (&optional (stream *standard-output*))
633   (with-out-stream stream (lisp-stream-misc :clear-output)
634                    (stream-force-output))
635   nil)
636
637 (defun write-byte (integer stream)
638   (with-out-stream stream (lisp-stream-bout integer)
639                    (stream-write-byte integer))
640   integer)
641 \f
642 ;;; This is called from LISP-STREAM routines that encapsulate CLOS
643 ;;; streams to handle the misc routines and dispatch to the
644 ;;; appropriate Gray stream functions.
645 (defun stream-misc-dispatch (stream operation &optional arg1 arg2)
646   (declare (type fundamental-stream stream)
647            (ignore arg2))
648   (case operation
649     (:listen
650      ;; Return T if input available, :EOF for end-of-file, otherwise NIL.
651      (let ((char (stream-read-char-no-hang stream)))
652        (when (characterp char)
653          (stream-unread-char stream char))
654        char))
655     (:unread
656      (stream-unread-char stream arg1))
657     (:close
658      (close stream))
659     (:clear-input
660      (stream-clear-input stream))
661     (:force-output
662      (stream-force-output stream))
663     (:finish-output
664      (stream-finish-output stream))
665     (:element-type
666      (stream-element-type stream))
667     (:interactive-p
668      (interactive-stream-p stream))
669     (:line-length
670      (stream-line-length stream))
671     (:charpos
672      (stream-line-column stream))
673     (:file-length
674      (file-length stream))
675     (:file-position
676      (file-position stream arg1))))
677 \f
678 ;;;; broadcast streams
679
680 (defstruct (broadcast-stream (:include lisp-stream
681                                        (out #'broadcast-out)
682                                        (bout #'broadcast-bout)
683                                        (sout #'broadcast-sout)
684                                        (misc #'broadcast-misc))
685                              (:constructor #!-high-security-support
686                                            make-broadcast-stream
687                                            #!+high-security-support
688                                            %make-broadcast-stream (&rest
689                                                                    streams))
690                              (:copier nil))
691   ;; a list of all the streams we broadcast to
692   (streams () :type list :read-only t))
693
694 #!+high-security-support
695 (defun make-broadcast-stream (&rest streams)
696   (dolist (stream streams)
697     (unless (or (and (synonym-stream-p stream)
698                      (output-stream-p (symbol-value
699                                        (synonym-stream-symbol stream))))
700                 (output-stream-p stream))
701       (error 'type-error
702              :datum stream
703              :expected-type '(satisfies output-stream-p))))
704   (apply #'%make-broadcast-stream streams))
705
706 (macrolet ((out-fun (fun method stream-method &rest args)
707              `(defun ,fun (stream ,@args)
708                 (dolist (stream (broadcast-stream-streams stream))
709                   (if (lisp-stream-p stream)
710                       (funcall (,method stream) stream ,@args)
711                       (,stream-method stream ,@args))))))
712   (out-fun broadcast-out lisp-stream-out stream-write-char char)
713   (out-fun broadcast-bout lisp-stream-bout stream-write-byte byte)
714   (out-fun broadcast-sout lisp-stream-sout stream-write-string
715            string start end))
716
717 (defun broadcast-misc (stream operation &optional arg1 arg2)
718   (let ((streams (broadcast-stream-streams stream)))
719     (case operation
720       (:charpos
721        (dolist (stream streams)
722          (let ((charpos (charpos stream)))
723            (if charpos (return charpos)))))
724       (:line-length
725        (let ((min nil))
726          (dolist (stream streams min)
727            (let ((res (line-length stream)))
728              (when res (setq min (if min (min res min) res)))))))
729       (:element-type
730        (let (res)
731          (dolist (stream streams (if (> (length res) 1) `(and ,@res) res))
732            (pushnew (stream-element-type stream) res :test #'equal))))
733       (:close)
734       (t
735        (let ((res nil))
736          (dolist (stream streams res)
737            (setq res
738                  (if (lisp-stream-p stream)
739                      (funcall (lisp-stream-misc stream) stream operation
740                               arg1 arg2)
741                      (stream-misc-dispatch stream operation arg1 arg2)))))))))
742 \f
743 ;;;; synonym streams
744
745 (defstruct (synonym-stream (:include lisp-stream
746                                      (in #'synonym-in)
747                                      (bin #'synonym-bin)
748                                      (n-bin #'synonym-n-bin)
749                                      (out #'synonym-out)
750                                      (bout #'synonym-bout)
751                                      (sout #'synonym-sout)
752                                      (misc #'synonym-misc))
753                            (:constructor make-synonym-stream (symbol))
754                            (:copier nil))
755   ;; This is the symbol, the value of which is the stream we are synonym to.
756   (symbol nil :type symbol :read-only t))
757 (def!method print-object ((x synonym-stream) stream)
758   (print-unreadable-object (x stream :type t :identity t)
759     (format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
760
761 ;;; The output simple output methods just call the corresponding method
762 ;;; in the synonymed stream.
763 (macrolet ((out-fun (name slot stream-method &rest args)
764              `(defun ,name (stream ,@args)
765                 (declare (optimize (safety 1)))
766                 (let ((syn (symbol-value (synonym-stream-symbol stream))))
767                   (if (lisp-stream-p syn)
768                       (funcall (,slot syn) syn ,@args)
769                       (,stream-method syn ,@args))))))
770   (out-fun synonym-out lisp-stream-out stream-write-char ch)
771   (out-fun synonym-bout lisp-stream-bout stream-write-byte n)
772   (out-fun synonym-sout lisp-stream-sout stream-write-string string start end))
773
774 ;;; For the input methods, we just call the corresponding function on the
775 ;;; synonymed stream. These functions deal with getting input out of
776 ;;; the In-Buffer if there is any.
777 (macrolet ((in-fun (name fun &rest args)
778              `(defun ,name (stream ,@args)
779                 (declare (optimize (safety 1)))
780                 (,fun (symbol-value (synonym-stream-symbol stream))
781                       ,@args))))
782   (in-fun synonym-in read-char eof-error-p eof-value)
783   (in-fun synonym-bin read-byte eof-error-p eof-value)
784   (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
785
786 (defun synonym-misc (stream operation &optional arg1 arg2)
787   (declare (optimize (safety 1)))
788   (let ((syn (symbol-value (synonym-stream-symbol stream))))
789     (if (lisp-stream-p syn)
790         ;; We have to special-case some operations which interact with
791         ;; the in-buffer of the wrapped stream, since just calling
792         ;; LISP-STREAM-MISC on them
793         (case operation
794           (:listen (or (/= (the fixnum (lisp-stream-in-index syn))
795                            +in-buffer-length+)
796                        (funcall (lisp-stream-misc syn) syn :listen)))
797           (:clear-input (clear-input syn))
798           (:unread (unread-char arg1 syn))
799           (t
800            (funcall (lisp-stream-misc syn) syn operation arg1 arg2)))
801         (stream-misc-dispatch syn operation arg1 arg2))))
802 \f
803 ;;;; two-way streams
804
805 (defstruct (two-way-stream
806             (:include lisp-stream
807                       (in #'two-way-in)
808                       (bin #'two-way-bin)
809                       (n-bin #'two-way-n-bin)
810                       (out #'two-way-out)
811                       (bout #'two-way-bout)
812                       (sout #'two-way-sout)
813                       (misc #'two-way-misc))
814             (:constructor #!-high-security-support
815                           make-two-way-stream
816                           #!+high-security-support
817                           %make-two-way-stream (input-stream output-stream))
818             (:copier nil))
819   (input-stream (required-argument) :type stream :read-only t)
820   (output-stream (required-argument) :type stream :read-only t))
821 (defprinter (two-way-stream) input-stream output-stream)
822
823 #!-high-security-support
824 (setf (fdocumentation 'make-two-way-stream 'function)
825   "Return a bidirectional stream which gets its input from Input-Stream and
826    sends its output to Output-Stream.")
827 #!+high-security-support
828 (defun make-two-way-stream (input-stream output-stream)
829   #!+sb-doc
830   "Return a bidirectional stream which gets its input from Input-Stream and
831    sends its output to Output-Stream."
832   ;; FIXME: This idiom of the-real-stream-of-a-possibly-synonym-stream
833   ;; should be encapsulated in a function, and used here and most of
834   ;; the other places that SYNONYM-STREAM-P appears.
835   (unless (or (and (synonym-stream-p output-stream)
836                    (output-stream-p (symbol-value
837                                      (synonym-stream-symbol output-stream))))
838               (output-stream-p output-stream))
839     (error 'type-error
840            :datum output-stream
841            :expected-type '(satisfies output-stream-p)))
842   (unless (or (and (synonym-stream-p input-stream)
843                    (input-stream-p (symbol-value
844                                     (synonym-stream-symbol input-stream))))
845               (input-stream-p input-stream))
846     (error 'type-error
847            :datum input-stream
848            :expected-type '(satisfies input-stream-p)))
849   (funcall #'%make-two-way-stream input-stream output-stream))
850
851 (macrolet ((out-fun (name slot stream-method &rest args)
852              `(defun ,name (stream ,@args)
853                 (let ((syn (two-way-stream-output-stream stream)))
854                   (if (lisp-stream-p syn)
855                       (funcall (,slot syn) syn ,@args)
856                       (,stream-method syn ,@args))))))
857   (out-fun two-way-out lisp-stream-out stream-write-char ch)
858   (out-fun two-way-bout lisp-stream-bout stream-write-byte n)
859   (out-fun two-way-sout lisp-stream-sout stream-write-string string start end))
860
861 (macrolet ((in-fun (name fun &rest args)
862              `(defun ,name (stream ,@args)
863                 (force-output (two-way-stream-output-stream stream))
864                 (,fun (two-way-stream-input-stream stream) ,@args))))
865   (in-fun two-way-in read-char eof-error-p eof-value)
866   (in-fun two-way-bin read-byte eof-error-p eof-value)
867   (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
868
869 (defun two-way-misc (stream operation &optional arg1 arg2)
870   (let* ((in (two-way-stream-input-stream stream))
871          (out (two-way-stream-output-stream stream))
872          (in-lisp-stream-p (lisp-stream-p in))
873          (out-lisp-stream-p (lisp-stream-p out)))
874     (case operation
875       (:listen
876        (if in-lisp-stream-p
877            (or (/= (the fixnum (lisp-stream-in-index in)) +in-buffer-length+)
878                (funcall (lisp-stream-misc in) in :listen))
879            (stream-listen in)))
880       ((:finish-output :force-output :clear-output)
881        (if out-lisp-stream-p
882            (funcall (lisp-stream-misc out) out operation arg1 arg2)
883            (stream-misc-dispatch out operation arg1 arg2)))
884       (:clear-input (clear-input in))
885       (:unread (unread-char arg1 in))
886       (:element-type
887        (let ((in-type (stream-element-type in))
888              (out-type (stream-element-type out)))
889          (if (equal in-type out-type)
890              in-type `(and ,in-type ,out-type))))
891       (:close
892        (set-closed-flame stream))
893       (t
894        (or (if in-lisp-stream-p
895                (funcall (lisp-stream-misc in) in operation arg1 arg2)
896                (stream-misc-dispatch in operation arg1 arg2))
897            (if out-lisp-stream-p
898                (funcall (lisp-stream-misc out) out operation arg1 arg2)
899                (stream-misc-dispatch out operation arg1 arg2)))))))
900 \f
901 ;;;; concatenated streams
902
903 (defstruct (concatenated-stream
904             (:include lisp-stream
905                       (in #'concatenated-in)
906                       (bin #'concatenated-bin)
907                       (n-bin #'concatenated-n-bin)
908                       (misc #'concatenated-misc))
909             (:constructor
910              #!-high-security-support make-concatenated-stream
911              #!+high-security-support %make-concatenated-stream
912                  (&rest streams &aux (current streams)))
913             (:copier nil))
914   ;; The car of this is the substream we are reading from now.
915   current
916   ;; This is a list of all the substreams there ever were. We need to
917   ;; remember them so that we can close them.
918   ;;
919   ;; FIXME: ANSI says this is supposed to be the list of streams that
920   ;; we still have to read from. So either this needs to become a
921   ;; private member %STREAM (with CONCATENATED-STREAM-STREAMS a wrapper
922   ;; around it which discards closed files from the head of the list)
923   ;; or we need to update it as we run out of files.
924   (streams nil :type list :read-only t))
925 (def!method print-object ((x concatenated-stream) stream)
926   (print-unreadable-object (x stream :type t :identity t)
927     (format stream
928             ":STREAMS ~S"
929             (concatenated-stream-streams x))))
930
931 #!-high-security-support
932 (setf (fdocumentation 'make-concatenated-stream 'function)
933   "Returns a stream which takes its input from each of the Streams in turn,
934    going on to the next at EOF.")
935
936 #!+high-security-support
937 (defun make-concatenated-stream (&rest streams)
938   #!+sb-doc
939   "Returns a stream which takes its input from each of the Streams in turn,
940    going on to the next at EOF."
941   (dolist (stream streams)
942     (unless (or (and (synonym-stream-p stream)
943                      (input-stream-p (symbol-value
944                                       (synonym-stream-symbol stream))))
945                 (input-stream-p stream))
946       (error 'type-error
947              :datum stream
948              :expected-type '(satisfies input-stream-p))))
949   (apply #'%make-concatenated-stream streams))
950
951 (macrolet ((in-fun (name fun)
952              `(defun ,name (stream eof-error-p eof-value)
953                 (do ((current (concatenated-stream-current stream)
954                               (cdr current)))
955                     ((null current)
956                      (eof-or-lose stream eof-error-p eof-value))
957                   (let* ((stream (car current))
958                          (result (,fun stream nil nil)))
959                     (when result (return result)))
960                   (setf (concatenated-stream-current stream) current)))))
961   (in-fun concatenated-in read-char)
962   (in-fun concatenated-bin read-byte))
963
964 (defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
965   (do ((current (concatenated-stream-current stream) (cdr current))
966        (current-start start)
967        (remaining-bytes numbytes))
968       ((null current)
969        (if eof-errorp
970            (error 'end-of-file :stream stream)
971            (- numbytes remaining-bytes)))
972     (let* ((stream (car current))
973            (bytes-read (read-n-bytes stream buffer current-start
974                                      remaining-bytes nil)))
975       (incf current-start bytes-read)
976       (decf remaining-bytes bytes-read)
977       (when (zerop remaining-bytes) (return numbytes)))
978     (setf (concatenated-stream-current stream) (cdr current))))
979
980 (defun concatenated-misc (stream operation &optional arg1 arg2)
981   (let ((left (concatenated-stream-current stream)))
982     (when left
983       (let* ((current (car left)))
984         (case operation
985           (:listen
986            (loop
987              (let ((stuff (if (lisp-stream-p current)
988                               (funcall (lisp-stream-misc current) current
989                                        :listen)
990                               (stream-misc-dispatch current :listen))))
991                (cond ((eq stuff :eof)
992                       ;; Advance CURRENT, and try again.
993                       (pop (concatenated-stream-current stream))
994                       (setf current
995                             (car (concatenated-stream-current stream)))
996                       (unless current
997                         ;; No further streams. EOF.
998                         (return :eof)))
999                      (stuff
1000                       ;; Stuff's available.
1001                       (return t))
1002                      (t
1003                       ;; Nothing is available yet.
1004                       (return nil))))))
1005           (:clear-input (clear-input current))
1006           (:unread (unread-char arg1 current))
1007           (:close
1008            (set-closed-flame stream))
1009           (t
1010            (if (lisp-stream-p current)
1011                (funcall (lisp-stream-misc current) current operation arg1 arg2)
1012                (stream-misc-dispatch current operation arg1 arg2))))))))
1013 \f
1014 ;;;; echo streams
1015
1016 (defstruct (echo-stream
1017             (:include two-way-stream
1018                       (in #'echo-in)
1019                       (bin #'echo-bin)
1020                       (misc #'echo-misc)
1021                       (n-bin #'ill-bin))
1022             (:constructor make-echo-stream (input-stream output-stream))
1023             (:copier nil))
1024   unread-stuff)
1025 (def!method print-object ((x echo-stream) stream)
1026   (print-unreadable-object (x stream :type t :identity t)
1027     (format stream
1028             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
1029             (two-way-stream-input-stream x)
1030             (two-way-stream-output-stream x))))
1031
1032 (macrolet ((in-fun (name fun out-slot stream-method &rest args)
1033              `(defun ,name (stream ,@args)
1034                 (or (pop (echo-stream-unread-stuff stream))
1035                     (let* ((in (echo-stream-input-stream stream))
1036                            (out (echo-stream-output-stream stream))
1037                            (result (,fun in ,@args)))
1038                       (if (lisp-stream-p out)
1039                           (funcall (,out-slot out) out result)
1040                           (,stream-method out result))
1041                       result)))))
1042   (in-fun echo-in read-char lisp-stream-out stream-write-char
1043           eof-error-p eof-value)
1044   (in-fun echo-bin read-byte lisp-stream-bout stream-write-byte
1045           eof-error-p eof-value))
1046
1047 (defun echo-misc (stream operation &optional arg1 arg2)
1048   (let* ((in (two-way-stream-input-stream stream))
1049          (out (two-way-stream-output-stream stream)))
1050     (case operation
1051       (:listen
1052        (or (not (null (echo-stream-unread-stuff stream)))
1053            (if (lisp-stream-p in)
1054                (or (/= (the fixnum (lisp-stream-in-index in))
1055                        +in-buffer-length+)
1056                    (funcall (lisp-stream-misc in) in :listen))
1057                (stream-misc-dispatch in :listen))))
1058       (:unread (push arg1 (echo-stream-unread-stuff stream)))
1059       (:element-type
1060        (let ((in-type (stream-element-type in))
1061              (out-type (stream-element-type out)))
1062          (if (equal in-type out-type)
1063              in-type `(and ,in-type ,out-type))))
1064       (:close
1065        (set-closed-flame stream))
1066       (t
1067        (or (if (lisp-stream-p in)
1068                (funcall (lisp-stream-misc in) in operation arg1 arg2)
1069                (stream-misc-dispatch in operation arg1 arg2))
1070            (if (lisp-stream-p out)
1071                (funcall (lisp-stream-misc out) out operation arg1 arg2)
1072                (stream-misc-dispatch out operation arg1 arg2)))))))
1073
1074 #!+sb-doc
1075 (setf (fdocumentation 'make-echo-stream 'function)
1076   "Returns a bidirectional stream which gets its input from Input-Stream and
1077    sends its output to Output-Stream. In addition, all input is echoed to
1078    the output stream")
1079 \f
1080 ;;;; string input streams
1081
1082 (defstruct (string-input-stream
1083              (:include lisp-stream
1084                        (in #'string-inch)
1085                        (bin #'string-binch)
1086                        (n-bin #'string-stream-read-n-bytes)
1087                        (misc #'string-in-misc))
1088              (:constructor internal-make-string-input-stream
1089                            (string current end))
1090              (:copier nil))
1091   (string nil :type simple-string)
1092   (current nil :type index)
1093   (end nil :type index))
1094
1095 (defun string-inch (stream eof-error-p eof-value)
1096   (let ((string (string-input-stream-string stream))
1097         (index (string-input-stream-current stream)))
1098     (declare (simple-string string) (fixnum index))
1099     (cond ((= index (the index (string-input-stream-end stream)))
1100            (eof-or-lose stream eof-error-p eof-value))
1101           (t
1102            (setf (string-input-stream-current stream) (1+ index))
1103            (aref string index)))))
1104
1105 (defun string-binch (stream eof-error-p eof-value)
1106   (let ((string (string-input-stream-string stream))
1107         (index (string-input-stream-current stream)))
1108     (declare (simple-string string)
1109              (type index index))
1110     (cond ((= index (the index (string-input-stream-end stream)))
1111            (eof-or-lose stream eof-error-p eof-value))
1112           (t
1113            (setf (string-input-stream-current stream) (1+ index))
1114            (char-code (aref string index))))))
1115
1116 (defun string-stream-read-n-bytes (stream buffer start requested eof-error-p)
1117   (declare (type string-input-stream stream)
1118            (type index start requested))
1119   (let* ((string (string-input-stream-string stream))
1120          (index (string-input-stream-current stream))
1121          (available (- (string-input-stream-end stream) index))
1122          (copy (min available requested)))
1123     (declare (simple-string string)
1124              (type index index available copy))
1125     (when (plusp copy)
1126       (setf (string-input-stream-current stream)
1127             (truly-the index (+ index copy)))
1128       (sb!sys:without-gcing
1129        (system-area-copy (vector-sap string)
1130                          (* index sb!vm:byte-bits)
1131                          (if (typep buffer 'system-area-pointer)
1132                              buffer
1133                              (vector-sap buffer))
1134                          (* start sb!vm:byte-bits)
1135                          (* copy sb!vm:byte-bits))))
1136     (if (and (> requested copy) eof-error-p)
1137         (error 'end-of-file :stream stream)
1138         copy)))
1139
1140 (defun string-in-misc (stream operation &optional arg1 arg2)
1141   (declare (ignore arg2))
1142   (case operation
1143     (:file-position
1144      (if arg1
1145          (setf (string-input-stream-current stream) arg1)
1146          (string-input-stream-current stream)))
1147     (:file-length (length (string-input-stream-string stream)))
1148     (:unread (decf (string-input-stream-current stream)))
1149     (:listen (or (/= (the fixnum (string-input-stream-current stream))
1150                      (the fixnum (string-input-stream-end stream)))
1151                  :eof))
1152     (:element-type 'base-char)))
1153
1154 (defun make-string-input-stream (string &optional
1155                                         (start 0) (end (length string)))
1156   #!+sb-doc
1157   "Returns an input stream which will supply the characters of String between
1158   Start and End in order."
1159   (declare (type string string)
1160            (type index start)
1161            (type (or index null) end))
1162
1163   #!+high-security
1164   (when (> end (length string))
1165     (cerror "Continue with end changed from ~S to ~S"
1166             "Write-string: end (~S) is larger then the length of the string (~S)"
1167             end (1- (length string))))
1168
1169   (internal-make-string-input-stream (coerce string 'simple-string)
1170                                      start end))
1171 \f
1172 ;;;; string output streams
1173
1174 (defstruct (string-output-stream
1175             (:include lisp-stream
1176                       (out #'string-ouch)
1177                       (sout #'string-sout)
1178                       (misc #'string-out-misc))
1179             (:constructor make-string-output-stream ())
1180             (:copier nil))
1181   ;; The string we throw stuff in.
1182   (string (make-string 40) :type simple-string)
1183   ;; Index of the next location to use.
1184   (index 0 :type fixnum))
1185
1186 #!+sb-doc
1187 (setf (fdocumentation 'make-string-output-stream 'function)
1188   "Returns an Output stream which will accumulate all output given it for
1189    the benefit of the function Get-Output-Stream-String.")
1190
1191 (defun string-ouch (stream character)
1192   (let ((current (string-output-stream-index stream))
1193         (workspace (string-output-stream-string stream)))
1194     (declare (simple-string workspace) (fixnum current))
1195     (if (= current (the fixnum (length workspace)))
1196         (let ((new-workspace (make-string (* current 2))))
1197           (replace new-workspace workspace)
1198           (setf (aref new-workspace current) character)
1199           (setf (string-output-stream-string stream) new-workspace))
1200         (setf (aref workspace current) character))
1201     (setf (string-output-stream-index stream) (1+ current))))
1202
1203 (defun string-sout (stream string start end)
1204   (declare (simple-string string) (fixnum start end))
1205   (let* ((current (string-output-stream-index stream))
1206          (length (- end start))
1207          (dst-end (+ length current))
1208          (workspace (string-output-stream-string stream)))
1209     (declare (simple-string workspace)
1210              (fixnum current length dst-end))
1211     (if (> dst-end (the fixnum (length workspace)))
1212         (let ((new-workspace (make-string (+ (* current 2) length))))
1213           (replace new-workspace workspace :end2 current)
1214           (replace new-workspace string
1215                    :start1 current :end1 dst-end
1216                    :start2 start :end2 end)
1217           (setf (string-output-stream-string stream) new-workspace))
1218         (replace workspace string
1219                  :start1 current :end1 dst-end
1220                  :start2 start :end2 end))
1221     (setf (string-output-stream-index stream) dst-end)))
1222
1223 (defun string-out-misc (stream operation &optional arg1 arg2)
1224   (declare (ignore arg2))
1225   (case operation
1226     (:file-position
1227      (if (null arg1)
1228          (string-output-stream-index stream)))
1229     (:charpos
1230      (do ((index (1- (the fixnum (string-output-stream-index stream)))
1231                  (1- index))
1232           (count 0 (1+ count))
1233           (string (string-output-stream-string stream)))
1234          ((< index 0) count)
1235        (declare (simple-string string)
1236                 (fixnum index count))
1237        (if (char= (schar string index) #\newline)
1238            (return count))))
1239     (:element-type 'base-char)))
1240
1241 ;;; Return a string of all the characters sent to a stream made by
1242 ;;; MAKE-STRING-OUTPUT-STREAM since the last call to this function.
1243 (defun get-output-stream-string (stream)
1244   (declare (type string-output-stream stream))
1245   (let* ((length (string-output-stream-index stream))
1246          (result (make-string length)))
1247     (replace result (string-output-stream-string stream))
1248     (setf (string-output-stream-index stream) 0)
1249     result))
1250
1251 ;;; Dump the characters buffer up in IN-STREAM to OUT-STREAM as
1252 ;;; GET-OUTPUT-STREAM-STRING would return them.
1253 (defun dump-output-stream-string (in-stream out-stream)
1254   (write-string* (string-output-stream-string in-stream) out-stream
1255                  0 (string-output-stream-index in-stream))
1256   (setf (string-output-stream-index in-stream) 0))
1257 \f
1258 ;;;; fill-pointer streams
1259
1260 ;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
1261 ;;; the CLM, but they are required for the implementation of
1262 ;;; WITH-OUTPUT-TO-STRING.
1263
1264 (defstruct (fill-pointer-output-stream
1265             (:include lisp-stream
1266                       (out #'fill-pointer-ouch)
1267                       (sout #'fill-pointer-sout)
1268                       (misc #'fill-pointer-misc))
1269             (:constructor make-fill-pointer-output-stream (string))
1270             (:copier nil))
1271   ;; the string we throw stuff in
1272   string)
1273
1274 (defun fill-pointer-ouch (stream character)
1275   (let* ((buffer (fill-pointer-output-stream-string stream))
1276          (current (fill-pointer buffer))
1277          (current+1 (1+ current)))
1278     (declare (fixnum current))
1279     (with-array-data ((workspace buffer) (start) (end))
1280       (declare (simple-string workspace))
1281       (let ((offset-current (+ start current)))
1282         (declare (fixnum offset-current))
1283         (if (= offset-current end)
1284             (let* ((new-length (* current 2))
1285                    (new-workspace (make-string new-length)))
1286               (declare (simple-string new-workspace))
1287               (%primitive sb!c:byte-blt
1288                           workspace
1289                           start
1290                           new-workspace
1291                           0
1292                           current)
1293               (setf workspace new-workspace)
1294               (setf offset-current current)
1295               (set-array-header buffer workspace new-length
1296                                 current+1 0 new-length nil))
1297             (setf (fill-pointer buffer) current+1))
1298         (setf (schar workspace offset-current) character)))
1299     current+1))
1300
1301 (defun fill-pointer-sout (stream string start end)
1302   (declare (simple-string string) (fixnum start end))
1303   (let* ((buffer (fill-pointer-output-stream-string stream))
1304          (current (fill-pointer buffer))
1305          (string-len (- end start))
1306          (dst-end (+ string-len current)))
1307     (declare (fixnum current dst-end string-len))
1308     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1309       (declare (simple-string workspace))
1310       (let ((offset-dst-end (+ dst-start dst-end))
1311             (offset-current (+ dst-start current)))
1312         (declare (fixnum offset-dst-end offset-current))
1313         (if (> offset-dst-end dst-length)
1314             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1315                    (new-workspace (make-string new-length)))
1316               (declare (simple-string new-workspace))
1317               (%primitive sb!c:byte-blt
1318                           workspace
1319                           dst-start
1320                           new-workspace
1321                           0
1322                           current)
1323               (setf workspace new-workspace)
1324               (setf offset-current current)
1325               (setf offset-dst-end dst-end)
1326               (set-array-header buffer
1327                                 workspace
1328                                 new-length
1329                                 dst-end
1330                                 0
1331                                 new-length
1332                                 nil))
1333             (setf (fill-pointer buffer) dst-end))
1334         (%primitive sb!c:byte-blt
1335                     string
1336                     start
1337                     workspace
1338                     offset-current
1339                     offset-dst-end)))
1340     dst-end))
1341
1342 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1343   (declare (ignore arg1 arg2))
1344   (case operation
1345     (:charpos
1346      (let* ((buffer (fill-pointer-output-stream-string stream))
1347             (current (fill-pointer buffer)))
1348        (with-array-data ((string buffer) (start) (end current))
1349          (declare (simple-string string) (ignore start))
1350          (let ((found (position #\newline string :test #'char=
1351                                 :end end :from-end t)))
1352            (if found
1353                (- end (the fixnum found))
1354                current)))))
1355      (:element-type 'base-char)))
1356 \f
1357 ;;;; indenting streams
1358
1359 (defstruct (indenting-stream (:include lisp-stream
1360                                        (out #'indenting-out)
1361                                        (sout #'indenting-sout)
1362                                        (misc #'indenting-misc))
1363                              (:constructor make-indenting-stream (stream))
1364                              (:copier nil))
1365   ;; the stream we're based on
1366   stream
1367   ;; how much we indent on each line
1368   (indentation 0))
1369
1370 #!+sb-doc
1371 (setf (fdocumentation 'make-indenting-stream 'function)
1372  "Returns an output stream which indents its output by some amount.")
1373
1374 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1375 ;;; output on the given STREAM based on the specified SUB-STREAM.
1376 (defmacro indenting-indent (stream sub-stream)
1377   ;; KLUDGE: bare magic number 60
1378   `(do ((i 0 (+ i 60))
1379         (indentation (indenting-stream-indentation ,stream)))
1380        ((>= i indentation))
1381      (write-string*
1382       "                                                     "
1383       ,sub-stream 0 (min 60 (- indentation i)))))
1384
1385 ;;; INDENTING-OUT writes a character to an indenting stream.
1386 (defun indenting-out (stream char)
1387   (let ((sub-stream (indenting-stream-stream stream)))
1388     (write-char char sub-stream)
1389     (if (char= char #\newline)
1390         (indenting-indent stream sub-stream))))
1391
1392 ;;; INDENTING-SOUT writes a string to an indenting stream.
1393 (defun indenting-sout (stream string start end)
1394   (declare (simple-string string) (fixnum start end))
1395   (do ((i start)
1396        (sub-stream (indenting-stream-stream stream)))
1397       ((= i end))
1398     (let ((newline (position #\newline string :start i :end end)))
1399       (cond (newline
1400              (write-string* string sub-stream i (1+ newline))
1401              (indenting-indent stream sub-stream)
1402              (setq i (+ newline 1)))
1403             (t
1404              (write-string* string sub-stream i end)
1405              (setq i end))))))
1406
1407 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1408 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1409 ;;; the base stream minus the stream's indentation.
1410 (defun indenting-misc (stream operation &optional arg1 arg2)
1411   (let ((sub-stream (indenting-stream-stream stream)))
1412     (if (lisp-stream-p sub-stream)
1413         (let ((method (lisp-stream-misc sub-stream)))
1414           (case operation
1415             (:line-length
1416              (let ((line-length (funcall method sub-stream operation)))
1417                (if line-length
1418                    (- line-length (indenting-stream-indentation stream)))))
1419             (:charpos
1420              (let ((charpos (funcall method sub-stream operation)))
1421                (if charpos
1422                    (- charpos (indenting-stream-indentation stream)))))
1423             (t
1424              (funcall method sub-stream operation arg1 arg2))))
1425         ;; must be Gray streams FUNDAMENTAL-STREAM
1426         (case operation
1427           (:line-length
1428            (let ((line-length (stream-line-length sub-stream)))
1429              (if line-length
1430                  (- line-length (indenting-stream-indentation stream)))))
1431           (:charpos
1432            (let ((charpos (stream-line-column sub-stream)))
1433              (if charpos
1434                  (- charpos (indenting-stream-indentation stream)))))
1435           (t
1436            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1437
1438 (declaim (maybe-inline read-char unread-char read-byte listen))
1439 \f
1440 ;;;; case frobbing streams, used by FORMAT ~(...~)
1441
1442 (defstruct (case-frob-stream
1443             (:include lisp-stream
1444                       (:misc #'case-frob-misc))
1445             (:constructor %make-case-frob-stream (target out sout))
1446             (:copier nil))
1447   (target (required-argument) :type stream))
1448
1449 (defun make-case-frob-stream (target kind)
1450   #!+sb-doc
1451   "Returns a stream that sends all output to the stream TARGET, but modifies
1452    the case of letters, depending on KIND, which should be one of:
1453      :upcase - convert to upper case.
1454      :downcase - convert to lower case.
1455      :capitalize - convert the first letter of words to upper case and the
1456         rest of the word to lower case.
1457      :capitalize-first - convert the first letter of the first word to upper
1458         case and everything else to lower case."
1459   (declare (type stream target)
1460            (type (member :upcase :downcase :capitalize :capitalize-first)
1461                  kind)
1462            (values stream))
1463   (if (case-frob-stream-p target)
1464       ;; If we are going to be writing to a stream that already does
1465       ;; case frobbing, why bother frobbing the case just so it can
1466       ;; frob it again?
1467       target
1468       (multiple-value-bind (out sout)
1469           (ecase kind
1470             (:upcase
1471              (values #'case-frob-upcase-out
1472                      #'case-frob-upcase-sout))
1473             (:downcase
1474              (values #'case-frob-downcase-out
1475                      #'case-frob-downcase-sout))
1476             (:capitalize
1477              (values #'case-frob-capitalize-out
1478                      #'case-frob-capitalize-sout))
1479             (:capitalize-first
1480              (values #'case-frob-capitalize-first-out
1481                      #'case-frob-capitalize-first-sout)))
1482         (%make-case-frob-stream target out sout))))
1483
1484 (defun case-frob-misc (stream op &optional arg1 arg2)
1485   (declare (type case-frob-stream stream))
1486   (case op
1487     (:close)
1488     (t
1489      (let ((target (case-frob-stream-target stream)))
1490        (if (lisp-stream-p target)
1491            (funcall (lisp-stream-misc target) target op arg1 arg2)
1492            (stream-misc-dispatch target op arg1 arg2))))))
1493
1494 (defun case-frob-upcase-out (stream char)
1495   (declare (type case-frob-stream stream)
1496            (type base-char char))
1497   (let ((target (case-frob-stream-target stream))
1498         (char (char-upcase char)))
1499     (if (lisp-stream-p target)
1500         (funcall (lisp-stream-out target) target char)
1501         (stream-write-char target char))))
1502
1503 (defun case-frob-upcase-sout (stream str start end)
1504   (declare (type case-frob-stream stream)
1505            (type simple-base-string str)
1506            (type index start)
1507            (type (or index null) end))
1508   (let* ((target (case-frob-stream-target stream))
1509          (len (length str))
1510          (end (or end len))
1511          (string (if (and (zerop start) (= len end))
1512                      (string-upcase str)
1513                      (nstring-upcase (subseq str start end))))
1514          (string-len (- end start)))
1515     (if (lisp-stream-p target)
1516         (funcall (lisp-stream-sout target) target string 0 string-len)
1517         (stream-write-string target string 0 string-len))))
1518
1519 (defun case-frob-downcase-out (stream char)
1520   (declare (type case-frob-stream stream)
1521            (type base-char char))
1522   (let ((target (case-frob-stream-target stream))
1523         (char (char-downcase char)))
1524     (if (lisp-stream-p target)
1525         (funcall (lisp-stream-out target) target char)
1526         (stream-write-char target char))))
1527
1528 (defun case-frob-downcase-sout (stream str start end)
1529   (declare (type case-frob-stream stream)
1530            (type simple-base-string str)
1531            (type index start)
1532            (type (or index null) end))
1533   (let* ((target (case-frob-stream-target stream))
1534          (len (length str))
1535          (end (or end len))
1536          (string (if (and (zerop start) (= len end))
1537                      (string-downcase str)
1538                      (nstring-downcase (subseq str start end))))
1539          (string-len (- end start)))
1540     (if (lisp-stream-p target)
1541         (funcall (lisp-stream-sout target) target string 0 string-len)
1542         (stream-write-string target string 0 string-len))))
1543
1544 (defun case-frob-capitalize-out (stream char)
1545   (declare (type case-frob-stream stream)
1546            (type base-char char))
1547   (let ((target (case-frob-stream-target stream)))
1548     (cond ((alphanumericp char)
1549            (let ((char (char-upcase char)))
1550              (if (lisp-stream-p target)
1551                  (funcall (lisp-stream-out target) target char)
1552                  (stream-write-char target char)))
1553            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1554            (setf (case-frob-stream-sout stream)
1555                  #'case-frob-capitalize-aux-sout))
1556           (t
1557            (if (lisp-stream-p target)
1558                (funcall (lisp-stream-out target) target char)
1559                (stream-write-char target char))))))
1560
1561 (defun case-frob-capitalize-sout (stream str start end)
1562   (declare (type case-frob-stream stream)
1563            (type simple-base-string str)
1564            (type index start)
1565            (type (or index null) end))
1566   (let* ((target (case-frob-stream-target stream))
1567          (str (subseq str start end))
1568          (len (length str))
1569          (inside-word nil))
1570     (dotimes (i len)
1571       (let ((char (schar str i)))
1572         (cond ((not (alphanumericp char))
1573                (setf inside-word nil))
1574               (inside-word
1575                (setf (schar str i) (char-downcase char)))
1576               (t
1577                (setf inside-word t)
1578                (setf (schar str i) (char-upcase char))))))
1579     (when inside-word
1580       (setf (case-frob-stream-out stream)
1581             #'case-frob-capitalize-aux-out)
1582       (setf (case-frob-stream-sout stream)
1583             #'case-frob-capitalize-aux-sout))
1584     (if (lisp-stream-p target)
1585         (funcall (lisp-stream-sout target) target str 0 len)
1586         (stream-write-string target str 0 len))))
1587
1588 (defun case-frob-capitalize-aux-out (stream char)
1589   (declare (type case-frob-stream stream)
1590            (type base-char char))
1591   (let ((target (case-frob-stream-target stream)))
1592     (cond ((alphanumericp char)
1593            (let ((char (char-downcase char)))
1594              (if (lisp-stream-p target)
1595                  (funcall (lisp-stream-out target) target char)
1596                  (stream-write-char target char))))
1597           (t
1598            (if (lisp-stream-p target)
1599                (funcall (lisp-stream-out target) target char)
1600                (stream-write-char target char))
1601            (setf (case-frob-stream-out stream)
1602                  #'case-frob-capitalize-out)
1603            (setf (case-frob-stream-sout stream)
1604                  #'case-frob-capitalize-sout)))))
1605
1606 (defun case-frob-capitalize-aux-sout (stream str start end)
1607   (declare (type case-frob-stream stream)
1608            (type simple-base-string str)
1609            (type index start)
1610            (type (or index null) end))
1611   (let* ((target (case-frob-stream-target stream))
1612          (str (subseq str start end))
1613          (len (length str))
1614          (inside-word t))
1615     (dotimes (i len)
1616       (let ((char (schar str i)))
1617         (cond ((not (alphanumericp char))
1618                (setf inside-word nil))
1619               (inside-word
1620                (setf (schar str i) (char-downcase char)))
1621               (t
1622                (setf inside-word t)
1623                (setf (schar str i) (char-upcase char))))))
1624     (unless inside-word
1625       (setf (case-frob-stream-out stream)
1626             #'case-frob-capitalize-out)
1627       (setf (case-frob-stream-sout stream)
1628             #'case-frob-capitalize-sout))
1629     (if (lisp-stream-p target)
1630         (funcall (lisp-stream-sout target) target str 0 len)
1631         (stream-write-string target str 0 len))))
1632
1633 (defun case-frob-capitalize-first-out (stream char)
1634   (declare (type case-frob-stream stream)
1635            (type base-char char))
1636   (let ((target (case-frob-stream-target stream)))
1637     (cond ((alphanumericp char)
1638            (let ((char (char-upcase char)))
1639              (if (lisp-stream-p target)
1640                  (funcall (lisp-stream-out target) target char)
1641                  (stream-write-char target char)))
1642            (setf (case-frob-stream-out stream)
1643                  #'case-frob-downcase-out)
1644            (setf (case-frob-stream-sout stream)
1645                  #'case-frob-downcase-sout))
1646           (t
1647            (if (lisp-stream-p target)
1648                (funcall (lisp-stream-out target) target char)
1649                (stream-write-char target char))))))
1650
1651 (defun case-frob-capitalize-first-sout (stream str start end)
1652   (declare (type case-frob-stream stream)
1653            (type simple-base-string str)
1654            (type index start)
1655            (type (or index null) end))
1656   (let* ((target (case-frob-stream-target stream))
1657          (str (subseq str start end))
1658          (len (length str)))
1659     (dotimes (i len)
1660       (let ((char (schar str i)))
1661         (when (alphanumericp char)
1662           (setf (schar str i) (char-upcase char))
1663           (do ((i (1+ i) (1+ i)))
1664               ((= i len))
1665             (setf (schar str i) (char-downcase (schar str i))))
1666           (setf (case-frob-stream-out stream)
1667                 #'case-frob-downcase-out)
1668           (setf (case-frob-stream-sout stream)
1669                 #'case-frob-downcase-sout)
1670           (return))))
1671     (if (lisp-stream-p target)
1672         (funcall (lisp-stream-sout target) target str 0 len)
1673         (stream-write-string target str 0 len))))
1674 \f
1675 ;;;; stream commands
1676
1677 (defstruct (stream-command (:constructor make-stream-command
1678                                          (name &optional args))
1679                            (:copier nil))
1680   (name nil :type symbol)
1681   (args nil :type list))
1682 (def!method print-object ((obj stream-command) str)
1683   (print-unreadable-object (obj str :type t :identity t)
1684     (prin1 (stream-command-name obj) str)))
1685
1686 ;;; Take a stream and wait for text or a command to appear on it. If
1687 ;;; text appears before a command, return NIL, otherwise return a
1688 ;;; command.
1689 ;;;
1690 ;;; We can't simply call the stream's misc method because NIL is an
1691 ;;; ambiguous return value: does it mean text arrived, or does it mean
1692 ;;; the stream's misc method had no :GET-COMMAND implementation? We
1693 ;;; can't return NIL until there is text input. We don't need to loop
1694 ;;; because any stream implementing :GET-COMMAND would wait until it
1695 ;;; had some input. If the LISTEN fails, then we have some stream we
1696 ;;; must wait on.
1697 (defun get-stream-command (stream)
1698   (let ((cmdp (funcall (lisp-stream-misc stream) stream :get-command)))
1699     (cond (cmdp)
1700           ((listen stream)
1701            nil)
1702           (t
1703            ;; This waits for input and returns NIL when it arrives.
1704            (unread-char (read-char stream) stream)))))
1705 \f
1706 (defun read-sequence (seq stream &key (start 0) (end nil))
1707   #!+sb-doc
1708   "Destructively modify SEQ by reading elements from STREAM.
1709   That part of SEQ bounded by START and END is destructively modified by
1710   copying successive elements into it from STREAM. If the end of file
1711   for STREAM is reached before copying all elements of the subsequence,
1712   then the extra elements near the end of sequence are not updated, and
1713   the index of the next element is returned."
1714   (declare (type sequence seq)
1715            (type stream stream)
1716            (type index start)
1717            (type sequence-end end)
1718            (values index))
1719   (let ((end (or end (length seq))))
1720     (declare (type index end))
1721     (etypecase seq
1722       (list
1723        (let ((read-function
1724               (if (subtypep (stream-element-type stream) 'character)
1725                   #'read-char
1726                   #'read-byte)))
1727          (do ((rem (nthcdr start seq) (rest rem))
1728               (i start (1+ i)))
1729              ((or (endp rem) (>= i end)) i)
1730            (declare (type list rem)
1731                     (type index i))
1732            (let ((el (funcall read-function stream nil :eof)))
1733              (when (eq el :eof)
1734                (return i))
1735              (setf (first rem) el)))))
1736       (vector
1737        (with-array-data ((data seq) (offset-start start) (offset-end end))
1738          (typecase data
1739            ((or (simple-array (unsigned-byte 8) (*))
1740                 (simple-array (signed-byte 8) (*))
1741                 simple-string)
1742             (let* ((numbytes (- end start))
1743                    (bytes-read (sb!sys:read-n-bytes stream
1744                                                     data
1745                                                     offset-start
1746                                                     numbytes
1747                                                     nil)))
1748               (if (< bytes-read numbytes)
1749                   (+ start bytes-read)
1750                   end)))
1751            (t
1752             (let ((read-function
1753                    (if (subtypep (stream-element-type stream) 'character)
1754                        #'read-char
1755                        #'read-byte)))
1756               (do ((i offset-start (1+ i)))
1757                   ((>= i offset-end) end)
1758                 (declare (type index i))
1759                 (let ((el (funcall read-function stream nil :eof)))
1760                   (when (eq el :eof)
1761                     (return (+ start (- i offset-start))))
1762                   (setf (aref data i) el)))))))))))
1763
1764 (defun write-sequence (seq stream &key (start 0) (end nil))
1765   #!+sb-doc
1766   "Write the elements of SEQ bounded by START and END to STREAM."
1767   (declare (type sequence seq)
1768            (type stream stream)
1769            (type index start)
1770            (type sequence-end end)
1771            (values sequence))
1772   (let ((end (or end (length seq))))
1773     (declare (type index start end))
1774     (etypecase seq
1775       (list
1776        (let ((write-function
1777               (if (subtypep (stream-element-type stream) 'character)
1778                   #'write-char
1779                   #'write-byte)))
1780          (do ((rem (nthcdr start seq) (rest rem))
1781               (i start (1+ i)))
1782              ((or (endp rem) (>= i end)) seq)
1783            (declare (type list rem)
1784                     (type index i))
1785            (funcall write-function (first rem) stream))))
1786       (string
1787        (write-string* seq stream start end))
1788       (vector
1789        (let ((write-function
1790               (if (subtypep (stream-element-type stream) 'character)
1791                   #'write-char
1792                   #'write-byte)))
1793          (do ((i start (1+ i)))
1794              ((>= i end) seq)
1795            (declare (type index i))
1796            (funcall write-function (aref seq i) stream)))))))
1797
1798 ;;; (These were inline throughout this file, but that's not appropriate
1799 ;;; globally.)
1800 (declaim (maybe-inline read-char unread-char read-byte listen))