0.pre7.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
338                             recursive-p)
339   (declare (ignore recursive-p))
340   ;; FIXME: The type of PEEK-TYPE is also declared in a DEFKNOWN, but
341   ;; the compiler doesn't seem to be smart enough to go from there to
342   ;; imposing a type check. Figure out why (because PEEK-TYPE is an
343   ;; &OPTIONAL argument?) and fix it, and then this explicit type
344   ;; check can go away.
345   (unless (typep peek-type '(or character boolean))
346     (error 'simple-type-error
347            :datum peek-type
348            :expected-type '(or character boolean)
349            :format-control "~@<bad PEEK-TYPE=~S, ~_expected ~S~:>"
350            :format-arguments (list peek-type '(or character boolean))))
351   (let ((stream (in-synonym-of stream)))
352     (if (lisp-stream-p stream)
353         (let ((char (read-char stream eof-error-p eof-value)))
354           (cond ((eq char eof-value) char)
355                 ((characterp peek-type)
356                  (do ((char char (read-char stream eof-error-p eof-value)))
357                      ((or (eq char eof-value) (char= char peek-type))
358                       (unless (eq char eof-value)
359                         (unread-char char stream))
360                       char)))
361                 ((eq peek-type t)
362                  (do ((char char (read-char stream eof-error-p eof-value)))
363                      ((or (eq char eof-value) (not (whitespace-char-p char)))
364                       (unless (eq char eof-value)
365                         (unread-char char stream))
366                       char)))
367                 ((null peek-type)
368                  (unread-char char stream)
369                  char)
370                 (t
371                  (error "internal error: impossible case"))))
372         ;; by elimination, must be Gray streams FUNDAMENTAL-STREAM
373         (cond ((characterp peek-type)
374                (do ((char (stream-read-char stream)
375                           (stream-read-char stream)))
376                    ((or (eq char :eof) (char= char peek-type))
377                     (cond ((eq char :eof)
378                            (eof-or-lose stream eof-error-p eof-value))
379                           (t
380                            (stream-unread-char stream char)
381                            char)))))
382               ((eq peek-type t)
383                (do ((char (stream-read-char stream)
384                           (stream-read-char stream)))
385                    ((or (eq char :eof) (not (whitespace-char-p char)))
386                     (cond ((eq char :eof)
387                            (eof-or-lose stream eof-error-p eof-value))
388                           (t
389                            (stream-unread-char stream char)
390                            char)))))
391               ((null peek-type)
392                (let ((char (stream-peek-char stream)))
393                  (if (eq char :eof)
394                      (eof-or-lose stream eof-error-p eof-value)
395                      char)))
396               (t
397                (error "internal error: impossible case"))))))
398
399 (defun listen (&optional (stream *standard-input*))
400   (let ((stream (in-synonym-of stream)))
401     (if (lisp-stream-p stream)
402         (or (/= (the fixnum (lisp-stream-in-index stream)) +in-buffer-length+)
403             ;; Test for T explicitly since misc methods return :EOF sometimes.
404             (eq (funcall (lisp-stream-misc stream) stream :listen) t))
405         ;; Fall through to Gray streams FUNDAMENTAL-STREAM case.
406         (stream-listen stream))))
407
408 (defun read-char-no-hang (&optional (stream *standard-input*)
409                                     (eof-error-p t)
410                                     eof-value
411                                     recursive-p)
412   (declare (ignore recursive-p))
413   (let ((stream (in-synonym-of stream)))
414     (if (lisp-stream-p stream)
415         (if (funcall (lisp-stream-misc stream) stream :listen)
416             ;; On T or :EOF get READ-CHAR to do the work.
417             (read-char stream eof-error-p eof-value)
418             nil)
419         ;; must be Gray streams FUNDAMENTAL-STREAM
420         (let ((char (stream-read-char-no-hang stream)))
421           (if (eq char :eof)
422               (eof-or-lose stream eof-error-p eof-value)
423               char)))))
424
425 (defun clear-input (&optional (stream *standard-input*))
426   (let ((stream (in-synonym-of stream)))
427     (cond ((lisp-stream-p stream)
428            (setf (lisp-stream-in-index stream) +in-buffer-length+)
429            (funcall (lisp-stream-misc stream) stream :clear-input))
430           (t
431            (stream-clear-input stream))))
432   nil)
433 \f
434 (declaim (maybe-inline read-byte))
435 (defun read-byte (stream &optional (eof-error-p t) eof-value)
436   (let ((stream (in-synonym-of stream)))
437     (if (lisp-stream-p stream)
438         (prepare-for-fast-read-byte stream
439           (prog1
440               (fast-read-byte eof-error-p eof-value t)
441             (done-with-fast-read-byte)))
442         ;; must be Gray streams FUNDAMENTAL-STREAM
443         (let ((char (stream-read-byte stream)))
444           (if (eq char :eof)
445               (eof-or-lose stream eof-error-p eof-value)
446               char)))))
447
448 ;;; Read NUMBYTES bytes into BUFFER beginning at START, and return the
449 ;;; number of bytes read.
450 ;;;
451 ;;; Note: CMU CL's version of this had a special interpretation of
452 ;;; EOF-ERROR-P which SBCL does not have. (In the EOF-ERROR-P=NIL
453 ;;; case, CMU CL's version would return as soon as any data became
454 ;;; available.) This could be useful behavior for things like pipes in
455 ;;; some cases, but it wasn't being used in SBCL, so it was dropped.
456 ;;; If we ever need it, it could be added later as a new variant N-BIN
457 ;;; method (perhaps N-BIN-ASAP?) or something.
458 (defun read-n-bytes (stream buffer start numbytes &optional (eof-error-p t))
459   (declare (type lisp-stream stream)
460            (type index numbytes start)
461            (type (or (simple-array * (*)) system-area-pointer) buffer))
462   (let* ((stream (in-synonym-of stream lisp-stream))
463          (in-buffer (lisp-stream-in-buffer stream))
464          (index (lisp-stream-in-index stream))
465          (num-buffered (- +in-buffer-length+ index)))
466     (declare (fixnum index num-buffered))
467     (cond
468      ((not in-buffer)
469       (funcall (lisp-stream-n-bin stream)
470                stream
471                buffer
472                start
473                numbytes
474                eof-error-p))
475      ((<= numbytes num-buffered)
476       (%byte-blt in-buffer index
477                  buffer start (+ start numbytes))
478       (setf (lisp-stream-in-index stream) (+ index numbytes))
479       numbytes)
480      (t
481       (let ((end (+ start num-buffered)))
482         (%byte-blt in-buffer index buffer start end)
483         (setf (lisp-stream-in-index stream) +in-buffer-length+)
484         (+ (funcall (lisp-stream-n-bin stream)
485                     stream
486                     buffer
487                     end
488                     (- numbytes num-buffered)
489                     eof-error-p)
490            num-buffered))))))
491
492 ;;; the amount of space we leave at the start of the in-buffer for
493 ;;; unreading
494 ;;;
495 ;;; (It's 4 instead of 1 to allow word-aligned copies.)
496 (defconstant +in-buffer-extra+ 4) ; FIXME: should be symbolic constant
497
498 ;;; This function is called by the FAST-READ-CHAR expansion to refill
499 ;;; the IN-BUFFER for text streams. There is definitely an IN-BUFFER,
500 ;;; and hence must be an N-BIN method.
501 (defun fast-read-char-refill (stream eof-error-p eof-value)
502   (let* ((ibuf (lisp-stream-in-buffer stream))
503          (count (funcall (lisp-stream-n-bin stream)
504                          stream
505                          ibuf
506                          +in-buffer-extra+
507                          (- +in-buffer-length+ +in-buffer-extra+)
508                          nil))
509          (start (- +in-buffer-length+ count)))
510     (declare (type index start count))
511     (cond ((zerop count)
512            (setf (lisp-stream-in-index stream) +in-buffer-length+)
513            (funcall (lisp-stream-in stream) stream eof-error-p eof-value))
514           (t
515            (when (/= start +in-buffer-extra+)
516              (bit-bash-copy ibuf (+ (* +in-buffer-extra+ sb!vm:byte-bits)
517                                     (* sb!vm:vector-data-offset
518                                        sb!vm:word-bits))
519                             ibuf (+ (the index (* start sb!vm:byte-bits))
520                                     (* sb!vm:vector-data-offset
521                                        sb!vm:word-bits))
522                             (* count sb!vm:byte-bits)))
523            (setf (lisp-stream-in-index stream) (1+ start))
524            (code-char (aref ibuf start))))))
525
526 ;;; This is similar to FAST-READ-CHAR-REFILL, but we don't have to
527 ;;; leave room for unreading.
528 (defun fast-read-byte-refill (stream eof-error-p eof-value)
529   (let* ((ibuf (lisp-stream-in-buffer stream))
530          (count (funcall (lisp-stream-n-bin stream) stream
531                          ibuf 0 +in-buffer-length+
532                          nil))
533          (start (- +in-buffer-length+ count)))
534     (declare (type index start count))
535     (cond ((zerop count)
536            (setf (lisp-stream-in-index stream) +in-buffer-length+)
537            (funcall (lisp-stream-bin stream) stream eof-error-p eof-value))
538           (t
539            (unless (zerop start)
540              (bit-bash-copy ibuf (* sb!vm:vector-data-offset sb!vm:word-bits)
541                             ibuf (+ (the index (* start sb!vm:byte-bits))
542                                     (* sb!vm:vector-data-offset
543                                        sb!vm:word-bits))
544                             (* count sb!vm:byte-bits)))
545            (setf (lisp-stream-in-index stream) (1+ start))
546            (aref ibuf start)))))
547 \f
548 ;;; output functions
549
550 (defun write-char (character &optional (stream *standard-output*))
551   (with-out-stream stream (lisp-stream-out character)
552                    (stream-write-char character))
553   character)
554
555 (defun terpri (&optional (stream *standard-output*))
556   (with-out-stream stream (lisp-stream-out #\newline) (stream-terpri))
557   nil)
558
559 (defun fresh-line (&optional (stream *standard-output*))
560   (let ((stream (out-synonym-of stream)))
561     (if (lisp-stream-p stream)
562         (when (/= (or (charpos stream) 1) 0)
563           (funcall (lisp-stream-out stream) stream #\newline)
564           t)
565         ;; must be Gray streams FUNDAMENTAL-STREAM
566         (stream-fresh-line stream))))
567
568 (defun write-string (string &optional (stream *standard-output*)
569                             &key (start 0) (end nil))
570   (%write-string string stream start (or end (length string)))
571   string)
572
573 (defun %write-string (string stream start end)
574   (declare (type string string))
575   (declare (type streamlike stream))
576   (declare (type index start end))
577
578   ;; Note that even though you might expect, based on the behavior of
579   ;; things like AREF, that the correct upper bound here is
580   ;; (ARRAY-DIMENSION STRING 0), the ANSI glossary definitions for
581   ;; "bounding index" and "length" indicate that in this case (i.e.
582   ;; for the ANSI-specified functions WRITE-STRING and WRITE-LINE
583   ;; which are implemented in terms of this function), (LENGTH STRING)
584   ;; is the required upper bound. A foolish consistency is the
585   ;; hobgoblin of lesser languages..
586   (unless (<= 0 start end (length string))
587     (error "~@<bad bounding indices START=~W END=~W for ~2I~_~S~:>"
588            start
589            end
590            string))
591
592   (let ((stream (out-synonym-of stream)))
593     (cond ((lisp-stream-p stream)
594            (if (array-header-p string)
595                (with-array-data ((data string) (offset-start start)
596                                  (offset-end end))
597                  (funcall (lisp-stream-sout stream)
598                           stream data offset-start offset-end))
599                (funcall (lisp-stream-sout stream) stream string start end))
600            string)
601           (t ; must be Gray streams FUNDAMENTAL-STREAM
602            (stream-write-string stream string start end)))))
603
604 (defun write-line (string &optional (stream *standard-output*)
605                           &key (start 0) (end nil))
606   (let ((defaulted-stream (out-synonym-of stream))
607         (defaulted-end (or end (length string))))
608     (%write-string string defaulted-stream start defaulted-end)
609     (write-char #\newline defaulted-stream))
610   string)
611
612 (defun charpos (&optional (stream *standard-output*))
613   (with-out-stream stream (lisp-stream-misc :charpos) (stream-line-column)))
614
615 (defun line-length (&optional (stream *standard-output*))
616   (with-out-stream stream (lisp-stream-misc :line-length)
617                    (stream-line-length)))
618
619 (defun finish-output (&optional (stream *standard-output*))
620   (with-out-stream stream (lisp-stream-misc :finish-output)
621                    (stream-finish-output))
622   nil)
623
624 (defun force-output (&optional (stream *standard-output*))
625   (with-out-stream stream (lisp-stream-misc :force-output)
626                    (stream-force-output))
627   nil)
628
629 (defun clear-output (&optional (stream *standard-output*))
630   (with-out-stream stream (lisp-stream-misc :clear-output)
631                    (stream-force-output))
632   nil)
633
634 (defun write-byte (integer stream)
635   (with-out-stream stream (lisp-stream-bout integer)
636                    (stream-write-byte integer))
637   integer)
638 \f
639 ;;; This is called from LISP-STREAM routines that encapsulate CLOS
640 ;;; streams to handle the misc routines and dispatch to the
641 ;;; appropriate Gray stream functions.
642 (defun stream-misc-dispatch (stream operation &optional arg1 arg2)
643   (declare (type fundamental-stream stream)
644            (ignore arg2))
645   (case operation
646     (:listen
647      ;; Return T if input available, :EOF for end-of-file, otherwise NIL.
648      (let ((char (stream-read-char-no-hang stream)))
649        (when (characterp char)
650          (stream-unread-char stream char))
651        char))
652     (:unread
653      (stream-unread-char stream arg1))
654     (:close
655      (close stream))
656     (:clear-input
657      (stream-clear-input stream))
658     (:force-output
659      (stream-force-output stream))
660     (:finish-output
661      (stream-finish-output stream))
662     (:element-type
663      (stream-element-type stream))
664     (:interactive-p
665      (interactive-stream-p stream))
666     (:line-length
667      (stream-line-length stream))
668     (:charpos
669      (stream-line-column stream))
670     (:file-length
671      (file-length stream))
672     (:file-position
673      (file-position stream arg1))))
674 \f
675 ;;;; broadcast streams
676
677 (defstruct (broadcast-stream (:include lisp-stream
678                                        (out #'broadcast-out)
679                                        (bout #'broadcast-bout)
680                                        (sout #'broadcast-sout)
681                                        (misc #'broadcast-misc))
682                              (:constructor #!-high-security-support
683                                            make-broadcast-stream
684                                            #!+high-security-support
685                                            %make-broadcast-stream (&rest
686                                                                    streams))
687                              (:copier nil))
688   ;; a list of all the streams we broadcast to
689   (streams () :type list :read-only t))
690
691 #!+high-security-support
692 (defun make-broadcast-stream (&rest streams)
693   (dolist (stream streams)
694     (unless (or (and (synonym-stream-p stream)
695                      (output-stream-p (symbol-value
696                                        (synonym-stream-symbol stream))))
697                 (output-stream-p stream))
698       (error 'type-error
699              :datum stream
700              :expected-type '(satisfies output-stream-p))))
701   (apply #'%make-broadcast-stream streams))
702
703 (macrolet ((out-fun (fun method stream-method &rest args)
704              `(defun ,fun (stream ,@args)
705                 (dolist (stream (broadcast-stream-streams stream))
706                   (if (lisp-stream-p stream)
707                       (funcall (,method stream) stream ,@args)
708                       (,stream-method stream ,@args))))))
709   (out-fun broadcast-out lisp-stream-out stream-write-char char)
710   (out-fun broadcast-bout lisp-stream-bout stream-write-byte byte)
711   (out-fun broadcast-sout lisp-stream-sout stream-write-string
712            string start end))
713
714 (defun broadcast-misc (stream operation &optional arg1 arg2)
715   (let ((streams (broadcast-stream-streams stream)))
716     (case operation
717       (:charpos
718        (dolist (stream streams)
719          (let ((charpos (charpos stream)))
720            (if charpos (return charpos)))))
721       (:line-length
722        (let ((min nil))
723          (dolist (stream streams min)
724            (let ((res (line-length stream)))
725              (when res (setq min (if min (min res min) res)))))))
726       (:element-type
727        (let (res)
728          (dolist (stream streams (if (> (length res) 1) `(and ,@res) res))
729            (pushnew (stream-element-type stream) res :test #'equal))))
730       (:close)
731       (t
732        (let ((res nil))
733          (dolist (stream streams res)
734            (setq res
735                  (if (lisp-stream-p stream)
736                      (funcall (lisp-stream-misc stream) stream operation
737                               arg1 arg2)
738                      (stream-misc-dispatch stream operation arg1 arg2)))))))))
739 \f
740 ;;;; synonym streams
741
742 (defstruct (synonym-stream (:include lisp-stream
743                                      (in #'synonym-in)
744                                      (bin #'synonym-bin)
745                                      (n-bin #'synonym-n-bin)
746                                      (out #'synonym-out)
747                                      (bout #'synonym-bout)
748                                      (sout #'synonym-sout)
749                                      (misc #'synonym-misc))
750                            (:constructor make-synonym-stream (symbol))
751                            (:copier nil))
752   ;; This is the symbol, the value of which is the stream we are synonym to.
753   (symbol nil :type symbol :read-only t))
754 (def!method print-object ((x synonym-stream) stream)
755   (print-unreadable-object (x stream :type t :identity t)
756     (format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
757
758 ;;; The output simple output methods just call the corresponding method
759 ;;; in the synonymed stream.
760 (macrolet ((out-fun (name slot stream-method &rest args)
761              `(defun ,name (stream ,@args)
762                 (declare (optimize (safety 1)))
763                 (let ((syn (symbol-value (synonym-stream-symbol stream))))
764                   (if (lisp-stream-p syn)
765                       (funcall (,slot syn) syn ,@args)
766                       (,stream-method syn ,@args))))))
767   (out-fun synonym-out lisp-stream-out stream-write-char ch)
768   (out-fun synonym-bout lisp-stream-bout stream-write-byte n)
769   (out-fun synonym-sout lisp-stream-sout stream-write-string string start end))
770
771 ;;; For the input methods, we just call the corresponding function on the
772 ;;; synonymed stream. These functions deal with getting input out of
773 ;;; the In-Buffer if there is any.
774 (macrolet ((in-fun (name fun &rest args)
775              `(defun ,name (stream ,@args)
776                 (declare (optimize (safety 1)))
777                 (,fun (symbol-value (synonym-stream-symbol stream))
778                       ,@args))))
779   (in-fun synonym-in read-char eof-error-p eof-value)
780   (in-fun synonym-bin read-byte eof-error-p eof-value)
781   (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
782
783 (defun synonym-misc (stream operation &optional arg1 arg2)
784   (declare (optimize (safety 1)))
785   (let ((syn (symbol-value (synonym-stream-symbol stream))))
786     (if (lisp-stream-p syn)
787         ;; We have to special-case some operations which interact with
788         ;; the in-buffer of the wrapped stream, since just calling
789         ;; LISP-STREAM-MISC on them
790         (case operation
791           (:listen (or (/= (the fixnum (lisp-stream-in-index syn))
792                            +in-buffer-length+)
793                        (funcall (lisp-stream-misc syn) syn :listen)))
794           (:clear-input (clear-input syn))
795           (:unread (unread-char arg1 syn))
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 (clear-input in))
882       (:unread (unread-char arg1 in))
883       (:element-type
884        (let ((in-type (stream-element-type in))
885              (out-type (stream-element-type out)))
886          (if (equal in-type out-type)
887              in-type `(and ,in-type ,out-type))))
888       (:close
889        (set-closed-flame stream))
890       (t
891        (or (if in-lisp-stream-p
892                (funcall (lisp-stream-misc in) in operation arg1 arg2)
893                (stream-misc-dispatch in operation arg1 arg2))
894            (if out-lisp-stream-p
895                (funcall (lisp-stream-misc out) out operation arg1 arg2)
896                (stream-misc-dispatch out operation arg1 arg2)))))))
897 \f
898 ;;;; concatenated streams
899
900 (defstruct (concatenated-stream
901             (:include lisp-stream
902                       (in #'concatenated-in)
903                       (bin #'concatenated-bin)
904                       (n-bin #'concatenated-n-bin)
905                       (misc #'concatenated-misc))
906             (:constructor
907              #!-high-security-support make-concatenated-stream
908              #!+high-security-support %make-concatenated-stream
909                  (&rest streams &aux (current streams)))
910             (:copier nil))
911   ;; The car of this is the substream we are reading from now.
912   current
913   ;; This is a list of all the substreams there ever were. We need to
914   ;; remember them so that we can close them.
915   ;;
916   ;; FIXME: ANSI says this is supposed to be the list of streams that
917   ;; we still have to read from. So either this needs to become a
918   ;; private member %STREAM (with CONCATENATED-STREAM-STREAMS a wrapper
919   ;; around it which discards closed files from the head of the list)
920   ;; or we need to update it as we run out of files.
921   (streams nil :type list :read-only t))
922 (def!method print-object ((x concatenated-stream) stream)
923   (print-unreadable-object (x stream :type t :identity t)
924     (format stream
925             ":STREAMS ~S"
926             (concatenated-stream-streams x))))
927
928 #!-high-security-support
929 (setf (fdocumentation 'make-concatenated-stream 'function)
930   "Returns a stream which takes its input from each of the Streams in turn,
931    going on to the next at EOF.")
932
933 #!+high-security-support
934 (defun make-concatenated-stream (&rest streams)
935   #!+sb-doc
936   "Returns a stream which takes its input from each of the Streams in turn,
937    going on to the next at EOF."
938   (dolist (stream streams)
939     (unless (or (and (synonym-stream-p stream)
940                      (input-stream-p (symbol-value
941                                       (synonym-stream-symbol stream))))
942                 (input-stream-p stream))
943       (error 'type-error
944              :datum stream
945              :expected-type '(satisfies input-stream-p))))
946   (apply #'%make-concatenated-stream streams))
947
948 (macrolet ((in-fun (name fun)
949              `(defun ,name (stream eof-error-p eof-value)
950                 (do ((current (concatenated-stream-current stream)
951                               (cdr current)))
952                     ((null current)
953                      (eof-or-lose stream eof-error-p eof-value))
954                   (let* ((stream (car current))
955                          (result (,fun stream nil nil)))
956                     (when result (return result)))
957                   (setf (concatenated-stream-current stream) current)))))
958   (in-fun concatenated-in read-char)
959   (in-fun concatenated-bin read-byte))
960
961 (defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
962   (do ((current (concatenated-stream-current stream) (cdr current))
963        (current-start start)
964        (remaining-bytes numbytes))
965       ((null current)
966        (if eof-errorp
967            (error 'end-of-file :stream stream)
968            (- numbytes remaining-bytes)))
969     (let* ((stream (car current))
970            (bytes-read (read-n-bytes stream buffer current-start
971                                      remaining-bytes nil)))
972       (incf current-start bytes-read)
973       (decf remaining-bytes bytes-read)
974       (when (zerop remaining-bytes) (return numbytes)))
975     (setf (concatenated-stream-current stream) (cdr current))))
976
977 (defun concatenated-misc (stream operation &optional arg1 arg2)
978   (let ((left (concatenated-stream-current stream)))
979     (when left
980       (let* ((current (car left)))
981         (case operation
982           (:listen
983            (loop
984              (let ((stuff (if (lisp-stream-p current)
985                               (funcall (lisp-stream-misc current) current
986                                        :listen)
987                               (stream-misc-dispatch current :listen))))
988                (cond ((eq stuff :eof)
989                       ;; Advance CURRENT, and try again.
990                       (pop (concatenated-stream-current stream))
991                       (setf current
992                             (car (concatenated-stream-current stream)))
993                       (unless current
994                         ;; No further streams. EOF.
995                         (return :eof)))
996                      (stuff
997                       ;; Stuff's available.
998                       (return t))
999                      (t
1000                       ;; Nothing is available yet.
1001                       (return nil))))))
1002           (:clear-input (clear-input current))
1003           (:unread (unread-char arg1 current))
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)
1252                  out-stream
1253                  0
1254                  (string-output-stream-index in-stream))
1255   (setf (string-output-stream-index in-stream) 0))
1256 \f
1257 ;;;; fill-pointer streams
1258
1259 ;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
1260 ;;; the CLM, but they are required for the implementation of
1261 ;;; WITH-OUTPUT-TO-STRING.
1262
1263 (defstruct (fill-pointer-output-stream
1264             (:include lisp-stream
1265                       (out #'fill-pointer-ouch)
1266                       (sout #'fill-pointer-sout)
1267                       (misc #'fill-pointer-misc))
1268             (:constructor make-fill-pointer-output-stream (string))
1269             (:copier nil))
1270   ;; the string we throw stuff in
1271   string)
1272
1273 (defun fill-pointer-ouch (stream character)
1274   (let* ((buffer (fill-pointer-output-stream-string stream))
1275          (current (fill-pointer buffer))
1276          (current+1 (1+ current)))
1277     (declare (fixnum current))
1278     (with-array-data ((workspace buffer) (start) (end))
1279       (declare (simple-string workspace))
1280       (let ((offset-current (+ start current)))
1281         (declare (fixnum offset-current))
1282         (if (= offset-current end)
1283             (let* ((new-length (1+ (* current 2)))
1284                    (new-workspace (make-string new-length)))
1285               (declare (simple-string new-workspace))
1286               (%byte-blt workspace start
1287                          new-workspace 0 current)
1288               (setf workspace new-workspace)
1289               (setf offset-current current)
1290               (set-array-header buffer workspace new-length
1291                                 current+1 0 new-length nil))
1292             (setf (fill-pointer buffer) current+1))
1293         (setf (schar workspace offset-current) character)))
1294     current+1))
1295
1296 (defun fill-pointer-sout (stream string start end)
1297   (declare (simple-string string) (fixnum start end))
1298   (let* ((buffer (fill-pointer-output-stream-string stream))
1299          (current (fill-pointer buffer))
1300          (string-len (- end start))
1301          (dst-end (+ string-len current)))
1302     (declare (fixnum current dst-end string-len))
1303     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1304       (declare (simple-string workspace))
1305       (let ((offset-dst-end (+ dst-start dst-end))
1306             (offset-current (+ dst-start current)))
1307         (declare (fixnum offset-dst-end offset-current))
1308         (if (> offset-dst-end dst-length)
1309             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1310                    (new-workspace (make-string new-length)))
1311               (declare (simple-string new-workspace))
1312               (%byte-blt workspace dst-start
1313                          new-workspace 0 current)
1314               (setf workspace new-workspace)
1315               (setf offset-current current)
1316               (setf offset-dst-end dst-end)
1317               (set-array-header buffer
1318                                 workspace
1319                                 new-length
1320                                 dst-end
1321                                 0
1322                                 new-length
1323                                 nil))
1324             (setf (fill-pointer buffer) dst-end))
1325         (%byte-blt string start
1326                    workspace offset-current offset-dst-end)))
1327     dst-end))
1328
1329 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1330   (declare (ignore arg1 arg2))
1331   (case operation
1332     (:charpos
1333      (let* ((buffer (fill-pointer-output-stream-string stream))
1334             (current (fill-pointer buffer)))
1335        (with-array-data ((string buffer) (start) (end current))
1336          (declare (simple-string string) (ignore start))
1337          (let ((found (position #\newline string :test #'char=
1338                                 :end end :from-end t)))
1339            (if found
1340                (- end (the fixnum found))
1341                current)))))
1342      (:element-type 'base-char)))
1343 \f
1344 ;;;; indenting streams
1345
1346 (defstruct (indenting-stream (:include lisp-stream
1347                                        (out #'indenting-out)
1348                                        (sout #'indenting-sout)
1349                                        (misc #'indenting-misc))
1350                              (:constructor make-indenting-stream (stream))
1351                              (:copier nil))
1352   ;; the stream we're based on
1353   stream
1354   ;; how much we indent on each line
1355   (indentation 0))
1356
1357 #!+sb-doc
1358 (setf (fdocumentation 'make-indenting-stream 'function)
1359  "Returns an output stream which indents its output by some amount.")
1360
1361 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1362 ;;; output on the given STREAM based on the specified SUB-STREAM.
1363 (defmacro indenting-indent (stream sub-stream)
1364   ;; KLUDGE: bare magic number 60
1365   `(do ((i 0 (+ i 60))
1366         (indentation (indenting-stream-indentation ,stream)))
1367        ((>= i indentation))
1368      (%write-string
1369       "                                                     "
1370       ,sub-stream
1371       0
1372       (min 60 (- indentation i)))))
1373
1374 ;;; INDENTING-OUT writes a character to an indenting stream.
1375 (defun indenting-out (stream char)
1376   (let ((sub-stream (indenting-stream-stream stream)))
1377     (write-char char sub-stream)
1378     (if (char= char #\newline)
1379         (indenting-indent stream sub-stream))))
1380
1381 ;;; INDENTING-SOUT writes a string to an indenting stream.
1382 (defun indenting-sout (stream string start end)
1383   (declare (simple-string string) (fixnum start end))
1384   (do ((i start)
1385        (sub-stream (indenting-stream-stream stream)))
1386       ((= i end))
1387     (let ((newline (position #\newline string :start i :end end)))
1388       (cond (newline
1389              (%write-string string sub-stream i (1+ newline))
1390              (indenting-indent stream sub-stream)
1391              (setq i (+ newline 1)))
1392             (t
1393              (%write-string string sub-stream i end)
1394              (setq i end))))))
1395
1396 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1397 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1398 ;;; the base stream minus the stream's indentation.
1399 (defun indenting-misc (stream operation &optional arg1 arg2)
1400   (let ((sub-stream (indenting-stream-stream stream)))
1401     (if (lisp-stream-p sub-stream)
1402         (let ((method (lisp-stream-misc sub-stream)))
1403           (case operation
1404             (:line-length
1405              (let ((line-length (funcall method sub-stream operation)))
1406                (if line-length
1407                    (- line-length (indenting-stream-indentation stream)))))
1408             (:charpos
1409              (let ((charpos (funcall method sub-stream operation)))
1410                (if charpos
1411                    (- charpos (indenting-stream-indentation stream)))))
1412             (t
1413              (funcall method sub-stream operation arg1 arg2))))
1414         ;; must be Gray streams FUNDAMENTAL-STREAM
1415         (case operation
1416           (:line-length
1417            (let ((line-length (stream-line-length sub-stream)))
1418              (if line-length
1419                  (- line-length (indenting-stream-indentation stream)))))
1420           (:charpos
1421            (let ((charpos (stream-line-column sub-stream)))
1422              (if charpos
1423                  (- charpos (indenting-stream-indentation stream)))))
1424           (t
1425            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1426
1427 (declaim (maybe-inline read-char unread-char read-byte listen))
1428 \f
1429 ;;;; case frobbing streams, used by FORMAT ~(...~)
1430
1431 (defstruct (case-frob-stream
1432             (:include lisp-stream
1433                       (:misc #'case-frob-misc))
1434             (:constructor %make-case-frob-stream (target out sout))
1435             (:copier nil))
1436   (target (required-argument) :type stream))
1437
1438 (defun make-case-frob-stream (target kind)
1439   #!+sb-doc
1440   "Returns a stream that sends all output to the stream TARGET, but modifies
1441    the case of letters, depending on KIND, which should be one of:
1442      :upcase - convert to upper case.
1443      :downcase - convert to lower case.
1444      :capitalize - convert the first letter of words to upper case and the
1445         rest of the word to lower case.
1446      :capitalize-first - convert the first letter of the first word to upper
1447         case and everything else to lower case."
1448   (declare (type stream target)
1449            (type (member :upcase :downcase :capitalize :capitalize-first)
1450                  kind)
1451            (values stream))
1452   (if (case-frob-stream-p target)
1453       ;; If we are going to be writing to a stream that already does
1454       ;; case frobbing, why bother frobbing the case just so it can
1455       ;; frob it again?
1456       target
1457       (multiple-value-bind (out sout)
1458           (ecase kind
1459             (:upcase
1460              (values #'case-frob-upcase-out
1461                      #'case-frob-upcase-sout))
1462             (:downcase
1463              (values #'case-frob-downcase-out
1464                      #'case-frob-downcase-sout))
1465             (:capitalize
1466              (values #'case-frob-capitalize-out
1467                      #'case-frob-capitalize-sout))
1468             (:capitalize-first
1469              (values #'case-frob-capitalize-first-out
1470                      #'case-frob-capitalize-first-sout)))
1471         (%make-case-frob-stream target out sout))))
1472
1473 (defun case-frob-misc (stream op &optional arg1 arg2)
1474   (declare (type case-frob-stream stream))
1475   (case op
1476     (:close)
1477     (t
1478      (let ((target (case-frob-stream-target stream)))
1479        (if (lisp-stream-p target)
1480            (funcall (lisp-stream-misc target) target op arg1 arg2)
1481            (stream-misc-dispatch target op arg1 arg2))))))
1482
1483 (defun case-frob-upcase-out (stream char)
1484   (declare (type case-frob-stream stream)
1485            (type base-char char))
1486   (let ((target (case-frob-stream-target stream))
1487         (char (char-upcase char)))
1488     (if (lisp-stream-p target)
1489         (funcall (lisp-stream-out target) target char)
1490         (stream-write-char target char))))
1491
1492 (defun case-frob-upcase-sout (stream str start end)
1493   (declare (type case-frob-stream stream)
1494            (type simple-base-string str)
1495            (type index start)
1496            (type (or index null) end))
1497   (let* ((target (case-frob-stream-target stream))
1498          (len (length str))
1499          (end (or end len))
1500          (string (if (and (zerop start) (= len end))
1501                      (string-upcase str)
1502                      (nstring-upcase (subseq str start end))))
1503          (string-len (- end start)))
1504     (if (lisp-stream-p target)
1505         (funcall (lisp-stream-sout target) target string 0 string-len)
1506         (stream-write-string target string 0 string-len))))
1507
1508 (defun case-frob-downcase-out (stream char)
1509   (declare (type case-frob-stream stream)
1510            (type base-char char))
1511   (let ((target (case-frob-stream-target stream))
1512         (char (char-downcase char)))
1513     (if (lisp-stream-p target)
1514         (funcall (lisp-stream-out target) target char)
1515         (stream-write-char target char))))
1516
1517 (defun case-frob-downcase-sout (stream str start end)
1518   (declare (type case-frob-stream stream)
1519            (type simple-base-string str)
1520            (type index start)
1521            (type (or index null) end))
1522   (let* ((target (case-frob-stream-target stream))
1523          (len (length str))
1524          (end (or end len))
1525          (string (if (and (zerop start) (= len end))
1526                      (string-downcase str)
1527                      (nstring-downcase (subseq str start end))))
1528          (string-len (- end start)))
1529     (if (lisp-stream-p target)
1530         (funcall (lisp-stream-sout target) target string 0 string-len)
1531         (stream-write-string target string 0 string-len))))
1532
1533 (defun case-frob-capitalize-out (stream char)
1534   (declare (type case-frob-stream stream)
1535            (type base-char char))
1536   (let ((target (case-frob-stream-target stream)))
1537     (cond ((alphanumericp char)
1538            (let ((char (char-upcase char)))
1539              (if (lisp-stream-p target)
1540                  (funcall (lisp-stream-out target) target char)
1541                  (stream-write-char target char)))
1542            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1543            (setf (case-frob-stream-sout stream)
1544                  #'case-frob-capitalize-aux-sout))
1545           (t
1546            (if (lisp-stream-p target)
1547                (funcall (lisp-stream-out target) target char)
1548                (stream-write-char target char))))))
1549
1550 (defun case-frob-capitalize-sout (stream str start end)
1551   (declare (type case-frob-stream stream)
1552            (type simple-base-string str)
1553            (type index start)
1554            (type (or index null) end))
1555   (let* ((target (case-frob-stream-target stream))
1556          (str (subseq str start end))
1557          (len (length str))
1558          (inside-word nil))
1559     (dotimes (i len)
1560       (let ((char (schar str i)))
1561         (cond ((not (alphanumericp char))
1562                (setf inside-word nil))
1563               (inside-word
1564                (setf (schar str i) (char-downcase char)))
1565               (t
1566                (setf inside-word t)
1567                (setf (schar str i) (char-upcase char))))))
1568     (when inside-word
1569       (setf (case-frob-stream-out stream)
1570             #'case-frob-capitalize-aux-out)
1571       (setf (case-frob-stream-sout stream)
1572             #'case-frob-capitalize-aux-sout))
1573     (if (lisp-stream-p target)
1574         (funcall (lisp-stream-sout target) target str 0 len)
1575         (stream-write-string target str 0 len))))
1576
1577 (defun case-frob-capitalize-aux-out (stream char)
1578   (declare (type case-frob-stream stream)
1579            (type base-char char))
1580   (let ((target (case-frob-stream-target stream)))
1581     (cond ((alphanumericp char)
1582            (let ((char (char-downcase char)))
1583              (if (lisp-stream-p target)
1584                  (funcall (lisp-stream-out target) target char)
1585                  (stream-write-char target char))))
1586           (t
1587            (if (lisp-stream-p target)
1588                (funcall (lisp-stream-out target) target char)
1589                (stream-write-char target char))
1590            (setf (case-frob-stream-out stream)
1591                  #'case-frob-capitalize-out)
1592            (setf (case-frob-stream-sout stream)
1593                  #'case-frob-capitalize-sout)))))
1594
1595 (defun case-frob-capitalize-aux-sout (stream str start end)
1596   (declare (type case-frob-stream stream)
1597            (type simple-base-string str)
1598            (type index start)
1599            (type (or index null) end))
1600   (let* ((target (case-frob-stream-target stream))
1601          (str (subseq str start end))
1602          (len (length str))
1603          (inside-word t))
1604     (dotimes (i len)
1605       (let ((char (schar str i)))
1606         (cond ((not (alphanumericp char))
1607                (setf inside-word nil))
1608               (inside-word
1609                (setf (schar str i) (char-downcase char)))
1610               (t
1611                (setf inside-word t)
1612                (setf (schar str i) (char-upcase char))))))
1613     (unless inside-word
1614       (setf (case-frob-stream-out stream)
1615             #'case-frob-capitalize-out)
1616       (setf (case-frob-stream-sout stream)
1617             #'case-frob-capitalize-sout))
1618     (if (lisp-stream-p target)
1619         (funcall (lisp-stream-sout target) target str 0 len)
1620         (stream-write-string target str 0 len))))
1621
1622 (defun case-frob-capitalize-first-out (stream char)
1623   (declare (type case-frob-stream stream)
1624            (type base-char char))
1625   (let ((target (case-frob-stream-target stream)))
1626     (cond ((alphanumericp char)
1627            (let ((char (char-upcase char)))
1628              (if (lisp-stream-p target)
1629                  (funcall (lisp-stream-out target) target char)
1630                  (stream-write-char target char)))
1631            (setf (case-frob-stream-out stream)
1632                  #'case-frob-downcase-out)
1633            (setf (case-frob-stream-sout stream)
1634                  #'case-frob-downcase-sout))
1635           (t
1636            (if (lisp-stream-p target)
1637                (funcall (lisp-stream-out target) target char)
1638                (stream-write-char target char))))))
1639
1640 (defun case-frob-capitalize-first-sout (stream str start end)
1641   (declare (type case-frob-stream stream)
1642            (type simple-base-string str)
1643            (type index start)
1644            (type (or index null) end))
1645   (let* ((target (case-frob-stream-target stream))
1646          (str (subseq str start end))
1647          (len (length str)))
1648     (dotimes (i len)
1649       (let ((char (schar str i)))
1650         (when (alphanumericp char)
1651           (setf (schar str i) (char-upcase char))
1652           (do ((i (1+ i) (1+ i)))
1653               ((= i len))
1654             (setf (schar str i) (char-downcase (schar str i))))
1655           (setf (case-frob-stream-out stream)
1656                 #'case-frob-downcase-out)
1657           (setf (case-frob-stream-sout stream)
1658                 #'case-frob-downcase-sout)
1659           (return))))
1660     (if (lisp-stream-p target)
1661         (funcall (lisp-stream-sout target) target str 0 len)
1662         (stream-write-string target str 0 len))))
1663 \f
1664 ;;;; stream commands
1665
1666 (defstruct (stream-command (:constructor make-stream-command
1667                                          (name &optional args))
1668                            (:copier nil))
1669   (name nil :type symbol)
1670   (args nil :type list))
1671 (def!method print-object ((obj stream-command) str)
1672   (print-unreadable-object (obj str :type t :identity t)
1673     (prin1 (stream-command-name obj) str)))
1674
1675 ;;; Take a stream and wait for text or a command to appear on it. If
1676 ;;; text appears before a command, return NIL, otherwise return a
1677 ;;; command.
1678 ;;;
1679 ;;; We can't simply call the stream's misc method because NIL is an
1680 ;;; ambiguous return value: does it mean text arrived, or does it mean
1681 ;;; the stream's misc method had no :GET-COMMAND implementation? We
1682 ;;; can't return NIL until there is text input. We don't need to loop
1683 ;;; because any stream implementing :GET-COMMAND would wait until it
1684 ;;; had some input. If the LISTEN fails, then we have some stream we
1685 ;;; must wait on.
1686 (defun get-stream-command (stream)
1687   (let ((cmdp (funcall (lisp-stream-misc stream) stream :get-command)))
1688     (cond (cmdp)
1689           ((listen stream)
1690            nil)
1691           (t
1692            ;; This waits for input and returns NIL when it arrives.
1693            (unread-char (read-char stream) stream)))))
1694 \f
1695 (defun read-sequence (seq stream &key (start 0) (end nil))
1696   #!+sb-doc
1697   "Destructively modify SEQ by reading elements from STREAM.
1698   That part of SEQ bounded by START and END is destructively modified by
1699   copying successive elements into it from STREAM. If the end of file
1700   for STREAM is reached before copying all elements of the subsequence,
1701   then the extra elements near the end of sequence are not updated, and
1702   the index of the next element is returned."
1703   (declare (type sequence seq)
1704            (type stream stream)
1705            (type index start)
1706            (type sequence-end end)
1707            (values index))
1708   (let ((end (or end (length seq))))
1709     (declare (type index end))
1710     (etypecase seq
1711       (list
1712        (let ((read-function
1713               (if (subtypep (stream-element-type stream) 'character)
1714                   #'read-char
1715                   #'read-byte)))
1716          (do ((rem (nthcdr start seq) (rest rem))
1717               (i start (1+ i)))
1718              ((or (endp rem) (>= i end)) i)
1719            (declare (type list rem)
1720                     (type index i))
1721            (let ((el (funcall read-function stream nil :eof)))
1722              (when (eq el :eof)
1723                (return i))
1724              (setf (first rem) el)))))
1725       (vector
1726        (with-array-data ((data seq) (offset-start start) (offset-end end))
1727          (typecase data
1728            ((or (simple-array (unsigned-byte 8) (*))
1729                 (simple-array (signed-byte 8) (*))
1730                 simple-string)
1731             (let* ((numbytes (- end start))
1732                    (bytes-read (sb!sys:read-n-bytes stream
1733                                                     data
1734                                                     offset-start
1735                                                     numbytes
1736                                                     nil)))
1737               (if (< bytes-read numbytes)
1738                   (+ start bytes-read)
1739                   end)))
1740            (t
1741             (let ((read-function
1742                    (if (subtypep (stream-element-type stream) 'character)
1743                        #'read-char
1744                        #'read-byte)))
1745               (do ((i offset-start (1+ i)))
1746                   ((>= i offset-end) end)
1747                 (declare (type index i))
1748                 (let ((el (funcall read-function stream nil :eof)))
1749                   (when (eq el :eof)
1750                     (return (+ start (- i offset-start))))
1751                   (setf (aref data i) el)))))))))))
1752
1753 (defun write-sequence (seq stream &key (start 0) (end nil))
1754   #!+sb-doc
1755   "Write the elements of SEQ bounded by START and END to STREAM."
1756   (declare (type sequence seq)
1757            (type stream stream)
1758            (type index start)
1759            (type sequence-end end)
1760            (values sequence))
1761   (let ((end (or end (length seq))))
1762     (declare (type index start end))
1763     (etypecase seq
1764       (list
1765        (let ((write-function
1766               (if (subtypep (stream-element-type stream) 'character)
1767                   #'write-char
1768                   #'write-byte)))
1769          (do ((rem (nthcdr start seq) (rest rem))
1770               (i start (1+ i)))
1771              ((or (endp rem) (>= i end)) seq)
1772            (declare (type list rem)
1773                     (type index i))
1774            (funcall write-function (first rem) stream))))
1775       (string
1776        (%write-string seq stream start end))
1777       (vector
1778        (let ((write-function
1779               (if (subtypep (stream-element-type stream) 'character)
1780                   #'write-char
1781                   #'write-byte)))
1782          (do ((i start (1+ i)))
1783              ((>= i end) seq)
1784            (declare (type index i))
1785            (funcall write-function (aref seq i) stream)))))))
1786
1787 ;;; (These were inline throughout this file, but that's not appropriate
1788 ;;; globally.)
1789 (declaim (maybe-inline read-char unread-char read-byte listen))