6631e6b61f6b2ff3ba3ae55968fc765aeb1c8a9b
[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 (defun read-n-bytes (stream buffer start numbytes &optional (eof-error-p t))
428   (declare (type ansi-stream stream)
429            (type index numbytes start)
430            (type (or (simple-array * (*)) system-area-pointer) buffer))
431   (let* ((stream (in-synonym-of stream ansi-stream))
432          (in-buffer (ansi-stream-in-buffer stream))
433          (index (ansi-stream-in-index stream))
434          (num-buffered (- +ansi-stream-in-buffer-length+ index)))
435     (declare (fixnum index num-buffered))
436     (cond
437      ((not in-buffer)
438       (funcall (ansi-stream-n-bin stream)
439                stream
440                buffer
441                start
442                numbytes
443                eof-error-p))
444      ((<= numbytes num-buffered)
445       #+nil
446       (let ((copy-function (typecase buffer
447                              ((simple-array * (*)) #'ub8-bash-copy)
448                              (system-area-pointer #'copy-ub8-to-system-area))))
449         (funcall copy-function in-buffer index buffer start numbytes))
450       (%byte-blt in-buffer index
451                  buffer start (+ start numbytes))
452       (setf (ansi-stream-in-index stream) (+ index numbytes))
453       numbytes)
454      (t
455       (let ((end (+ start num-buffered)))
456         #+nil
457         (let ((copy-function (typecase buffer
458                              ((simple-array * (*)) #'ub8-bash-copy)
459                              (system-area-pointer #'copy-ub8-to-system-area))))
460           (funcall copy-function in-buffer index buffer start num-buffered))
461         (%byte-blt in-buffer index buffer start end)
462         (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
463         (+ (funcall (ansi-stream-n-bin stream)
464                     stream
465                     buffer
466                     end
467                     (- numbytes num-buffered)
468                     eof-error-p)
469            num-buffered))))))
470
471 ;;; the amount of space we leave at the start of the in-buffer for
472 ;;; unreading
473 ;;;
474 ;;; (It's 4 instead of 1 to allow word-aligned copies.)
475 (defconstant +ansi-stream-in-buffer-extra+
476   4) ; FIXME: should be symbolic constant
477
478 ;;; This function is called by the FAST-READ-CHAR expansion to refill
479 ;;; the IN-BUFFER for text streams. There is definitely an IN-BUFFER,
480 ;;; and hence must be an N-BIN method.
481 (defun fast-read-char-refill (stream eof-error-p eof-value)
482   (let* ((ibuf (ansi-stream-cin-buffer stream))
483          (count (funcall (ansi-stream-n-bin stream)
484                          stream
485                          ibuf
486                          +ansi-stream-in-buffer-extra+
487                          (- +ansi-stream-in-buffer-length+
488                             +ansi-stream-in-buffer-extra+)
489                          nil))
490          (start (- +ansi-stream-in-buffer-length+ count)))
491     (declare (type index start count))
492     (cond ((zerop count)
493            (setf (ansi-stream-in-index stream)
494                  +ansi-stream-in-buffer-length+)
495            (funcall (ansi-stream-in stream) stream eof-error-p eof-value))
496           (t
497            (when (/= start +ansi-stream-in-buffer-extra+)
498              (#.(let* ((n-character-array-bits
499                         (sb!vm:saetp-n-bits
500                          (find 'character
501                                sb!vm:*specialized-array-element-type-properties*
502                                :key #'sb!vm:saetp-specifier)))
503                        (bash-function (intern (format nil "UB~D-BASH-COPY" n-character-array-bits)
504                                               (find-package "SB!KERNEL"))))
505                   bash-function)
506                 ibuf +ansi-stream-in-buffer-extra+
507                 ibuf start
508                 count))
509            (setf (ansi-stream-in-index stream) (1+ start))
510            (aref ibuf start)))))
511
512 ;;; This is similar to FAST-READ-CHAR-REFILL, but we don't have to
513 ;;; leave room for unreading.
514 (defun fast-read-byte-refill (stream eof-error-p eof-value)
515   (let* ((ibuf (ansi-stream-in-buffer stream))
516          (count (funcall (ansi-stream-n-bin stream) stream
517                          ibuf 0 +ansi-stream-in-buffer-length+
518                          nil))
519          (start (- +ansi-stream-in-buffer-length+ count)))
520     (declare (type index start count))
521     (cond ((zerop count)
522            (setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
523            (funcall (ansi-stream-bin stream) stream eof-error-p eof-value))
524           (t
525            (unless (zerop start)
526              (ub8-bash-copy ibuf 0
527                             ibuf start
528                             count))
529            (setf (ansi-stream-in-index stream) (1+ start))
530            (aref ibuf start)))))
531 \f
532 ;;; output functions
533
534 (defun write-char (character &optional (stream *standard-output*))
535   (with-out-stream stream (ansi-stream-out character)
536                    (stream-write-char character))
537   character)
538
539 (defun terpri (&optional (stream *standard-output*))
540   (with-out-stream stream (ansi-stream-out #\newline) (stream-terpri))
541   nil)
542
543 #!-sb-fluid (declaim (inline ansi-stream-fresh-line))
544 (defun ansi-stream-fresh-line (stream)
545   (when (/= (or (charpos stream) 1) 0)
546     (funcall (ansi-stream-out stream) stream #\newline)
547     t))
548
549 (defun fresh-line (&optional (stream *standard-output*))
550   (let ((stream (out-synonym-of stream)))
551     (if (ansi-stream-p stream)
552         (ansi-stream-fresh-line stream)
553         ;; must be Gray streams FUNDAMENTAL-STREAM
554         (stream-fresh-line stream))))
555
556 (defun write-string (string &optional (stream *standard-output*)
557                             &key (start 0) end)
558   (declare (type string string))
559   ;; Note that even though you might expect, based on the behavior of
560   ;; things like AREF, that the correct upper bound here is
561   ;; (ARRAY-DIMENSION STRING 0), the ANSI glossary definitions for
562   ;; "bounding index" and "length" indicate that in this case (i.e.
563   ;; for the ANSI-specified functions WRITE-STRING [and WRITE-LINE]),
564   ;; (LENGTH STRING) is the required upper bound. A foolish
565   ;; consistency is the hobgoblin of lesser languages..
566   (%write-string string stream start (%check-vector-sequence-bounds
567                                       string start end))
568   string)
569
570 #!-sb-fluid (declaim (inline ansi-stream-write-string))
571 (defun ansi-stream-write-string (string stream start end)
572   (declare (type string string))
573   (declare (type ansi-stream stream))
574   (declare (type index start end))
575   (if (array-header-p string)
576       (with-array-data ((data string) (offset-start start)
577                         (offset-end end))
578         (funcall (ansi-stream-sout stream)
579                  stream data offset-start offset-end))
580       (funcall (ansi-stream-sout stream) stream string start end))
581   string)
582
583 (defun %write-string (string stream start end)
584   (declare (type string string))
585   (declare (type stream-designator stream))
586   (declare (type index start end))
587   (let ((stream (out-synonym-of stream)))
588     (if(ansi-stream-p stream)
589        (ansi-stream-write-string string stream start end)
590        ;; must be Gray streams FUNDAMENTAL-STREAM
591        (stream-write-string stream string start end))))
592
593 ;;; A wrapper function for all those (MACROLET OUT-FUN) definitions,
594 ;;; which cannot deal with keyword arguments.
595 (declaim (inline write-string-no-key))
596 (defun write-string-no-key (string stream start end)
597   (write-string string stream :start start :end end))
598
599 (defun write-line (string &optional (stream *standard-output*)
600                           &key (start 0) end)
601   (declare (type string string))
602   ;; FIXME: Why is there this difference between the treatments of the
603   ;; STREAM argument in WRITE-STRING and WRITE-LINE?
604   (let ((defaulted-stream (out-synonym-of stream)))
605     (%write-string string defaulted-stream start (%check-vector-sequence-bounds
606                                                   string start end))
607     (write-char #\newline defaulted-stream))
608   string)
609
610 (defun charpos (&optional (stream *standard-output*))
611   (with-out-stream stream (ansi-stream-misc :charpos) (stream-line-column)))
612
613 (defun line-length (&optional (stream *standard-output*))
614   (with-out-stream stream (ansi-stream-misc :line-length)
615                    (stream-line-length)))
616
617 (defun finish-output (&optional (stream *standard-output*))
618   (with-out-stream stream (ansi-stream-misc :finish-output)
619                    (stream-finish-output))
620   nil)
621
622 (defun force-output (&optional (stream *standard-output*))
623   (with-out-stream stream (ansi-stream-misc :force-output)
624                    (stream-force-output))
625   nil)
626
627 (defun clear-output (&optional (stream *standard-output*))
628   (with-out-stream stream (ansi-stream-misc :clear-output)
629                    (stream-force-output))
630   nil)
631
632 (defun write-byte (integer stream)
633   (with-out-stream/no-synonym stream (ansi-stream-bout integer)
634                               (stream-write-byte integer))
635   integer)
636 \f
637
638 ;;; (These were inline throughout this file, but that's not appropriate
639 ;;; globally.  And we must not inline them in the rest of this file if
640 ;;; dispatch to gray or simple streams is to work, since both redefine
641 ;;; these functions later.)
642 (declaim (notinline read-char unread-char read-byte listen))
643
644 ;;; This is called from ANSI-STREAM routines that encapsulate CLOS
645 ;;; streams to handle the misc routines and dispatch to the
646 ;;; appropriate SIMPLE- or FUNDAMENTAL-STREAM functions.
647 (defun stream-misc-dispatch (stream operation &optional arg1 arg2)
648   (declare (type stream stream) (ignore arg2))
649   (ecase operation
650     (:listen
651      ;; Return T if input available, :EOF for end-of-file, otherwise NIL.
652      (let ((char (read-char-no-hang stream nil :eof)))
653        (when (characterp char)
654          (unread-char char stream))
655        char))
656     (:unread
657      (unread-char arg1 stream))
658     (:close
659      (close stream))
660     (:clear-input
661      (clear-input stream))
662     (:force-output
663      (force-output stream))
664     (:finish-output
665      (finish-output stream))
666     (:element-type
667      (stream-element-type stream))
668     (:stream-external-format
669      (stream-external-format stream))
670     (:interactive-p
671      (interactive-stream-p stream))
672     (:line-length
673      (line-length stream))
674     (:charpos
675      (charpos stream))
676     (:file-length
677      (file-length stream))
678     (:file-string-length
679      (file-string-length stream arg1))
680     (:file-position
681      (file-position stream arg1))))
682 \f
683 ;;;; broadcast streams
684
685 (defstruct (broadcast-stream (:include ansi-stream
686                                        (out #'broadcast-out)
687                                        (bout #'broadcast-bout)
688                                        (sout #'broadcast-sout)
689                                        (misc #'broadcast-misc))
690                              (:constructor %make-broadcast-stream
691                                            (&rest streams))
692                              (:copier nil))
693   ;; a list of all the streams we broadcast to
694   (streams () :type list :read-only t))
695
696 (defun make-broadcast-stream (&rest streams)
697   (dolist (stream streams)
698     (unless (output-stream-p stream)
699       (error 'type-error
700              :datum stream
701              :expected-type '(satisfies output-stream-p))))
702   (apply #'%make-broadcast-stream streams))
703
704 (macrolet ((out-fun (name fun &rest args)
705              `(defun ,name (stream ,@args)
706                 (dolist (stream (broadcast-stream-streams stream))
707                   (,fun ,(car args) stream ,@(cdr args))))))
708   (out-fun broadcast-out write-char char)
709   (out-fun broadcast-bout write-byte byte)
710   (out-fun broadcast-sout write-string-no-key string start end))
711
712 (defun broadcast-misc (stream operation &optional arg1 arg2)
713   (let ((streams (broadcast-stream-streams stream)))
714     (case operation
715       ;; FIXME: This may not be the best place to note this, but I
716       ;; think the :CHARPOS protocol needs revision.  Firstly, I think
717       ;; this is the last place where a NULL return value was possible
718       ;; (before adjusting it to be 0), so a bunch of conditionals IF
719       ;; CHARPOS can be removed; secondly, it is my belief that
720       ;; FD-STREAMS, when running FILE-POSITION, do not update the
721       ;; CHARPOS, and consequently there will be much wrongness.
722       ;;
723       ;; FIXME: see also TWO-WAY-STREAM treatment of :CHARPOS -- why
724       ;; is it testing the :charpos of an input stream?
725       ;;
726       ;; -- CSR, 2004-02-04
727       (:charpos
728        (dolist (stream streams 0)
729          (let ((charpos (charpos stream)))
730            (if charpos (return charpos)))))
731       (:line-length
732        (let ((min nil))
733          (dolist (stream streams min)
734            (let ((res (line-length stream)))
735              (when res (setq min (if min (min res min) res)))))))
736       (:element-type
737        #+nil ; old, arguably more logical, version
738        (let (res)
739          (dolist (stream streams (if (> (length res) 1) `(and ,@res) t))
740            (pushnew (stream-element-type stream) res :test #'equal)))
741        ;; ANSI-specified version (under System Class BROADCAST-STREAM)
742        (let ((res t))
743          (do ((streams streams (cdr streams)))
744              ((null streams) res)
745            (when (null (cdr streams))
746              (setq res (stream-element-type (car streams)))))))
747       (:external-format
748        (let ((res :default))
749          (dolist (stream streams res)
750            (setq res (stream-external-format stream)))))
751       (:file-length
752        (let ((last (last streams)))
753          (if last
754              (file-length (car last))
755              0)))
756       (:file-position
757        (if arg1
758            (let ((res (or (eql arg1 :start) (eql arg1 0))))
759              (dolist (stream streams res)
760                (setq res (file-position stream arg1))))
761            (let ((res 0))
762              (dolist (stream streams res)
763                (setq res (file-position stream))))))
764       (:file-string-length
765        (let ((res 1))
766          (dolist (stream streams res)
767            (setq res (file-string-length stream arg1)))))
768       (:close
769        (set-closed-flame stream))
770       (t
771        (let ((res nil))
772          (dolist (stream streams res)
773            (setq res
774                  (if (ansi-stream-p stream)
775                      (funcall (ansi-stream-misc stream) stream operation
776                               arg1 arg2)
777                      (stream-misc-dispatch stream operation arg1 arg2)))))))))
778 \f
779 ;;;; synonym streams
780
781 (defstruct (synonym-stream (:include ansi-stream
782                                      (in #'synonym-in)
783                                      (bin #'synonym-bin)
784                                      (n-bin #'synonym-n-bin)
785                                      (out #'synonym-out)
786                                      (bout #'synonym-bout)
787                                      (sout #'synonym-sout)
788                                      (misc #'synonym-misc))
789                            (:constructor make-synonym-stream (symbol))
790                            (:copier nil))
791   ;; This is the symbol, the value of which is the stream we are synonym to.
792   (symbol nil :type symbol :read-only t))
793 (def!method print-object ((x synonym-stream) stream)
794   (print-unreadable-object (x stream :type t :identity t)
795     (format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
796
797 ;;; The output simple output methods just call the corresponding
798 ;;; function on the synonymed stream.
799 (macrolet ((out-fun (name fun &rest args)
800              `(defun ,name (stream ,@args)
801                 (declare (optimize (safety 1)))
802                 (let ((syn (symbol-value (synonym-stream-symbol stream))))
803                   (,fun ,(car args) syn ,@(cdr args))))))
804   (out-fun synonym-out write-char ch)
805   (out-fun synonym-bout write-byte n)
806   (out-fun synonym-sout write-string-no-key string start end))
807
808 ;;; For the input methods, we just call the corresponding function on the
809 ;;; synonymed stream. These functions deal with getting input out of
810 ;;; the In-Buffer if there is any.
811 (macrolet ((in-fun (name fun &rest args)
812              `(defun ,name (stream ,@args)
813                 (declare (optimize (safety 1)))
814                 (,fun (symbol-value (synonym-stream-symbol stream))
815                       ,@args))))
816   (in-fun synonym-in read-char eof-error-p eof-value)
817   (in-fun synonym-bin read-byte eof-error-p eof-value)
818   (in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
819
820 (defun synonym-misc (stream operation &optional arg1 arg2)
821   (declare (optimize (safety 1)))
822   (let ((syn (symbol-value (synonym-stream-symbol stream))))
823     (if (ansi-stream-p syn)
824         ;; We have to special-case some operations which interact with
825         ;; the in-buffer of the wrapped stream, since just calling
826         ;; ANSI-STREAM-MISC on them
827         (case operation
828           (:listen (or (/= (the fixnum (ansi-stream-in-index syn))
829                            +ansi-stream-in-buffer-length+)
830                        (funcall (ansi-stream-misc syn) syn :listen)))
831           (:clear-input (clear-input syn))
832           (:unread (unread-char arg1 syn))
833           (t
834            (funcall (ansi-stream-misc syn) syn operation arg1 arg2)))
835         (stream-misc-dispatch syn operation arg1 arg2))))
836 \f
837 ;;;; two-way streams
838
839 (defstruct (two-way-stream
840             (:include ansi-stream
841                       (in #'two-way-in)
842                       (bin #'two-way-bin)
843                       (n-bin #'two-way-n-bin)
844                       (out #'two-way-out)
845                       (bout #'two-way-bout)
846                       (sout #'two-way-sout)
847                       (misc #'two-way-misc))
848             (:constructor %make-two-way-stream (input-stream output-stream))
849             (:copier nil))
850   (input-stream (missing-arg) :type stream :read-only t)
851   (output-stream (missing-arg) :type stream :read-only t))
852 (defprinter (two-way-stream) input-stream output-stream)
853
854 (defun make-two-way-stream (input-stream output-stream)
855   #!+sb-doc
856   "Return a bidirectional stream which gets its input from INPUT-STREAM and
857    sends its output to OUTPUT-STREAM."
858   ;; FIXME: This idiom of the-real-stream-of-a-possibly-synonym-stream
859   ;; should be encapsulated in a function, and used here and most of
860   ;; the other places that SYNONYM-STREAM-P appears.
861   (unless (output-stream-p output-stream)
862     (error 'type-error
863            :datum output-stream
864            :expected-type '(satisfies output-stream-p)))
865   (unless (input-stream-p input-stream)
866     (error 'type-error
867            :datum input-stream
868            :expected-type '(satisfies input-stream-p)))
869   (funcall #'%make-two-way-stream input-stream output-stream))
870
871 (macrolet ((out-fun (name fun &rest args)
872              `(defun ,name (stream ,@args)
873                 (let ((syn (two-way-stream-output-stream stream)))
874                   (,fun ,(car args) syn ,@(cdr args))))))
875   (out-fun two-way-out write-char ch)
876   (out-fun two-way-bout write-byte n)
877   (out-fun two-way-sout write-string-no-key string start end))
878
879 (macrolet ((in-fun (name fun &rest args)
880              `(defun ,name (stream ,@args)
881                 (force-output (two-way-stream-output-stream stream))
882                 (,fun (two-way-stream-input-stream stream) ,@args))))
883   (in-fun two-way-in read-char eof-error-p eof-value)
884   (in-fun two-way-bin read-byte eof-error-p eof-value)
885   (in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
886
887 (defun two-way-misc (stream operation &optional arg1 arg2)
888   (let* ((in (two-way-stream-input-stream stream))
889          (out (two-way-stream-output-stream stream))
890          (in-ansi-stream-p (ansi-stream-p in))
891          (out-ansi-stream-p (ansi-stream-p out)))
892     (case operation
893       (:listen
894        (if in-ansi-stream-p
895            (or (/= (the fixnum (ansi-stream-in-index in))
896                    +ansi-stream-in-buffer-length+)
897                (funcall (ansi-stream-misc in) in :listen))
898            (listen in)))
899       ((:finish-output :force-output :clear-output)
900        (if out-ansi-stream-p
901            (funcall (ansi-stream-misc out) out operation arg1 arg2)
902            (stream-misc-dispatch out operation arg1 arg2)))
903       (:clear-input (clear-input in))
904       (:unread (unread-char arg1 in))
905       (:element-type
906        (let ((in-type (stream-element-type in))
907              (out-type (stream-element-type out)))
908          (if (equal in-type out-type)
909              in-type `(and ,in-type ,out-type))))
910       (:close
911        (set-closed-flame stream))
912       (t
913        (or (if in-ansi-stream-p
914                (funcall (ansi-stream-misc in) in operation arg1 arg2)
915                (stream-misc-dispatch in operation arg1 arg2))
916            (if out-ansi-stream-p
917                (funcall (ansi-stream-misc out) out operation arg1 arg2)
918                (stream-misc-dispatch out operation arg1 arg2)))))))
919 \f
920 ;;;; concatenated streams
921
922 (defstruct (concatenated-stream
923             (:include ansi-stream
924                       (in #'concatenated-in)
925                       (bin #'concatenated-bin)
926                       (n-bin #'concatenated-n-bin)
927                       (misc #'concatenated-misc))
928             (:constructor %make-concatenated-stream (&rest streams))
929             (:copier nil))
930   ;; The car of this is the substream we are reading from now.
931   (streams nil :type list))
932 (def!method print-object ((x concatenated-stream) stream)
933   (print-unreadable-object (x stream :type t :identity t)
934     (format stream
935             ":STREAMS ~S"
936             (concatenated-stream-streams x))))
937
938 (defun make-concatenated-stream (&rest streams)
939   #!+sb-doc
940   "Return a stream which takes its input from each of the streams in turn,
941    going on to the next at EOF."
942   (dolist (stream streams)
943     (unless (input-stream-p stream)
944       (error 'type-error
945              :datum stream
946              :expected-type '(satisfies input-stream-p))))
947   (apply #'%make-concatenated-stream streams))
948
949 (macrolet ((in-fun (name fun)
950              `(defun ,name (stream eof-error-p eof-value)
951                 (do ((streams (concatenated-stream-streams stream)
952                               (cdr streams)))
953                     ((null streams)
954                      (eof-or-lose stream eof-error-p eof-value))
955                   (let* ((stream (car streams))
956                          (result (,fun stream nil nil)))
957                     (when result (return result)))
958                   (pop (concatenated-stream-streams stream))))))
959   (in-fun concatenated-in read-char)
960   (in-fun concatenated-bin read-byte))
961
962 (defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
963   (do ((streams (concatenated-stream-streams stream) (cdr streams))
964        (current-start start)
965        (remaining-bytes numbytes))
966       ((null streams)
967        (if eof-errorp
968            (error 'end-of-file :stream stream)
969            (- numbytes remaining-bytes)))
970     (let* ((stream (car streams))
971            (bytes-read (read-n-bytes stream buffer current-start
972                                      remaining-bytes nil)))
973       (incf current-start bytes-read)
974       (decf remaining-bytes bytes-read)
975       (when (zerop remaining-bytes) (return numbytes)))
976     (setf (concatenated-stream-streams stream) (cdr streams))))
977
978 (defun concatenated-misc (stream operation &optional arg1 arg2)
979   (let* ((left (concatenated-stream-streams stream))
980          (current (car left)))
981     (case operation
982       (:listen
983        (unless left
984          (return-from concatenated-misc :eof))
985        (loop
986         (let ((stuff (if (ansi-stream-p current)
987                          (funcall (ansi-stream-misc current) current
988                                   :listen)
989                          (stream-misc-dispatch current :listen))))
990           (cond ((eq stuff :eof)
991                  ;; Advance STREAMS, and try again.
992                  (pop (concatenated-stream-streams stream))
993                  (setf current
994                        (car (concatenated-stream-streams stream)))
995                  (unless current
996                    ;; No further streams. EOF.
997                    (return :eof)))
998                 (stuff
999                  ;; Stuff's available.
1000                  (return t))
1001                 (t
1002                  ;; Nothing is available yet.
1003                  (return nil))))))
1004       (:clear-input (when left (clear-input current)))
1005       (:unread (when left (unread-char arg1 current)))
1006       (:close
1007        (set-closed-flame stream))
1008       (t
1009        (when left
1010          (if (ansi-stream-p current)
1011              (funcall (ansi-stream-misc current) current operation arg1 arg2)
1012              (stream-misc-dispatch current operation arg1 arg2)))))))
1013 \f
1014 ;;;; echo streams
1015
1016 (defstruct (echo-stream
1017             (:include two-way-stream
1018                       (in #'echo-in)
1019                       (bin #'echo-bin)
1020                       (misc #'echo-misc)
1021                       (n-bin #'echo-n-bin))
1022             (:constructor %make-echo-stream (input-stream output-stream))
1023             (:copier nil))
1024   unread-stuff)
1025 (def!method print-object ((x echo-stream) stream)
1026   (print-unreadable-object (x stream :type t :identity t)
1027     (format stream
1028             ":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
1029             (two-way-stream-input-stream x)
1030             (two-way-stream-output-stream x))))
1031
1032 (defun make-echo-stream (input-stream output-stream)
1033   #!+sb-doc
1034   "Return a bidirectional stream which gets its input from INPUT-STREAM and
1035    sends its output to OUTPUT-STREAM. In addition, all input is echoed to
1036    the output stream."
1037   (unless (output-stream-p output-stream)
1038     (error 'type-error
1039            :datum output-stream
1040            :expected-type '(satisfies output-stream-p)))
1041   (unless (input-stream-p input-stream)
1042     (error 'type-error
1043            :datum input-stream
1044            :expected-type '(satisfies input-stream-p)))
1045   (funcall #'%make-echo-stream input-stream output-stream))
1046
1047 (macrolet ((in-fun (name in-fun out-fun &rest args)
1048              `(defun ,name (stream ,@args)
1049                 (or (pop (echo-stream-unread-stuff stream))
1050                     (let* ((in (echo-stream-input-stream stream))
1051                            (out (echo-stream-output-stream stream))
1052                            (result (if eof-error-p
1053                                        (,in-fun in ,@args)
1054                                        (,in-fun in nil in))))
1055                       (cond
1056                         ((eql result in) eof-value)
1057                         (t (,out-fun result out) result)))))))
1058   (in-fun echo-in read-char write-char eof-error-p eof-value)
1059   (in-fun echo-bin read-byte write-byte eof-error-p eof-value))
1060
1061 (defun echo-n-bin (stream buffer start numbytes eof-error-p)
1062   (let ((new-start start)
1063         (read 0))
1064     (loop
1065      (let ((thing (pop (echo-stream-unread-stuff stream))))
1066        (cond
1067          (thing
1068           (setf (aref buffer new-start) thing)
1069           (incf new-start)
1070           (incf read)
1071           (when (= read numbytes)
1072             (return-from echo-n-bin numbytes)))
1073          (t (return nil)))))
1074     (let ((bytes-read (read-n-bytes (echo-stream-input-stream stream) buffer
1075                                     new-start (- numbytes read) nil)))
1076       (cond
1077         ((not eof-error-p)
1078          (write-sequence buffer (echo-stream-output-stream stream)
1079                          :start new-start :end (+ new-start bytes-read))
1080          (+ bytes-read read))
1081         ((> numbytes (+ read bytes-read))
1082          (write-sequence buffer (echo-stream-output-stream stream)
1083                          :start new-start :end (+ new-start bytes-read))
1084          (error 'end-of-file :stream stream))
1085         (t
1086          (write-sequence buffer (echo-stream-output-stream stream)
1087                          :start new-start :end (+ new-start bytes-read))
1088          (aver (= numbytes (+ new-start bytes-read)))
1089          numbytes)))))
1090 \f
1091 ;;;; STRING-INPUT-STREAM stuff
1092
1093 (defstruct (string-input-stream
1094              (:include ansi-stream
1095                        (in #'string-inch)
1096                        (bin #'ill-bin)
1097                        (n-bin #'ill-bin)
1098                        (misc #'string-in-misc))
1099              (:constructor internal-make-string-input-stream
1100                            (string current end))
1101              (:copier nil))
1102   (string (missing-arg) :type simple-string)
1103   (current (missing-arg) :type index)
1104   (end (missing-arg) :type index))
1105
1106 (defun string-inch (stream eof-error-p eof-value)
1107   (declare (type string-input-stream stream))
1108   (let ((string (string-input-stream-string stream))
1109         (index (string-input-stream-current stream)))
1110     (cond ((>= index (the index (string-input-stream-end stream)))
1111            (eof-or-lose stream eof-error-p eof-value))
1112           (t
1113            (setf (string-input-stream-current stream) (1+ index))
1114            (char string index)))))
1115
1116 (defun string-binch (stream eof-error-p eof-value)
1117   (declare (type string-input-stream stream))
1118   (let ((string (string-input-stream-string stream))
1119         (index (string-input-stream-current stream)))
1120     (cond ((>= index (the index (string-input-stream-end stream)))
1121            (eof-or-lose stream eof-error-p eof-value))
1122           (t
1123            (setf (string-input-stream-current stream) (1+ index))
1124            (char-code (char string index))))))
1125
1126 (defun string-stream-read-n-bytes (stream buffer start requested eof-error-p)
1127   (declare (type string-input-stream stream)
1128            (type index start requested))
1129   (let* ((string (string-input-stream-string stream))
1130          (index (string-input-stream-current stream))
1131          (available (- (string-input-stream-end stream) index))
1132          (copy (min available requested)))
1133     (declare (type simple-string string))
1134     (when (plusp copy)
1135       (setf (string-input-stream-current stream)
1136             (truly-the index (+ index copy)))
1137       ;; FIXME: why are we VECTOR-SAP'ing things here?  what's the point?
1138       ;; and are there SB-UNICODE issues here as well?  --njf, 2005-03-24
1139       (with-pinned-objects (string buffer)
1140         (system-area-ub8-copy (vector-sap string)
1141                               index
1142                               (if (typep buffer 'system-area-pointer)
1143                                   buffer
1144                                   (vector-sap buffer))
1145                               start
1146                               copy)))
1147     (if (and (> requested copy) eof-error-p)
1148         (error 'end-of-file :stream stream)
1149         copy)))
1150
1151 (defun string-in-misc (stream operation &optional arg1 arg2)
1152   (declare (type string-input-stream stream)
1153            (ignore arg2))
1154   (case operation
1155     (:file-position
1156      (if arg1
1157          (setf (string-input-stream-current stream)
1158                (case arg1
1159                  (:start 0)
1160                  (:end (string-input-stream-end stream))
1161                  ;; We allow moving position beyond EOF. Errors happen
1162                  ;; on read, not move -- or the user may extend the
1163                  ;; input string.
1164                  (t arg1)))
1165          (string-input-stream-current stream)))
1166     ;; According to ANSI: "Should signal an error of type type-error
1167     ;; if stream is not a stream associated with a file."
1168     ;; This is checked by FILE-LENGTH, so no need to do it here either.
1169     ;; (:file-length (length (string-input-stream-string stream)))
1170     (:unread (decf (string-input-stream-current stream)))
1171     (:close (set-closed-flame stream))
1172     (:listen (or (/= (the index (string-input-stream-current stream))
1173                      (the index (string-input-stream-end stream)))
1174                  :eof))
1175     (:element-type (array-element-type (string-input-stream-string stream)))))
1176
1177 (defun make-string-input-stream (string &optional (start 0) end)
1178   #!+sb-doc
1179   "Return an input stream which will supply the characters of STRING between
1180   START and END in order."
1181   (declare (type string string)
1182            (type index start)
1183            (type (or index null) end))
1184   (let* ((string (coerce string '(simple-array character (*))))
1185          (end (%check-vector-sequence-bounds string start end)))
1186     (with-array-data ((string string) (start start) (end end))
1187       (internal-make-string-input-stream
1188        string ;; now simple
1189        start
1190        end))))
1191 \f
1192 ;;;; STRING-OUTPUT-STREAM stuff
1193 ;;;;
1194 ;;;; FIXME: This, like almost none of the stream code is particularly
1195 ;;;; interrupt or thread-safe. While it should not be possible to
1196 ;;;; corrupt the heap here, it certainly is possible to end up with
1197 ;;;; a string-output-stream whose internal state is messed up.
1198 ;;;;
1199 ;;;; FIXME: It would be nice to support space-efficient
1200 ;;;; string-output-streams with element-type base-char. This would
1201 ;;;; mean either a separate subclass, or typecases in functions.
1202
1203 (defparameter *string-output-stream-buffer-initial-size* 64)
1204
1205 #!-sb-fluid
1206 (declaim (inline string-output-string-stream-buffer
1207                  string-output-string-stream-pointer
1208                  string-output-string-stream-index))
1209 (defstruct (string-output-stream
1210             (:include ansi-stream
1211                       (out #'string-ouch)
1212                       (sout #'string-sout)
1213                       (misc #'string-out-misc))
1214             (:constructor make-string-output-stream
1215                           (&key (element-type 'character)
1216                            &aux (buffer
1217                                  (make-string
1218                                   *string-output-stream-buffer-initial-size*))))
1219             (:copier nil))
1220   ;; The string we throw stuff in.
1221   (buffer (missing-arg) :type (simple-array character (*)))
1222   ;; Chains of buffers to use
1223   (prev nil)
1224   (next nil)
1225   ;; Index of the next location to use in the current string.
1226   (pointer 0 :type index)
1227   ;; Global location in the stream
1228   (index 0 :type index)
1229   ;; Index cache: when we move backwards we save the greater of this
1230   ;; and index here, so the the greater of index and this is always
1231   ;; the end of the stream.
1232   (index-cache 0 :type index)
1233   ;; Requested element type
1234   (element-type 'character))
1235
1236 #!+sb-doc
1237 (setf (fdocumentation 'make-string-output-stream 'function)
1238   "Return an output stream which will accumulate all output given it for the
1239 benefit of the function GET-OUTPUT-STREAM-STRING.")
1240
1241 ;;; Pushes the current segment onto the prev-list, and either pops
1242 ;;; or allocates a new one.
1243 (defun string-output-stream-new-buffer (stream size)
1244   (declare (index size))
1245   (/show0 "/string-output-stream-new-buffer")
1246   (push (string-output-stream-buffer stream)
1247         (string-output-stream-prev stream))
1248   (setf (string-output-stream-buffer stream)
1249         (or (pop (string-output-stream-next stream))
1250             ;; FIXME: This would be the correct place to detect that
1251             ;; more then FIXNUM characters are being written to the
1252             ;; stream, and do something about it.
1253             (make-string size))))
1254
1255 ;;; Moves to the end of the next segment or the current one if there are
1256 ;;; no more segments. Returns true as long as there are next segments.
1257 (defun string-output-stream-next-buffer (stream)
1258   (/show0 "/string-output-stream-next-buffer")
1259   (let* ((old (string-output-stream-buffer stream))
1260          (new (pop (string-output-stream-next stream)))
1261          (old-size (length old))
1262          (skipped (- old-size (string-output-stream-pointer stream))))
1263     (cond (new
1264            (let ((new-size (length new)))
1265              (push old (string-output-stream-prev stream))
1266              (setf (string-output-stream-buffer stream) new
1267                    (string-output-stream-pointer stream) new-size)
1268              (incf (string-output-stream-index stream) (+ skipped new-size)))
1269            t)
1270           (t
1271            (setf (string-output-stream-pointer stream) old-size)
1272            (incf (string-output-stream-index stream) skipped)
1273            nil))))
1274
1275 ;;; Moves to the start of the previous segment or the current one if there
1276 ;;; are no more segments. Returns true as long as there are prev segments.
1277 (defun string-output-stream-prev-buffer (stream)
1278   (/show0 "/string-output-stream-prev-buffer")
1279   (let ((old (string-output-stream-buffer stream))
1280         (new (pop (string-output-stream-prev stream)))
1281         (skipped (string-output-stream-pointer stream)))
1282     (cond (new
1283            (push old (string-output-stream-next stream))
1284            (setf (string-output-stream-buffer stream) new
1285                  (string-output-stream-pointer stream) 0)
1286            (decf (string-output-stream-index stream) (+ skipped (length new)))
1287            t)
1288           (t
1289            (setf (string-output-stream-pointer stream) 0)
1290            (decf (string-output-stream-index stream) skipped)
1291            nil))))
1292
1293 (defun string-ouch (stream character)
1294   (/show0 "/string-ouch")
1295   (let ((pointer (string-output-stream-pointer stream))
1296         (buffer (string-output-stream-buffer stream))
1297         (index (string-output-stream-index stream)))
1298     (cond ((= pointer (length buffer))
1299            (setf buffer (string-output-stream-new-buffer stream index)
1300                  (aref buffer 0) character
1301                  (string-output-stream-pointer stream) 1))
1302           (t
1303            (setf (aref buffer pointer) character
1304                  (string-output-stream-pointer stream) (1+ pointer))))
1305     (setf (string-output-stream-index stream) (1+ index))))
1306
1307 (defun string-sout (stream string start end)
1308   (declare (type simple-string string)
1309            (type index start end))
1310   (let* ((full-length (- end start))
1311          (length full-length)
1312          (buffer (string-output-stream-buffer stream))
1313          (pointer (string-output-stream-pointer stream))
1314          (space (- (length buffer) pointer))
1315          (here (min space length))
1316          (stop (+ start here))
1317          (overflow (- length space)))
1318     (declare (index length space here stop full-length)
1319              (fixnum overflow)
1320              (type (simple-array character (*)) buffer))
1321     (tagbody
1322      :more
1323        (when (plusp here)
1324          (etypecase string
1325            ((simple-array character (*))
1326             (replace buffer string :start1 pointer :start2 start :end2 stop))
1327            (simple-base-string
1328             (replace buffer string :start1 pointer :start2 start :end2 stop))
1329            ((simple-array nil (*))
1330             (replace buffer string :start1 pointer :start2 start :end2 stop)))
1331          (setf (string-output-stream-pointer stream) (+ here pointer)))
1332        (when (plusp overflow)
1333          (setf start stop
1334                length (- end start)
1335                buffer (string-output-stream-new-buffer
1336                        stream (max overflow (string-output-stream-index stream)))
1337                pointer 0
1338                space (length buffer)
1339                here (min space length)
1340                stop (+ start here)
1341                ;; there may be more overflow if we used a buffer
1342                ;; already allocated to the stream
1343                overflow (- length space))
1344          (go :more)))
1345     (incf (string-output-stream-index stream) full-length)))
1346
1347 ;;; Factored out of the -misc method due to size.
1348 (defun set-string-output-stream-file-position (stream pos)
1349   (let* ((index (string-output-stream-index stream))
1350          (end (max index (string-output-stream-index-cache stream))))
1351     (declare (index index end))
1352     (setf (string-output-stream-index-cache stream) end)
1353     (cond ((eq :start pos)
1354            (loop while (string-output-stream-prev-buffer stream)))
1355           ((eq :end pos)
1356            (loop while (string-output-stream-next-buffer stream))
1357            (let ((over (- (string-output-stream-index stream) end)))
1358              (decf (string-output-stream-pointer stream) over))
1359            (setf (string-output-stream-index stream) end))
1360           ((< pos index)
1361            (loop while (< pos index)
1362                  do (string-output-stream-prev-buffer stream)
1363                  (setf index (string-output-stream-index stream)))
1364            (let ((step (- pos index)))
1365              (incf (string-output-stream-pointer stream) step)
1366              (setf (string-output-stream-index stream) pos)))
1367           ((> pos index)
1368            ;; We allow moving beyond the end of stream, implicitly
1369            ;; extending the output stream.
1370            (let ((next (string-output-stream-next-buffer stream)))
1371              ;; Update after -next-buffer, INDEX is kept pointing at
1372              ;; the end of the current buffer.
1373              (setf index (string-output-stream-index stream))
1374              (loop while (and next (> pos index))
1375                    do (setf next (string-output-stream-next-buffer stream)
1376                             index (string-output-stream-index stream))))
1377            ;; Allocate new buffer if needed, or step back to
1378            ;; the desired index and set pointer and index
1379            ;; correctly.
1380            (let ((diff (- pos index)))
1381              (if (plusp diff)
1382                  (let* ((new (string-output-stream-new-buffer stream diff))
1383                         (size (length new)))
1384                    (aver (= pos (+ index size)))
1385                    (setf (string-output-stream-pointer stream) size
1386                          (string-output-stream-index stream) pos))
1387                  (let ((size (length (string-output-stream-buffer stream))))
1388                    (setf (string-output-stream-pointer stream) (+ size diff)
1389                          (string-output-stream-index stream) pos))))))))
1390
1391 (defun string-out-misc (stream operation &optional arg1 arg2)
1392   (declare (ignore arg2))
1393   (case operation
1394     (:charpos
1395      ;; Keeping this first is a silly micro-optimization: FRESH-LINE
1396      ;; makes this the most common one.
1397      (/show0 "/string-out-misc charpos")
1398      (prog ((pointer (string-output-stream-pointer stream))
1399             (buffer (string-output-stream-buffer stream))
1400             (prev (string-output-stream-prev stream))
1401             (base 0))
1402       :next
1403       (let ((pos (position #\newline buffer :from-end t :end pointer)))
1404         (when (or pos (not buffer))
1405           ;; If newline is at index I, and pointer at index I+N, charpos
1406           ;; is N-1. If there is no newline, and pointer is at index N,
1407           ;; charpos is N.
1408           (return (+ base (if pos (- pointer pos 1) pointer))))
1409         (setf base (+ base pointer)
1410               buffer (pop prev)
1411               pointer (length buffer))
1412         (/show0 "/string-out-misc charpos next")
1413         (go :next))))
1414     (:file-position
1415      (/show0 "/string-out-misc file-position")
1416      (when arg1
1417        (set-string-output-stream-file-position stream arg1))
1418      (string-output-stream-index stream))
1419     (:close
1420      (/show0 "/string-out-misc close")
1421      (set-closed-flame stream))
1422     (:element-type (string-output-stream-element-type stream))))
1423
1424 ;;; Return a string of all the characters sent to a stream made by
1425 ;;; MAKE-STRING-OUTPUT-STREAM since the last call to this function.
1426 (defun get-output-stream-string (stream)
1427   (declare (type string-output-stream stream))
1428   (let* ((length (max (string-output-stream-index stream)
1429                       (string-output-stream-index-cache stream)))
1430          (element-type (string-output-stream-element-type stream))
1431          (prev (string-output-stream-prev stream))
1432          (this (string-output-stream-buffer stream))
1433          (next (string-output-stream-next stream))
1434          (result
1435           (case element-type
1436             ;; overwhelmingly common case: can be inlined
1437             ;;
1438             ;; FIXME: If we were willing to use %SHRINK-VECTOR here,
1439             ;; and allocate new strings the size of 2 * index in
1440             ;; STRING-SOUT, we would not need to allocate one here in
1441             ;; the common case, but could just use the last one
1442             ;; allocated, and chop it down to size..
1443             ;;
1444             ((character) (make-string length))
1445             ;; slightly less common cases: inline it anyway
1446             ((base-char standard-char)
1447              (make-string length :element-type 'base-char))
1448             (t
1449              (make-string length :element-type element-type)))))
1450
1451     (setf (string-output-stream-index stream) 0
1452           (string-output-stream-index-cache stream) 0
1453           (string-output-stream-pointer stream) 0
1454           ;; throw them away for simplicity's sake: this way the rest of the
1455           ;; implementation can assume that the greater of INDEX and INDEX-CACHE
1456           ;; is always within the last buffer.
1457           (string-output-stream-prev stream) nil
1458           (string-output-stream-next stream) nil)
1459
1460     (flet ((replace-all (fun)
1461              (let ((start 0))
1462                (declare (index start))
1463                (dolist (buffer (nreverse prev))
1464                  (funcall fun buffer start)
1465                  (incf start (length buffer)))
1466                (funcall fun this start)
1467                (incf start (length this))
1468                (dolist (buffer next)
1469                  (funcall fun buffer start)
1470                  (incf start (length buffer))))))
1471       (macrolet ((frob (type)
1472                    `(replace-all (lambda (buffer from)
1473                                    (declare (type ,type result)
1474                                             (type (simple-array character (*))
1475                                                   buffer))
1476                                    (replace result buffer :start1 from)))))
1477         (etypecase result
1478           ((simple-array character (*))
1479            (frob (simple-array character (*))))
1480           (simple-base-string
1481            (frob simple-base-string))
1482           ((simple-array nil (*))
1483            (frob (simple-array nil (*)))))))
1484
1485     result))
1486 \f
1487 ;;;; fill-pointer streams
1488
1489 ;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
1490 ;;; the CLM, but they are required for the implementation of
1491 ;;; WITH-OUTPUT-TO-STRING.
1492
1493 ;;; FIXME: need to support (VECTOR BASE-CHAR) and (VECTOR NIL),
1494 ;;; ideally without destroying all hope of efficiency.
1495 (deftype string-with-fill-pointer ()
1496   '(and (vector character)
1497         (satisfies array-has-fill-pointer-p)))
1498
1499 (defstruct (fill-pointer-output-stream
1500             (:include ansi-stream
1501                       (out #'fill-pointer-ouch)
1502                       (sout #'fill-pointer-sout)
1503                       (misc #'fill-pointer-misc))
1504             (:constructor make-fill-pointer-output-stream (string))
1505             (:copier nil))
1506   ;; a string with a fill pointer where we stuff the stuff we write
1507   (string (missing-arg) :type string-with-fill-pointer :read-only t))
1508
1509 (defun fill-pointer-ouch (stream character)
1510   (let* ((buffer (fill-pointer-output-stream-string stream))
1511          (current (fill-pointer buffer))
1512          (current+1 (1+ current)))
1513     (declare (fixnum current))
1514     (with-array-data ((workspace buffer) (start) (end))
1515       (declare (type (simple-array character (*)) workspace))
1516       (let ((offset-current (+ start current)))
1517         (declare (fixnum offset-current))
1518         (if (= offset-current end)
1519             (let* ((new-length (1+ (* current 2)))
1520                    (new-workspace (make-string new-length)))
1521               (declare (type (simple-array character (*)) new-workspace))
1522               (replace new-workspace workspace
1523                        :start2 start :end2 offset-current)
1524               (setf workspace new-workspace
1525                     offset-current current)
1526               (set-array-header buffer workspace new-length
1527                                 current+1 0 new-length nil))
1528             (setf (fill-pointer buffer) current+1))
1529         (setf (schar workspace offset-current) character)))
1530     current+1))
1531
1532 (defun fill-pointer-sout (stream string start end)
1533   (declare (simple-string string) (fixnum start end))
1534   (let* ((string (if (typep string '(simple-array character (*)))
1535                      string
1536                      (coerce string '(simple-array character (*)))))
1537          (buffer (fill-pointer-output-stream-string stream))
1538          (current (fill-pointer buffer))
1539          (string-len (- end start))
1540          (dst-end (+ string-len current)))
1541     (declare (fixnum current dst-end string-len))
1542     (with-array-data ((workspace buffer) (dst-start) (dst-length))
1543       (declare (type (simple-array character (*)) workspace))
1544       (let ((offset-dst-end (+ dst-start dst-end))
1545             (offset-current (+ dst-start current)))
1546         (declare (fixnum offset-dst-end offset-current))
1547         (if (> offset-dst-end dst-length)
1548             (let* ((new-length (+ (the fixnum (* current 2)) string-len))
1549                    (new-workspace (make-string new-length)))
1550               (declare (type (simple-array character (*)) new-workspace))
1551               (replace new-workspace workspace
1552                        :start2 dst-start :end2 offset-current)
1553               (setf workspace new-workspace
1554                     offset-current current
1555                     offset-dst-end dst-end)
1556               (set-array-header buffer workspace new-length
1557                                 dst-end 0 new-length nil))
1558             (setf (fill-pointer buffer) dst-end))
1559         (replace workspace string
1560                  :start1 offset-current :start2 start :end2 end)))
1561     dst-end))
1562
1563 (defun fill-pointer-misc (stream operation &optional arg1 arg2)
1564   (declare (ignore arg2))
1565   (case operation
1566     (:file-position
1567      (let ((buffer (fill-pointer-output-stream-string stream)))
1568        (if arg1
1569            (setf (fill-pointer buffer)
1570                  (case arg1
1571                    (:start 0)
1572                    ;; Fill-pointer is always at fill-pointer we will
1573                    ;; make :END move to the end of the actual string.
1574                    (:end (array-total-size buffer))
1575                    ;; We allow moving beyond the end of string if the
1576                    ;; string is adjustable.
1577                    (t (when (>= arg1 (array-total-size buffer))
1578                         (if (adjustable-array-p buffer)
1579                             (adjust-array buffer arg1)
1580                             (error "Cannot move FILE-POSITION beyond the end ~
1581                                     of WITH-OUTPUT-TO-STRING stream ~
1582                                     constructed with non-adjustable string.")))
1583                       arg1)))
1584            (fill-pointer buffer))))
1585     (:charpos
1586      (let* ((buffer (fill-pointer-output-stream-string stream))
1587             (current (fill-pointer buffer)))
1588        (with-array-data ((string buffer) (start) (end current))
1589          (declare (simple-string string) (ignore start))
1590          (let ((found (position #\newline string :test #'char=
1591                                 :end end :from-end t)))
1592            (if found
1593                (- end (the fixnum found))
1594                current)))))
1595      (:element-type (array-element-type
1596                      (fill-pointer-output-stream-string stream)))))
1597 \f
1598 ;;;; indenting streams
1599
1600 (defstruct (indenting-stream (:include ansi-stream
1601                                        (out #'indenting-out)
1602                                        (sout #'indenting-sout)
1603                                        (misc #'indenting-misc))
1604                              (:constructor make-indenting-stream (stream))
1605                              (:copier nil))
1606   ;; the stream we're based on
1607   stream
1608   ;; how much we indent on each line
1609   (indentation 0))
1610
1611 #!+sb-doc
1612 (setf (fdocumentation 'make-indenting-stream 'function)
1613  "Return an output stream which indents its output by some amount.")
1614
1615 ;;; INDENTING-INDENT writes the correct number of spaces needed to indent
1616 ;;; output on the given STREAM based on the specified SUB-STREAM.
1617 (defmacro indenting-indent (stream sub-stream)
1618   ;; KLUDGE: bare magic number 60
1619   `(do ((i 0 (+ i 60))
1620         (indentation (indenting-stream-indentation ,stream)))
1621        ((>= i indentation))
1622      (%write-string
1623       #.(make-string 60 :initial-element #\Space)
1624       ,sub-stream
1625       0
1626       (min 60 (- indentation i)))))
1627
1628 ;;; INDENTING-OUT writes a character to an indenting stream.
1629 (defun indenting-out (stream char)
1630   (let ((sub-stream (indenting-stream-stream stream)))
1631     (write-char char sub-stream)
1632     (if (char= char #\newline)
1633         (indenting-indent stream sub-stream))))
1634
1635 ;;; INDENTING-SOUT writes a string to an indenting stream.
1636 (defun indenting-sout (stream string start end)
1637   (declare (simple-string string) (fixnum start end))
1638   (do ((i start)
1639        (sub-stream (indenting-stream-stream stream)))
1640       ((= i end))
1641     (let ((newline (position #\newline string :start i :end end)))
1642       (cond (newline
1643              (%write-string string sub-stream i (1+ newline))
1644              (indenting-indent stream sub-stream)
1645              (setq i (+ newline 1)))
1646             (t
1647              (%write-string string sub-stream i end)
1648              (setq i end))))))
1649
1650 ;;; INDENTING-MISC just treats just the :LINE-LENGTH message
1651 ;;; differently. INDENTING-CHARPOS says the charpos is the charpos of
1652 ;;; the base stream minus the stream's indentation.
1653 (defun indenting-misc (stream operation &optional arg1 arg2)
1654   (let ((sub-stream (indenting-stream-stream stream)))
1655     (if (ansi-stream-p sub-stream)
1656         (let ((method (ansi-stream-misc sub-stream)))
1657           (case operation
1658             (:line-length
1659              (let ((line-length (funcall method sub-stream operation)))
1660                (if line-length
1661                    (- line-length (indenting-stream-indentation stream)))))
1662             (:charpos
1663              (let ((charpos (funcall method sub-stream operation)))
1664                (if charpos
1665                    (- charpos (indenting-stream-indentation stream)))))
1666             (t
1667              (funcall method sub-stream operation arg1 arg2))))
1668         ;; must be Gray streams FUNDAMENTAL-STREAM
1669         (case operation
1670           (:line-length
1671            (let ((line-length (stream-line-length sub-stream)))
1672              (if line-length
1673                  (- line-length (indenting-stream-indentation stream)))))
1674           (:charpos
1675            (let ((charpos (stream-line-column sub-stream)))
1676              (if charpos
1677                  (- charpos (indenting-stream-indentation stream)))))
1678           (t
1679            (stream-misc-dispatch sub-stream operation arg1 arg2))))))
1680
1681 (declaim (maybe-inline read-char unread-char read-byte listen))
1682 \f
1683 ;;;; case frobbing streams, used by FORMAT ~(...~)
1684
1685 (defstruct (case-frob-stream
1686             (:include ansi-stream
1687                       (misc #'case-frob-misc))
1688             (:constructor %make-case-frob-stream (target out sout))
1689             (:copier nil))
1690   (target (missing-arg) :type stream))
1691
1692 (defun make-case-frob-stream (target kind)
1693   #!+sb-doc
1694   "Return a stream that sends all output to the stream TARGET, but modifies
1695    the case of letters, depending on KIND, which should be one of:
1696      :UPCASE - convert to upper case.
1697      :DOWNCASE - convert to lower case.
1698      :CAPITALIZE - convert the first letter of words to upper case and the
1699         rest of the word to lower case.
1700      :CAPITALIZE-FIRST - convert the first letter of the first word to upper
1701         case and everything else to lower case."
1702   (declare (type stream target)
1703            (type (member :upcase :downcase :capitalize :capitalize-first)
1704                  kind)
1705            (values stream))
1706   (if (case-frob-stream-p target)
1707       ;; If we are going to be writing to a stream that already does
1708       ;; case frobbing, why bother frobbing the case just so it can
1709       ;; frob it again?
1710       target
1711       (multiple-value-bind (out sout)
1712           (ecase kind
1713             (:upcase
1714              (values #'case-frob-upcase-out
1715                      #'case-frob-upcase-sout))
1716             (:downcase
1717              (values #'case-frob-downcase-out
1718                      #'case-frob-downcase-sout))
1719             (:capitalize
1720              (values #'case-frob-capitalize-out
1721                      #'case-frob-capitalize-sout))
1722             (:capitalize-first
1723              (values #'case-frob-capitalize-first-out
1724                      #'case-frob-capitalize-first-sout)))
1725         (%make-case-frob-stream target out sout))))
1726
1727 (defun case-frob-misc (stream op &optional arg1 arg2)
1728   (declare (type case-frob-stream stream))
1729   (case op
1730     (:close
1731      (set-closed-flame stream))
1732     (t
1733      (let ((target (case-frob-stream-target stream)))
1734        (if (ansi-stream-p target)
1735            (funcall (ansi-stream-misc target) target op arg1 arg2)
1736            (stream-misc-dispatch target op arg1 arg2))))))
1737
1738 (defun case-frob-upcase-out (stream char)
1739   (declare (type case-frob-stream stream)
1740            (type character char))
1741   (let ((target (case-frob-stream-target stream))
1742         (char (char-upcase char)))
1743     (if (ansi-stream-p target)
1744         (funcall (ansi-stream-out target) target char)
1745         (stream-write-char target char))))
1746
1747 (defun case-frob-upcase-sout (stream str start end)
1748   (declare (type case-frob-stream stream)
1749            (type simple-string str)
1750            (type index start)
1751            (type (or index null) end))
1752   (let* ((target (case-frob-stream-target stream))
1753          (len (length str))
1754          (end (or end len))
1755          (string (if (and (zerop start) (= len end))
1756                      (string-upcase str)
1757                      (nstring-upcase (subseq str start end))))
1758          (string-len (- end start)))
1759     (if (ansi-stream-p target)
1760         (funcall (ansi-stream-sout target) target string 0 string-len)
1761         (stream-write-string target string 0 string-len))))
1762
1763 (defun case-frob-downcase-out (stream char)
1764   (declare (type case-frob-stream stream)
1765            (type character char))
1766   (let ((target (case-frob-stream-target stream))
1767         (char (char-downcase char)))
1768     (if (ansi-stream-p target)
1769         (funcall (ansi-stream-out target) target char)
1770         (stream-write-char target char))))
1771
1772 (defun case-frob-downcase-sout (stream str start end)
1773   (declare (type case-frob-stream stream)
1774            (type simple-string str)
1775            (type index start)
1776            (type (or index null) end))
1777   (let* ((target (case-frob-stream-target stream))
1778          (len (length str))
1779          (end (or end len))
1780          (string (if (and (zerop start) (= len end))
1781                      (string-downcase str)
1782                      (nstring-downcase (subseq str start end))))
1783          (string-len (- end start)))
1784     (if (ansi-stream-p target)
1785         (funcall (ansi-stream-sout target) target string 0 string-len)
1786         (stream-write-string target string 0 string-len))))
1787
1788 (defun case-frob-capitalize-out (stream char)
1789   (declare (type case-frob-stream stream)
1790            (type character char))
1791   (let ((target (case-frob-stream-target stream)))
1792     (cond ((alphanumericp char)
1793            (let ((char (char-upcase char)))
1794              (if (ansi-stream-p target)
1795                  (funcall (ansi-stream-out target) target char)
1796                  (stream-write-char target char)))
1797            (setf (case-frob-stream-out stream) #'case-frob-capitalize-aux-out)
1798            (setf (case-frob-stream-sout stream)
1799                  #'case-frob-capitalize-aux-sout))
1800           (t
1801            (if (ansi-stream-p target)
1802                (funcall (ansi-stream-out target) target char)
1803                (stream-write-char target char))))))
1804
1805 (defun case-frob-capitalize-sout (stream str start end)
1806   (declare (type case-frob-stream stream)
1807            (type simple-string str)
1808            (type index start)
1809            (type (or index null) end))
1810   (let* ((target (case-frob-stream-target stream))
1811          (str (subseq str start end))
1812          (len (length str))
1813          (inside-word nil))
1814     (dotimes (i len)
1815       (let ((char (schar str i)))
1816         (cond ((not (alphanumericp char))
1817                (setf inside-word nil))
1818               (inside-word
1819                (setf (schar str i) (char-downcase char)))
1820               (t
1821                (setf inside-word t)
1822                (setf (schar str i) (char-upcase char))))))
1823     (when inside-word
1824       (setf (case-frob-stream-out stream)
1825             #'case-frob-capitalize-aux-out)
1826       (setf (case-frob-stream-sout stream)
1827             #'case-frob-capitalize-aux-sout))
1828     (if (ansi-stream-p target)
1829         (funcall (ansi-stream-sout target) target str 0 len)
1830         (stream-write-string target str 0 len))))
1831
1832 (defun case-frob-capitalize-aux-out (stream char)
1833   (declare (type case-frob-stream stream)
1834            (type character char))
1835   (let ((target (case-frob-stream-target stream)))
1836     (cond ((alphanumericp char)
1837            (let ((char (char-downcase char)))
1838              (if (ansi-stream-p target)
1839                  (funcall (ansi-stream-out target) target char)
1840                  (stream-write-char target char))))
1841           (t
1842            (if (ansi-stream-p target)
1843                (funcall (ansi-stream-out target) target char)
1844                (stream-write-char target char))
1845            (setf (case-frob-stream-out stream)
1846                  #'case-frob-capitalize-out)
1847            (setf (case-frob-stream-sout stream)
1848                  #'case-frob-capitalize-sout)))))
1849
1850 (defun case-frob-capitalize-aux-sout (stream str start end)
1851   (declare (type case-frob-stream stream)
1852            (type simple-string str)
1853            (type index start)
1854            (type (or index null) end))
1855   (let* ((target (case-frob-stream-target stream))
1856          (str (subseq str start end))
1857          (len (length str))
1858          (inside-word t))
1859     (dotimes (i len)
1860       (let ((char (schar str i)))
1861         (cond ((not (alphanumericp char))
1862                (setf inside-word nil))
1863               (inside-word
1864                (setf (schar str i) (char-downcase char)))
1865               (t
1866                (setf inside-word t)
1867                (setf (schar str i) (char-upcase char))))))
1868     (unless inside-word
1869       (setf (case-frob-stream-out stream)
1870             #'case-frob-capitalize-out)
1871       (setf (case-frob-stream-sout stream)
1872             #'case-frob-capitalize-sout))
1873     (if (ansi-stream-p target)
1874         (funcall (ansi-stream-sout target) target str 0 len)
1875         (stream-write-string target str 0 len))))
1876
1877 (defun case-frob-capitalize-first-out (stream char)
1878   (declare (type case-frob-stream stream)
1879            (type character char))
1880   (let ((target (case-frob-stream-target stream)))
1881     (cond ((alphanumericp char)
1882            (let ((char (char-upcase char)))
1883              (if (ansi-stream-p target)
1884                  (funcall (ansi-stream-out target) target char)
1885                  (stream-write-char target char)))
1886            (setf (case-frob-stream-out stream)
1887                  #'case-frob-downcase-out)
1888            (setf (case-frob-stream-sout stream)
1889                  #'case-frob-downcase-sout))
1890           (t
1891            (if (ansi-stream-p target)
1892                (funcall (ansi-stream-out target) target char)
1893                (stream-write-char target char))))))
1894
1895 (defun case-frob-capitalize-first-sout (stream str start end)
1896   (declare (type case-frob-stream stream)
1897            (type simple-string str)
1898            (type index start)
1899            (type (or index null) end))
1900   (let* ((target (case-frob-stream-target stream))
1901          (str (subseq str start end))
1902          (len (length str)))
1903     (dotimes (i len)
1904       (let ((char (schar str i)))
1905         (when (alphanumericp char)
1906           (setf (schar str i) (char-upcase char))
1907           (do ((i (1+ i) (1+ i)))
1908               ((= i len))
1909             (setf (schar str i) (char-downcase (schar str i))))
1910           (setf (case-frob-stream-out stream)
1911                 #'case-frob-downcase-out)
1912           (setf (case-frob-stream-sout stream)
1913                 #'case-frob-downcase-sout)
1914           (return))))
1915     (if (ansi-stream-p target)
1916         (funcall (ansi-stream-sout target) target str 0 len)
1917         (stream-write-string target str 0 len))))
1918 \f
1919 ;;;; READ-SEQUENCE
1920
1921 (defun read-sequence (seq stream &key (start 0) end)
1922   #!+sb-doc
1923   "Destructively modify SEQ by reading elements from STREAM.
1924   That part of SEQ bounded by START and END is destructively modified by
1925   copying successive elements into it from STREAM. If the end of file
1926   for STREAM is reached before copying all elements of the subsequence,
1927   then the extra elements near the end of sequence are not updated, and
1928   the index of the next element is returned."
1929   (declare (type sequence seq)
1930            (type stream stream)
1931            (type index start)
1932            (type sequence-end end)
1933            (values index))
1934   (if (ansi-stream-p stream)
1935       (ansi-stream-read-sequence seq stream start end)
1936       ;; must be Gray streams FUNDAMENTAL-STREAM
1937       (stream-read-sequence stream seq start end)))
1938
1939 (declaim (inline compatible-vector-and-stream-element-types-p))
1940 (defun compatible-vector-and-stream-element-types-p (vector stream)
1941   (declare (type vector vector)
1942            (type ansi-stream stream))
1943   (or (and (typep vector '(simple-array (unsigned-byte 8) (*)))
1944            (subtypep (stream-element-type stream) '(unsigned-byte 8)))
1945       (and (typep vector '(simple-array (signed-byte 8) (*)))
1946            (subtypep (stream-element-type stream) '(signed-byte 8)))))
1947
1948 (defun ansi-stream-read-sequence (seq stream start %end)
1949   (declare (type sequence seq)
1950            (type ansi-stream stream)
1951            (type index start)
1952            (type sequence-end %end)
1953            (values index))
1954   (let ((end (or %end (length seq))))
1955     (declare (type index end))
1956     (etypecase seq
1957       (list
1958        (let ((read-function
1959               (if (subtypep (stream-element-type stream) 'character)
1960                   #'ansi-stream-read-char
1961                   #'ansi-stream-read-byte)))
1962          (do ((rem (nthcdr start seq) (rest rem))
1963               (i start (1+ i)))
1964              ((or (endp rem) (>= i end)) i)
1965            (declare (type list rem)
1966                     (type index i))
1967            (let ((el (funcall read-function stream nil :eof nil)))
1968              (when (eq el :eof)
1969                (return i))
1970              (setf (first rem) el)))))
1971       (vector
1972        (with-array-data ((data seq) (offset-start start) (offset-end end))
1973          (if (compatible-vector-and-stream-element-types-p data stream)
1974              (let* ((numbytes (- end start))
1975                     (bytes-read (read-n-bytes stream data offset-start
1976                                               numbytes nil)))
1977                (if (< bytes-read numbytes)
1978                    (+ start bytes-read)
1979                    end))
1980              (let ((read-function
1981                     (if (subtypep (stream-element-type stream) 'character)
1982                         ;; If the stream-element-type is CHARACTER,
1983                         ;; this might be a bivalent stream. If the
1984                         ;; sequence is a specialized unsigned-byte
1985                         ;; vector, try to read use binary IO. It'll
1986                         ;; signal an error if stream is an pure
1987                         ;; character stream.
1988                         (if (subtypep (array-element-type data)
1989                                       'unsigned-byte)
1990                             #'ansi-stream-read-byte
1991                             #'ansi-stream-read-char)
1992                         #'ansi-stream-read-byte)))
1993                (do ((i offset-start (1+ i)))
1994                    ((>= i offset-end) end)
1995                  (declare (type index i))
1996                  (let ((el (funcall read-function stream nil :eof nil)))
1997                    (when (eq el :eof)
1998                      (return (+ start (- i offset-start))))
1999                    (setf (aref data i) el))))))))))
2000 \f
2001 ;;;; WRITE-SEQUENCE
2002
2003 (defun write-sequence (seq stream &key (start 0) (end nil))
2004   #!+sb-doc
2005   "Write the elements of SEQ bounded by START and END to STREAM."
2006   (declare (type sequence seq)
2007            (type stream stream)
2008            (type index start)
2009            (type sequence-end end)
2010            (values sequence))
2011   (if (ansi-stream-p stream)
2012       (ansi-stream-write-sequence seq stream start end)
2013       ;; must be Gray-streams FUNDAMENTAL-STREAM
2014       (stream-write-sequence stream seq start end)))
2015
2016 (defun ansi-stream-write-sequence (seq stream start %end)
2017   (declare (type sequence seq)
2018            (type ansi-stream stream)
2019            (type index start)
2020            (type sequence-end %end)
2021            (values sequence))
2022   (let ((end (or %end (length seq))))
2023     (declare (type index end))
2024     (etypecase seq
2025       (list
2026        (let ((write-function
2027               (if (subtypep (stream-element-type stream) 'character)
2028                   (ansi-stream-out stream)
2029                   (ansi-stream-bout stream))))
2030          (do ((rem (nthcdr start seq) (rest rem))
2031               (i start (1+ i)))
2032              ((or (endp rem) (>= i end)))
2033            (declare (type list rem)
2034                     (type index i))
2035            (funcall write-function stream (first rem)))))
2036       (string
2037        (%write-string seq stream start end))
2038       (vector
2039        (with-array-data ((data seq) (offset-start start) (offset-end end))
2040          (labels
2041              ((output-seq-in-loop ()
2042                 (let ((write-function
2043                        (if (subtypep (stream-element-type stream) 'character)
2044                            (lambda (stream object)
2045                              ;; This might be a bivalent stream, so we need
2046                              ;; to dispatch on a per-element basis, rather
2047                              ;; than just based on the sequence or stream
2048                              ;; element types.
2049                              (if (characterp object)
2050                                  (funcall (ansi-stream-out stream)
2051                                           stream object)
2052                                  (funcall (ansi-stream-bout stream)
2053                                           stream object)))
2054                            (ansi-stream-bout stream))))
2055                   (do ((i offset-start (1+ i)))
2056                       ((>= i offset-end))
2057                     (declare (type index i))
2058                     (funcall write-function stream (aref data i))))))
2059            (if (and (fd-stream-p stream)
2060                     (compatible-vector-and-stream-element-types-p data stream))
2061                (buffer-output stream data offset-start offset-end)
2062                (output-seq-in-loop)))))))
2063   seq)
2064 \f
2065 ;;;; etc.