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