0.7.7.24:
[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   ;; a string with a fill pointer where we stuff the stuff we write
1196   (string (error "missing argument") :type string :read-only t))
1197
1198 (defun make-fill-pointer-output-stream (string)
1199   (declare (type string string))
1200   (fill-pointer string) ; called for side effect of checking has-fill-pointer
1201   (%make-fill-pointer-output-stream string))
1202
1203 (defun fill-pointer-ouch (stream character)
1204   (let* ((buffer (fill-pointer-output-stream-string stream))
1205          (current (fill-pointer buffer))
1206          (current+1 (1+ current)))
1207     (declare (fixnum current))
1208     (with-array-data ((workspace buffer) (start) (end))
1209       (declare (simple-string workspace))
1210       (let ((offset-current (+ start current)))
1211         (declare (fixnum offset-current))
1212         (if (= offset-current end)
1213             (let* ((new-length (1+ (* current 2)))
1214                    (new-workspace (make-string new-length)))
1215               (declare (simple-string new-workspace))
1216               (%byte-blt workspace start
1217                          new-workspace 0 current)
1218               (setf workspace new-workspace)
1219               (setf offset-current current)
1220               (set-array-header buffer workspace new-length
1221                                 current+1 0 new-length nil))
1222             (setf (fill-pointer buffer) current+1))
1223         (setf (schar workspace offset-current) character)))
1224     current+1))
1225
1226 (defun fill-pointer-sout (stream string start end)
1227   (declare (simple-string string) (fixnum start end))
1228   (let* ((buffer (fill-pointer-output-stream-string stream))
1229          (current (fill-pointer buffer))
1230          (string-len (- end start))
1231          (dst-end (+ string-len current)))
1232     (declare (fixnum current dst-end string-len))
1233     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1234       (declare (simple-string workspace))
1235       (let ((offset-dst-end (+ dst-start dst-end))
1236             (offset-current (+ dst-start current)))
1237         (declare (fixnum offset-dst-end offset-current))
1238         (if (> offset-dst-end dst-length)
1239             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1240                    (new-workspace (make-string new-length)))
1241               (declare (simple-string new-workspace))
1242               (%byte-blt workspace dst-start
1243                          new-workspace 0 current)
1244               (setf workspace new-workspace)
1245               (setf offset-current current)
1246               (setf offset-dst-end dst-end)
1247               (set-array-header buffer
1248                                 workspace
1249                                 new-length
1250                                 dst-end
1251                                 0
1252                                 new-length
1253                                 nil))
1254             (setf (fill-pointer buffer) dst-end))
1255         (%byte-blt string start
1256                    workspace offset-current offset-dst-end)))
1257     dst-end))
1258
1259 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1260   (declare (ignore arg1 arg2))
1261   (case operation
1262     (:charpos
1263      (let* ((buffer (fill-pointer-output-stream-string stream))
1264             (current (fill-pointer buffer)))
1265        (with-array-data ((string buffer) (start) (end current))
1266          (declare (simple-string string) (ignore start))
1267          (let ((found (position #\newline string :test #'char=
1268                                 :end end :from-end t)))
1269            (if found
1270                (- end (the fixnum found))
1271                current)))))
1272      (:element-type 'base-char)))
1273 \f
1274 ;;;; indenting streams
1275
1276 (defstruct (indenting-stream (:include ansi-stream
1277                                        (out #'indenting-out)
1278                                        (sout #'indenting-sout)
1279                                        (misc #'indenting-misc))
1280                              (:constructor make-indenting-stream (stream))
1281                              (:copier nil))
1282   ;; the stream we're based on
1283   stream
1284   ;; how much we indent on each line
1285   (indentation 0))
1286
1287 #!+sb-doc
1288 (setf (fdocumentation 'make-indenting-stream 'function)
1289  "Return an output stream which indents its output by some amount.")
1290
1291 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1292 ;;; output on the given STREAM based on the specified SUB-STREAM.
1293 (defmacro indenting-indent (stream sub-stream)
1294   ;; KLUDGE: bare magic number 60
1295   `(do ((i 0 (+ i 60))
1296         (indentation (indenting-stream-indentation ,stream)))
1297        ((>= i indentation))
1298      (%write-string
1299       "                                                     "
1300       ,sub-stream
1301       0
1302       (min 60 (- indentation i)))))
1303
1304 ;;; INDENTING-OUT writes a character to an indenting stream.
1305 (defun indenting-out (stream char)
1306   (let ((sub-stream (indenting-stream-stream stream)))
1307     (write-char char sub-stream)
1308     (if (char= char #\newline)
1309         (indenting-indent stream sub-stream))))
1310
1311 ;;; INDENTING-SOUT writes a string to an indenting stream.
1312 (defun indenting-sout (stream string start end)
1313   (declare (simple-string string) (fixnum start end))
1314   (do ((i start)
1315        (sub-stream (indenting-stream-stream stream)))
1316       ((= i end))
1317     (let ((newline (position #\newline string :start i :end end)))
1318       (cond (newline
1319              (%write-string string sub-stream i (1+ newline))
1320              (indenting-indent stream sub-stream)
1321              (setq i (+ newline 1)))
1322             (t
1323              (%write-string string sub-stream i end)
1324              (setq i end))))))
1325
1326 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1327 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1328 ;;; the base stream minus the stream's indentation.
1329 (defun indenting-misc (stream operation &optional arg1 arg2)
1330   (let ((sub-stream (indenting-stream-stream stream)))
1331     (if (ansi-stream-p sub-stream)
1332         (let ((method (ansi-stream-misc sub-stream)))
1333           (case operation
1334             (:line-length
1335              (let ((line-length (funcall method sub-stream operation)))
1336                (if line-length
1337                    (- line-length (indenting-stream-indentation stream)))))
1338             (:charpos
1339              (let ((charpos (funcall method sub-stream operation)))
1340                (if charpos
1341                    (- charpos (indenting-stream-indentation stream)))))
1342             (t
1343              (funcall method sub-stream operation arg1 arg2))))
1344         ;; must be Gray streams FUNDAMENTAL-STREAM
1345         (case operation
1346           (:line-length
1347            (let ((line-length (stream-line-length sub-stream)))
1348              (if line-length
1349                  (- line-length (indenting-stream-indentation stream)))))
1350           (:charpos
1351            (let ((charpos (stream-line-column sub-stream)))
1352              (if charpos
1353                  (- charpos (indenting-stream-indentation stream)))))
1354           (t
1355            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1356
1357 (declaim (maybe-inline read-char unread-char read-byte listen))
1358 \f
1359 ;;;; case frobbing streams, used by FORMAT ~(...~)
1360
1361 (defstruct (case-frob-stream
1362             (:include ansi-stream
1363                       (misc #'case-frob-misc))
1364             (:constructor %make-case-frob-stream (target out sout))
1365             (:copier nil))
1366   (target (missing-arg) :type stream))
1367
1368 (defun make-case-frob-stream (target kind)
1369   #!+sb-doc
1370   "Return a stream that sends all output to the stream TARGET, but modifies
1371    the case of letters, depending on KIND, which should be one of:
1372      :upcase - convert to upper case.
1373      :downcase - convert to lower case.
1374      :capitalize - convert the first letter of words to upper case and the
1375         rest of the word to lower case.
1376      :capitalize-first - convert the first letter of the first word to upper
1377         case and everything else to lower case."
1378   (declare (type stream target)
1379            (type (member :upcase :downcase :capitalize :capitalize-first)
1380                  kind)
1381            (values stream))
1382   (if (case-frob-stream-p target)
1383       ;; If we are going to be writing to a stream that already does
1384       ;; case frobbing, why bother frobbing the case just so it can
1385       ;; frob it again?
1386       target
1387       (multiple-value-bind (out sout)
1388           (ecase kind
1389             (:upcase
1390              (values #'case-frob-upcase-out
1391                      #'case-frob-upcase-sout))
1392             (:downcase
1393              (values #'case-frob-downcase-out
1394                      #'case-frob-downcase-sout))
1395             (:capitalize
1396              (values #'case-frob-capitalize-out
1397                      #'case-frob-capitalize-sout))
1398             (:capitalize-first
1399              (values #'case-frob-capitalize-first-out
1400                      #'case-frob-capitalize-first-sout)))
1401         (%make-case-frob-stream target out sout))))
1402
1403 (defun case-frob-misc (stream op &optional arg1 arg2)
1404   (declare (type case-frob-stream stream))
1405   (case op
1406     (:close)
1407     (t
1408      (let ((target (case-frob-stream-target stream)))
1409        (if (ansi-stream-p target)
1410            (funcall (ansi-stream-misc target) target op arg1 arg2)
1411            (stream-misc-dispatch target op arg1 arg2))))))
1412
1413 (defun case-frob-upcase-out (stream char)
1414   (declare (type case-frob-stream stream)
1415            (type base-char char))
1416   (let ((target (case-frob-stream-target stream))
1417         (char (char-upcase char)))
1418     (if (ansi-stream-p target)
1419         (funcall (ansi-stream-out target) target char)
1420         (stream-write-char target char))))
1421
1422 (defun case-frob-upcase-sout (stream str start end)
1423   (declare (type case-frob-stream stream)
1424            (type simple-base-string str)
1425            (type index start)
1426            (type (or index null) end))
1427   (let* ((target (case-frob-stream-target stream))
1428          (len (length str))
1429          (end (or end len))
1430          (string (if (and (zerop start) (= len end))
1431                      (string-upcase str)
1432                      (nstring-upcase (subseq str start end))))
1433          (string-len (- end start)))
1434     (if (ansi-stream-p target)
1435         (funcall (ansi-stream-sout target) target string 0 string-len)
1436         (stream-write-string target string 0 string-len))))
1437
1438 (defun case-frob-downcase-out (stream char)
1439   (declare (type case-frob-stream stream)
1440            (type base-char char))
1441   (let ((target (case-frob-stream-target stream))
1442         (char (char-downcase char)))
1443     (if (ansi-stream-p target)
1444         (funcall (ansi-stream-out target) target char)
1445         (stream-write-char target char))))
1446
1447 (defun case-frob-downcase-sout (stream str start end)
1448   (declare (type case-frob-stream stream)
1449            (type simple-base-string str)
1450            (type index start)
1451            (type (or index null) end))
1452   (let* ((target (case-frob-stream-target stream))
1453          (len (length str))
1454          (end (or end len))
1455          (string (if (and (zerop start) (= len end))
1456                      (string-downcase str)
1457                      (nstring-downcase (subseq str start end))))
1458          (string-len (- end start)))
1459     (if (ansi-stream-p target)
1460         (funcall (ansi-stream-sout target) target string 0 string-len)
1461         (stream-write-string target string 0 string-len))))
1462
1463 (defun case-frob-capitalize-out (stream char)
1464   (declare (type case-frob-stream stream)
1465            (type base-char char))
1466   (let ((target (case-frob-stream-target stream)))
1467     (cond ((alphanumericp char)
1468            (let ((char (char-upcase char)))
1469              (if (ansi-stream-p target)
1470                  (funcall (ansi-stream-out target) target char)
1471                  (stream-write-char target char)))
1472            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1473            (setf (case-frob-stream-sout stream)
1474                  #'case-frob-capitalize-aux-sout))
1475           (t
1476            (if (ansi-stream-p target)
1477                (funcall (ansi-stream-out target) target char)
1478                (stream-write-char target char))))))
1479
1480 (defun case-frob-capitalize-sout (stream str start end)
1481   (declare (type case-frob-stream stream)
1482            (type simple-base-string str)
1483            (type index start)
1484            (type (or index null) end))
1485   (let* ((target (case-frob-stream-target stream))
1486          (str (subseq str start end))
1487          (len (length str))
1488          (inside-word nil))
1489     (dotimes (i len)
1490       (let ((char (schar str i)))
1491         (cond ((not (alphanumericp char))
1492                (setf inside-word nil))
1493               (inside-word
1494                (setf (schar str i) (char-downcase char)))
1495               (t
1496                (setf inside-word t)
1497                (setf (schar str i) (char-upcase char))))))
1498     (when inside-word
1499       (setf (case-frob-stream-out stream)
1500             #'case-frob-capitalize-aux-out)
1501       (setf (case-frob-stream-sout stream)
1502             #'case-frob-capitalize-aux-sout))
1503     (if (ansi-stream-p target)
1504         (funcall (ansi-stream-sout target) target str 0 len)
1505         (stream-write-string target str 0 len))))
1506
1507 (defun case-frob-capitalize-aux-out (stream char)
1508   (declare (type case-frob-stream stream)
1509            (type base-char char))
1510   (let ((target (case-frob-stream-target stream)))
1511     (cond ((alphanumericp char)
1512            (let ((char (char-downcase char)))
1513              (if (ansi-stream-p target)
1514                  (funcall (ansi-stream-out target) target char)
1515                  (stream-write-char target char))))
1516           (t
1517            (if (ansi-stream-p target)
1518                (funcall (ansi-stream-out target) target char)
1519                (stream-write-char target char))
1520            (setf (case-frob-stream-out stream)
1521                  #'case-frob-capitalize-out)
1522            (setf (case-frob-stream-sout stream)
1523                  #'case-frob-capitalize-sout)))))
1524
1525 (defun case-frob-capitalize-aux-sout (stream str start end)
1526   (declare (type case-frob-stream stream)
1527            (type simple-base-string str)
1528            (type index start)
1529            (type (or index null) end))
1530   (let* ((target (case-frob-stream-target stream))
1531          (str (subseq str start end))
1532          (len (length str))
1533          (inside-word t))
1534     (dotimes (i len)
1535       (let ((char (schar str i)))
1536         (cond ((not (alphanumericp char))
1537                (setf inside-word nil))
1538               (inside-word
1539                (setf (schar str i) (char-downcase char)))
1540               (t
1541                (setf inside-word t)
1542                (setf (schar str i) (char-upcase char))))))
1543     (unless inside-word
1544       (setf (case-frob-stream-out stream)
1545             #'case-frob-capitalize-out)
1546       (setf (case-frob-stream-sout stream)
1547             #'case-frob-capitalize-sout))
1548     (if (ansi-stream-p target)
1549         (funcall (ansi-stream-sout target) target str 0 len)
1550         (stream-write-string target str 0 len))))
1551
1552 (defun case-frob-capitalize-first-out (stream char)
1553   (declare (type case-frob-stream stream)
1554            (type base-char char))
1555   (let ((target (case-frob-stream-target stream)))
1556     (cond ((alphanumericp char)
1557            (let ((char (char-upcase char)))
1558              (if (ansi-stream-p target)
1559                  (funcall (ansi-stream-out target) target char)
1560                  (stream-write-char target char)))
1561            (setf (case-frob-stream-out stream)
1562                  #'case-frob-downcase-out)
1563            (setf (case-frob-stream-sout stream)
1564                  #'case-frob-downcase-sout))
1565           (t
1566            (if (ansi-stream-p target)
1567                (funcall (ansi-stream-out target) target char)
1568                (stream-write-char target char))))))
1569
1570 (defun case-frob-capitalize-first-sout (stream str start end)
1571   (declare (type case-frob-stream stream)
1572            (type simple-base-string str)
1573            (type index start)
1574            (type (or index null) end))
1575   (let* ((target (case-frob-stream-target stream))
1576          (str (subseq str start end))
1577          (len (length str)))
1578     (dotimes (i len)
1579       (let ((char (schar str i)))
1580         (when (alphanumericp char)
1581           (setf (schar str i) (char-upcase char))
1582           (do ((i (1+ i) (1+ i)))
1583               ((= i len))
1584             (setf (schar str i) (char-downcase (schar str i))))
1585           (setf (case-frob-stream-out stream)
1586                 #'case-frob-downcase-out)
1587           (setf (case-frob-stream-sout stream)
1588                 #'case-frob-downcase-sout)
1589           (return))))
1590     (if (ansi-stream-p target)
1591         (funcall (ansi-stream-sout target) target str 0 len)
1592         (stream-write-string target str 0 len))))
1593 \f
1594 ;;;; stream commands
1595
1596 (defstruct (stream-command (:constructor make-stream-command
1597                                          (name &optional args))
1598                            (:copier nil))
1599   (name nil :type symbol)
1600   (args nil :type list))
1601 (def!method print-object ((obj stream-command) str)
1602   (print-unreadable-object (obj str :type t :identity t)
1603     (prin1 (stream-command-name obj) str)))
1604
1605 ;;; Take a stream and wait for text or a command to appear on it. If
1606 ;;; text appears before a command, return NIL, otherwise return a
1607 ;;; command.
1608 ;;;
1609 ;;; We can't simply call the stream's misc method because NIL is an
1610 ;;; ambiguous return value: does it mean text arrived, or does it mean
1611 ;;; the stream's misc method had no :GET-COMMAND implementation? We
1612 ;;; can't return NIL until there is text input. We don't need to loop
1613 ;;; because any stream implementing :GET-COMMAND would wait until it
1614 ;;; had some input. If the LISTEN fails, then we have some stream we
1615 ;;; must wait on.
1616 (defun get-stream-command (stream)
1617   (let ((cmdp (funcall (ansi-stream-misc stream) stream :get-command)))
1618     (cond (cmdp)
1619           ((listen stream)
1620            nil)
1621           (t
1622            ;; This waits for input and returns NIL when it arrives.
1623            (unread-char (read-char stream) stream)))))
1624 \f
1625 ;;;; READ-SEQUENCE
1626
1627 (defun read-sequence (seq stream &key (start 0) (end nil))
1628   #!+sb-doc
1629   "Destructively modify SEQ by reading elements from STREAM.
1630   That part of SEQ bounded by START and END is destructively modified by
1631   copying successive elements into it from STREAM. If the end of file
1632   for STREAM is reached before copying all elements of the subsequence,
1633   then the extra elements near the end of sequence are not updated, and
1634   the index of the next element is returned."
1635   (declare (type sequence seq)
1636            (type stream stream)
1637            (type index start)
1638            (type sequence-end end)
1639            (values index))
1640   (if (ansi-stream-p stream)
1641       (ansi-stream-read-sequence seq stream start end)
1642       ;; must be Gray streams FUNDAMENTAL-STREAM
1643       (stream-read-sequence stream seq start end)))
1644
1645 (defun ansi-stream-read-sequence (seq stream start %end)
1646   (declare (type sequence seq)
1647            (type ansi-stream stream)
1648            (type index start)
1649            (type sequence-end %end)
1650            (values index))
1651   (let ((end (or %end (length seq))))
1652     (declare (type index end))
1653     (etypecase seq
1654       (list
1655        (let ((read-function
1656               (if (subtypep (stream-element-type stream) 'character)
1657                   #'read-char
1658                   #'read-byte)))
1659          (do ((rem (nthcdr start seq) (rest rem))
1660               (i start (1+ i)))
1661              ((or (endp rem) (>= i end)) i)
1662            (declare (type list rem)
1663                     (type index i))
1664            (let ((el (funcall read-function stream nil :eof)))
1665              (when (eq el :eof)
1666                (return i))
1667              (setf (first rem) el)))))
1668       (vector
1669        (with-array-data ((data seq) (offset-start start) (offset-end end))
1670          (typecase data
1671            ((or (simple-array (unsigned-byte 8) (*))
1672                 (simple-array (signed-byte 8) (*))
1673                 simple-string)
1674             (let* ((numbytes (- end start))
1675                    (bytes-read (sb!sys:read-n-bytes stream
1676                                                     data
1677                                                     offset-start
1678                                                     numbytes
1679                                                     nil)))
1680               (if (< bytes-read numbytes)
1681                   (+ start bytes-read)
1682                   end)))
1683            (t
1684             (let ((read-function
1685                    (if (subtypep (stream-element-type stream) 'character)
1686                        #'read-char
1687                        #'read-byte)))
1688               (do ((i offset-start (1+ i)))
1689                   ((>= i offset-end) end)
1690                 (declare (type index i))
1691                 (let ((el (funcall read-function stream nil :eof)))
1692                   (when (eq el :eof)
1693                     (return (+ start (- i offset-start))))
1694                   (setf (aref data i) el)))))))))))
1695 \f
1696 ;;;; WRITE-SEQUENCE
1697
1698 (defun write-sequence (seq stream &key (start 0) (end nil))
1699   #!+sb-doc
1700   "Write the elements of SEQ bounded by START and END to STREAM."
1701   (declare (type sequence seq)
1702            (type stream stream)
1703            (type index start)
1704            (type sequence-end end)
1705            (values sequence))
1706   (if (ansi-stream-p stream)
1707       (ansi-stream-write-sequence seq stream start end)
1708       ;; must be Gray-streams FUNDAMENTAL-STREAM
1709       (stream-write-sequence stream seq start end)))
1710
1711 (defun ansi-stream-write-sequence (seq stream start %end)
1712   (declare (type sequence seq)
1713            (type ansi-stream stream)
1714            (type index start)
1715            (type sequence-end %end)
1716            (values sequence))
1717   (let ((end (or %end (length seq))))
1718     (declare (type index end))
1719     (etypecase seq
1720       (list
1721        (let ((write-function
1722               (if (subtypep (stream-element-type stream) 'character)
1723                   #'write-char
1724                   #'write-byte)))
1725          (do ((rem (nthcdr start seq) (rest rem))
1726               (i start (1+ i)))
1727              ((or (endp rem) (>= i end)) seq)
1728            (declare (type list rem)
1729                     (type index i))
1730            (funcall write-function (first rem) stream))))
1731       (string
1732        (%write-string seq stream start end))
1733       (vector
1734        (let ((write-function
1735               (if (subtypep (stream-element-type stream) 'character)
1736                   #'write-char
1737                   #'write-byte)))
1738          (do ((i start (1+ i)))
1739              ((>= i end) seq)
1740            (declare (type index i))
1741            (funcall write-function (aref seq i) stream)))))))
1742 \f
1743 ;;;; etc.
1744
1745 ;;; (These were inline throughout this file, but that's not appropriate
1746 ;;; globally.)
1747 (declaim (maybe-inline read-char unread-char read-byte listen))