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