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