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