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