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