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