5676b14fda6a0d7c5d6b5bc38b975004dcb36459
[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 (deftype string-stream ()
15   '(or string-input-stream string-output-stream
16        fill-pointer-output-stream))
17
18 ;;;; standard streams
19
20 ;;; The initialization of these streams is performed by
21 ;;; STREAM-COLD-INIT-OR-RESET.
22 (defvar *terminal-io* () #!+sb-doc "terminal I/O stream")
23 (defvar *standard-input* () #!+sb-doc "default input stream")
24 (defvar *standard-output* () #!+sb-doc "default output stream")
25 (defvar *error-output* () #!+sb-doc "error output stream")
26 (defvar *query-io* () #!+sb-doc "query I/O stream")
27 (defvar *trace-output* () #!+sb-doc "trace output stream")
28 (defvar *debug-io* () #!+sb-doc "interactive debugging stream")
29
30 (defun ill-in (stream &rest ignore)
31   (declare (ignore ignore))
32   (error 'simple-type-error
33          :datum stream
34          :expected-type '(satisfies input-stream-p)
35          :format-control "~S is not a character input stream."
36          :format-arguments (list stream)))
37 (defun ill-out (stream &rest ignore)
38   (declare (ignore ignore))
39   (error 'simple-type-error
40          :datum stream
41          :expected-type '(satisfies output-stream-p)
42          :format-control "~S is not a character output stream."
43          :format-arguments (list stream)))
44 (defun ill-bin (stream &rest ignore)
45   (declare (ignore ignore))
46   (error 'simple-type-error
47          :datum stream
48          :expected-type '(satisfies input-stream-p)
49          :format-control "~S is not a binary input stream."
50          :format-arguments (list stream)))
51 (defun ill-bout (stream &rest ignore)
52   (declare (ignore ignore))
53   (error 'simple-type-error
54          :datum stream
55          :expected-type '(satisfies output-stream-p)
56          :format-control "~S is not a binary output stream."
57          :format-arguments (list stream)))
58 (defun closed-flame (stream &rest ignore)
59   (declare (ignore ignore))
60   (error "~S is closed." stream))
61 (defun no-op-placeholder (&rest ignore)
62   (declare (ignore ignore)))
63 \f
64 ;;; stream manipulation functions
65
66 (defun input-stream-p (stream)
67   (declare (type stream stream))
68
69   #!+high-security
70   (when (synonym-stream-p stream)
71     (setf stream
72           (symbol-value (synonym-stream-symbol stream))))
73
74   (and (ansi-stream-p stream)
75        (not (eq (ansi-stream-in stream) #'closed-flame))
76        ;;; KLUDGE: It's probably not good to have EQ tests on function
77        ;;; values like this. What if someone's redefined the function?
78        ;;; Is there a better way? (Perhaps just VALID-FOR-INPUT and
79        ;;; VALID-FOR-OUTPUT flags? -- WHN 19990902
80        (or (not (eq (ansi-stream-in stream) #'ill-in))
81            (not (eq (ansi-stream-bin stream) #'ill-bin)))))
82
83 (defun output-stream-p (stream)
84   (declare (type stream stream))
85
86   #!+high-security
87   (when (synonym-stream-p stream)
88     (setf stream (symbol-value
89                   (synonym-stream-symbol stream))))
90
91   (and (ansi-stream-p stream)
92        (not (eq (ansi-stream-in stream) #'closed-flame))
93        (or (not (eq (ansi-stream-out stream) #'ill-out))
94            (not (eq (ansi-stream-bout stream) #'ill-bout)))))
95
96 (defun open-stream-p (stream)
97   (declare (type stream stream))
98   (not (eq (ansi-stream-in stream) #'closed-flame)))
99
100 (defun stream-element-type (stream)
101   (declare (type stream stream))
102   (funcall (ansi-stream-misc stream) stream :element-type))
103
104 (defun interactive-stream-p (stream)
105   (declare (type stream stream))
106   (funcall (ansi-stream-misc stream) stream :interactive-p))
107
108 (defun close (stream &key abort)
109   (declare (type stream stream))
110   (when (open-stream-p stream)
111     (funcall (ansi-stream-misc stream) stream :close abort))
112   t)
113
114 (defun set-closed-flame (stream)
115   (setf (ansi-stream-in stream) #'closed-flame)
116   (setf (ansi-stream-bin stream) #'closed-flame)
117   (setf (ansi-stream-n-bin stream) #'closed-flame)
118   (setf (ansi-stream-in stream) #'closed-flame)
119   (setf (ansi-stream-out stream) #'closed-flame)
120   (setf (ansi-stream-bout stream) #'closed-flame)
121   (setf (ansi-stream-sout stream) #'closed-flame)
122   (setf (ansi-stream-misc stream) #'closed-flame))
123 \f
124 ;;;; file position and file length
125
126 ;;; Call the MISC method with the :FILE-POSITION operation.
127 (defun file-position (stream &optional position)
128   (declare (type stream stream))
129   (declare (type (or index (member nil :start :end)) position))
130   (cond
131    (position
132     (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
133     (funcall (ansi-stream-misc stream) stream :file-position position))
134    (t
135     (let ((res (funcall (ansi-stream-misc stream) stream :file-position nil)))
136       (when res
137         (- res
138            (- +ansi-stream-in-buffer-length+
139               (ansi-stream-in-index stream))))))))
140
141 ;;; This is a literal translation of the ANSI glossary entry "stream
142 ;;; associated with a file".
143 ;;;
144 ;;; KLUDGE: Note that since Unix famously thinks "everything is a
145 ;;; file", and in particular stdin, stdout, and stderr are files, we
146 ;;; end up with this test being satisfied for weird things like
147 ;;; *STANDARD-OUTPUT* (to a tty). That seems unlikely to be what the
148 ;;; ANSI spec really had in mind, especially since this is used as a
149 ;;; qualification for operations like FILE-LENGTH (so that ANSI was
150 ;;; probably thinking of something like what Unix calls block devices)
151 ;;; but I can't see any better way to do it. -- WHN 2001-04-14
152 (defun stream-associated-with-file-p (x)
153   "Test for the ANSI concept \"stream associated with a file\"."
154   (or (typep x 'file-stream)
155       (and (synonym-stream-p x)
156            (stream-associated-with-file-p (symbol-value
157                                            (synonym-stream-symbol x))))))
158
159 (defun stream-must-be-associated-with-file (stream)
160   (declare (type stream stream))
161   (unless (stream-associated-with-file-p stream)
162     (error 'simple-type-error
163            ;; KLUDGE: The ANSI spec for FILE-LENGTH specifically says
164            ;; this should be TYPE-ERROR. But what then can we use for
165            ;; EXPECTED-TYPE? This SATISFIES type (with a nonstandard
166            ;; private predicate function..) is ugly and confusing, but
167            ;; I can't see any other way. -- WHN 2001-04-14
168            :expected-type '(satisfies stream-associated-with-file-p)
169            :format-string
170            "~@<The stream ~2I~_~S ~I~_isn't associated with a file.~:>"
171            :format-arguments (list stream))))
172
173 ;;; like FILE-POSITION, only using :FILE-LENGTH
174 (defun file-length (stream)
175   (declare (type (or file-stream synonym-stream) stream))
176   (stream-must-be-associated-with-file stream)
177   (funcall (ansi-stream-misc stream) stream :file-length))
178 \f
179 ;;;; input functions
180
181 (defun read-line (&optional (stream *standard-input*) (eof-error-p t) eof-value
182                             recursive-p)
183   (declare (ignore recursive-p))
184   (let ((stream (in-synonym-of stream)))
185     (if (ansi-stream-p stream)
186         (prepare-for-fast-read-char stream
187           (let ((res (make-string 80))
188                 (len 80)
189                 (index 0))
190             (loop
191              (let ((ch (fast-read-char nil nil)))
192                (cond (ch
193                       (when (char= ch #\newline)
194                         (done-with-fast-read-char)
195                         (return (values (shrink-vector res index) nil)))
196                       (when (= index len)
197                         (setq len (* len 2))
198                         (let ((new (make-string len)))
199                           (replace new res)
200                           (setq res new)))
201                       (setf (schar res index) ch)
202                       (incf index))
203                      ((zerop index)
204                       (done-with-fast-read-char)
205                       (return (values (eof-or-lose stream
206                                                    eof-error-p
207                                                    eof-value)
208                                       t)))
209                      ;; Since FAST-READ-CHAR already hit the eof char, we
210                      ;; shouldn't do another READ-CHAR.
211                      (t
212                       (done-with-fast-read-char)
213                       (return (values (shrink-vector res index) t))))))))
214         ;; must be Gray streams FUNDAMENTAL-STREAM
215         (multiple-value-bind (string eof) (stream-read-line stream)
216           (if (and eof (zerop (length string)))
217               (values (eof-or-lose stream eof-error-p eof-value) t)
218               (values string eof))))))
219
220 ;;; We proclaim them INLINE here, then proclaim them MAYBE-INLINE at EOF,
221 ;;; so, except in this file, they are not inline by default, but they can be.
222 #!-sb-fluid (declaim (inline read-char unread-char read-byte listen))
223
224 (defun read-char (&optional (stream *standard-input*)
225                             (eof-error-p t)
226                             eof-value
227                             recursive-p)
228   (declare (ignore recursive-p))
229   (let ((stream (in-synonym-of stream)))
230     (if (ansi-stream-p stream)
231         (prepare-for-fast-read-char stream
232           (prog1
233               (fast-read-char eof-error-p eof-value)
234             (done-with-fast-read-char)))
235         ;; must be Gray streams FUNDAMENTAL-STREAM
236         (let ((char (stream-read-char stream)))
237           (if (eq char :eof)
238               (eof-or-lose stream eof-error-p eof-value)
239               char)))))
240
241 (defun unread-char (character &optional (stream *standard-input*))
242   (let ((stream (in-synonym-of stream)))
243     (if (ansi-stream-p stream)
244         (let ((index (1- (ansi-stream-in-index stream)))
245               (buffer (ansi-stream-in-buffer stream)))
246           (declare (fixnum index))
247           (when (minusp index) (error "nothing to unread"))
248           (cond (buffer
249                  (setf (aref buffer index) (char-code character))
250                  (setf (ansi-stream-in-index stream) index))
251                 (t
252                  (funcall (ansi-stream-misc stream) stream
253                           :unread character))))
254         ;; must be Gray streams FUNDAMENTAL-STREAM
255         (stream-unread-char stream character)))
256   nil)
257
258 (defun peek-char (&optional (peek-type nil)
259                             (stream *standard-input*)
260                             (eof-error-p t)
261                             eof-value
262                             recursive-p)
263   (declare (ignore recursive-p))
264   ;; FIXME: The type of PEEK-TYPE is also declared in a DEFKNOWN, but
265   ;; the compiler doesn't seem to be smart enough to go from there to
266   ;; imposing a type check. Figure out why (because PEEK-TYPE is an
267   ;; &OPTIONAL argument?) and fix it, and then this explicit type
268   ;; check can go away.
269   (unless (typep peek-type '(or character boolean))
270     (error 'simple-type-error
271            :datum peek-type
272            :expected-type '(or character boolean)
273            :format-control "~@<bad PEEK-TYPE=~S, ~_expected ~S~:>"
274            :format-arguments (list peek-type '(or character boolean))))
275   (let ((stream (in-synonym-of stream)))
276     (if (ansi-stream-p stream)
277         (let ((char (read-char stream eof-error-p eof-value)))
278           (cond ((eq char eof-value) char)
279                 ((characterp peek-type)
280                  (do ((char char (read-char stream eof-error-p eof-value)))
281                      ((or (eq char eof-value) (char= char peek-type))
282                       (unless (eq char eof-value)
283                         (unread-char char stream))
284                       char)))
285                 ((eq peek-type t)
286                  (do ((char char (read-char stream eof-error-p eof-value)))
287                      ((or (eq char eof-value) (not (whitespace-char-p char)))
288                       (unless (eq char eof-value)
289                         (unread-char char stream))
290                       char)))
291                 ((null peek-type)
292                  (unread-char char stream)
293                  char)
294                 (t
295                  (bug "impossible case"))))
296         ;; by elimination, must be Gray streams FUNDAMENTAL-STREAM
297         (cond ((characterp peek-type)
298                (do ((char (stream-read-char stream)
299                           (stream-read-char stream)))
300                    ((or (eq char :eof) (char= char peek-type))
301                     (cond ((eq char :eof)
302                            (eof-or-lose stream eof-error-p eof-value))
303                           (t
304                            (stream-unread-char stream char)
305                            char)))))
306               ((eq peek-type t)
307                (do ((char (stream-read-char stream)
308                           (stream-read-char stream)))
309                    ((or (eq char :eof) (not (whitespace-char-p char)))
310                     (cond ((eq char :eof)
311                            (eof-or-lose stream eof-error-p eof-value))
312                           (t
313                            (stream-unread-char stream char)
314                            char)))))
315               ((null peek-type)
316                (let ((char (stream-peek-char stream)))
317                  (if (eq char :eof)
318                      (eof-or-lose stream eof-error-p eof-value)
319                      char)))
320               (t
321                (bug "impossible case"))))))
322
323 (defun listen (&optional (stream *standard-input*))
324   (let ((stream (in-synonym-of stream)))
325     (if (ansi-stream-p stream)
326         (or (/= (the fixnum (ansi-stream-in-index stream))
327                 +ansi-stream-in-buffer-length+)
328             ;; Test for T explicitly since misc methods return :EOF sometimes.
329             (eq (funcall (ansi-stream-misc stream) stream :listen) t))
330         ;; Fall through to Gray streams FUNDAMENTAL-STREAM case.
331         (stream-listen stream))))
332
333 (defun read-char-no-hang (&optional (stream *standard-input*)
334                                     (eof-error-p t)
335                                     eof-value
336                                     recursive-p)
337   (declare (ignore recursive-p))
338   (let ((stream (in-synonym-of stream)))
339     (if (ansi-stream-p stream)
340         (if (funcall (ansi-stream-misc stream) stream :listen)
341             ;; On T or :EOF get READ-CHAR to do the work.
342             (read-char stream eof-error-p eof-value)
343             nil)
344         ;; must be Gray streams FUNDAMENTAL-STREAM
345         (let ((char (stream-read-char-no-hang stream)))
346           (if (eq char :eof)
347               (eof-or-lose stream eof-error-p eof-value)
348               char)))))
349
350 (defun clear-input (&optional (stream *standard-input*))
351   (let ((stream (in-synonym-of stream)))
352     (cond ((ansi-stream-p stream)
353            (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
354            (funcall (ansi-stream-misc stream) stream :clear-input))
355           (t
356            (stream-clear-input stream))))
357   nil)
358 \f
359 (declaim (maybe-inline read-byte))
360 (defun read-byte (stream &optional (eof-error-p t) eof-value)
361   (let ((stream (in-synonym-of stream)))
362     (if (ansi-stream-p stream)
363         (prepare-for-fast-read-byte stream
364           (prog1
365               (fast-read-byte eof-error-p eof-value t)
366             (done-with-fast-read-byte)))
367         ;; must be Gray streams FUNDAMENTAL-STREAM
368         (let ((char (stream-read-byte stream)))
369           (if (eq char :eof)
370               (eof-or-lose stream eof-error-p eof-value)
371               char)))))
372
373 ;;; Read NUMBYTES bytes into BUFFER beginning at START, and return the
374 ;;; number of bytes read.
375 ;;;
376 ;;; Note: CMU CL's version of this had a special interpretation of
377 ;;; EOF-ERROR-P which SBCL does not have. (In the EOF-ERROR-P=NIL
378 ;;; case, CMU CL's version would return as soon as any data became
379 ;;; available.) This could be useful behavior for things like pipes in
380 ;;; some cases, but it wasn't being used in SBCL, so it was dropped.
381 ;;; If we ever need it, it could be added later as a new variant N-BIN
382 ;;; method (perhaps N-BIN-ASAP?) or something.
383 (defun read-n-bytes (stream buffer start numbytes &optional (eof-error-p t))
384   (declare (type ansi-stream stream)
385            (type index numbytes start)
386            (type (or (simple-array * (*)) system-area-pointer) buffer))
387   (let* ((stream (in-synonym-of stream ansi-stream))
388          (in-buffer (ansi-stream-in-buffer stream))
389          (index (ansi-stream-in-index stream))
390          (num-buffered (- +ansi-stream-in-buffer-length+ index)))
391     (declare (fixnum index num-buffered))
392     (cond
393      ((not in-buffer)
394       (funcall (ansi-stream-n-bin stream)
395                stream
396                buffer
397                start
398                numbytes
399                eof-error-p))
400      ((<= numbytes num-buffered)
401       (%byte-blt in-buffer index
402                  buffer start (+ start numbytes))
403       (setf (ansi-stream-in-index stream) (+ index numbytes))
404       numbytes)
405      (t
406       (let ((end (+ start num-buffered)))
407         (%byte-blt in-buffer index buffer start end)
408         (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
409         (+ (funcall (ansi-stream-n-bin stream)
410                     stream
411                     buffer
412                     end
413                     (- numbytes num-buffered)
414                     eof-error-p)
415            num-buffered))))))
416
417 ;;; the amount of space we leave at the start of the in-buffer for
418 ;;; unreading
419 ;;;
420 ;;; (It's 4 instead of 1 to allow word-aligned copies.)
421 (defconstant +ansi-stream-in-buffer-extra+
422   4) ; FIXME: should be symbolic constant
423
424 ;;; This function is called by the FAST-READ-CHAR expansion to refill
425 ;;; the IN-BUFFER for text streams. There is definitely an IN-BUFFER,
426 ;;; and hence must be an N-BIN method.
427 (defun fast-read-char-refill (stream eof-error-p eof-value)
428   (let* ((ibuf (ansi-stream-in-buffer stream))
429          (count (funcall (ansi-stream-n-bin stream)
430                          stream
431                          ibuf
432                          +ansi-stream-in-buffer-extra+
433                          (- +ansi-stream-in-buffer-length+
434                             +ansi-stream-in-buffer-extra+)
435                          nil))
436          (start (- +ansi-stream-in-buffer-length+ count)))
437     (declare (type index start count))
438     (cond ((zerop count)
439            (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
440            (funcall (ansi-stream-in stream) stream eof-error-p eof-value))
441           (t
442            (when (/= start +ansi-stream-in-buffer-extra+)
443              (bit-bash-copy ibuf (+ (* +ansi-stream-in-buffer-extra+
444                                        sb!vm:n-byte-bits)
445                                     (* sb!vm:vector-data-offset
446                                        sb!vm:n-word-bits))
447                             ibuf (+ (the index (* start sb!vm:n-byte-bits))
448                                     (* sb!vm:vector-data-offset
449                                        sb!vm:n-word-bits))
450                             (* count sb!vm:n-byte-bits)))
451            (setf (ansi-stream-in-index stream) (1+ start))
452            (code-char (aref ibuf start))))))
453
454 ;;; This is similar to FAST-READ-CHAR-REFILL, but we don't have to
455 ;;; leave room for unreading.
456 (defun fast-read-byte-refill (stream eof-error-p eof-value)
457   (let* ((ibuf (ansi-stream-in-buffer stream))
458          (count (funcall (ansi-stream-n-bin stream) stream
459                          ibuf 0 +ansi-stream-in-buffer-length+
460                          nil))
461          (start (- +ansi-stream-in-buffer-length+ count)))
462     (declare (type index start count))
463     (cond ((zerop count)
464            (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
465            (funcall (ansi-stream-bin stream) stream eof-error-p eof-value))
466           (t
467            (unless (zerop start)
468              (bit-bash-copy ibuf (* sb!vm:vector-data-offset sb!vm:n-word-bits)
469                             ibuf (+ (the index (* start sb!vm:n-byte-bits))
470                                     (* sb!vm:vector-data-offset
471                                        sb!vm:n-word-bits))
472                             (* count sb!vm:n-byte-bits)))
473            (setf (ansi-stream-in-index stream) (1+ start))
474            (aref ibuf start)))))
475 \f
476 ;;; output functions
477
478 (defun write-char (character &optional (stream *standard-output*))
479   (with-out-stream stream (ansi-stream-out character)
480                    (stream-write-char character))
481   character)
482
483 (defun terpri (&optional (stream *standard-output*))
484   (with-out-stream stream (ansi-stream-out #\newline) (stream-terpri))
485   nil)
486
487 (defun fresh-line (&optional (stream *standard-output*))
488   (let ((stream (out-synonym-of stream)))
489     (if (ansi-stream-p stream)
490         (when (/= (or (charpos stream) 1) 0)
491           (funcall (ansi-stream-out stream) stream #\newline)
492           t)
493         ;; must be Gray streams FUNDAMENTAL-STREAM
494         (stream-fresh-line stream))))
495
496 (defun write-string (string &optional (stream *standard-output*)
497                             &key (start 0) (end nil))
498   (%write-string string stream start (or end (length string)))
499   string)
500
501 (defun %write-string (string stream start end)
502   (declare (type string string))
503   (declare (type streamlike stream))
504   (declare (type index start end))
505
506   ;; Note that even though you might expect, based on the behavior of
507   ;; things like AREF, that the correct upper bound here is
508   ;; (ARRAY-DIMENSION STRING 0), the ANSI glossary definitions for
509   ;; "bounding index" and "length" indicate that in this case (i.e.
510   ;; for the ANSI-specified functions WRITE-STRING and WRITE-LINE
511   ;; which are implemented in terms of this function), (LENGTH STRING)
512   ;; is the required upper bound. A foolish consistency is the
513   ;; hobgoblin of lesser languages..
514   (unless (<= 0 start end (length string))
515     (error "~@<bad bounding indices START=~W END=~W for ~2I~_~S~:>"
516            start
517            end
518            string))
519
520   (let ((stream (out-synonym-of stream)))
521     (cond ((ansi-stream-p stream)
522            (if (array-header-p string)
523                (with-array-data ((data string) (offset-start start)
524                                  (offset-end end))
525                  (funcall (ansi-stream-sout stream)
526                           stream data offset-start offset-end))
527                (funcall (ansi-stream-sout stream) stream string start end))
528            string)
529           (t ; must be Gray streams FUNDAMENTAL-STREAM
530            (stream-write-string stream string start end)))))
531
532 (defun write-line (string &optional (stream *standard-output*)
533                           &key (start 0) (end nil))
534   (let ((defaulted-stream (out-synonym-of stream))
535         (defaulted-end (or end (length string))))
536     (%write-string string defaulted-stream start defaulted-end)
537     (write-char #\newline defaulted-stream))
538   string)
539
540 (defun charpos (&optional (stream *standard-output*))
541   (with-out-stream stream (ansi-stream-misc :charpos) (stream-line-column)))
542
543 (defun line-length (&optional (stream *standard-output*))
544   (with-out-stream stream (ansi-stream-misc :line-length)
545                    (stream-line-length)))
546
547 (defun finish-output (&optional (stream *standard-output*))
548   (with-out-stream stream (ansi-stream-misc :finish-output)
549                    (stream-finish-output))
550   nil)
551
552 (defun force-output (&optional (stream *standard-output*))
553   (with-out-stream stream (ansi-stream-misc :force-output)
554                    (stream-force-output))
555   nil)
556
557 (defun clear-output (&optional (stream *standard-output*))
558   (with-out-stream stream (ansi-stream-misc :clear-output)
559                    (stream-force-output))
560   nil)
561
562 (defun write-byte (integer stream)
563   (with-out-stream stream (ansi-stream-bout integer)
564                    (stream-write-byte integer))
565   integer)
566 \f
567 ;;; This is called from ANSI-STREAM routines that encapsulate CLOS
568 ;;; streams to handle the misc routines and dispatch to the
569 ;;; appropriate Gray stream functions.
570 (defun stream-misc-dispatch (stream operation &optional arg1 arg2)
571   (declare (type fundamental-stream stream)
572            (ignore arg2))
573   (case operation
574     (:listen
575      ;; Return T if input available, :EOF for end-of-file, otherwise NIL.
576      (let ((char (stream-read-char-no-hang stream)))
577        (when (characterp char)
578          (stream-unread-char stream char))
579        char))
580     (:unread
581      (stream-unread-char stream arg1))
582     (:close
583      (close stream))
584     (:clear-input
585      (stream-clear-input stream))
586     (:force-output
587      (stream-force-output stream))
588     (:finish-output
589      (stream-finish-output stream))
590     (:element-type
591      (stream-element-type stream))
592     (:interactive-p
593      (interactive-stream-p stream))
594     (:line-length
595      (stream-line-length stream))
596     (:charpos
597      (stream-line-column stream))
598     (:file-length
599      (file-length stream))
600     (:file-position
601      (file-position stream arg1))))
602 \f
603 ;;;; broadcast streams
604
605 (defstruct (broadcast-stream (:include ansi-stream
606                                        (out #'broadcast-out)
607                                        (bout #'broadcast-bout)
608                                        (sout #'broadcast-sout)
609                                        (misc #'broadcast-misc))
610                              (:constructor %make-broadcast-stream
611                                            (&rest streams))
612                              (:copier nil))
613   ;; a list of all the streams we broadcast to
614   (streams () :type list :read-only t))
615
616 (defun make-broadcast-stream (&rest streams)
617   (dolist (stream streams)
618     (unless (or (and (synonym-stream-p stream)
619                      (output-stream-p (symbol-value
620                                        (synonym-stream-symbol stream))))
621                 (output-stream-p stream))
622       (error 'type-error
623              :datum stream
624              :expected-type '(satisfies output-stream-p))))
625   (apply #'%make-broadcast-stream streams))
626
627 (macrolet ((out-fun (fun method stream-method &rest args)
628              `(defun ,fun (stream ,@args)
629                 (dolist (stream (broadcast-stream-streams stream))
630                   (if (ansi-stream-p stream)
631                       (funcall (,method stream) stream ,@args)
632                       (,stream-method stream ,@args))))))
633   (out-fun broadcast-out ansi-stream-out stream-write-char char)
634   (out-fun broadcast-bout ansi-stream-bout stream-write-byte byte)
635   (out-fun broadcast-sout ansi-stream-sout stream-write-string
636            string start end))
637
638 (defun broadcast-misc (stream operation &optional arg1 arg2)
639   (let ((streams (broadcast-stream-streams stream)))
640     (case operation
641       (:charpos
642        (dolist (stream streams)
643          (let ((charpos (charpos stream)))
644            (if charpos (return charpos)))))
645       (:line-length
646        (let ((min nil))
647          (dolist (stream streams min)
648            (let ((res (line-length stream)))
649              (when res (setq min (if min (min res min) res)))))))
650       (:element-type
651        (let (res)
652          (dolist (stream streams (if (> (length res) 1) `(and ,@res) res))
653            (pushnew (stream-element-type stream) res :test #'equal))))
654       (:close)
655       (t
656        (let ((res nil))
657          (dolist (stream streams res)
658            (setq res
659                  (if (ansi-stream-p stream)
660                      (funcall (ansi-stream-misc stream) stream operation
661                               arg1 arg2)
662                      (stream-misc-dispatch stream operation arg1 arg2)))))))))
663 \f
664 ;;;; synonym streams
665
666 (defstruct (synonym-stream (:include ansi-stream
667                                      (in #'synonym-in)
668                                      (bin #'synonym-bin)
669                                      (n-bin #'synonym-n-bin)
670                                      (out #'synonym-out)
671                                      (bout #'synonym-bout)
672                                      (sout #'synonym-sout)
673                                      (misc #'synonym-misc))
674                            (:constructor make-synonym-stream (symbol))
675                            (:copier nil))
676   ;; This is the symbol, the value of which is the stream we are synonym to.
677   (symbol nil :type symbol :read-only t))
678 (def!method print-object ((x synonym-stream) stream)
679   (print-unreadable-object (x stream :type t :identity t)
680     (format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
681
682 ;;; The output simple output methods just call the corresponding method
683 ;;; in the synonymed stream.
684 (macrolet ((out-fun (name slot stream-method &rest args)
685              `(defun ,name (stream ,@args)
686                 (declare (optimize (safety 1)))
687                 (let ((syn (symbol-value (synonym-stream-symbol stream))))
688                   (if (ansi-stream-p syn)
689                       (funcall (,slot syn) syn ,@args)
690                       (,stream-method syn ,@args))))))
691   (out-fun synonym-out ansi-stream-out stream-write-char ch)
692   (out-fun synonym-bout ansi-stream-bout stream-write-byte n)
693   (out-fun synonym-sout ansi-stream-sout stream-write-string string start end))
694
695 ;;; For the input methods, we just call the corresponding function on the
696 ;;; synonymed stream. These functions deal with getting input out of
697 ;;; the In-Buffer if there is any.
698 (macrolet ((in-fun (name fun &rest args)
699              `(defun ,name (stream ,@args)
700                 (declare (optimize (safety 1)))
701                 (,fun (symbol-value (synonym-stream-symbol stream))
702                       ,@args))))
703   (in-fun synonym-in read-char eof-error-p eof-value)
704   (in-fun synonym-bin read-byte eof-error-p eof-value)
705   (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
706
707 (defun synonym-misc (stream operation &optional arg1 arg2)
708   (declare (optimize (safety 1)))
709   (let ((syn (symbol-value (synonym-stream-symbol stream))))
710     (if (ansi-stream-p syn)
711         ;; We have to special-case some operations which interact with
712         ;; the in-buffer of the wrapped stream, since just calling
713         ;; ANSI-STREAM-MISC on them
714         (case operation
715           (:listen (or (/= (the fixnum (ansi-stream-in-index syn))
716                            +ansi-stream-in-buffer-length+)
717                        (funcall (ansi-stream-misc syn) syn :listen)))
718           (:clear-input (clear-input syn))
719           (:unread (unread-char arg1 syn))
720           (t
721            (funcall (ansi-stream-misc syn) syn operation arg1 arg2)))
722         (stream-misc-dispatch syn operation arg1 arg2))))
723 \f
724 ;;;; two-way streams
725
726 (defstruct (two-way-stream
727             (:include ansi-stream
728                       (in #'two-way-in)
729                       (bin #'two-way-bin)
730                       (n-bin #'two-way-n-bin)
731                       (out #'two-way-out)
732                       (bout #'two-way-bout)
733                       (sout #'two-way-sout)
734                       (misc #'two-way-misc))
735             (:constructor %make-two-way-stream (input-stream output-stream))
736             (:copier nil))
737   (input-stream (missing-arg) :type stream :read-only t)
738   (output-stream (missing-arg) :type stream :read-only t))
739 (defprinter (two-way-stream) input-stream output-stream)
740
741 (defun make-two-way-stream (input-stream output-stream)
742   #!+sb-doc
743   "Return a bidirectional stream which gets its input from INPUT-STREAM and
744    sends its output to OUTPUT-STREAM."
745   ;; FIXME: This idiom of the-real-stream-of-a-possibly-synonym-stream
746   ;; should be encapsulated in a function, and used here and most of
747   ;; the other places that SYNONYM-STREAM-P appears.
748   (unless (or (and (synonym-stream-p output-stream)
749                    (output-stream-p (symbol-value
750                                      (synonym-stream-symbol output-stream))))
751               (output-stream-p output-stream))
752     (error 'type-error
753            :datum output-stream
754            :expected-type '(satisfies output-stream-p)))
755   (unless (or (and (synonym-stream-p input-stream)
756                    (input-stream-p (symbol-value
757                                     (synonym-stream-symbol input-stream))))
758               (input-stream-p input-stream))
759     (error 'type-error
760            :datum input-stream
761            :expected-type '(satisfies input-stream-p)))
762   (funcall #'%make-two-way-stream input-stream output-stream))
763
764 (macrolet ((out-fun (name slot stream-method &rest args)
765              `(defun ,name (stream ,@args)
766                 (let ((syn (two-way-stream-output-stream stream)))
767                   (if (ansi-stream-p syn)
768                       (funcall (,slot syn) syn ,@args)
769                       (,stream-method syn ,@args))))))
770   (out-fun two-way-out ansi-stream-out stream-write-char ch)
771   (out-fun two-way-bout ansi-stream-bout stream-write-byte n)
772   (out-fun two-way-sout ansi-stream-sout stream-write-string string start end))
773
774 (macrolet ((in-fun (name fun &rest args)
775              `(defun ,name (stream ,@args)
776                 (force-output (two-way-stream-output-stream stream))
777                 (,fun (two-way-stream-input-stream stream) ,@args))))
778   (in-fun two-way-in read-char eof-error-p eof-value)
779   (in-fun two-way-bin read-byte eof-error-p eof-value)
780   (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
781
782 (defun two-way-misc (stream operation &optional arg1 arg2)
783   (let* ((in (two-way-stream-input-stream stream))
784          (out (two-way-stream-output-stream stream))
785          (in-ansi-stream-p (ansi-stream-p in))
786          (out-ansi-stream-p (ansi-stream-p out)))
787     (case operation
788       (:listen
789        (if in-ansi-stream-p
790            (or (/= (the fixnum (ansi-stream-in-index in))
791                    +ansi-stream-in-buffer-length+)
792                (funcall (ansi-stream-misc in) in :listen))
793            (stream-listen in)))
794       ((:finish-output :force-output :clear-output)
795        (if out-ansi-stream-p
796            (funcall (ansi-stream-misc out) out operation arg1 arg2)
797            (stream-misc-dispatch out operation arg1 arg2)))
798       (:clear-input (clear-input in))
799       (:unread (unread-char arg1 in))
800       (:element-type
801        (let ((in-type (stream-element-type in))
802              (out-type (stream-element-type out)))
803          (if (equal in-type out-type)
804              in-type `(and ,in-type ,out-type))))
805       (:close
806        (set-closed-flame stream))
807       (t
808        (or (if in-ansi-stream-p
809                (funcall (ansi-stream-misc in) in operation arg1 arg2)
810                (stream-misc-dispatch in operation arg1 arg2))
811            (if out-ansi-stream-p
812                (funcall (ansi-stream-misc out) out operation arg1 arg2)
813                (stream-misc-dispatch out operation arg1 arg2)))))))
814 \f
815 ;;;; concatenated streams
816
817 (defstruct (concatenated-stream
818             (:include ansi-stream
819                       (in #'concatenated-in)
820                       (bin #'concatenated-bin)
821                       (n-bin #'concatenated-n-bin)
822                       (misc #'concatenated-misc))
823             (:constructor %make-concatenated-stream
824                           (&rest streams &aux (current streams)))
825             (:copier nil))
826   ;; The car of this is the substream we are reading from now.
827   current
828   ;; This is a list of all the substreams there ever were. We need to
829   ;; remember them so that we can close them.
830   ;;
831   ;; FIXME: ANSI says this is supposed to be the list of streams that
832   ;; we still have to read from. So either this needs to become a
833   ;; private member %STREAM (with CONCATENATED-STREAM-STREAMS a wrapper
834   ;; around it which discards closed files from the head of the list)
835   ;; or we need to update it as we run out of files.
836   (streams nil :type list :read-only t))
837 (def!method print-object ((x concatenated-stream) stream)
838   (print-unreadable-object (x stream :type t :identity t)
839     (format stream
840             ":STREAMS ~S"
841             (concatenated-stream-streams x))))
842
843 (defun make-concatenated-stream (&rest streams)
844   #!+sb-doc
845   "Return a stream which takes its input from each of the streams in turn,
846    going on to the next at EOF."
847   (dolist (stream streams)
848     (unless (or (and (synonym-stream-p stream)
849                      (input-stream-p (symbol-value
850                                       (synonym-stream-symbol stream))))
851                 (input-stream-p stream))
852       (error 'type-error
853              :datum stream
854              :expected-type '(satisfies input-stream-p))))
855   (apply #'%make-concatenated-stream streams))
856
857 (macrolet ((in-fun (name fun)
858              `(defun ,name (stream eof-error-p eof-value)
859                 (do ((current (concatenated-stream-current stream)
860                               (cdr current)))
861                     ((null current)
862                      (eof-or-lose stream eof-error-p eof-value))
863                   (let* ((stream (car current))
864                          (result (,fun stream nil nil)))
865                     (when result (return result)))
866                   (setf (concatenated-stream-current stream) current)))))
867   (in-fun concatenated-in read-char)
868   (in-fun concatenated-bin read-byte))
869
870 (defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
871   (do ((current (concatenated-stream-current stream) (cdr current))
872        (current-start start)
873        (remaining-bytes numbytes))
874       ((null current)
875        (if eof-errorp
876            (error 'end-of-file :stream stream)
877            (- numbytes remaining-bytes)))
878     (let* ((stream (car current))
879            (bytes-read (read-n-bytes stream buffer current-start
880                                      remaining-bytes nil)))
881       (incf current-start bytes-read)
882       (decf remaining-bytes bytes-read)
883       (when (zerop remaining-bytes) (return numbytes)))
884     (setf (concatenated-stream-current stream) (cdr current))))
885
886 (defun concatenated-misc (stream operation &optional arg1 arg2)
887   (let ((left (concatenated-stream-current stream)))
888     (when left
889       (let* ((current (car left)))
890         (case operation
891           (:listen
892            (loop
893              (let ((stuff (if (ansi-stream-p current)
894                               (funcall (ansi-stream-misc current) current
895                                        :listen)
896                               (stream-misc-dispatch current :listen))))
897                (cond ((eq stuff :eof)
898                       ;; Advance CURRENT, and try again.
899                       (pop (concatenated-stream-current stream))
900                       (setf current
901                             (car (concatenated-stream-current stream)))
902                       (unless current
903                         ;; No further streams. EOF.
904                         (return :eof)))
905                      (stuff
906                       ;; Stuff's available.
907                       (return t))
908                      (t
909                       ;; Nothing is available yet.
910                       (return nil))))))
911           (:clear-input (clear-input current))
912           (:unread (unread-char arg1 current))
913           (:close
914            (set-closed-flame stream))
915           (t
916            (if (ansi-stream-p current)
917                (funcall (ansi-stream-misc current) current operation arg1 arg2)
918                (stream-misc-dispatch current operation arg1 arg2))))))))
919 \f
920 ;;;; echo streams
921
922 (defstruct (echo-stream
923             (:include two-way-stream
924                       (in #'echo-in)
925                       (bin #'echo-bin)
926                       (misc #'echo-misc)
927                       (n-bin #'ill-bin))
928             (:constructor %make-echo-stream (input-stream output-stream))
929             (:copier nil))
930   unread-stuff)
931 (def!method print-object ((x echo-stream) stream)
932   (print-unreadable-object (x stream :type t :identity t)
933     (format stream
934             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
935             (two-way-stream-input-stream x)
936             (two-way-stream-output-stream x))))
937
938 (defun make-echo-stream (input-stream output-stream)
939   #!+sb-doc
940   "Return a bidirectional stream which gets its input from INPUT-STREAM and
941    sends its output to OUTPUT-STREAM. In addition, all input is echoed to
942    the output stream."
943   (unless (or (and (synonym-stream-p output-stream)
944                    (output-stream-p (symbol-value
945                                      (synonym-stream-symbol output-stream))))
946               (output-stream-p output-stream))
947     (error 'type-error
948            :datum output-stream
949            :expected-type '(satisfies output-stream-p)))
950   (unless (or (and (synonym-stream-p input-stream)
951                    (input-stream-p (symbol-value
952                                     (synonym-stream-symbol input-stream))))
953               (input-stream-p input-stream))
954     (error 'type-error
955            :datum input-stream
956            :expected-type '(satisfies input-stream-p)))
957   (funcall #'%make-echo-stream input-stream output-stream))
958
959 (macrolet ((in-fun (name fun out-slot stream-method &rest args)
960              `(defun ,name (stream ,@args)
961                 (or (pop (echo-stream-unread-stuff stream))
962                     (let* ((in (echo-stream-input-stream stream))
963                            (out (echo-stream-output-stream stream))
964                            (result (,fun in ,@args)))
965                       (if (ansi-stream-p out)
966                           (funcall (,out-slot out) out result)
967                           (,stream-method out result))
968                       result)))))
969   (in-fun echo-in read-char ansi-stream-out stream-write-char
970           eof-error-p eof-value)
971   (in-fun echo-bin read-byte ansi-stream-bout stream-write-byte
972           eof-error-p eof-value))
973
974 (defun echo-misc (stream operation &optional arg1 arg2)
975   (let* ((in (two-way-stream-input-stream stream))
976          (out (two-way-stream-output-stream stream)))
977     (case operation
978       (:listen
979        (or (not (null (echo-stream-unread-stuff stream)))
980            (if (ansi-stream-p in)
981                (or (/= (the fixnum (ansi-stream-in-index in))
982                        +ansi-stream-in-buffer-length+)
983                    (funcall (ansi-stream-misc in) in :listen))
984                (stream-misc-dispatch in :listen))))
985       (:unread (push arg1 (echo-stream-unread-stuff stream)))
986       (:element-type
987        (let ((in-type (stream-element-type in))
988              (out-type (stream-element-type out)))
989          (if (equal in-type out-type)
990              in-type `(and ,in-type ,out-type))))
991       (:close
992        (set-closed-flame stream))
993       (t
994        (or (if (ansi-stream-p in)
995                (funcall (ansi-stream-misc in) in operation arg1 arg2)
996                (stream-misc-dispatch in operation arg1 arg2))
997            (if (ansi-stream-p out)
998                (funcall (ansi-stream-misc out) out operation arg1 arg2)
999                (stream-misc-dispatch out operation arg1 arg2)))))))
1000
1001 \f
1002 ;;;; string input streams
1003
1004 (defstruct (string-input-stream
1005              (:include ansi-stream
1006                        (in #'string-inch)
1007                        (bin #'string-binch)
1008                        (n-bin #'string-stream-read-n-bytes)
1009                        (misc #'string-in-misc))
1010              (:constructor internal-make-string-input-stream
1011                            (string current end))
1012              (:copier nil))
1013   (string nil :type simple-string)
1014   (current nil :type index)
1015   (end nil :type index))
1016
1017 (defun string-inch (stream eof-error-p eof-value)
1018   (let ((string (string-input-stream-string stream))
1019         (index (string-input-stream-current stream)))
1020     (declare (simple-string string) (fixnum index))
1021     (cond ((= index (the index (string-input-stream-end stream)))
1022            (eof-or-lose stream eof-error-p eof-value))
1023           (t
1024            (setf (string-input-stream-current stream) (1+ index))
1025            (aref string index)))))
1026
1027 (defun string-binch (stream eof-error-p eof-value)
1028   (let ((string (string-input-stream-string stream))
1029         (index (string-input-stream-current stream)))
1030     (declare (simple-string string)
1031              (type index index))
1032     (cond ((= index (the index (string-input-stream-end stream)))
1033            (eof-or-lose stream eof-error-p eof-value))
1034           (t
1035            (setf (string-input-stream-current stream) (1+ index))
1036            (char-code (aref string index))))))
1037
1038 (defun string-stream-read-n-bytes (stream buffer start requested eof-error-p)
1039   (declare (type string-input-stream stream)
1040            (type index start requested))
1041   (let* ((string (string-input-stream-string stream))
1042          (index (string-input-stream-current stream))
1043          (available (- (string-input-stream-end stream) index))
1044          (copy (min available requested)))
1045     (declare (simple-string string)
1046              (type index index available copy))
1047     (when (plusp copy)
1048       (setf (string-input-stream-current stream)
1049             (truly-the index (+ index copy)))
1050       (sb!sys:without-gcing
1051        (system-area-copy (vector-sap string)
1052                          (* index sb!vm:n-byte-bits)
1053                          (if (typep buffer 'system-area-pointer)
1054                              buffer
1055                              (vector-sap buffer))
1056                          (* start sb!vm:n-byte-bits)
1057                          (* copy sb!vm:n-byte-bits))))
1058     (if (and (> requested copy) eof-error-p)
1059         (error 'end-of-file :stream stream)
1060         copy)))
1061
1062 (defun string-in-misc (stream operation &optional arg1 arg2)
1063   (declare (ignore arg2))
1064   (case operation
1065     (:file-position
1066      (if arg1
1067          (setf (string-input-stream-current stream) arg1)
1068          (string-input-stream-current stream)))
1069     (:file-length (length (string-input-stream-string stream)))
1070     (:unread (decf (string-input-stream-current stream)))
1071     (:listen (or (/= (the fixnum (string-input-stream-current stream))
1072                      (the fixnum (string-input-stream-end stream)))
1073                  :eof))
1074     (:element-type 'base-char)))
1075
1076 (defun make-string-input-stream (string &optional
1077                                         (start 0) (end (length string)))
1078   #!+sb-doc
1079   "Return an input stream which will supply the characters of STRING between
1080   START and END in order."
1081   (declare (type string string)
1082            (type index start)
1083            (type (or index null) end))
1084
1085   #!+high-security
1086   (when (> end (length string))
1087     (cerror "Continue with end changed from ~S to ~S"
1088             "Write-string: end (~S) is larger then the length of the string (~S)"
1089             end (1- (length string))))
1090
1091   (internal-make-string-input-stream (coerce string 'simple-string)
1092                                      start end))
1093 \f
1094 ;;;; string output streams
1095
1096 (defstruct (string-output-stream
1097             (:include ansi-stream
1098                       (out #'string-ouch)
1099                       (sout #'string-sout)
1100                       (misc #'string-out-misc))
1101             (:constructor make-string-output-stream ())
1102             (:copier nil))
1103   ;; The string we throw stuff in.
1104   (string (make-string 40) :type simple-string)
1105   ;; Index of the next location to use.
1106   (index 0 :type fixnum))
1107
1108 #!+sb-doc
1109 (setf (fdocumentation 'make-string-output-stream 'function)
1110   "Return an output stream which will accumulate all output given it for
1111    the benefit of the function GET-OUTPUT-STREAM-STRING.")
1112
1113 (defun string-ouch (stream character)
1114   (let ((current (string-output-stream-index stream))
1115         (workspace (string-output-stream-string stream)))
1116     (declare (simple-string workspace) (fixnum current))
1117     (if (= current (the fixnum (length workspace)))
1118         (let ((new-workspace (make-string (* current 2))))
1119           (replace new-workspace workspace)
1120           (setf (aref new-workspace current) character)
1121           (setf (string-output-stream-string stream) new-workspace))
1122         (setf (aref workspace current) character))
1123     (setf (string-output-stream-index stream) (1+ current))))
1124
1125 (defun string-sout (stream string start end)
1126   (declare (simple-string string) (fixnum start end))
1127   (let* ((current (string-output-stream-index stream))
1128          (length (- end start))
1129          (dst-end (+ length current))
1130          (workspace (string-output-stream-string stream)))
1131     (declare (simple-string workspace)
1132              (fixnum current length dst-end))
1133     (if (> dst-end (the fixnum (length workspace)))
1134         (let ((new-workspace (make-string (+ (* current 2) length))))
1135           (replace new-workspace workspace :end2 current)
1136           (replace new-workspace string
1137                    :start1 current :end1 dst-end
1138                    :start2 start :end2 end)
1139           (setf (string-output-stream-string stream) new-workspace))
1140         (replace workspace string
1141                  :start1 current :end1 dst-end
1142                  :start2 start :end2 end))
1143     (setf (string-output-stream-index stream) dst-end)))
1144
1145 (defun string-out-misc (stream operation &optional arg1 arg2)
1146   (declare (ignore arg2))
1147   (case operation
1148     (:file-position
1149      (if (null arg1)
1150          (string-output-stream-index stream)))
1151     (:charpos
1152      (do ((index (1- (the fixnum (string-output-stream-index stream)))
1153                  (1- index))
1154           (count 0 (1+ count))
1155           (string (string-output-stream-string stream)))
1156          ((< index 0) count)
1157        (declare (simple-string string)
1158                 (fixnum index count))
1159        (if (char= (schar string index) #\newline)
1160            (return count))))
1161     (:element-type 'base-char)))
1162
1163 ;;; Return a string of all the characters sent to a stream made by
1164 ;;; MAKE-STRING-OUTPUT-STREAM since the last call to this function.
1165 (defun get-output-stream-string (stream)
1166   (declare (type string-output-stream stream))
1167   (let* ((length (string-output-stream-index stream))
1168          (result (make-string length)))
1169     (replace result (string-output-stream-string stream))
1170     (setf (string-output-stream-index stream) 0)
1171     result))
1172
1173 ;;; Dump the characters buffer up in IN-STREAM to OUT-STREAM as
1174 ;;; GET-OUTPUT-STREAM-STRING would return them.
1175 (defun dump-output-stream-string (in-stream out-stream)
1176   (%write-string (string-output-stream-string in-stream)
1177                  out-stream
1178                  0
1179                  (string-output-stream-index in-stream))
1180   (setf (string-output-stream-index in-stream) 0))
1181 \f
1182 ;;;; fill-pointer streams
1183
1184 ;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
1185 ;;; the CLM, but they are required for the implementation of
1186 ;;; WITH-OUTPUT-TO-STRING.
1187
1188 (defstruct (fill-pointer-output-stream
1189             (:include ansi-stream
1190                       (out #'fill-pointer-ouch)
1191                       (sout #'fill-pointer-sout)
1192                       (misc #'fill-pointer-misc))
1193             (:constructor make-fill-pointer-output-stream (string))
1194             (:copier nil))
1195   ;; the string we throw stuff in
1196   string)
1197
1198 (defun fill-pointer-ouch (stream character)
1199   (let* ((buffer (fill-pointer-output-stream-string stream))
1200          (current (fill-pointer buffer))
1201          (current+1 (1+ current)))
1202     (declare (fixnum current))
1203     (with-array-data ((workspace buffer) (start) (end))
1204       (declare (simple-string workspace))
1205       (let ((offset-current (+ start current)))
1206         (declare (fixnum offset-current))
1207         (if (= offset-current end)
1208             (let* ((new-length (1+ (* current 2)))
1209                    (new-workspace (make-string new-length)))
1210               (declare (simple-string new-workspace))
1211               (%byte-blt workspace start
1212                          new-workspace 0 current)
1213               (setf workspace new-workspace)
1214               (setf offset-current current)
1215               (set-array-header buffer workspace new-length
1216                                 current+1 0 new-length nil))
1217             (setf (fill-pointer buffer) current+1))
1218         (setf (schar workspace offset-current) character)))
1219     current+1))
1220
1221 (defun fill-pointer-sout (stream string start end)
1222   (declare (simple-string string) (fixnum start end))
1223   (let* ((buffer (fill-pointer-output-stream-string stream))
1224          (current (fill-pointer buffer))
1225          (string-len (- end start))
1226          (dst-end (+ string-len current)))
1227     (declare (fixnum current dst-end string-len))
1228     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1229       (declare (simple-string workspace))
1230       (let ((offset-dst-end (+ dst-start dst-end))
1231             (offset-current (+ dst-start current)))
1232         (declare (fixnum offset-dst-end offset-current))
1233         (if (> offset-dst-end dst-length)
1234             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1235                    (new-workspace (make-string new-length)))
1236               (declare (simple-string new-workspace))
1237               (%byte-blt workspace dst-start
1238                          new-workspace 0 current)
1239               (setf workspace new-workspace)
1240               (setf offset-current current)
1241               (setf offset-dst-end dst-end)
1242               (set-array-header buffer
1243                                 workspace
1244                                 new-length
1245                                 dst-end
1246                                 0
1247                                 new-length
1248                                 nil))
1249             (setf (fill-pointer buffer) dst-end))
1250         (%byte-blt string start
1251                    workspace offset-current offset-dst-end)))
1252     dst-end))
1253
1254 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1255   (declare (ignore arg1 arg2))
1256   (case operation
1257     (:charpos
1258      (let* ((buffer (fill-pointer-output-stream-string stream))
1259             (current (fill-pointer buffer)))
1260        (with-array-data ((string buffer) (start) (end current))
1261          (declare (simple-string string) (ignore start))
1262          (let ((found (position #\newline string :test #'char=
1263                                 :end end :from-end t)))
1264            (if found
1265                (- end (the fixnum found))
1266                current)))))
1267      (:element-type 'base-char)))
1268 \f
1269 ;;;; indenting streams
1270
1271 (defstruct (indenting-stream (:include ansi-stream
1272                                        (out #'indenting-out)
1273                                        (sout #'indenting-sout)
1274                                        (misc #'indenting-misc))
1275                              (:constructor make-indenting-stream (stream))
1276                              (:copier nil))
1277   ;; the stream we're based on
1278   stream
1279   ;; how much we indent on each line
1280   (indentation 0))
1281
1282 #!+sb-doc
1283 (setf (fdocumentation 'make-indenting-stream 'function)
1284  "Return an output stream which indents its output by some amount.")
1285
1286 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1287 ;;; output on the given STREAM based on the specified SUB-STREAM.
1288 (defmacro indenting-indent (stream sub-stream)
1289   ;; KLUDGE: bare magic number 60
1290   `(do ((i 0 (+ i 60))
1291         (indentation (indenting-stream-indentation ,stream)))
1292        ((>= i indentation))
1293      (%write-string
1294       "                                                     "
1295       ,sub-stream
1296       0
1297       (min 60 (- indentation i)))))
1298
1299 ;;; INDENTING-OUT writes a character to an indenting stream.
1300 (defun indenting-out (stream char)
1301   (let ((sub-stream (indenting-stream-stream stream)))
1302     (write-char char sub-stream)
1303     (if (char= char #\newline)
1304         (indenting-indent stream sub-stream))))
1305
1306 ;;; INDENTING-SOUT writes a string to an indenting stream.
1307 (defun indenting-sout (stream string start end)
1308   (declare (simple-string string) (fixnum start end))
1309   (do ((i start)
1310        (sub-stream (indenting-stream-stream stream)))
1311       ((= i end))
1312     (let ((newline (position #\newline string :start i :end end)))
1313       (cond (newline
1314              (%write-string string sub-stream i (1+ newline))
1315              (indenting-indent stream sub-stream)
1316              (setq i (+ newline 1)))
1317             (t
1318              (%write-string string sub-stream i end)
1319              (setq i end))))))
1320
1321 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1322 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1323 ;;; the base stream minus the stream's indentation.
1324 (defun indenting-misc (stream operation &optional arg1 arg2)
1325   (let ((sub-stream (indenting-stream-stream stream)))
1326     (if (ansi-stream-p sub-stream)
1327         (let ((method (ansi-stream-misc sub-stream)))
1328           (case operation
1329             (:line-length
1330              (let ((line-length (funcall method sub-stream operation)))
1331                (if line-length
1332                    (- line-length (indenting-stream-indentation stream)))))
1333             (:charpos
1334              (let ((charpos (funcall method sub-stream operation)))
1335                (if charpos
1336                    (- charpos (indenting-stream-indentation stream)))))
1337             (t
1338              (funcall method sub-stream operation arg1 arg2))))
1339         ;; must be Gray streams FUNDAMENTAL-STREAM
1340         (case operation
1341           (:line-length
1342            (let ((line-length (stream-line-length sub-stream)))
1343              (if line-length
1344                  (- line-length (indenting-stream-indentation stream)))))
1345           (:charpos
1346            (let ((charpos (stream-line-column sub-stream)))
1347              (if charpos
1348                  (- charpos (indenting-stream-indentation stream)))))
1349           (t
1350            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1351
1352 (declaim (maybe-inline read-char unread-char read-byte listen))
1353 \f
1354 ;;;; case frobbing streams, used by FORMAT ~(...~)
1355
1356 (defstruct (case-frob-stream
1357             (:include ansi-stream
1358                       (misc #'case-frob-misc))
1359             (:constructor %make-case-frob-stream (target out sout))
1360             (:copier nil))
1361   (target (missing-arg) :type stream))
1362
1363 (defun make-case-frob-stream (target kind)
1364   #!+sb-doc
1365   "Return a stream that sends all output to the stream TARGET, but modifies
1366    the case of letters, depending on KIND, which should be one of:
1367      :upcase - convert to upper case.
1368      :downcase - convert to lower case.
1369      :capitalize - convert the first letter of words to upper case and the
1370         rest of the word to lower case.
1371      :capitalize-first - convert the first letter of the first word to upper
1372         case and everything else to lower case."
1373   (declare (type stream target)
1374            (type (member :upcase :downcase :capitalize :capitalize-first)
1375                  kind)
1376            (values stream))
1377   (if (case-frob-stream-p target)
1378       ;; If we are going to be writing to a stream that already does
1379       ;; case frobbing, why bother frobbing the case just so it can
1380       ;; frob it again?
1381       target
1382       (multiple-value-bind (out sout)
1383           (ecase kind
1384             (:upcase
1385              (values #'case-frob-upcase-out
1386                      #'case-frob-upcase-sout))
1387             (:downcase
1388              (values #'case-frob-downcase-out
1389                      #'case-frob-downcase-sout))
1390             (:capitalize
1391              (values #'case-frob-capitalize-out
1392                      #'case-frob-capitalize-sout))
1393             (:capitalize-first
1394              (values #'case-frob-capitalize-first-out
1395                      #'case-frob-capitalize-first-sout)))
1396         (%make-case-frob-stream target out sout))))
1397
1398 (defun case-frob-misc (stream op &optional arg1 arg2)
1399   (declare (type case-frob-stream stream))
1400   (case op
1401     (:close)
1402     (t
1403      (let ((target (case-frob-stream-target stream)))
1404        (if (ansi-stream-p target)
1405            (funcall (ansi-stream-misc target) target op arg1 arg2)
1406            (stream-misc-dispatch target op arg1 arg2))))))
1407
1408 (defun case-frob-upcase-out (stream char)
1409   (declare (type case-frob-stream stream)
1410            (type base-char char))
1411   (let ((target (case-frob-stream-target stream))
1412         (char (char-upcase char)))
1413     (if (ansi-stream-p target)
1414         (funcall (ansi-stream-out target) target char)
1415         (stream-write-char target char))))
1416
1417 (defun case-frob-upcase-sout (stream str start end)
1418   (declare (type case-frob-stream stream)
1419            (type simple-base-string str)
1420            (type index start)
1421            (type (or index null) end))
1422   (let* ((target (case-frob-stream-target stream))
1423          (len (length str))
1424          (end (or end len))
1425          (string (if (and (zerop start) (= len end))
1426                      (string-upcase str)
1427                      (nstring-upcase (subseq str start end))))
1428          (string-len (- end start)))
1429     (if (ansi-stream-p target)
1430         (funcall (ansi-stream-sout target) target string 0 string-len)
1431         (stream-write-string target string 0 string-len))))
1432
1433 (defun case-frob-downcase-out (stream char)
1434   (declare (type case-frob-stream stream)
1435            (type base-char char))
1436   (let ((target (case-frob-stream-target stream))
1437         (char (char-downcase char)))
1438     (if (ansi-stream-p target)
1439         (funcall (ansi-stream-out target) target char)
1440         (stream-write-char target char))))
1441
1442 (defun case-frob-downcase-sout (stream str start end)
1443   (declare (type case-frob-stream stream)
1444            (type simple-base-string str)
1445            (type index start)
1446            (type (or index null) end))
1447   (let* ((target (case-frob-stream-target stream))
1448          (len (length str))
1449          (end (or end len))
1450          (string (if (and (zerop start) (= len end))
1451                      (string-downcase str)
1452                      (nstring-downcase (subseq str start end))))
1453          (string-len (- end start)))
1454     (if (ansi-stream-p target)
1455         (funcall (ansi-stream-sout target) target string 0 string-len)
1456         (stream-write-string target string 0 string-len))))
1457
1458 (defun case-frob-capitalize-out (stream char)
1459   (declare (type case-frob-stream stream)
1460            (type base-char char))
1461   (let ((target (case-frob-stream-target stream)))
1462     (cond ((alphanumericp char)
1463            (let ((char (char-upcase char)))
1464              (if (ansi-stream-p target)
1465                  (funcall (ansi-stream-out target) target char)
1466                  (stream-write-char target char)))
1467            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1468            (setf (case-frob-stream-sout stream)
1469                  #'case-frob-capitalize-aux-sout))
1470           (t
1471            (if (ansi-stream-p target)
1472                (funcall (ansi-stream-out target) target char)
1473                (stream-write-char target char))))))
1474
1475 (defun case-frob-capitalize-sout (stream str start end)
1476   (declare (type case-frob-stream stream)
1477            (type simple-base-string str)
1478            (type index start)
1479            (type (or index null) end))
1480   (let* ((target (case-frob-stream-target stream))
1481          (str (subseq str start end))
1482          (len (length str))
1483          (inside-word nil))
1484     (dotimes (i len)
1485       (let ((char (schar str i)))
1486         (cond ((not (alphanumericp char))
1487                (setf inside-word nil))
1488               (inside-word
1489                (setf (schar str i) (char-downcase char)))
1490               (t
1491                (setf inside-word t)
1492                (setf (schar str i) (char-upcase char))))))
1493     (when inside-word
1494       (setf (case-frob-stream-out stream)
1495             #'case-frob-capitalize-aux-out)
1496       (setf (case-frob-stream-sout stream)
1497             #'case-frob-capitalize-aux-sout))
1498     (if (ansi-stream-p target)
1499         (funcall (ansi-stream-sout target) target str 0 len)
1500         (stream-write-string target str 0 len))))
1501
1502 (defun case-frob-capitalize-aux-out (stream char)
1503   (declare (type case-frob-stream stream)
1504            (type base-char char))
1505   (let ((target (case-frob-stream-target stream)))
1506     (cond ((alphanumericp char)
1507            (let ((char (char-downcase char)))
1508              (if (ansi-stream-p target)
1509                  (funcall (ansi-stream-out target) target char)
1510                  (stream-write-char target char))))
1511           (t
1512            (if (ansi-stream-p target)
1513                (funcall (ansi-stream-out target) target char)
1514                (stream-write-char target char))
1515            (setf (case-frob-stream-out stream)
1516                  #'case-frob-capitalize-out)
1517            (setf (case-frob-stream-sout stream)
1518                  #'case-frob-capitalize-sout)))))
1519
1520 (defun case-frob-capitalize-aux-sout (stream str start end)
1521   (declare (type case-frob-stream stream)
1522            (type simple-base-string str)
1523            (type index start)
1524            (type (or index null) end))
1525   (let* ((target (case-frob-stream-target stream))
1526          (str (subseq str start end))
1527          (len (length str))
1528          (inside-word t))
1529     (dotimes (i len)
1530       (let ((char (schar str i)))
1531         (cond ((not (alphanumericp char))
1532                (setf inside-word nil))
1533               (inside-word
1534                (setf (schar str i) (char-downcase char)))
1535               (t
1536                (setf inside-word t)
1537                (setf (schar str i) (char-upcase char))))))
1538     (unless inside-word
1539       (setf (case-frob-stream-out stream)
1540             #'case-frob-capitalize-out)
1541       (setf (case-frob-stream-sout stream)
1542             #'case-frob-capitalize-sout))
1543     (if (ansi-stream-p target)
1544         (funcall (ansi-stream-sout target) target str 0 len)
1545         (stream-write-string target str 0 len))))
1546
1547 (defun case-frob-capitalize-first-out (stream char)
1548   (declare (type case-frob-stream stream)
1549            (type base-char char))
1550   (let ((target (case-frob-stream-target stream)))
1551     (cond ((alphanumericp char)
1552            (let ((char (char-upcase char)))
1553              (if (ansi-stream-p target)
1554                  (funcall (ansi-stream-out target) target char)
1555                  (stream-write-char target char)))
1556            (setf (case-frob-stream-out stream)
1557                  #'case-frob-downcase-out)
1558            (setf (case-frob-stream-sout stream)
1559                  #'case-frob-downcase-sout))
1560           (t
1561            (if (ansi-stream-p target)
1562                (funcall (ansi-stream-out target) target char)
1563                (stream-write-char target char))))))
1564
1565 (defun case-frob-capitalize-first-sout (stream str start end)
1566   (declare (type case-frob-stream stream)
1567            (type simple-base-string str)
1568            (type index start)
1569            (type (or index null) end))
1570   (let* ((target (case-frob-stream-target stream))
1571          (str (subseq str start end))
1572          (len (length str)))
1573     (dotimes (i len)
1574       (let ((char (schar str i)))
1575         (when (alphanumericp char)
1576           (setf (schar str i) (char-upcase char))
1577           (do ((i (1+ i) (1+ i)))
1578               ((= i len))
1579             (setf (schar str i) (char-downcase (schar str i))))
1580           (setf (case-frob-stream-out stream)
1581                 #'case-frob-downcase-out)
1582           (setf (case-frob-stream-sout stream)
1583                 #'case-frob-downcase-sout)
1584           (return))))
1585     (if (ansi-stream-p target)
1586         (funcall (ansi-stream-sout target) target str 0 len)
1587         (stream-write-string target str 0 len))))
1588 \f
1589 ;;;; stream commands
1590
1591 (defstruct (stream-command (:constructor make-stream-command
1592                                          (name &optional args))
1593                            (:copier nil))
1594   (name nil :type symbol)
1595   (args nil :type list))
1596 (def!method print-object ((obj stream-command) str)
1597   (print-unreadable-object (obj str :type t :identity t)
1598     (prin1 (stream-command-name obj) str)))
1599
1600 ;;; Take a stream and wait for text or a command to appear on it. If
1601 ;;; text appears before a command, return NIL, otherwise return a
1602 ;;; command.
1603 ;;;
1604 ;;; We can't simply call the stream's misc method because NIL is an
1605 ;;; ambiguous return value: does it mean text arrived, or does it mean
1606 ;;; the stream's misc method had no :GET-COMMAND implementation? We
1607 ;;; can't return NIL until there is text input. We don't need to loop
1608 ;;; because any stream implementing :GET-COMMAND would wait until it
1609 ;;; had some input. If the LISTEN fails, then we have some stream we
1610 ;;; must wait on.
1611 (defun get-stream-command (stream)
1612   (let ((cmdp (funcall (ansi-stream-misc stream) stream :get-command)))
1613     (cond (cmdp)
1614           ((listen stream)
1615            nil)
1616           (t
1617            ;; This waits for input and returns NIL when it arrives.
1618            (unread-char (read-char stream) stream)))))
1619 \f
1620 ;;;; READ-SEQUENCE
1621
1622 (defun read-sequence (seq stream &key (start 0) (end nil))
1623   #!+sb-doc
1624   "Destructively modify SEQ by reading elements from STREAM.
1625   That part of SEQ bounded by START and END is destructively modified by
1626   copying successive elements into it from STREAM. If the end of file
1627   for STREAM is reached before copying all elements of the subsequence,
1628   then the extra elements near the end of sequence are not updated, and
1629   the index of the next element is returned."
1630   (declare (type sequence seq)
1631            (type stream stream)
1632            (type index start)
1633            (type sequence-end end)
1634            (values index))
1635   (if (ansi-stream-p stream)
1636       (ansi-stream-read-sequence seq stream start end)
1637       ;; must be Gray streams FUNDAMENTAL-STREAM
1638       (stream-read-sequence stream seq start end)))
1639
1640 (defun ansi-stream-read-sequence (seq stream start %end)
1641   (declare (type sequence seq)
1642            (type ansi-stream stream)
1643            (type index start)
1644            (type sequence-end %end)
1645            (values index))
1646   (let ((end (or %end (length seq))))
1647     (declare (type index end))
1648     (etypecase seq
1649       (list
1650        (let ((read-function
1651               (if (subtypep (stream-element-type stream) 'character)
1652                   #'read-char
1653                   #'read-byte)))
1654          (do ((rem (nthcdr start seq) (rest rem))
1655               (i start (1+ i)))
1656              ((or (endp rem) (>= i end)) i)
1657            (declare (type list rem)
1658                     (type index i))
1659            (let ((el (funcall read-function stream nil :eof)))
1660              (when (eq el :eof)
1661                (return i))
1662              (setf (first rem) el)))))
1663       (vector
1664        (with-array-data ((data seq) (offset-start start) (offset-end end))
1665          (typecase data
1666            ((or (simple-array (unsigned-byte 8) (*))
1667                 (simple-array (signed-byte 8) (*))
1668                 simple-string)
1669             (let* ((numbytes (- end start))
1670                    (bytes-read (sb!sys:read-n-bytes stream
1671                                                     data
1672                                                     offset-start
1673                                                     numbytes
1674                                                     nil)))
1675               (if (< bytes-read numbytes)
1676                   (+ start bytes-read)
1677                   end)))
1678            (t
1679             (let ((read-function
1680                    (if (subtypep (stream-element-type stream) 'character)
1681                        #'read-char
1682                        #'read-byte)))
1683               (do ((i offset-start (1+ i)))
1684                   ((>= i offset-end) end)
1685                 (declare (type index i))
1686                 (let ((el (funcall read-function stream nil :eof)))
1687                   (when (eq el :eof)
1688                     (return (+ start (- i offset-start))))
1689                   (setf (aref data i) el)))))))))))
1690 \f
1691 ;;;; WRITE-SEQUENCE
1692
1693 (defun write-sequence (seq stream &key (start 0) (end nil))
1694   #!+sb-doc
1695   "Write the elements of SEQ bounded by START and END to STREAM."
1696   (declare (type sequence seq)
1697            (type stream stream)
1698            (type index start)
1699            (type sequence-end end)
1700            (values sequence))
1701   (if (ansi-stream-p stream)
1702       (ansi-stream-write-sequence seq stream start end)
1703       ;; must be Gray-streams FUNDAMENTAL-STREAM
1704       (stream-write-sequence stream seq start end)))
1705
1706 (defun ansi-stream-write-sequence (seq stream start %end)
1707   (declare (type sequence seq)
1708            (type ansi-stream stream)
1709            (type index start)
1710            (type sequence-end %end)
1711            (values sequence))
1712   (let ((end (or %end (length seq))))
1713     (declare (type index end))
1714     (etypecase seq
1715       (list
1716        (let ((write-function
1717               (if (subtypep (stream-element-type stream) 'character)
1718                   #'write-char
1719                   #'write-byte)))
1720          (do ((rem (nthcdr start seq) (rest rem))
1721               (i start (1+ i)))
1722              ((or (endp rem) (>= i end)) seq)
1723            (declare (type list rem)
1724                     (type index i))
1725            (funcall write-function (first rem) stream))))
1726       (string
1727        (%write-string seq stream start end))
1728       (vector
1729        (let ((write-function
1730               (if (subtypep (stream-element-type stream) 'character)
1731                   #'write-char
1732                   #'write-byte)))
1733          (do ((i start (1+ i)))
1734              ((>= i end) seq)
1735            (declare (type index i))
1736            (funcall write-function (aref seq i) stream)))))))
1737 \f
1738 ;;;; etc.
1739
1740 ;;; (These were inline throughout this file, but that's not appropriate
1741 ;;; globally.)
1742 (declaim (maybe-inline read-char unread-char read-byte listen))