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