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