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