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