0.6.11.37:
[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 ;;; We have to special-case the operations which could look at stuff in
787 ;;; the in-buffer.
788 (defun synonym-misc (stream operation &optional arg1 arg2)
789   (declare (optimize (safety 1)))
790   (let ((syn (symbol-value (synonym-stream-symbol stream))))
791     (if (lisp-stream-p syn)
792         (case operation
793           (:listen (or (/= (the fixnum (lisp-stream-in-index syn))
794                            +in-buffer-length+)
795                        (funcall (lisp-stream-misc syn) syn :listen)))
796           (t
797            (funcall (lisp-stream-misc syn) syn operation arg1 arg2)))
798         (stream-misc-dispatch syn operation arg1 arg2))))
799 \f
800 ;;;; two-way streams
801
802 (defstruct (two-way-stream
803             (:include lisp-stream
804                       (in #'two-way-in)
805                       (bin #'two-way-bin)
806                       (n-bin #'two-way-n-bin)
807                       (out #'two-way-out)
808                       (bout #'two-way-bout)
809                       (sout #'two-way-sout)
810                       (misc #'two-way-misc))
811             (:constructor #!-high-security-support
812                           make-two-way-stream
813                           #!+high-security-support
814                           %make-two-way-stream (input-stream output-stream))
815             (:copier nil))
816   (input-stream (required-argument) :type stream :read-only t)
817   (output-stream (required-argument) :type stream :read-only t))
818 (defprinter (two-way-stream) input-stream output-stream)
819
820 #!-high-security-support
821 (setf (fdocumentation 'make-two-way-stream 'function)
822   "Return a bidirectional stream which gets its input from Input-Stream and
823    sends its output to Output-Stream.")
824 #!+high-security-support
825 (defun make-two-way-stream (input-stream output-stream)
826   #!+sb-doc
827   "Return a bidirectional stream which gets its input from Input-Stream and
828    sends its output to Output-Stream."
829   ;; FIXME: This idiom of the-real-stream-of-a-possibly-synonym-stream
830   ;; should be encapsulated in a function, and used here and most of
831   ;; the other places that SYNONYM-STREAM-P appears.
832   (unless (or (and (synonym-stream-p output-stream)
833                    (output-stream-p (symbol-value
834                                      (synonym-stream-symbol output-stream))))
835               (output-stream-p output-stream))
836     (error 'type-error
837            :datum output-stream
838            :expected-type '(satisfies output-stream-p)))
839   (unless (or (and (synonym-stream-p input-stream)
840                    (input-stream-p (symbol-value
841                                     (synonym-stream-symbol input-stream))))
842               (input-stream-p input-stream))
843     (error 'type-error
844            :datum input-stream
845            :expected-type '(satisfies input-stream-p)))
846   (funcall #'%make-two-way-stream input-stream output-stream))
847
848 (macrolet ((out-fun (name slot stream-method &rest args)
849              `(defun ,name (stream ,@args)
850                 (let ((syn (two-way-stream-output-stream stream)))
851                   (if (lisp-stream-p syn)
852                       (funcall (,slot syn) syn ,@args)
853                       (,stream-method syn ,@args))))))
854   (out-fun two-way-out lisp-stream-out stream-write-char ch)
855   (out-fun two-way-bout lisp-stream-bout stream-write-byte n)
856   (out-fun two-way-sout lisp-stream-sout stream-write-string string start end))
857
858 (macrolet ((in-fun (name fun &rest args)
859              `(defun ,name (stream ,@args)
860                 (force-output (two-way-stream-output-stream stream))
861                 (,fun (two-way-stream-input-stream stream) ,@args))))
862   (in-fun two-way-in read-char eof-error-p eof-value)
863   (in-fun two-way-bin read-byte eof-error-p eof-value)
864   (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
865
866 (defun two-way-misc (stream operation &optional arg1 arg2)
867   (let* ((in (two-way-stream-input-stream stream))
868          (out (two-way-stream-output-stream stream))
869          (in-lisp-stream-p (lisp-stream-p in))
870          (out-lisp-stream-p (lisp-stream-p out)))
871     (case operation
872       (:listen
873        (if in-lisp-stream-p
874            (or (/= (the fixnum (lisp-stream-in-index in)) +in-buffer-length+)
875                (funcall (lisp-stream-misc in) in :listen))
876            (stream-listen in)))
877       ((:finish-output :force-output :clear-output)
878        (if out-lisp-stream-p
879            (funcall (lisp-stream-misc out) out operation arg1 arg2)
880            (stream-misc-dispatch out operation arg1 arg2)))
881       ((:clear-input :unread)
882        (if in-lisp-stream-p
883            (funcall (lisp-stream-misc in) in operation arg1 arg2)
884            (stream-misc-dispatch in operation arg1 arg2)))
885       (:element-type
886        (let ((in-type (stream-element-type in))
887              (out-type (stream-element-type out)))
888          (if (equal in-type out-type)
889              in-type `(and ,in-type ,out-type))))
890       (:close
891        (set-closed-flame stream))
892       (t
893        (or (if in-lisp-stream-p
894                (funcall (lisp-stream-misc in) in operation arg1 arg2)
895                (stream-misc-dispatch in operation arg1 arg2))
896            (if out-lisp-stream-p
897                (funcall (lisp-stream-misc out) out operation arg1 arg2)
898                (stream-misc-dispatch out operation arg1 arg2)))))))
899 \f
900 ;;;; concatenated streams
901
902 (defstruct (concatenated-stream
903             (:include lisp-stream
904                       (in #'concatenated-in)
905                       (bin #'concatenated-bin)
906                       (n-bin #'concatenated-n-bin)
907                       (misc #'concatenated-misc))
908             (:constructor
909              #!-high-security-support make-concatenated-stream
910              #!+high-security-support %make-concatenated-stream
911                  (&rest streams &aux (current streams)))
912             (:copier nil))
913   ;; The car of this is the substream we are reading from now.
914   current
915   ;; This is a list of all the substreams there ever were. We need to
916   ;; remember them so that we can close them.
917   ;;
918   ;; FIXME: ANSI says this is supposed to be the list of streams that
919   ;; we still have to read from. So either this needs to become a
920   ;; private member %STREAM (with CONCATENATED-STREAM-STREAMS a wrapper
921   ;; around it which discards closed files from the head of the list)
922   ;; or we need to update it as we run out of files.
923   (streams nil :type list :read-only t))
924 (def!method print-object ((x concatenated-stream) stream)
925   (print-unreadable-object (x stream :type t :identity t)
926     (format stream
927             ":STREAMS ~S"
928             (concatenated-stream-streams x))))
929
930 #!-high-security-support
931 (setf (fdocumentation 'make-concatenated-stream 'function)
932   "Returns a stream which takes its input from each of the Streams in turn,
933    going on to the next at EOF.")
934
935 #!+high-security-support
936 (defun make-concatenated-stream (&rest streams)
937   #!+sb-doc
938   "Returns a stream which takes its input from each of the Streams in turn,
939    going on to the next at EOF."
940   (dolist (stream streams)
941     (unless (or (and (synonym-stream-p stream)
942                      (input-stream-p (symbol-value
943                                       (synonym-stream-symbol stream))))
944                 (input-stream-p stream))
945       (error 'type-error
946              :datum stream
947              :expected-type '(satisfies input-stream-p))))
948   (apply #'%make-concatenated-stream streams))
949
950 (macrolet ((in-fun (name fun)
951              `(defun ,name (stream eof-error-p eof-value)
952                 (do ((current (concatenated-stream-current stream)
953                               (cdr current)))
954                     ((null current)
955                      (eof-or-lose stream eof-error-p eof-value))
956                   (let* ((stream (car current))
957                          (result (,fun stream nil nil)))
958                     (when result (return result)))
959                   (setf (concatenated-stream-current stream) current)))))
960   (in-fun concatenated-in read-char)
961   (in-fun concatenated-bin read-byte))
962
963 (defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
964   (do ((current (concatenated-stream-current stream) (cdr current))
965        (current-start start)
966        (remaining-bytes numbytes))
967       ((null current)
968        (if eof-errorp
969            (error 'end-of-file :stream stream)
970            (- numbytes remaining-bytes)))
971     (let* ((stream (car current))
972            (bytes-read (read-n-bytes stream buffer current-start
973                                      remaining-bytes nil)))
974       (incf current-start bytes-read)
975       (decf remaining-bytes bytes-read)
976       (when (zerop remaining-bytes) (return numbytes)))
977     (setf (concatenated-stream-current stream) (cdr current))))
978
979 (defun concatenated-misc (stream operation &optional arg1 arg2)
980   (let ((left (concatenated-stream-current stream)))
981     (when left
982       (let* ((current (car left)))
983         (case operation
984           (:listen
985            (loop
986              (let ((stuff (if (lisp-stream-p current)
987                               (funcall (lisp-stream-misc current) current
988                                        :listen)
989                               (stream-misc-dispatch current :listen))))
990                (cond ((eq stuff :eof)
991                       ;; Advance CURRENT, and try again.
992                       (pop (concatenated-stream-current stream))
993                       (setf current
994                             (car (concatenated-stream-current stream)))
995                       (unless current
996                         ;; No further streams. EOF.
997                         (return :eof)))
998                      (stuff
999                       ;; Stuff's available.
1000                       (return t))
1001                      (t
1002                       ;; Nothing is available yet.
1003                       (return nil))))))
1004           (:close
1005            (set-closed-flame stream))
1006           (t
1007            (if (lisp-stream-p current)
1008                (funcall (lisp-stream-misc current) current operation arg1 arg2)
1009                (stream-misc-dispatch current operation arg1 arg2))))))))
1010 \f
1011 ;;;; echo streams
1012
1013 (defstruct (echo-stream
1014             (:include two-way-stream
1015                       (in #'echo-in)
1016                       (bin #'echo-bin)
1017                       (misc #'echo-misc)
1018                       (n-bin #'ill-bin))
1019             (:constructor make-echo-stream (input-stream output-stream))
1020             (:copier nil))
1021   unread-stuff)
1022 (def!method print-object ((x echo-stream) stream)
1023   (print-unreadable-object (x stream :type t :identity t)
1024     (format stream
1025             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
1026             (two-way-stream-input-stream x)
1027             (two-way-stream-output-stream x))))
1028
1029 (macrolet ((in-fun (name fun out-slot stream-method &rest args)
1030              `(defun ,name (stream ,@args)
1031                 (or (pop (echo-stream-unread-stuff stream))
1032                     (let* ((in (echo-stream-input-stream stream))
1033                            (out (echo-stream-output-stream stream))
1034                            (result (,fun in ,@args)))
1035                       (if (lisp-stream-p out)
1036                           (funcall (,out-slot out) out result)
1037                           (,stream-method out result))
1038                       result)))))
1039   (in-fun echo-in read-char lisp-stream-out stream-write-char
1040           eof-error-p eof-value)
1041   (in-fun echo-bin read-byte lisp-stream-bout stream-write-byte
1042           eof-error-p eof-value))
1043
1044 (defun echo-misc (stream operation &optional arg1 arg2)
1045   (let* ((in (two-way-stream-input-stream stream))
1046          (out (two-way-stream-output-stream stream)))
1047     (case operation
1048       (:listen
1049        (or (not (null (echo-stream-unread-stuff stream)))
1050            (if (lisp-stream-p in)
1051                (or (/= (the fixnum (lisp-stream-in-index in))
1052                        +in-buffer-length+)
1053                    (funcall (lisp-stream-misc in) in :listen))
1054                (stream-misc-dispatch in :listen))))
1055       (:unread (push arg1 (echo-stream-unread-stuff stream)))
1056       (:element-type
1057        (let ((in-type (stream-element-type in))
1058              (out-type (stream-element-type out)))
1059          (if (equal in-type out-type)
1060              in-type `(and ,in-type ,out-type))))
1061       (:close
1062        (set-closed-flame stream))
1063       (t
1064        (or (if (lisp-stream-p in)
1065                (funcall (lisp-stream-misc in) in operation arg1 arg2)
1066                (stream-misc-dispatch in operation arg1 arg2))
1067            (if (lisp-stream-p out)
1068                (funcall (lisp-stream-misc out) out operation arg1 arg2)
1069                (stream-misc-dispatch out operation arg1 arg2)))))))
1070
1071 #!+sb-doc
1072 (setf (fdocumentation 'make-echo-stream 'function)
1073   "Returns a bidirectional stream which gets its input from Input-Stream and
1074    sends its output to Output-Stream. In addition, all input is echoed to
1075    the output stream")
1076 \f
1077 ;;;; string input streams
1078
1079 (defstruct (string-input-stream
1080              (:include lisp-stream
1081                        (in #'string-inch)
1082                        (bin #'string-binch)
1083                        (n-bin #'string-stream-read-n-bytes)
1084                        (misc #'string-in-misc))
1085              (:constructor internal-make-string-input-stream
1086                            (string current end))
1087              (:copier nil))
1088   (string nil :type simple-string)
1089   (current nil :type index)
1090   (end nil :type index))
1091
1092 (defun string-inch (stream eof-error-p eof-value)
1093   (let ((string (string-input-stream-string stream))
1094         (index (string-input-stream-current stream)))
1095     (declare (simple-string string) (fixnum index))
1096     (cond ((= index (the index (string-input-stream-end stream)))
1097            (eof-or-lose stream eof-error-p eof-value))
1098           (t
1099            (setf (string-input-stream-current stream) (1+ index))
1100            (aref string index)))))
1101
1102 (defun string-binch (stream eof-error-p eof-value)
1103   (let ((string (string-input-stream-string stream))
1104         (index (string-input-stream-current stream)))
1105     (declare (simple-string string)
1106              (type index index))
1107     (cond ((= index (the index (string-input-stream-end stream)))
1108            (eof-or-lose stream eof-error-p eof-value))
1109           (t
1110            (setf (string-input-stream-current stream) (1+ index))
1111            (char-code (aref string index))))))
1112
1113 (defun string-stream-read-n-bytes (stream buffer start requested eof-error-p)
1114   (declare (type string-input-stream stream)
1115            (type index start requested))
1116   (let* ((string (string-input-stream-string stream))
1117          (index (string-input-stream-current stream))
1118          (available (- (string-input-stream-end stream) index))
1119          (copy (min available requested)))
1120     (declare (simple-string string)
1121              (type index index available copy))
1122     (when (plusp copy)
1123       (setf (string-input-stream-current stream)
1124             (truly-the index (+ index copy)))
1125       (sb!sys:without-gcing
1126        (system-area-copy (vector-sap string)
1127                          (* index sb!vm:byte-bits)
1128                          (if (typep buffer 'system-area-pointer)
1129                              buffer
1130                              (vector-sap buffer))
1131                          (* start sb!vm:byte-bits)
1132                          (* copy sb!vm:byte-bits))))
1133     (if (and (> requested copy) eof-error-p)
1134         (error 'end-of-file :stream stream)
1135         copy)))
1136
1137 (defun string-in-misc (stream operation &optional arg1 arg2)
1138   (declare (ignore arg2))
1139   (case operation
1140     (:file-position
1141      (if arg1
1142          (setf (string-input-stream-current stream) arg1)
1143          (string-input-stream-current stream)))
1144     (:file-length (length (string-input-stream-string stream)))
1145     (:unread (decf (string-input-stream-current stream)))
1146     (:listen (or (/= (the fixnum (string-input-stream-current stream))
1147                      (the fixnum (string-input-stream-end stream)))
1148                  :eof))
1149     (:element-type 'base-char)))
1150
1151 (defun make-string-input-stream (string &optional
1152                                         (start 0) (end (length string)))
1153   #!+sb-doc
1154   "Returns an input stream which will supply the characters of String between
1155   Start and End in order."
1156   (declare (type string string)
1157            (type index start)
1158            (type (or index null) end))
1159
1160   #!+high-security
1161   (when (> end (length string))
1162     (cerror "Continue with end changed from ~S to ~S"
1163             "Write-string: end (~S) is larger then the length of the string (~S)"
1164             end (1- (length string))))
1165
1166   (internal-make-string-input-stream (coerce string 'simple-string)
1167                                      start end))
1168 \f
1169 ;;;; string output streams
1170
1171 (defstruct (string-output-stream
1172             (:include lisp-stream
1173                       (out #'string-ouch)
1174                       (sout #'string-sout)
1175                       (misc #'string-out-misc))
1176             (:constructor make-string-output-stream ())
1177             (:copier nil))
1178   ;; The string we throw stuff in.
1179   (string (make-string 40) :type simple-string)
1180   ;; Index of the next location to use.
1181   (index 0 :type fixnum))
1182
1183 #!+sb-doc
1184 (setf (fdocumentation 'make-string-output-stream 'function)
1185   "Returns an Output stream which will accumulate all output given it for
1186    the benefit of the function Get-Output-Stream-String.")
1187
1188 (defun string-ouch (stream character)
1189   (let ((current (string-output-stream-index stream))
1190         (workspace (string-output-stream-string stream)))
1191     (declare (simple-string workspace) (fixnum current))
1192     (if (= current (the fixnum (length workspace)))
1193         (let ((new-workspace (make-string (* current 2))))
1194           (replace new-workspace workspace)
1195           (setf (aref new-workspace current) character)
1196           (setf (string-output-stream-string stream) new-workspace))
1197         (setf (aref workspace current) character))
1198     (setf (string-output-stream-index stream) (1+ current))))
1199
1200 (defun string-sout (stream string start end)
1201   (declare (simple-string string) (fixnum start end))
1202   (let* ((current (string-output-stream-index stream))
1203          (length (- end start))
1204          (dst-end (+ length current))
1205          (workspace (string-output-stream-string stream)))
1206     (declare (simple-string workspace)
1207              (fixnum current length dst-end))
1208     (if (> dst-end (the fixnum (length workspace)))
1209         (let ((new-workspace (make-string (+ (* current 2) length))))
1210           (replace new-workspace workspace :end2 current)
1211           (replace new-workspace string
1212                    :start1 current :end1 dst-end
1213                    :start2 start :end2 end)
1214           (setf (string-output-stream-string stream) new-workspace))
1215         (replace workspace string
1216                  :start1 current :end1 dst-end
1217                  :start2 start :end2 end))
1218     (setf (string-output-stream-index stream) dst-end)))
1219
1220 (defun string-out-misc (stream operation &optional arg1 arg2)
1221   (declare (ignore arg2))
1222   (case operation
1223     (:file-position
1224      (if (null arg1)
1225          (string-output-stream-index stream)))
1226     (:charpos
1227      (do ((index (1- (the fixnum (string-output-stream-index stream)))
1228                  (1- index))
1229           (count 0 (1+ count))
1230           (string (string-output-stream-string stream)))
1231          ((< index 0) count)
1232        (declare (simple-string string)
1233                 (fixnum index count))
1234        (if (char= (schar string index) #\newline)
1235            (return count))))
1236     (:element-type 'base-char)))
1237
1238 ;;; Return a string of all the characters sent to a stream made by
1239 ;;; MAKE-STRING-OUTPUT-STREAM since the last call to this function.
1240 (defun get-output-stream-string (stream)
1241   (declare (type string-output-stream stream))
1242   (let* ((length (string-output-stream-index stream))
1243          (result (make-string length)))
1244     (replace result (string-output-stream-string stream))
1245     (setf (string-output-stream-index stream) 0)
1246     result))
1247
1248 ;;; Dump the characters buffer up in IN-STREAM to OUT-STREAM as
1249 ;;; GET-OUTPUT-STREAM-STRING would return them.
1250 (defun dump-output-stream-string (in-stream out-stream)
1251   (write-string* (string-output-stream-string in-stream) out-stream
1252                  0 (string-output-stream-index in-stream))
1253   (setf (string-output-stream-index in-stream) 0))
1254 \f
1255 ;;;; fill-pointer streams
1256
1257 ;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
1258 ;;; the CLM, but they are required for the implementation of
1259 ;;; WITH-OUTPUT-TO-STRING.
1260
1261 (defstruct (fill-pointer-output-stream
1262             (:include lisp-stream
1263                       (out #'fill-pointer-ouch)
1264                       (sout #'fill-pointer-sout)
1265                       (misc #'fill-pointer-misc))
1266             (:constructor make-fill-pointer-output-stream (string))
1267             (:copier nil))
1268   ;; the string we throw stuff in
1269   string)
1270
1271 (defun fill-pointer-ouch (stream character)
1272   (let* ((buffer (fill-pointer-output-stream-string stream))
1273          (current (fill-pointer buffer))
1274          (current+1 (1+ current)))
1275     (declare (fixnum current))
1276     (with-array-data ((workspace buffer) (start) (end))
1277       (declare (simple-string workspace))
1278       (let ((offset-current (+ start current)))
1279         (declare (fixnum offset-current))
1280         (if (= offset-current end)
1281             (let* ((new-length (* current 2))
1282                    (new-workspace (make-string new-length)))
1283               (declare (simple-string new-workspace))
1284               (%primitive sb!c:byte-blt
1285                           workspace
1286                           start
1287                           new-workspace
1288                           0
1289                           current)
1290               (setf workspace new-workspace)
1291               (setf offset-current current)
1292               (set-array-header buffer workspace new-length
1293                                 current+1 0 new-length nil))
1294             (setf (fill-pointer buffer) current+1))
1295         (setf (schar workspace offset-current) character)))
1296     current+1))
1297
1298 (defun fill-pointer-sout (stream string start end)
1299   (declare (simple-string string) (fixnum start end))
1300   (let* ((buffer (fill-pointer-output-stream-string stream))
1301          (current (fill-pointer buffer))
1302          (string-len (- end start))
1303          (dst-end (+ string-len current)))
1304     (declare (fixnum current dst-end string-len))
1305     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1306       (declare (simple-string workspace))
1307       (let ((offset-dst-end (+ dst-start dst-end))
1308             (offset-current (+ dst-start current)))
1309         (declare (fixnum offset-dst-end offset-current))
1310         (if (> offset-dst-end dst-length)
1311             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1312                    (new-workspace (make-string new-length)))
1313               (declare (simple-string new-workspace))
1314               (%primitive sb!c:byte-blt
1315                           workspace
1316                           dst-start
1317                           new-workspace
1318                           0
1319                           current)
1320               (setf workspace new-workspace)
1321               (setf offset-current current)
1322               (setf offset-dst-end dst-end)
1323               (set-array-header buffer
1324                                 workspace
1325                                 new-length
1326                                 dst-end
1327                                 0
1328                                 new-length
1329                                 nil))
1330             (setf (fill-pointer buffer) dst-end))
1331         (%primitive sb!c:byte-blt
1332                     string
1333                     start
1334                     workspace
1335                     offset-current
1336                     offset-dst-end)))
1337     dst-end))
1338
1339 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1340   (declare (ignore arg1 arg2))
1341   (case operation
1342     (:charpos
1343      (let* ((buffer (fill-pointer-output-stream-string stream))
1344             (current (fill-pointer buffer)))
1345        (with-array-data ((string buffer) (start) (end current))
1346          (declare (simple-string string) (ignore start))
1347          (let ((found (position #\newline string :test #'char=
1348                                 :end end :from-end t)))
1349            (if found
1350                (- end (the fixnum found))
1351                current)))))
1352      (:element-type 'base-char)))
1353 \f
1354 ;;;; indenting streams
1355
1356 (defstruct (indenting-stream (:include lisp-stream
1357                                        (out #'indenting-out)
1358                                        (sout #'indenting-sout)
1359                                        (misc #'indenting-misc))
1360                              (:constructor make-indenting-stream (stream))
1361                              (:copier nil))
1362   ;; the stream we're based on
1363   stream
1364   ;; how much we indent on each line
1365   (indentation 0))
1366
1367 #!+sb-doc
1368 (setf (fdocumentation 'make-indenting-stream 'function)
1369  "Returns an output stream which indents its output by some amount.")
1370
1371 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1372 ;;; output on the given STREAM based on the specified SUB-STREAM.
1373 (defmacro indenting-indent (stream sub-stream)
1374   ;; KLUDGE: bare magic number 60
1375   `(do ((i 0 (+ i 60))
1376         (indentation (indenting-stream-indentation ,stream)))
1377        ((>= i indentation))
1378      (write-string*
1379       "                                                     "
1380       ,sub-stream 0 (min 60 (- indentation i)))))
1381
1382 ;;; INDENTING-OUT writes a character to an indenting stream.
1383 (defun indenting-out (stream char)
1384   (let ((sub-stream (indenting-stream-stream stream)))
1385     (write-char char sub-stream)
1386     (if (char= char #\newline)
1387         (indenting-indent stream sub-stream))))
1388
1389 ;;; INDENTING-SOUT writes a string to an indenting stream.
1390 (defun indenting-sout (stream string start end)
1391   (declare (simple-string string) (fixnum start end))
1392   (do ((i start)
1393        (sub-stream (indenting-stream-stream stream)))
1394       ((= i end))
1395     (let ((newline (position #\newline string :start i :end end)))
1396       (cond (newline
1397              (write-string* string sub-stream i (1+ newline))
1398              (indenting-indent stream sub-stream)
1399              (setq i (+ newline 1)))
1400             (t
1401              (write-string* string sub-stream i end)
1402              (setq i end))))))
1403
1404 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1405 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1406 ;;; the base stream minus the stream's indentation.
1407 (defun indenting-misc (stream operation &optional arg1 arg2)
1408   (let ((sub-stream (indenting-stream-stream stream)))
1409     (if (lisp-stream-p sub-stream)
1410         (let ((method (lisp-stream-misc sub-stream)))
1411           (case operation
1412             (:line-length
1413              (let ((line-length (funcall method sub-stream operation)))
1414                (if line-length
1415                    (- line-length (indenting-stream-indentation stream)))))
1416             (:charpos
1417              (let ((charpos (funcall method sub-stream operation)))
1418                (if charpos
1419                    (- charpos (indenting-stream-indentation stream)))))
1420             (t
1421              (funcall method sub-stream operation arg1 arg2))))
1422         ;; must be Gray streams FUNDAMENTAL-STREAM
1423         (case operation
1424           (:line-length
1425            (let ((line-length (stream-line-length sub-stream)))
1426              (if line-length
1427                  (- line-length (indenting-stream-indentation stream)))))
1428           (:charpos
1429            (let ((charpos (stream-line-column sub-stream)))
1430              (if charpos
1431                  (- charpos (indenting-stream-indentation stream)))))
1432           (t
1433            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1434
1435 (declaim (maybe-inline read-char unread-char read-byte listen))
1436 \f
1437 ;;;; case frobbing streams, used by FORMAT ~(...~)
1438
1439 (defstruct (case-frob-stream
1440             (:include lisp-stream
1441                       (:misc #'case-frob-misc))
1442             (:constructor %make-case-frob-stream (target out sout))
1443             (:copier nil))
1444   (target (required-argument) :type stream))
1445
1446 (defun make-case-frob-stream (target kind)
1447   #!+sb-doc
1448   "Returns a stream that sends all output to the stream TARGET, but modifies
1449    the case of letters, depending on KIND, which should be one of:
1450      :upcase - convert to upper case.
1451      :downcase - convert to lower case.
1452      :capitalize - convert the first letter of words to upper case and the
1453         rest of the word to lower case.
1454      :capitalize-first - convert the first letter of the first word to upper
1455         case and everything else to lower case."
1456   (declare (type stream target)
1457            (type (member :upcase :downcase :capitalize :capitalize-first)
1458                  kind)
1459            (values stream))
1460   (if (case-frob-stream-p target)
1461       ;; If we are going to be writing to a stream that already does
1462       ;; case frobbing, why bother frobbing the case just so it can
1463       ;; frob it again?
1464       target
1465       (multiple-value-bind (out sout)
1466           (ecase kind
1467             (:upcase
1468              (values #'case-frob-upcase-out
1469                      #'case-frob-upcase-sout))
1470             (:downcase
1471              (values #'case-frob-downcase-out
1472                      #'case-frob-downcase-sout))
1473             (:capitalize
1474              (values #'case-frob-capitalize-out
1475                      #'case-frob-capitalize-sout))
1476             (:capitalize-first
1477              (values #'case-frob-capitalize-first-out
1478                      #'case-frob-capitalize-first-sout)))
1479         (%make-case-frob-stream target out sout))))
1480
1481 (defun case-frob-misc (stream op &optional arg1 arg2)
1482   (declare (type case-frob-stream stream))
1483   (case op
1484     (:close)
1485     (t
1486      (let ((target (case-frob-stream-target stream)))
1487        (if (lisp-stream-p target)
1488            (funcall (lisp-stream-misc target) target op arg1 arg2)
1489            (stream-misc-dispatch target op arg1 arg2))))))
1490
1491 (defun case-frob-upcase-out (stream char)
1492   (declare (type case-frob-stream stream)
1493            (type base-char char))
1494   (let ((target (case-frob-stream-target stream))
1495         (char (char-upcase char)))
1496     (if (lisp-stream-p target)
1497         (funcall (lisp-stream-out target) target char)
1498         (stream-write-char target char))))
1499
1500 (defun case-frob-upcase-sout (stream str start end)
1501   (declare (type case-frob-stream stream)
1502            (type simple-base-string str)
1503            (type index start)
1504            (type (or index null) end))
1505   (let* ((target (case-frob-stream-target stream))
1506          (len (length str))
1507          (end (or end len))
1508          (string (if (and (zerop start) (= len end))
1509                      (string-upcase str)
1510                      (nstring-upcase (subseq str start end))))
1511          (string-len (- end start)))
1512     (if (lisp-stream-p target)
1513         (funcall (lisp-stream-sout target) target string 0 string-len)
1514         (stream-write-string target string 0 string-len))))
1515
1516 (defun case-frob-downcase-out (stream char)
1517   (declare (type case-frob-stream stream)
1518            (type base-char char))
1519   (let ((target (case-frob-stream-target stream))
1520         (char (char-downcase char)))
1521     (if (lisp-stream-p target)
1522         (funcall (lisp-stream-out target) target char)
1523         (stream-write-char target char))))
1524
1525 (defun case-frob-downcase-sout (stream str start end)
1526   (declare (type case-frob-stream stream)
1527            (type simple-base-string str)
1528            (type index start)
1529            (type (or index null) end))
1530   (let* ((target (case-frob-stream-target stream))
1531          (len (length str))
1532          (end (or end len))
1533          (string (if (and (zerop start) (= len end))
1534                      (string-downcase str)
1535                      (nstring-downcase (subseq str start end))))
1536          (string-len (- end start)))
1537     (if (lisp-stream-p target)
1538         (funcall (lisp-stream-sout target) target string 0 string-len)
1539         (stream-write-string target string 0 string-len))))
1540
1541 (defun case-frob-capitalize-out (stream char)
1542   (declare (type case-frob-stream stream)
1543            (type base-char char))
1544   (let ((target (case-frob-stream-target stream)))
1545     (cond ((alphanumericp char)
1546            (let ((char (char-upcase char)))
1547              (if (lisp-stream-p target)
1548                  (funcall (lisp-stream-out target) target char)
1549                  (stream-write-char target char)))
1550            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1551            (setf (case-frob-stream-sout stream)
1552                  #'case-frob-capitalize-aux-sout))
1553           (t
1554            (if (lisp-stream-p target)
1555                (funcall (lisp-stream-out target) target char)
1556                (stream-write-char target char))))))
1557
1558 (defun case-frob-capitalize-sout (stream str start end)
1559   (declare (type case-frob-stream stream)
1560            (type simple-base-string str)
1561            (type index start)
1562            (type (or index null) end))
1563   (let* ((target (case-frob-stream-target stream))
1564          (str (subseq str start end))
1565          (len (length str))
1566          (inside-word nil))
1567     (dotimes (i len)
1568       (let ((char (schar str i)))
1569         (cond ((not (alphanumericp char))
1570                (setf inside-word nil))
1571               (inside-word
1572                (setf (schar str i) (char-downcase char)))
1573               (t
1574                (setf inside-word t)
1575                (setf (schar str i) (char-upcase char))))))
1576     (when inside-word
1577       (setf (case-frob-stream-out stream)
1578             #'case-frob-capitalize-aux-out)
1579       (setf (case-frob-stream-sout stream)
1580             #'case-frob-capitalize-aux-sout))
1581     (if (lisp-stream-p target)
1582         (funcall (lisp-stream-sout target) target str 0 len)
1583         (stream-write-string target str 0 len))))
1584
1585 (defun case-frob-capitalize-aux-out (stream char)
1586   (declare (type case-frob-stream stream)
1587            (type base-char char))
1588   (let ((target (case-frob-stream-target stream)))
1589     (cond ((alphanumericp char)
1590            (let ((char (char-downcase char)))
1591              (if (lisp-stream-p target)
1592                  (funcall (lisp-stream-out target) target char)
1593                  (stream-write-char target char))))
1594           (t
1595            (if (lisp-stream-p target)
1596                (funcall (lisp-stream-out target) target char)
1597                (stream-write-char target char))
1598            (setf (case-frob-stream-out stream)
1599                  #'case-frob-capitalize-out)
1600            (setf (case-frob-stream-sout stream)
1601                  #'case-frob-capitalize-sout)))))
1602
1603 (defun case-frob-capitalize-aux-sout (stream str start end)
1604   (declare (type case-frob-stream stream)
1605            (type simple-base-string str)
1606            (type index start)
1607            (type (or index null) end))
1608   (let* ((target (case-frob-stream-target stream))
1609          (str (subseq str start end))
1610          (len (length str))
1611          (inside-word t))
1612     (dotimes (i len)
1613       (let ((char (schar str i)))
1614         (cond ((not (alphanumericp char))
1615                (setf inside-word nil))
1616               (inside-word
1617                (setf (schar str i) (char-downcase char)))
1618               (t
1619                (setf inside-word t)
1620                (setf (schar str i) (char-upcase char))))))
1621     (unless inside-word
1622       (setf (case-frob-stream-out stream)
1623             #'case-frob-capitalize-out)
1624       (setf (case-frob-stream-sout stream)
1625             #'case-frob-capitalize-sout))
1626     (if (lisp-stream-p target)
1627         (funcall (lisp-stream-sout target) target str 0 len)
1628         (stream-write-string target str 0 len))))
1629
1630 (defun case-frob-capitalize-first-out (stream char)
1631   (declare (type case-frob-stream stream)
1632            (type base-char char))
1633   (let ((target (case-frob-stream-target stream)))
1634     (cond ((alphanumericp char)
1635            (let ((char (char-upcase char)))
1636              (if (lisp-stream-p target)
1637                  (funcall (lisp-stream-out target) target char)
1638                  (stream-write-char target char)))
1639            (setf (case-frob-stream-out stream)
1640                  #'case-frob-downcase-out)
1641            (setf (case-frob-stream-sout stream)
1642                  #'case-frob-downcase-sout))
1643           (t
1644            (if (lisp-stream-p target)
1645                (funcall (lisp-stream-out target) target char)
1646                (stream-write-char target char))))))
1647
1648 (defun case-frob-capitalize-first-sout (stream str start end)
1649   (declare (type case-frob-stream stream)
1650            (type simple-base-string str)
1651            (type index start)
1652            (type (or index null) end))
1653   (let* ((target (case-frob-stream-target stream))
1654          (str (subseq str start end))
1655          (len (length str)))
1656     (dotimes (i len)
1657       (let ((char (schar str i)))
1658         (when (alphanumericp char)
1659           (setf (schar str i) (char-upcase char))
1660           (do ((i (1+ i) (1+ i)))
1661               ((= i len))
1662             (setf (schar str i) (char-downcase (schar str i))))
1663           (setf (case-frob-stream-out stream)
1664                 #'case-frob-downcase-out)
1665           (setf (case-frob-stream-sout stream)
1666                 #'case-frob-downcase-sout)
1667           (return))))
1668     (if (lisp-stream-p target)
1669         (funcall (lisp-stream-sout target) target str 0 len)
1670         (stream-write-string target str 0 len))))
1671 \f
1672 ;;;; stream commands
1673
1674 (defstruct (stream-command (:constructor make-stream-command
1675                                          (name &optional args))
1676                            (:copier nil))
1677   (name nil :type symbol)
1678   (args nil :type list))
1679 (def!method print-object ((obj stream-command) str)
1680   (print-unreadable-object (obj str :type t :identity t)
1681     (prin1 (stream-command-name obj) str)))
1682
1683 ;;; Take a stream and wait for text or a command to appear on it. If
1684 ;;; text appears before a command, return NIL, otherwise return a
1685 ;;; command.
1686 ;;;
1687 ;;; We can't simply call the stream's misc method because NIL is an
1688 ;;; ambiguous return value: does it mean text arrived, or does it mean
1689 ;;; the stream's misc method had no :GET-COMMAND implementation? We
1690 ;;; can't return NIL until there is text input. We don't need to loop
1691 ;;; because any stream implementing :GET-COMMAND would wait until it
1692 ;;; had some input. If the LISTEN fails, then we have some stream we
1693 ;;; must wait on.
1694 (defun get-stream-command (stream)
1695   (let ((cmdp (funcall (lisp-stream-misc stream) stream :get-command)))
1696     (cond (cmdp)
1697           ((listen stream)
1698            nil)
1699           (t
1700            ;; This waits for input and returns NIL when it arrives.
1701            (unread-char (read-char stream) stream)))))
1702 \f
1703 (defun read-sequence (seq stream &key (start 0) (end nil))
1704   #!+sb-doc
1705   "Destructively modify SEQ by reading elements from STREAM.
1706   That part of SEQ bounded by START and END is destructively modified by
1707   copying successive elements into it from STREAM. If the end of file
1708   for STREAM is reached before copying all elements of the subsequence,
1709   then the extra elements near the end of sequence are not updated, and
1710   the index of the next element is returned."
1711   (declare (type sequence seq)
1712            (type stream stream)
1713            (type index start)
1714            (type sequence-end end)
1715            (values index))
1716   (let ((end (or end (length seq))))
1717     (declare (type index end))
1718     (etypecase seq
1719       (list
1720        (let ((read-function
1721               (if (subtypep (stream-element-type stream) 'character)
1722                   #'read-char
1723                   #'read-byte)))
1724          (do ((rem (nthcdr start seq) (rest rem))
1725               (i start (1+ i)))
1726              ((or (endp rem) (>= i end)) i)
1727            (declare (type list rem)
1728                     (type index i))
1729            (let ((el (funcall read-function stream nil :eof)))
1730              (when (eq el :eof)
1731                (return i))
1732              (setf (first rem) el)))))
1733       (vector
1734        (with-array-data ((data seq) (offset-start start) (offset-end end))
1735          (typecase data
1736            ((or (simple-array (unsigned-byte 8) (*))
1737                 (simple-array (signed-byte 8) (*))
1738                 simple-string)
1739             (let* ((numbytes (- end start))
1740                    (bytes-read (sb!sys:read-n-bytes stream
1741                                                     data
1742                                                     offset-start
1743                                                     numbytes
1744                                                     nil)))
1745               (if (< bytes-read numbytes)
1746                   (+ start bytes-read)
1747                   end)))
1748            (t
1749             (let ((read-function
1750                    (if (subtypep (stream-element-type stream) 'character)
1751                        #'read-char
1752                        #'read-byte)))
1753               (do ((i offset-start (1+ i)))
1754                   ((>= i offset-end) end)
1755                 (declare (type index i))
1756                 (let ((el (funcall read-function stream nil :eof)))
1757                   (when (eq el :eof)
1758                     (return (+ start (- i offset-start))))
1759                   (setf (aref data i) el)))))))))))
1760
1761 (defun write-sequence (seq stream &key (start 0) (end nil))
1762   #!+sb-doc
1763   "Write the elements of SEQ bounded by START and END to STREAM."
1764   (declare (type sequence seq)
1765            (type stream stream)
1766            (type index start)
1767            (type sequence-end end)
1768            (values sequence))
1769   (let ((end (or end (length seq))))
1770     (declare (type index start end))
1771     (etypecase seq
1772       (list
1773        (let ((write-function
1774               (if (subtypep (stream-element-type stream) 'character)
1775                   #'write-char
1776                   #'write-byte)))
1777          (do ((rem (nthcdr start seq) (rest rem))
1778               (i start (1+ i)))
1779              ((or (endp rem) (>= i end)) seq)
1780            (declare (type list rem)
1781                     (type index i))
1782            (funcall write-function (first rem) stream))))
1783       (string
1784        (write-string* seq stream start end))
1785       (vector
1786        (let ((write-function
1787               (if (subtypep (stream-element-type stream) 'character)
1788                   #'write-char
1789                   #'write-byte)))
1790          (do ((i start (1+ i)))
1791              ((>= i end) seq)
1792            (declare (type index i))
1793            (funcall write-function (aref seq i) stream)))))))
1794
1795 ;;; (These were inline throughout this file, but that's not appropriate
1796 ;;; globally.)
1797 (declaim (maybe-inline read-char unread-char read-byte listen))