d5b709cb920f6c9a7703ca898f2696594231a07e
[sbcl.git] / contrib / sb-simple-streams / impl.lisp
1 ;;; -*- lisp -*-
2 ;;;
3 ;;; **********************************************************************
4 ;;; This code was written by Paul Foley and has been placed in the public
5 ;;; domain.
6 ;;; 
7
8 ;;; Sbcl port by Rudi Schlatte.
9
10 (in-package "SB-SIMPLE-STREAMS")
11
12 ;;;
13 ;;; **********************************************************************
14 ;;;
15 ;;; Implementations of standard Common Lisp functions for simple-streams
16
17 (defun %uninitialized (stream)
18   (error "~S has not been initialized." stream))
19
20 (defun %check (stream kind)
21   (declare (type simple-stream stream)
22            (optimize (speed 3) (space 1) (debug 0) (safety 0)))
23   (with-stream-class (simple-stream stream)
24     (cond ((not (any-stream-instance-flags stream :simple))
25            (%uninitialized stream))
26           ((and (eq kind :open)
27                 (not (any-stream-instance-flags stream :input :output)))
28            (sb-kernel:closed-flame stream))
29           ((and (or (eq kind :input) (eq kind :io))
30                 (not (any-stream-instance-flags stream :input)))
31            (sb-kernel:ill-in stream))
32           ((and (or (eq kind :output) (eq kind :io))
33                 (not (any-stream-instance-flags stream :output)))
34            (sb-kernel:ill-out stream)))))
35
36 (defmethod input-stream-p ((stream simple-stream))
37   (any-stream-instance-flags stream :input))
38
39 (defmethod output-stream-p ((stream simple-stream))
40   (any-stream-instance-flags stream :output))
41
42 (defmethod open-stream-p ((stream simple-stream))
43   (any-stream-instance-flags stream :input :output))
44
45 ;;; From the simple-streams documentation: "A generic function implies
46 ;;; a specialization capability that does not exist for
47 ;;; simple-streams; simple-stream specializations should be on
48 ;;; device-close."  So don't do it.
49 (defmethod close ((stream simple-stream) &key abort)
50   (device-close stream abort))
51
52 (defun %file-position (stream position)
53   (declare (type simple-stream stream)
54            (type (or (integer 0 *) (member nil :start :end)) position))
55   (with-stream-class (simple-stream stream)
56     (%check stream :open)
57     (if position
58         ;; Adjust current position
59         (let ((position (case position (:start 0) (:end -1)
60                               (otherwise position))))
61           (etypecase stream
62             (single-channel-simple-stream
63              (when (sc-dirty-p stream)
64                (flush-buffer stream t)))
65             (dual-channel-simple-stream
66              (with-stream-class (dual-channel-simple-stream stream)
67                (when (> (sm outpos stream) 0)
68                  (device-write stream :flush 0 nil t))))
69             (string-simple-stream
70              nil))
71
72           (setf (sm last-char-read-size stream) 0)
73           (setf (sm buffpos stream) 0   ; set pointer to 0 to force a read
74                 (sm buffer-ptr stream) 0)
75           (setf (sm charpos stream) nil)
76           (remove-stream-instance-flags stream :eof)
77           (setf (device-file-position stream) position))
78         ;; Just report current position
79         (let ((posn (device-file-position stream)))
80           (when posn
81             (when (sm handler stream)
82               (dolist (queued (sm pending stream))
83                 (incf posn (- (the sb-int:index (third queued))
84                               (the sb-int:index (second queued))))))
85             (etypecase stream
86               (single-channel-simple-stream
87                (case (sm mode stream)
88                  ((0 3)         ; read, read-modify
89                   ;; Note that posn can increase here if we wrote
90                   ;; past the end of previously-read data
91                   (decf posn (- (sm buffer-ptr stream) (sm buffpos stream))))
92                  (1                     ; write
93                   (incf posn (sm buffpos stream)))))
94               (dual-channel-simple-stream
95                (with-stream-class (dual-channel-simple-stream stream)
96                  (incf posn (sm outpos stream))
97                  (when (>= (sm buffer-ptr stream) 0)
98                    (decf posn (- (sm buffer-ptr stream) (sm buffpos stream))))))
99               (string-simple-stream
100                nil)))
101           posn))))
102
103 (defun %file-length (stream)
104   (declare (type simple-stream stream))
105   (%check stream :open)
106   (device-file-length stream))
107
108
109 (defun %file-name (stream)
110   (declare (type simple-stream stream))
111   (%check stream nil)
112   (typecase stream
113     (file-simple-stream
114      (with-stream-class (file-simple-stream stream)
115        (sm pathname stream)))
116     (probe-simple-stream
117      (with-stream-class (probe-simple-stream stream)
118        (sm pathname stream)))
119     (otherwise
120      nil)))
121
122
123 (defun %file-rename (stream new-name)
124   (declare (type simple-stream stream))
125   (%check stream nil)
126   (if (typep stream 'file-simple-stream)
127       (with-stream-class (file-simple-stream stream)
128         (setf (sm pathname stream) new-name)
129         (setf (sm filename stream) (sb-int:unix-namestring new-name nil))
130         t)
131       nil))
132
133
134 (defun %file-string-length (stream object)
135   (declare (type simple-stream stream))
136   (with-stream-class (simple-stream stream)
137     (%check stream :output)
138     ;; FIXME: need to account for compositions on the stream...
139     (let ((count 0))
140       (flet ((fn (octet)
141                (declare (ignore octet))
142                (incf count)))
143         (etypecase object
144           (character
145            (let ((x nil))
146              (char-to-octets (sm external-format stream) object x #'fn)))
147           (string
148            (let ((x nil)
149                  (ef (sm external-format stream)))
150              (dotimes (i (length object))
151                (declare (type sb-int:index i))
152                (char-to-octets ef (char object i) x #'fn))))))
153       count)))
154
155
156 (defun %read-line (stream eof-error-p eof-value recursive-p)
157   (declare (optimize (speed 3) (space 1) (safety 0) (debug 0))
158            (type simple-stream stream)
159            (ignore recursive-p))
160   (with-stream-class (simple-stream stream)
161     (%check stream :input)
162     (when (any-stream-instance-flags stream :eof)
163       (return-from %read-line
164         (sb-impl::eof-or-lose stream eof-error-p eof-value)))
165     ;; for interactive streams, finish output first to force prompt
166     (when (and (any-stream-instance-flags stream :output)
167                (any-stream-instance-flags stream :interactive))
168       (%finish-output stream))
169     (let* ((encap (sm melded-stream stream)) ; encapsulating stream
170            (cbuf (make-string 80))      ; current buffer
171            (bufs (list cbuf))           ; list of buffers
172            (tail bufs)                  ; last cons of bufs list
173            (index 0)                    ; current index in current buffer
174            (total 0))                   ; total characters
175       (declare (type simple-stream encap)
176                (type simple-base-string cbuf)
177                (type cons bufs tail)
178                (type sb-int:index index total))
179       (loop
180         (multiple-value-bind (chars done)
181             (funcall-stm-handler j-read-chars encap cbuf
182                                  #\Newline index (length cbuf) t)
183           (declare (type sb-int:index chars))
184           (incf index chars)
185           (incf total chars)
186           (when (and (eq done :eof) (zerop total))
187             (if eof-error-p
188                 (error 'end-of-file :stream stream)
189                 (return (values eof-value t))))
190           (when done
191             ;; If there's only one buffer in use, return it directly
192             (when (null (cdr bufs))
193               (return (values (sb-kernel:shrink-vector cbuf total)
194                               (eq done :eof))))
195             ;; If total fits in final buffer, use it
196             (when (<= total (length cbuf))
197               (replace cbuf cbuf :start1 (- total index) :end2 index)
198               (let ((idx 0))
199                 (declare (type sb-int:index idx))
200                 (do ((list bufs (cdr list)))
201                     ((eq list tail))
202                   (let ((buf (car list)))
203                     (declare (type simple-base-string buf))
204                     (replace cbuf buf :start1 idx)
205                     (incf idx (length buf)))))
206               (return (values (sb-kernel:shrink-vector cbuf total)
207                               (eq done :eof))))
208             ;; Allocate new string of appropriate length
209             (let ((string (make-string total))
210                   (index 0))
211               (declare (type sb-int:index index))
212               (dolist (buf bufs)
213                 (declare (type simple-base-string buf))
214                 (replace string buf :start1 index)
215                 (incf index (length buf)))
216               (return  (values string (eq done :eof)))))
217           (when (>= index (length cbuf))
218             (setf cbuf (make-string (the sb-int:index (* 2 index))))
219             (setf index 0)
220             (setf (cdr tail) (cons cbuf nil))
221             (setf tail (cdr tail))))))))
222
223 (defun %read-char (stream eof-error-p eof-value recursive-p blocking-p)
224   (declare (type simple-stream stream)
225            (ignore recursive-p))
226   (with-stream-class (simple-stream stream)
227     (%check stream :input)
228     (when (any-stream-instance-flags stream :eof)
229       (return-from %read-char
230         (sb-impl::eof-or-lose stream eof-error-p eof-value)))
231     ;; for interactive streams, finish output first to force prompt
232     (when (and (any-stream-instance-flags stream :output)
233                (any-stream-instance-flags stream :interactive))
234       (%finish-output stream))
235     (funcall-stm-handler j-read-char (sm melded-stream stream)
236                          eof-error-p eof-value blocking-p)))
237
238
239 (defun %unread-char (stream character)
240   (declare (type simple-stream stream) (ignore character))
241   (with-stream-class (simple-stream stream)
242     (%check stream :input)
243     (if (zerop (sm last-char-read-size stream))
244         (error "Nothing to unread.")
245         (progn
246           (funcall-stm-handler j-unread-char (sm melded-stream stream) nil)
247           (remove-stream-instance-flags stream :eof)
248           (setf (sm last-char-read-size stream) 0)))))
249
250
251 (defun %peek-char (stream peek-type eof-error-p eof-value recursive-p)
252   (declare (type simple-stream stream)
253            (ignore recursive-p))
254   (with-stream-class (simple-stream stream)
255     (%check stream :input)
256     (when (any-stream-instance-flags stream :eof)
257       (return-from %peek-char
258         (sb-impl::eof-or-lose stream eof-error-p eof-value)))
259     (let* ((encap (sm melded-stream stream))
260            (char (funcall-stm-handler j-read-char encap
261                                      eof-error-p stream t)))
262       (cond ((eq char stream) eof-value)
263             ((characterp peek-type)
264              (do ((char char (funcall-stm-handler j-read-char encap
265                                                   eof-error-p
266                                                   stream t)))
267                  ((or (eq char stream) (char= char peek-type))
268                   (unless (eq char stream)
269                     (funcall-stm-handler j-unread-char encap t))
270                   (if (eq char stream) eof-value char))))
271             ((eq peek-type t)
272              (do ((char char (funcall-stm-handler j-read-char encap
273                                                   eof-error-p
274                                                   stream t)))
275                  ((or (eq char stream)
276                       (not (sb-impl::whitespacep char)))
277                   (unless (eq char stream)
278                     (funcall-stm-handler j-unread-char encap t))
279                   (if (eq char stream) eof-value char))))
280             (t
281              (funcall-stm-handler j-unread-char encap t)
282              char)))))
283
284 (defun %listen (stream width)
285   (declare (type simple-stream stream))
286   ;; WIDTH is number of octets which must be available; any value
287   ;; other than 1 is treated as 'character.
288   (with-stream-class (simple-stream stream)
289     (%check stream :input)
290     (when (any-stream-instance-flags stream :eof)
291       (return-from %listen nil))
292     (if (not (or (eql width 1) (null width)))
293         (funcall-stm-handler j-listen (sm melded-stream stream))
294         (or (< (sm buffpos stream) (sm buffer-ptr stream))
295             (when (or (not (any-stream-instance-flags stream :dual :string))
296                       (>= (sm mode stream) 0)) ;; device-connected @@ single-channel
297               (let ((lcrs (sm last-char-read-size stream)))
298                 (unwind-protect
299                      (progn
300                        (setf (sm last-char-read-size stream) (1+ lcrs))
301                        (plusp (refill-buffer stream nil)))
302                   (setf (sm last-char-read-size stream) lcrs))))))))
303
304 (defun %clear-input (stream buffer-only)
305   (declare (type simple-stream stream))
306   (with-stream-class (simple-stream stream)
307     (%check stream :input)
308     (setf (sm buffpos stream) 0
309           (sm buffer-ptr stream) 0
310           (sm last-char-read-size stream) 0
311           #|(sm unread-past-soft-eof stream) nil|#)
312     #| (setf (sm reread-count stream) 0)  on dual-channel streams? |#
313     )
314   (device-clear-input stream buffer-only))
315
316
317 (defun %read-byte (stream eof-error-p eof-value)
318   (declare (type simple-stream stream))
319   (with-stream-class (simple-stream stream)
320     (%check stream :input)
321     (if (any-stream-instance-flags stream :eof)
322         (sb-impl::eof-or-lose stream eof-error-p eof-value)
323         (etypecase stream
324           (single-channel-simple-stream
325            (read-byte-internal stream eof-error-p eof-value t))
326           (dual-channel-simple-stream
327            (read-byte-internal stream eof-error-p eof-value t))
328           (string-simple-stream
329            (with-stream-class (string-simple-stream stream)
330              (let ((encap (sm input-handle stream)))
331                (unless encap
332                  (error 'simple-type-error
333                         :datum stream
334                         :expected-type 'stream
335                         :format-control "Can't read-byte on string streams"
336                         :format-arguments '()))
337                (prog1
338                    (read-byte encap eof-error-p eof-value)
339                  (setf (sm last-char-read-size stream) 0
340                        (sm encapsulated-char-read-size stream) 0)))))))))
341
342
343 (defun %write-char (stream character)
344   (declare (type simple-stream stream))
345   (with-stream-class (simple-stream stream)
346     (%check stream :output)
347     (funcall-stm-handler-2 j-write-char character (sm melded-stream stream))))
348
349
350 (defun %fresh-line (stream)
351   (declare (type simple-stream stream))
352   (with-stream-class (simple-stream stream)
353     (%check stream :output)
354     (when (/= (or (sm charpos stream) 1) 0)
355       (funcall-stm-handler-2 j-write-char #\Newline (sm melded-stream stream))
356       t)))
357
358
359 (defun %write-string (stream string start end)
360   (declare (type simple-stream stream))
361   (with-stream-class (simple-stream stream)
362     (%check stream :output)
363     (funcall-stm-handler-2 j-write-chars string (sm melded-stream stream)
364                            start end)))
365
366
367 (defun %line-length (stream)
368   (declare (type simple-stream stream))
369   (%check stream :output)
370   ;; implement me
371   nil)
372
373
374 (defun %finish-output (stream)
375   (declare (type simple-stream stream))
376   (with-stream-class (simple-stream stream)
377     (%check stream :output)
378     (when (sm handler stream)
379       (do ()
380           ((null (sm pending stream)))
381         (sb-sys:serve-all-events)))
382     (etypecase stream
383       (single-channel-simple-stream
384        ;(when (and (> (sm mode stream) 0) (> (sm buffer-ptr stream) 0))
385        ;  (setf (device-file-position stream)
386        ;        (- (device-file-position stream) (sm buffer-ptr stream))))
387        ;(device-write stream :flush 0 nil t)
388        (flush-buffer stream t)
389        (setf (sm buffpos stream) 0))
390       (dual-channel-simple-stream
391        (with-stream-class (dual-channel-simple-stream stream)
392          (device-write stream :flush 0 nil t)
393          (setf (sm outpos stream) 0)))
394       (string-simple-stream
395            (device-write stream :flush 0 nil t))))
396   nil)
397
398
399 (defun %force-output (stream)
400   (declare (type simple-stream stream))
401   (with-stream-class (simple-stream stream)
402     (%check stream :output)
403     (etypecase stream
404       (single-channel-simple-stream
405        ;(when (> (sm buffer-ptr stream) 0)
406        ;  (setf (device-file-position stream)
407        ;        (- (device-file-position stream) (sm buffer-ptr stream))))
408        ;(device-write stream :flush 0 nil nil)
409        (flush-buffer stream nil)
410        (setf (sm buffpos stream) 0))
411       (dual-channel-simple-stream
412        (with-stream-class (dual-channel-simple-stream stream)
413          (device-write stream :flush 0 nil nil)
414          (setf (sm outpos stream) 0)))
415       (string-simple-stream
416        (device-write stream :flush 0 nil nil))))
417   nil)
418
419
420 (defun %clear-output (stream)
421   (declare (type simple-stream stream))
422   (with-stream-class (simple-stream stream)
423     (%check stream :output)
424     (when (sm handler stream)
425       (sb-sys:remove-fd-handler (sm handler stream))
426       (setf (sm handler stream) nil
427             (sm pending stream) nil))
428     (etypecase stream
429       (single-channel-simple-stream
430        (with-stream-class (single-channel-simple-stream stream)
431          (case (sm mode stream)
432            (1 (setf (sm buffpos stream) 0))
433            (3 (setf (sm mode stream) 0)))))
434       (dual-channel-simple-stream
435        (setf (sm outpos stream) 0))
436       (string-simple-stream
437        nil))
438     (device-clear-output stream)))
439
440
441 (defun %write-byte (stream integer)
442   (declare (type simple-stream stream))
443   (with-stream-class (simple-stream stream)
444     (%check stream :output)
445     (etypecase stream
446       (single-channel-simple-stream
447        (with-stream-class (single-channel-simple-stream stream)
448          (let ((ptr (sm buffpos stream)))
449           (when (>= ptr (sm buf-len stream))
450             (setf ptr (flush-buffer stream t)))
451           (setf (sm buffpos stream) (1+ ptr))
452           (setf (sm charpos stream) nil)
453           (setf (bref (sm buffer stream) ptr) integer)
454           (sc-set-dirty stream))))
455       (dual-channel-simple-stream
456        (with-stream-class (dual-channel-simple-stream stream)
457          (let ((ptr (sm outpos stream)))
458            (when (>= ptr (sm max-out-pos stream))
459              (setf ptr (flush-out-buffer stream t)))
460            (setf (sm outpos stream) (1+ ptr))
461            (setf (sm charpos stream) nil)
462            (setf (bref (sm out-buffer stream) ptr) integer))))
463       (string-simple-stream
464        (with-stream-class (string-simple-stream stream)
465          (let ((encap (sm output-handle stream)))
466            (unless encap
467              (error 'simple-type-error
468                     :datum stream
469                     :expected-type 'stream
470                     :format-control "Can't write-byte on string streams."
471                     :format-arguments '()))
472            (write-byte integer encap)))))))
473
474
475 (defun %read-sequence (stream seq start end partial-fill)
476   (declare (type simple-stream stream)
477            (type sequence seq)
478            (type sb-int:index start end)
479            (type boolean partial-fill))
480   (with-stream-class (simple-stream stream)
481     (%check stream :input)
482     (when (any-stream-instance-flags stream :eof)
483       (return-from %read-sequence 0))
484     (when (and (not (any-stream-instance-flags stream :dual :string))
485                (sc-dirty-p stream))
486       (flush-buffer stream t))
487     (etypecase seq
488       (string
489        (funcall-stm-handler j-read-chars (sm melded-stream stream) seq nil
490                             start end
491                             (if partial-fill :bnb t)))
492       ((or (simple-array (unsigned-byte 8) (*))
493            (simple-array (signed-byte 8) (*)))
494        (when (any-stream-instance-flags stream :string)
495          (error "Can't read into byte sequence from a string stream."))       
496        ;; "read-vector" equivalent, but blocking if partial-fill is NIL
497        ;; FIXME: this could be implemented faster via buffer-copy
498        (loop with encap = (sm melded-stream stream)
499             for index from start below end
500             for byte = (read-byte-internal encap nil nil t)
501               then (read-byte-internal encap nil nil partial-fill)
502             while byte
503             do (setf (bref seq index) byte)
504             finally (return index)))
505       ;; extend to work on other sequences: repeated read-byte
506       )))
507
508 (defun %write-sequence (stream seq start end)
509   (declare (type simple-stream stream)
510            (type sequence seq)
511            (type sb-int:index start end))
512   (with-stream-class (simple-stream stream)
513     (%check stream :output)
514     (etypecase seq
515       (string
516        (funcall-stm-handler-2 j-write-chars seq (sm melded-stream stream)
517                               start end))
518       ((or (simple-array (unsigned-byte 8) (*))
519            (simple-array (signed-byte 8) (*)))
520        ;; "write-vector" equivalent
521        (setf (sm charpos stream) nil)
522        (etypecase stream
523          (single-channel-simple-stream
524           (with-stream-class (single-channel-simple-stream stream)
525             (loop with max-ptr fixnum = (sm buf-len stream)
526                   for src-pos fixnum = start then (+ src-pos count)
527                   for src-rest fixnum = (- end src-pos)
528                   while (> src-rest 0) ; FIXME: this is non-ANSI
529                   for ptr fixnum = (let ((ptr (sm buffpos stream)))
530                                      (if (>= ptr max-ptr)
531                                          (flush-buffer stream t)
532                                          ptr))
533                   for buf-rest fixnum = (- max-ptr ptr)
534                   for count fixnum = (min buf-rest src-rest)
535                   do (progn (setf (sm mode stream) 1)
536                             (setf (sm buffpos stream) (+ ptr count))
537                             (buffer-copy seq src-pos (sm buffer stream) ptr count)))))
538          (dual-channel-simple-stream
539           (with-stream-class (dual-channel-simple-stream stream)
540             (loop with max-ptr fixnum = (sm max-out-pos stream)
541                   for src-pos fixnum = start then (+ src-pos count)
542                   for src-rest fixnum = (- end src-pos)
543                   while (> src-rest 0) ; FIXME: this is non-ANSI
544                   for ptr fixnum = (let ((ptr (sm outpos stream)))
545                                      (if (>= ptr max-ptr)
546                                          (flush-out-buffer stream t)
547                                          ptr))
548                   for buf-rest fixnum = (- max-ptr ptr)
549                   for count fixnum = (min buf-rest src-rest)
550                   do (progn (setf (sm outpos stream) (+ ptr count))
551                             (buffer-copy seq src-pos (sm out-buffer stream) ptr count)))))
552          (string-simple-stream
553           (error 'simple-type-error
554                  :datum stream
555                  :expected-type 'stream
556                  :format-control "Can't write a byte sequence to a string stream."
557                  :format-arguments '())))
558        )
559       ;; extend to work on other sequences: repeated write-byte
560       ))
561   seq)
562
563
564 (defun read-vector (vector stream &key (start 0) end (endian-swap :byte-8))
565   (declare (type (sb-kernel:simple-unboxed-array (*)) vector)
566            (type stream stream))
567   ;; START and END are octet offsets, not vector indices!  [Except for strings]
568   ;; Return value is index of next octet to be read into (i.e., start+count)
569   (etypecase stream
570     (simple-stream
571      (with-stream-class (simple-stream stream)
572        (cond ((stringp vector)
573               (let* ((start (or start 0))
574                      (end (or end (length vector)))
575                      (encap (sm melded-stream stream))
576                      (char (funcall-stm-handler j-read-char encap nil nil t)))
577                 (when char
578                   (setf (schar vector start) char)
579                   (incf start)
580                   (+ start (funcall-stm-handler j-read-chars encap vector nil
581                                                 start end nil)))))
582              ((any-stream-instance-flags stream :string)
583               (error "Can't READ-BYTE on string streams."))
584              (t
585               (do* ((encap (sm melded-stream stream))
586                     (index (or start 0) (1+ index))
587                     (end (or end (* (length vector) (vector-elt-width vector))))
588                     (endian-swap (endian-swap-value vector endian-swap))
589                     (byte (read-byte-internal encap nil nil t)
590                           (read-byte-internal encap nil nil nil)))
591                    ((or (null byte) (>= index end)) index)
592                 (setf (bref vector (logxor index endian-swap)) byte))))))
593     ((or ansi-stream fundamental-stream)
594      (unless (typep vector '(or string
595                              (simple-array (signed-byte 8) (*))
596                              (simple-array (unsigned-byte 8) (*))))
597        (error "Wrong vector type for read-vector on stream not of type simple-stream."))
598      (read-sequence vector stream :start (or start 0) :end end))))
599
600
601 ;;;
602 ;;; USER-LEVEL FUNCTIONS
603 ;;;
604
605 (defmethod open-stream-p ((stream simple-stream))
606   (any-stream-instance-flags stream :input :output))
607
608 (defmethod input-stream-p ((stream simple-stream))
609   (any-stream-instance-flags stream :input))
610
611 (defmethod output-stream-p ((stream simple-stream))
612   (any-stream-instance-flags stream :output))
613
614 (defmethod stream-element-type ((stream simple-stream))
615   '(unsigned-byte 8))
616
617 (defun interactive-stream-p (stream)
618   "Return true if Stream does I/O on a terminal or other interactive device."
619   (etypecase stream
620     (simple-stream
621      (%check stream :open)
622      (any-stream-instance-flags stream :interactive))
623     (ansi-stream
624      (funcall (sb-kernel:ansi-stream-misc stream) stream :interactive-p))
625     (fundamental-stream
626      nil)))
627
628 (defun (setf interactive-stream-p) (flag stream)
629   (typecase stream
630     (simple-stream
631      (%check stream :open)
632      (if flag
633          (add-stream-instance-flags stream :interactive)
634          (remove-stream-instance-flags stream :interactive)))
635     (t
636      (error 'simple-type-error
637             :datum stream
638             :expected-type 'simple-stream
639             :format-control "Can't set interactive flag on ~S."
640             :format-arguments (list stream)))))
641
642 (defun file-string-length (stream object)
643   (declare (type (or string character) object) (type stream stream))
644   "Return the delta in STREAM's FILE-POSITION that would be caused by writing
645    OBJECT to STREAM. Non-trivial only in implementations that support
646    international character sets."
647   (typecase stream
648     (simple-stream (%file-string-length stream object))
649     (t
650      (etypecase object
651        (character 1)
652        (string (length object))))))
653
654 (defun stream-external-format (stream)
655   "Returns Stream's external-format."
656   (etypecase stream
657     (simple-stream
658      (with-stream-class (simple-stream)
659        (%check stream :open)
660        (sm external-format stream)))
661     (ansi-stream
662      :default)
663     (fundamental-stream
664      :default)))
665
666 (defun open (filename &rest options
667              &key (direction :input)
668              (element-type 'character element-type-given)
669              if-exists if-does-not-exist
670              (external-format :default)
671              class mapped input-handle output-handle
672              &allow-other-keys)
673   "Return a stream which reads from or writes to Filename.
674   Defined keywords:
675    :direction - one of :input, :output, :io, or :probe
676    :element-type - type of object to read or write, default BASE-CHAR
677    :if-exists - one of :error, :new-version, :rename, :rename-and-delete,
678                        :overwrite, :append, :supersede or NIL
679    :if-does-not-exist - one of :error, :create or NIL
680    :external-format - :default
681   See the manual for details.
682
683   The following are simple-streams-specific additions:
684    :class - class of stream object to be created
685    :mapped - T to open a memory-mapped file
686    :input-handle - a stream or Unix file descriptor to read from
687    :output-handle - a stream or Unix file descriptor to write to"
688   (declare (ignore element-type external-format input-handle output-handle
689                    if-exists if-does-not-exist))
690   (let ((class (or class 'sb-sys::file-stream))
691         (options (copy-list options))
692         (filespec (merge-pathnames filename)))
693     (cond ((eq class 'sb-sys::file-stream)
694            (remf options :class)
695            (remf options :mapped)
696            (remf options :input-handle)
697            (remf options :output-handle)
698            (apply #'open-fd-stream filespec options))
699           ((subtypep class 'simple-stream)
700            (when element-type-given
701              (cerror "Do it anyway."
702                      "Can't create simple-streams with an element-type."))
703            (when (and (eq class 'file-simple-stream) mapped)
704              (setq class 'mapped-file-simple-stream)
705              (setf (getf options :class) 'mapped-file-simple-stream))
706            (when (subtypep class 'file-simple-stream)
707              (when (eq direction :probe)
708                (setq class 'probe-simple-stream)))
709            (apply #'make-instance class :filename filespec options))
710           ((subtypep class 'sb-gray:fundamental-stream)
711            (remf options :class)
712            (remf options :mapped)
713            (remf options :input-handle)
714            (remf options :output-handle)
715            (make-instance class :lisp-stream
716                           (apply #'open-fd-stream filespec options))))))
717
718
719 (declaim (inline read-byte read-char read-char-no-hang unread-char))
720
721 (defun read-byte (stream &optional (eof-error-p t) eof-value)
722   "Returns the next byte of the Stream."
723   (let ((stream (sb-impl::in-synonym-of stream)))
724     (etypecase stream
725       (simple-stream
726        (%read-byte stream eof-error-p eof-value))
727       (ansi-stream
728        (sb-impl::ansi-stream-read-byte stream eof-error-p eof-value nil))
729       (fundamental-stream
730        (let ((char (sb-gray:stream-read-byte stream)))
731          (if (eq char :eof)
732              (sb-impl::eof-or-lose stream eof-error-p eof-value)
733              char))))))
734
735 (defun read-char (&optional (stream *standard-input*) (eof-error-p t)
736                             eof-value recursive-p)
737   "Inputs a character from Stream and returns it."
738   (let ((stream (sb-impl::in-synonym-of stream)))
739     (etypecase stream
740       (simple-stream
741        (%read-char stream eof-error-p eof-value recursive-p t))
742       (ansi-stream
743        (sb-impl::ansi-stream-read-char stream eof-error-p eof-value
744                                        recursive-p))
745       (fundamental-stream
746        (let ((char (sb-gray:stream-read-char stream)))
747          (if (eq char :eof)
748              (sb-impl::eof-or-lose stream eof-error-p eof-value)
749              char))))))
750
751 (defun read-char-no-hang (&optional (stream *standard-input*) (eof-error-p t)
752                                     eof-value recursive-p)
753   "Returns the next character from the Stream if one is availible, or nil."
754   (declare (ignore recursive-p))
755   (let ((stream (sb-impl::in-synonym-of stream)))
756     (etypecase stream
757       (simple-stream
758        (%check stream :input)
759        (with-stream-class (simple-stream)
760          (funcall-stm-handler j-read-char stream eof-error-p eof-value nil)))
761       (ansi-stream
762        (sb-impl::ansi-stream-read-char-no-hang stream eof-error-p eof-value
763                                                recursive-p))
764       (fundamental-stream
765        (let ((char (sb-gray:stream-read-char-no-hang stream)))
766          (if (eq char :eof)
767              (sb-impl::eof-or-lose stream eof-error-p eof-value)
768              char))))))
769
770 (defun unread-char (character &optional (stream *standard-input*))
771   "Puts the Character back on the front of the input Stream."
772   (let ((stream (sb-impl::in-synonym-of stream)))
773     (etypecase stream
774       (simple-stream
775        (%unread-char stream character))
776       (ansi-stream
777        (sb-impl::ansi-stream-unread-char character stream))
778       (fundamental-stream
779        (sb-gray:stream-unread-char stream character))))
780   nil)
781
782 (declaim (notinline read-byte read-char read-char-no-hang unread-char))
783
784 (defun peek-char (&optional (peek-type nil) (stream *standard-input*)
785                             (eof-error-p t) eof-value recursive-p)
786   "Peeks at the next character in the input Stream.  See manual for details."
787   (let ((stream (sb-impl::in-synonym-of stream)))
788     (etypecase stream
789       (simple-stream
790        (%peek-char stream peek-type eof-error-p eof-value recursive-p))
791       ;; FIXME: Broken on ECHO-STREAM (cf internal implementation?) --
792       ;; CSR, 2004-01-19
793       (ansi-stream
794        (sb-impl::ansi-stream-peek-char peek-type stream eof-error-p eof-value
795                                        recursive-p))
796       (fundamental-stream
797        (cond ((characterp peek-type)
798               (do ((char (sb-gray:stream-read-char stream)
799                          (sb-gray:stream-read-char stream)))
800                   ((or (eq char :eof) (char= char peek-type))
801                    (cond ((eq char :eof)
802                           (sb-impl::eof-or-lose stream eof-error-p eof-value))
803                          (t
804                           (sb-gray:stream-unread-char stream char)
805                           char)))))
806              ((eq peek-type t)
807               (do ((char (sb-gray:stream-read-char stream)
808                          (sb-gray:stream-read-char stream)))
809                   ((or (eq char :eof) (not (sb-impl::whitespacep char)))
810                    (cond ((eq char :eof)
811                           (sb-impl::eof-or-lose stream eof-error-p eof-value))
812                          (t
813                           (sb-gray:stream-unread-char stream char)
814                           char)))))
815              (t
816               (let ((char (sb-gray:stream-peek-char stream)))
817                 (if (eq char :eof)
818                     (sb-impl::eof-or-lose stream eof-error-p eof-value)
819                     char))))))))
820
821 (defun listen (&optional (stream *standard-input*) (width 1))
822   "Returns T if WIDTH octets are available on STREAM.  If WIDTH is
823 given as 'CHARACTER, check for a character.  Note: the WIDTH argument
824 is supported only on simple-streams."
825   ;; WIDTH is number of octets which must be available; any value
826   ;; other than 1 is treated as 'character.
827   (let ((stream (sb-impl::in-synonym-of stream)))
828     (etypecase stream
829       (simple-stream
830        (%listen stream width))
831       (ansi-stream
832        (sb-impl::ansi-stream-listen stream))
833       (fundamental-stream
834        (sb-gray:stream-listen stream)))))
835
836
837 (defun read-line (&optional (stream *standard-input*) (eof-error-p t)
838                             eof-value recursive-p)
839   "Returns a line of text read from the Stream as a string, discarding the
840   newline character."
841   (let ((stream (sb-impl::in-synonym-of stream)))
842     (etypecase stream
843       (simple-stream
844        (%read-line stream eof-error-p eof-value recursive-p))
845       (ansi-stream
846        (sb-impl::ansi-stream-read-line stream eof-error-p eof-value
847                                        recursive-p))
848       (fundamental-stream
849        (multiple-value-bind (string eof) (sb-gray:stream-read-line stream)
850          (if (and eof (zerop (length string)))
851              (values (sb-impl::eof-or-lose stream eof-error-p eof-value) t)
852              (values string eof)))))))
853
854 (defun read-sequence (seq stream &key (start 0) (end nil) partial-fill)
855   "Destructively modify SEQ by reading elements from STREAM.
856   SEQ is bounded by START and END. SEQ is destructively modified by
857   copying successive elements into it from STREAM. If the end of file
858   for STREAM is reached before copying all elements of the subsequence,
859   then the extra elements near the end of sequence are not updated, and
860   the index of the next element is returned."
861   (let ((stream (sb-impl::in-synonym-of stream))
862         (end (or end (length seq))))
863     (etypecase stream
864       (simple-stream
865        (with-stream-class (simple-stream stream)
866          (%read-sequence stream seq start end partial-fill)))
867       (ansi-stream
868        (sb-impl::ansi-stream-read-sequence seq stream start end))
869       (fundamental-stream
870        (sb-gray:stream-read-sequence stream seq start end)))))
871
872 (defun clear-input (&optional (stream *standard-input*) buffer-only)
873   "Clears any buffered input associated with the Stream."
874   (let ((stream (sb-impl::in-synonym-of stream)))
875     (etypecase stream
876       (simple-stream
877        (%clear-input stream buffer-only))
878       (ansi-stream
879        (sb-impl::ansi-stream-clear-input stream))
880       (fundamental-stream
881        (sb-gray:stream-clear-input stream))))
882   nil)
883
884 (defun write-byte (integer stream)
885   "Outputs an octet to the Stream."
886   (let ((stream (sb-impl::out-synonym-of stream)))
887     (etypecase stream
888       (simple-stream
889        (%write-byte stream integer))
890       (ansi-stream
891        (funcall (sb-kernel:ansi-stream-bout stream) stream integer))
892       (fundamental-stream
893        (sb-gray:stream-write-byte stream integer))))
894   integer)
895
896 (defun write-char (character &optional (stream *standard-output*))
897   "Outputs the Character to the Stream."
898   (let ((stream (sb-impl::out-synonym-of stream)))
899     (etypecase stream
900       (simple-stream
901        (%write-char stream character))
902       (ansi-stream
903        (funcall (sb-kernel:ansi-stream-out stream) stream character))
904       (fundamental-stream
905        (sb-gray:stream-write-char stream character))))
906   character)
907
908 (defun write-string (string &optional (stream *standard-output*)
909                             &key (start 0) (end nil))
910   "Outputs the String to the given Stream."
911   (let ((stream (sb-impl::out-synonym-of stream))
912         (end (sb-impl::%check-vector-sequence-bounds string start end)))
913     (etypecase stream
914       (simple-stream
915        (%write-string stream string start end)
916        string)
917       (ansi-stream
918        (sb-impl::ansi-stream-write-string string stream start end))
919       (fundamental-stream
920        (sb-gray:stream-write-string stream string start end)))))
921
922 (defun write-line (string &optional (stream *standard-output*)
923                           &key (start 0) end)
924   (declare (type string string))
925   (let ((stream (sb-impl::out-synonym-of stream))
926         (end (sb-impl::%check-vector-sequence-bounds string start end)))
927     (etypecase stream
928       (simple-stream
929        (%check stream :output)
930        (with-stream-class (simple-stream stream)
931          (funcall-stm-handler-2 j-write-chars string stream start end)
932          (funcall-stm-handler-2 j-write-char #\Newline stream)))
933       (ansi-stream
934        (sb-impl::ansi-stream-write-string string stream start end)
935        (funcall (sb-kernel:ansi-stream-out stream) stream #\Newline))
936       (fundamental-stream
937        (sb-gray:stream-write-string stream string start end)
938        (sb-gray:stream-terpri stream))))
939   string)
940
941 (defun write-sequence (seq stream &key (start 0) (end nil))
942   "Write the elements of SEQ bounded by START and END to STREAM."
943   (let ((stream (sb-impl::out-synonym-of stream))
944         (end (or end (length seq))))
945     (etypecase stream
946       (simple-stream
947        (%write-sequence stream seq start end))
948       (ansi-stream
949        (sb-impl::ansi-stream-write-sequence seq stream start end))
950       (fundamental-stream
951        (sb-gray:stream-write-sequence stream seq start end)))))
952
953 (defun terpri (&optional (stream *standard-output*))
954   "Outputs a new line to the Stream."
955   (let ((stream (sb-impl::out-synonym-of stream)))
956     (etypecase stream
957       (simple-stream
958        (%check stream :output)
959        (with-stream-class (simple-stream stream)
960          (funcall-stm-handler-2 j-write-char #\Newline stream)))
961       (ansi-stream
962        (funcall (sb-kernel:ansi-stream-out stream) stream #\Newline))
963       (fundamental-stream
964        (sb-gray:stream-terpri stream))))
965   nil)
966
967 (defun fresh-line (&optional (stream *standard-output*))
968   "Outputs a new line to the Stream if it is not positioned at the beginning of
969    a line.  Returns T if it output a new line, nil otherwise."
970   (let ((stream (sb-impl::out-synonym-of stream)))
971     (etypecase stream
972       (simple-stream
973        (%fresh-line stream))
974       (ansi-stream
975        (sb-impl::ansi-stream-fresh-line stream))
976       (fundamental-stream
977        (sb-gray:stream-fresh-line stream)))))
978
979 (defun finish-output (&optional (stream *standard-output*))
980   "Attempts to ensure that all output sent to the Stream has reached its
981    destination, and only then returns."
982   (let ((stream (sb-impl::out-synonym-of stream)))
983     (etypecase stream
984       (simple-stream
985        (%finish-output stream))
986       (ansi-stream
987        (funcall (sb-kernel:ansi-stream-misc stream) stream :finish-output))
988       (fundamental-stream
989        (sb-gray:stream-finish-output stream))))
990   nil)
991
992 (defun force-output (&optional (stream *standard-output*))
993   "Attempts to force any buffered output to be sent."
994   (let ((stream (sb-impl::out-synonym-of stream)))
995     (etypecase stream
996       (simple-stream
997        (%force-output stream))
998       (ansi-stream
999        (funcall (sb-kernel:ansi-stream-misc stream) stream :force-output))
1000       (fundamental-stream
1001        (sb-gray:stream-force-output stream))))
1002   nil)
1003
1004 (defun clear-output (&optional (stream *standard-output*))
1005   "Clears the given output Stream."
1006   (let ((stream (sb-impl::out-synonym-of stream)))
1007     (etypecase stream
1008       (simple-stream
1009        (%clear-output stream))
1010       (ansi-stream
1011        (funcall (sb-kernel:ansi-stream-misc stream) stream :clear-output))
1012       (fundamental-stream
1013        (sb-gray:stream-clear-output stream))))
1014   nil)
1015
1016
1017 (defun file-position (stream &optional position)
1018   "With one argument returns the current position within the file
1019    File-Stream is open to.  If the second argument is supplied, then
1020    this becomes the new file position.  The second argument may also
1021    be :start or :end for the start and end of the file, respectively."
1022   (declare (type (or sb-int:index (member nil :start :end)) position))
1023   (etypecase stream
1024     (simple-stream
1025      (%file-position stream position))
1026     (ansi-stream
1027      (sb-impl::ansi-stream-file-position stream position))))
1028
1029 (defun file-length (stream)
1030   "This function returns the length of the file that File-Stream is open to."
1031   (etypecase stream
1032     (simple-stream
1033      (%file-length stream))
1034     (ansi-stream
1035      (sb-impl::stream-must-be-associated-with-file stream)
1036      (funcall (sb-kernel:ansi-stream-misc stream) stream :file-length))))
1037
1038 (defun charpos (&optional (stream *standard-output*))
1039   "Returns the number of characters on the current line of output of the given
1040   Stream, or Nil if that information is not availible."
1041   (let ((stream (sb-impl::out-synonym-of stream)))
1042     (etypecase stream
1043       (simple-stream
1044        (with-stream-class (simple-stream stream)
1045          (%check stream :open)
1046          (sm charpos stream)))
1047       (ansi-stream
1048        (funcall (sb-kernel:ansi-stream-misc stream) stream :charpos))
1049       (fundamental-stream
1050        (sb-gray:stream-line-column stream)))))
1051
1052 (defun line-length (&optional (stream *standard-output*))
1053   "Returns the number of characters in a line of output of the given
1054   Stream, or Nil if that information is not availible."
1055   (let ((stream (sb-impl::out-synonym-of stream)))
1056     (etypecase stream
1057       (simple-stream
1058        (%check stream :output)
1059        ;; TODO (sat 2003-04-02): a way to specify a line length would
1060        ;; be good, I suppose.  Returning nil here means
1061        ;; sb-pretty::default-line-length is used.
1062        nil)
1063       (ansi-stream
1064        (funcall (sb-kernel:ansi-stream-misc stream) stream :line-length))
1065       (fundamental-stream
1066        (sb-gray:stream-line-length stream)))))
1067
1068 (defun wait-for-input-available (stream &optional timeout)
1069   "Waits for input to become available on the Stream and returns T.  If
1070   Timeout expires, Nil is returned."
1071   (let ((stream (sb-impl::in-synonym-of stream)))
1072     (etypecase stream
1073       (fixnum
1074        (sb-sys:wait-until-fd-usable stream :input timeout))
1075       (simple-stream
1076        (%check stream :input)
1077        (with-stream-class (simple-stream stream)
1078          (or (< (sm buffpos stream) (sm buffer-ptr stream))
1079              (wait-for-input-available (sm input-handle stream) timeout))))
1080       (two-way-stream
1081        (wait-for-input-available (two-way-stream-input-stream stream) timeout))
1082       (synonym-stream
1083        (wait-for-input-available (symbol-value (synonym-stream-symbol stream))
1084                                  timeout))
1085       (sb-sys::file-stream
1086        (or (< (sb-impl::fd-stream-in-index stream)
1087               (length (sb-impl::fd-stream-in-buffer stream)))
1088            (wait-for-input-available (sb-sys:fd-stream-fd stream) timeout))))))
1089
1090 ;; Make PATHNAME and NAMESTRING work
1091 (defun sb-int:file-name (stream &optional new-name)
1092   (typecase stream
1093     (file-simple-stream
1094      (with-stream-class (file-simple-stream stream)
1095        (cond (new-name
1096               (%file-rename stream new-name))
1097              (t
1098               (%file-name stream)))))
1099     (sb-sys::file-stream
1100      (cond (new-name
1101             (setf (sb-impl::fd-stream-pathname stream) new-name)
1102             (setf (sb-impl::fd-stream-file stream)
1103                   (sb-int:unix-namestring new-name nil))
1104             t)
1105            (t
1106             (sb-impl::fd-stream-pathname stream))))))