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