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