/[cmucl]/src/code/fd-stream.lisp
ViewVC logotype

Contents of /src/code/fd-stream.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.91.2.1.2.2 - (hide annotations)
Fri Sep 25 04:14:36 2009 UTC (4 years, 6 months ago) by rtoy
Branch: unicode-string-buffer-impl-branch
Changes since 1.91.2.1.2.1: +2 -2 lines
fd-stream.lisp:
o Make the string buffer length one more than in-buffer-length so we
  can have an extra character for unreading, and so we can convert the
  entire in-buffer for single-byte encodings.

stream.lisp:
o Use extra character to support unreading by backing up.  This means
  having to copy the last character to the first and making
  OCTETS-TO-STRING store the result in the string at index 1, not 0.
o The number of octets to convert was wrong---we need to add the
  number of octets that weren't already consumed.
1 ram 1.1 ;;; -*- Log: code.log; Package: LISP -*-
2 ram 1.11 ;;;
3 ram 1.1 ;;; **********************************************************************
4 ram 1.10 ;;; This code was written as part of the CMU Common Lisp project at
5     ;;; Carnegie Mellon University, and has been placed in the public domain.
6     ;;;
7     (ext:file-comment
8 rtoy 1.91.2.1.2.2 "$Header: /tiger/var/lib/cvsroots/cmucl/src/code/fd-stream.lisp,v 1.91.2.1.2.2 2009/09/25 04:14:36 rtoy Exp $")
9 ram 1.10 ;;;
10 ram 1.1 ;;; **********************************************************************
11     ;;;
12     ;;; Streams for UNIX file descriptors.
13     ;;;
14     ;;; Written by William Lott, July 1989 - January 1990.
15 ram 1.15 ;;; Some tuning by Rob MacLachlan.
16 ram 1.1 ;;;
17     ;;; **********************************************************************
18    
19    
20     (in-package "SYSTEM")
21    
22     (export '(fd-stream fd-stream-p fd-stream-fd make-fd-stream
23 ram 1.15 io-timeout beep *beep-function* output-raw-bytes
24 rtoy 1.83 *tty* *stdin* *stdout* *stderr*
25     binary-text-stream))
26 ram 1.1
27    
28     (in-package "EXTENSIONS")
29    
30     (export '(*backup-extension*))
31    
32    
33     (in-package "LISP")
34    
35 toy 1.66 (export '(file-stream file-string-length))
36 ram 1.22
37 ram 1.1
38     ;;;; Buffer manipulation routines.
39    
40     (defvar *available-buffers* ()
41 ram 1.12 "List of available buffers. Each buffer is an sap pointing to
42     bytes-per-buffer of memory.")
43 ram 1.1
44 rtoy 1.91.2.1.2.1 (defvar lisp::*enable-stream-buffer-p* nil)
45    
46 ram 1.1 (defconstant bytes-per-buffer (* 4 1024)
47     "Number of bytes per buffer.")
48    
49 rtoy 1.79 ;; This limit is rather arbitrary
50     (defconstant max-stream-element-size 1024
51     "The maximum supported byte size for a stream element-type.")
52    
53 ram 1.1 ;;; NEXT-AVAILABLE-BUFFER -- Internal.
54     ;;;
55 ram 1.12 ;;; Returns the next available buffer, creating one if necessary.
56 ram 1.1 ;;;
57 pw 1.55 (declaim (inline next-available-buffer))
58 ram 1.1 ;;;
59     (defun next-available-buffer ()
60     (if *available-buffers*
61     (pop *available-buffers*)
62 wlott 1.5 (allocate-system-memory bytes-per-buffer)))
63 ram 1.1
64 rtoy 1.85 (declaim (inline buffer-sap bref (setf bref) buffer-copy))
65    
66     (defun buffer-sap (thing &optional offset)
67     (declare (type simple-stream-buffer thing) (type (or fixnum null) offset)
68     (optimize (speed 3) (space 2) (debug 0) (safety 0)
69     ;; Suppress the note about having to box up the return:
70     (ext:inhibit-warnings 3)))
71     (let ((sap (if (vectorp thing) (sys:vector-sap thing) thing)))
72     (if offset (sys:sap+ sap offset) sap)))
73    
74     (defun bref (buffer index)
75     (declare (type simple-stream-buffer buffer)
76     (type (integer 0 #.most-positive-fixnum) index))
77     (sys:sap-ref-8 (buffer-sap buffer) index))
78    
79     (defun (setf bref) (octet buffer index)
80     (declare (type (unsigned-byte 8) octet)
81     (type simple-stream-buffer buffer)
82     (type (integer 0 #.most-positive-fixnum) index))
83     (setf (sys:sap-ref-8 (buffer-sap buffer) index) octet))
84    
85     (defun buffer-copy (src soff dst doff length)
86     (declare (type simple-stream-buffer src dst)
87     (type fixnum soff doff length))
88     (sys:without-gcing ;; is this necessary??
89     (kernel:system-area-copy (buffer-sap src) (* soff 8)
90     (buffer-sap dst) (* doff 8)
91     (* length 8))))
92    
93     #-(or big-endian little-endian)
94     (eval-when (:compile-toplevel)
95     (push (c::backend-byte-order c::*target-backend*) *features*))
96    
97     (defun vector-elt-width (vector)
98     ;; Return octet-width of vector elements
99     (etypecase vector
100     ;; (simple-array fixnum (*)) not supported
101     ;; (simple-array base-char (*)) treated specially; don't call this
102 rtoy 1.86 ((simple-array bit (*)) 1/8)
103     ((simple-array (unsigned-byte 2) (*)) 1/4)
104     ((simple-array (unsigned-byte 4) (*)) 1/2)
105 rtoy 1.85 ((simple-array (signed-byte 8) (*)) 1)
106     ((simple-array (unsigned-byte 8) (*)) 1)
107     ((simple-array (signed-byte 16) (*)) 2)
108     ((simple-array (unsigned-byte 16) (*)) 2)
109     ((simple-array (signed-byte 32) (*)) 4)
110     ((simple-array (unsigned-byte 32) (*)) 4)
111     ((simple-array single-float (*)) 4)
112     ((simple-array double-float (*)) 8)
113     ((simple-array (complex single-float) (*)) 8)
114     ((simple-array (complex double-float) (*)) 16)
115     #+long-float
116     ((simple-array long-float (*)) 10)
117     #+long-float
118     ((simple-array (complex long-float) (*)) 20)
119     #+double-double
120     ((simple-array double-double-float (*)) 16)
121     #+double-double
122     ((simple-array (complex double-double-float) (*)) 32)))
123    
124     (defun endian-swap-value (vector endian-swap)
125     (case endian-swap
126 rtoy 1.86 (:network-order
127     #+big-endian 0
128     ;; This is needed because the little-endian (x86) architectures
129     ;; store the lowest indexed element in the least significant part
130     ;; of a byte. On a big-endian machine (sparc, ppc), the lowest
131     ;; indexed element is at the most significant part of a byte.
132     #+little-endian
133     (typecase vector
134     ((array (unsigned-byte 4) (*))
135     -1)
136     ((array (unsigned-byte 2) (*))
137     -2)
138     ((array (unsigned-byte 1) (*))
139     -8)
140     (t
141     (1- (vector-elt-width vector)))))
142 rtoy 1.85 (:byte-8 0)
143     (:byte-16 1)
144     (:byte-32 3)
145     (:byte-64 7)
146     (:byte-128 15)
147     ;; additions by Lynn Quam
148     (:machine-endian 0)
149 rtoy 1.86 (:big-endian
150     #+big-endian 0
151     #+little-endian
152     (typecase vector
153     ((array (unsigned-byte 4) (*))
154     -1)
155     ((array (unsigned-byte 2) (*))
156     -2)
157     ((array (unsigned-byte 1) (*))
158     -8)
159     (t
160     (1- (vector-elt-width vector)))))
161     (:little-endian
162     #+big-endian
163     (typecase vector
164     ((array (unsigned-byte 4) (*))
165     -1)
166     ((array (unsigned-byte 2) (*))
167     -2)
168     ((array (unsigned-byte 1) (*))
169     -8)
170     (t
171     (1- (vector-elt-width vector))))
172     #+little-endian 0)
173 rtoy 1.85 (otherwise endian-swap)))
174    
175 ram 1.1
176     ;;;; The FD-STREAM structure.
177    
178 moore 1.62 ;;;; Superclass defined by the ANSI Spec
179     (defstruct (file-stream
180     (:include lisp-stream)
181     (:constructor nil)
182     (:copier nil)))
183    
184 ram 1.1 (defstruct (fd-stream
185     (:print-function %print-fd-stream)
186     (:constructor %make-fd-stream)
187 moore 1.62 (:include file-stream
188 ram 1.1 (misc #'fd-stream-misc-routine)))
189    
190     (name nil) ; The name of this stream
191     (file nil) ; The file this stream is for
192 ram 1.28 ;;
193     ;; The backup file namestring for the old file, for :if-exists :rename or
194     ;; :rename-and-delete.
195     (original nil :type (or simple-string null))
196 ram 1.1 (delete-original nil) ; for :if-exists :rename-and-delete
197 ram 1.14 ;;
198     ;;; Number of bytes per element.
199     (element-size 1 :type index)
200 wlott 1.16 (element-type 'base-char) ; The type of element being transfered.
201 ram 1.1 (fd -1 :type fixnum) ; The file descriptor
202 ram 1.14 ;;
203     ;; Controls when the output buffer is flushed.
204     (buffering :full :type (member :full :line :none))
205     ;;
206     ;; Character position if known.
207     (char-pos nil :type (or index null))
208     ;;
209     ;; T if input is waiting on FD. :EOF if we hit EOF.
210     (listen nil :type (member nil t :eof))
211     ;;
212 ram 1.1 ;; The input buffer.
213     (unread nil)
214 ram 1.14 (ibuf-sap nil :type (or system-area-pointer null))
215     (ibuf-length nil :type (or index null))
216     (ibuf-head 0 :type index)
217     (ibuf-tail 0 :type index)
218 ram 1.1
219     ;; The output buffer.
220 ram 1.14 (obuf-sap nil :type (or system-area-pointer null))
221     (obuf-length nil :type (or index null))
222     (obuf-tail 0 :type index)
223 ram 1.1
224     ;; Output flushed, but not written due to non-blocking io.
225     (output-later nil)
226 ram 1.15 (handler nil)
227     ;;
228     ;; Timeout specified for this stream, or NIL if none.
229 ram 1.28 (timeout nil :type (or index null))
230     ;;
231     ;; Pathname of the file this stream is opened to (returned by PATHNAME.)
232 rtoy 1.86 (pathname nil :type (or pathname null))
233     ;;
234     ;; External format support
235     ;;
236     ;; @@ I want to use :default here, but keyword pkg isn't set up yet at boot
237     ;; so initialize to NIL and fix it in SET-ROUTINES
238     #+unicode
239     (external-format nil :type (or null keyword cons))
240 rtoy 1.90 ;;
241     ;; State for octets-to-char (for reading from a stream). The
242     ;; contents of the state can be anything and is defined by the
243     ;; external format.
244 rtoy 1.86 #+unicode
245     (oc-state nil)
246 rtoy 1.90 ;;
247     ;; State for char-to-octets (for writing to a stream). The contents
248     ;; of the state can be anything and is defined by the external
249     ;; format. If not NIL, then the CAR is used by char-to-octets to
250     ;; hold some state information, and the CDR is available to the
251     ;; external format to hold whatever state information is needed.
252 rtoy 1.86 #+unicode
253     (co-state nil)
254     #+unicode
255     (last-char-read-size 0 :type index))
256 ram 1.1
257     (defun %print-fd-stream (fd-stream stream depth)
258 ram 1.14 (declare (ignore depth) (stream stream))
259 ram 1.1 (format stream "#<Stream for ~A>"
260     (fd-stream-name fd-stream)))
261    
262 rtoy 1.83 ;; CMUCL extension. This is a FD-STREAM, but it allows reading and
263     ;; writing of 8-bit characters and unsigned bytes from the stream.
264     (defstruct (binary-text-stream
265     (:print-function %print-binary-text-stream)
266     (:constructor %make-binary-text-stream)
267     (:include fd-stream)))
268    
269     (defun %print-binary-text-stream (fd-stream stream depth)
270     (declare (ignore depth) (stream stream))
271     (format stream "#<Binary-text Stream for ~A>"
272     (fd-stream-name fd-stream)))
273 ram 1.1
274 ram 1.31 (define-condition io-timeout (stream-error)
275     ((direction :reader io-timeout-direction :initarg :direction))
276 ram 1.15 (:report
277     (lambda (condition stream)
278 ram 1.23 (declare (stream stream))
279 ram 1.15 (format stream "Timeout ~(~A~)ing ~S."
280     (io-timeout-direction condition)
281     (stream-error-stream condition)))))
282    
283 ram 1.1
284     ;;;; Output routines and related noise.
285    
286     (defvar *output-routines* ()
287     "List of all available output routines. Each element is a list of the
288     element-type output, the kind of buffering, the function name, and the number
289     of bytes per element.")
290    
291     ;;; DO-OUTPUT-LATER -- internal
292     ;;;
293     ;;; Called by the server when we can write to the given file descriptor.
294 toy 1.67 ;;; Attempt to write the data again. If it worked, remove the data from the
295 ram 1.1 ;;; output-later list. If it didn't work, something is wrong.
296     ;;;
297     (defun do-output-later (stream)
298     (let* ((stuff (pop (fd-stream-output-later stream)))
299     (base (car stuff))
300     (start (cadr stuff))
301     (end (caddr stuff))
302 wlott 1.5 (reuse-sap (cadddr stuff))
303 ram 1.1 (length (- end start)))
304 ram 1.14 (declare (type index start end length))
305 ram 1.1 (multiple-value-bind
306     (count errno)
307 wlott 1.19 (unix:unix-write (fd-stream-fd stream)
308 ram 1.1 base
309     start
310     length)
311 ram 1.14 (cond ((not count)
312 wlott 1.19 (if (= errno unix:ewouldblock)
313 ram 1.14 (error "Write would have blocked, but SERVER told us to go.")
314     (error "While writing ~S: ~A"
315 wlott 1.19 stream (unix:get-unix-error-msg errno))))
316 toy 1.67 ((eql count length) ; Hot damn, it worked.
317 wlott 1.5 (when reuse-sap
318     (push base *available-buffers*)))
319 ram 1.1 ((not (null count)) ; Sorta worked.
320     (push (list base
321 ram 1.23 (the index (+ start count))
322 wlott 1.5 end)
323 ram 1.14 (fd-stream-output-later stream))))))
324 ram 1.1 (unless (fd-stream-output-later stream)
325     (system:remove-fd-handler (fd-stream-handler stream))
326     (setf (fd-stream-handler stream) nil)))
327    
328     ;;; OUTPUT-LATER -- internal
329     ;;;
330 toy 1.67 ;;; Arrange to output the string when we can write on the file descriptor.
331 ram 1.1 ;;;
332 wlott 1.5 (defun output-later (stream base start end reuse-sap)
333 ram 1.1 (cond ((null (fd-stream-output-later stream))
334     (setf (fd-stream-output-later stream)
335 wlott 1.5 (list (list base start end reuse-sap)))
336 ram 1.1 (setf (fd-stream-handler stream)
337     (system:add-fd-handler (fd-stream-fd stream)
338     :output
339     #'(lambda (fd)
340     (declare (ignore fd))
341     (do-output-later stream)))))
342     (t
343     (nconc (fd-stream-output-later stream)
344 wlott 1.5 (list (list base start end reuse-sap)))))
345     (when reuse-sap
346 ram 1.1 (let ((new-buffer (next-available-buffer)))
347 wlott 1.5 (setf (fd-stream-obuf-sap stream) new-buffer)
348 ram 1.14 (setf (fd-stream-obuf-length stream) bytes-per-buffer))))
349 ram 1.1
350     ;;; DO-OUTPUT -- internal
351     ;;;
352     ;;; Output the given noise. Check to see if there are any pending writes. If
353     ;;; so, just queue this one. Otherwise, try to write it. If this would block,
354     ;;; queue it.
355     ;;;
356 wlott 1.5 (defun do-output (stream base start end reuse-sap)
357 ram 1.14 (declare (type fd-stream stream)
358     (type (or system-area-pointer (simple-array * (*))) base)
359     (type index start end))
360 ram 1.1 (if (not (null (fd-stream-output-later stream))) ; something buffered.
361 ram 1.14 (progn
362     (output-later stream base start end reuse-sap)
363     ;; ### check to see if any of this noise can be output
364     )
365     (let ((length (- end start)))
366     (multiple-value-bind
367 dtc 1.51 (count errno)
368 wlott 1.19 (unix:unix-write (fd-stream-fd stream) base start length)
369 ram 1.14 (cond ((not count)
370 wlott 1.19 (if (= errno unix:ewouldblock)
371 ram 1.14 (output-later stream base start end reuse-sap)
372 emarsden 1.75 (error 'simple-stream-error
373     :stream stream
374     :format-control "while writing: ~A"
375     :format-arguments (list (unix:get-unix-error-msg errno)))))
376 ram 1.14 ((not (eql count length))
377 ram 1.23 (output-later stream base (the index (+ start count))
378     end reuse-sap)))))))
379 ram 1.1
380 rtoy 1.90 #+unicode
381     (stream::def-ef-macro ef-flush (extfmt lisp stream::+ef-max+ stream::+ef-flush+)
382     `(lambda (stream)
383     (declare (type fd-stream stream))
384     (let* ((tail (fd-stream-obuf-tail stream)))
385     (declare (type index tail))
386     (cond
387 rtoy 1.91 ((stream::ef-flush-state ,(stream::find-external-format extfmt))
388 rtoy 1.90 (stream::flush-state ,extfmt
389     (fd-stream-co-state stream)
390     (lambda (byte)
391     (when (= tail len)
392     (do-output stream sap 0 tail t)
393     (setq sap (fd-stream-obuf-sap stream)
394     tail 0))
395     (setf (bref sap (1- (incf tail))) byte)))
396     (setf (fd-stream-obuf-tail stream) tail))
397     (t
398     ;; No flush-state function, so just output a replacement
399     ;; character. We hack the co-state to what we need for this
400     ;; to work. This should be ok because we're closing the
401     ;; file anyway.
402     (let ((state (fd-stream-co-state stream)))
403     (when (and state (car state))
404     (setf (fd-stream-co-state stream)
405     (cons nil (cdr state)))
406     (funcall (ef-cout (fd-stream-external-format stream))
407     stream (code-char stream::+replacement-character-code+))))))
408     (values))))
409    
410 ram 1.1 ;;; FLUSH-OUTPUT-BUFFER -- internal
411     ;;;
412     ;;; Flush any data in the output buffer.
413     ;;;
414     (defun flush-output-buffer (stream)
415     (let ((length (fd-stream-obuf-tail stream)))
416     (unless (= length 0)
417 wlott 1.5 (do-output stream (fd-stream-obuf-sap stream) 0 length t)
418 ram 1.1 (setf (fd-stream-obuf-tail stream) 0))))
419    
420     ;;; DEF-OUTPUT-ROUTINES -- internal
421     ;;;
422     ;;; Define output routines that output numbers size bytes long for the
423     ;;; given bufferings. Use body to do the actual output.
424     ;;;
425     (defmacro def-output-routines ((name size &rest bufferings) &body body)
426 ram 1.23 (declare (optimize (speed 1)))
427 ram 1.1 (cons 'progn
428     (mapcar
429     #'(lambda (buffering)
430     (let ((function
431     (intern (let ((*print-case* :upcase))
432     (format nil name (car buffering))))))
433     `(progn
434     (defun ,function (stream byte)
435     ,(unless (eq (car buffering) :none)
436     `(when (< (fd-stream-obuf-length stream)
437     (+ (fd-stream-obuf-tail stream)
438     ,size))
439     (flush-output-buffer stream)))
440 gerd 1.73 ;;
441     ;; If there is any input read from UNIX but not
442     ;; supplied to the user of the stream, reposition
443     ;; to the real file position as seen from Lisp.
444     ,(unless (eq (car buffering) :none)
445     `(when (> (fd-stream-ibuf-tail stream)
446     (fd-stream-ibuf-head stream))
447     (file-position stream (file-position stream))))
448 ram 1.1 ,@body
449     (incf (fd-stream-obuf-tail stream) ,size)
450     ,(ecase (car buffering)
451     (:none
452     `(flush-output-buffer stream))
453     (:line
454 rtoy 1.86 `(when (eql (char-code byte) (char-code #\Newline))
455 ram 1.1 (flush-output-buffer stream)))
456     (:full
457     ))
458     (values))
459     (setf *output-routines*
460     (nconc *output-routines*
461     ',(mapcar
462     #'(lambda (type)
463     (list type
464     (car buffering)
465     function
466     size))
467     (cdr buffering)))))))
468     bufferings)))
469    
470 rtoy 1.86 #-unicode
471 wlott 1.5 (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
472     1
473 wlott 1.6 (:none character)
474     (:line character)
475     (:full character))
476 ram 1.37 (if (char= byte #\Newline)
477 wlott 1.5 (setf (fd-stream-char-pos stream) 0)
478     (incf (fd-stream-char-pos stream)))
479     (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
480     (char-code byte)))
481    
482 rtoy 1.86 #+unicode
483     (def-output-routines ("OUTPUT-CHAR-~A-BUFFERED"
484     1
485     (:none character)
486     (:line character)
487     (:full character))
488     (if (char= byte #\Newline)
489     (setf (fd-stream-char-pos stream) 0)
490     (incf (fd-stream-char-pos stream)))
491     ;; FIXME! We only use the low 8 bits of a character!
492     (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
493     (logand #xff (char-code byte))))
494    
495 ram 1.37 (def-output-routines ("OUTPUT-UNSIGNED-BYTE-~A-BUFFERED"
496 ram 1.1 1
497 ram 1.37 (:none (unsigned-byte 8))
498     (:full (unsigned-byte 8)))
499 wlott 1.5 (setf (sap-ref-8 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
500     byte))
501 ram 1.1
502 ram 1.37 (def-output-routines ("OUTPUT-SIGNED-BYTE-~A-BUFFERED"
503     1
504     (:none (signed-byte 8))
505     (:full (signed-byte 8)))
506     (setf (signed-sap-ref-8 (fd-stream-obuf-sap stream)
507     (fd-stream-obuf-tail stream))
508     byte))
509    
510     (def-output-routines ("OUTPUT-UNSIGNED-SHORT-~A-BUFFERED"
511 ram 1.1 2
512 ram 1.37 (:none (unsigned-byte 16))
513     (:full (unsigned-byte 16)))
514 wlott 1.20 (setf (sap-ref-16 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
515 wlott 1.5 byte))
516    
517 ram 1.37 (def-output-routines ("OUTPUT-SIGNED-SHORT-~A-BUFFERED"
518     2
519     (:none (signed-byte 16))
520     (:full (signed-byte 16)))
521     (setf (signed-sap-ref-16 (fd-stream-obuf-sap stream)
522     (fd-stream-obuf-tail stream))
523     byte))
524    
525     (def-output-routines ("OUTPUT-UNSIGNED-LONG-~A-BUFFERED"
526 ram 1.1 4
527 ram 1.37 (:none (unsigned-byte 32))
528     (:full (unsigned-byte 32)))
529 wlott 1.20 (setf (sap-ref-32 (fd-stream-obuf-sap stream) (fd-stream-obuf-tail stream))
530 wlott 1.5 byte))
531 ram 1.37
532     (def-output-routines ("OUTPUT-SIGNED-LONG-~A-BUFFERED"
533     4
534     (:none (signed-byte 32))
535     (:full (signed-byte 32)))
536     (setf (signed-sap-ref-32 (fd-stream-obuf-sap stream)
537     (fd-stream-obuf-tail stream))
538     byte))
539    
540 rtoy 1.86 (stream::def-ef-macro ef-cout (extfmt lisp stream::+ef-max+ stream::+ef-cout+)
541     `(lambda (stream char)
542     (declare (type fd-stream stream)
543     (type character char)
544     (optimize (speed 3) (space 0) (debug 0) (safety 0)))
545     ;; If there is any input read from UNIX but not
546     ;; supplied to the user of the stream, reposition
547     ;; to the real file position as seen from Lisp.
548     (when (> (fd-stream-ibuf-tail stream)
549     (fd-stream-ibuf-head stream))
550     (file-position stream (file-position stream)))
551     (let* ((sap (fd-stream-obuf-sap stream))
552     (len (fd-stream-obuf-length stream))
553     (tail (fd-stream-obuf-tail stream)))
554     (declare (type sys:system-area-pointer sap) (type index len tail))
555     (stream::char-to-octets ,extfmt
556     char
557     (fd-stream-co-state stream)
558     (lambda (byte)
559     (when (= tail len)
560     (do-output stream sap 0 tail t)
561     (setq sap (fd-stream-obuf-sap stream)
562     tail 0))
563     (setf (bref sap (1- (incf tail))) byte)))
564 rtoy 1.89 (setf (fd-stream-obuf-tail stream) tail))
565     (if (char= char #\Newline)
566     (setf (fd-stream-char-pos stream) 0)
567     (incf (fd-stream-char-pos stream)))
568     (ecase (fd-stream-buffering stream)
569     (:none (flush-output-buffer stream))
570     (:line (when (char= char #\Newline) (flush-output-buffer stream)))
571     (:full #| do nothing |#))
572     (values)))
573 rtoy 1.86
574 ram 1.1
575     ;;; OUTPUT-RAW-BYTES -- public
576     ;;;
577     ;;; Does the actual output. If there is space to buffer the string, buffer
578     ;;; it. If the string would normally fit in the buffer, but doesn't because
579     ;;; of other stuff in the buffer, flush the old noise out of the buffer and
580     ;;; put the string in it. Otherwise we have a very long string, so just
581     ;;; send it directly (after flushing the buffer, of course).
582     ;;;
583     (defun output-raw-bytes (stream thing &optional start end)
584     "Output THING to stream. THING can be any kind of vector or a sap. If THING
585     is a SAP, END must be supplied (as length won't work)."
586     (let ((start (or start 0))
587 ram 1.14 (end (or end (length (the (simple-array * (*)) thing)))))
588     (declare (type index start end))
589 gerd 1.74 ;;
590     ;; If there is any input read from UNIX but not
591     ;; supplied to the user of the stream, reposition
592     ;; to the real file position as seen from Lisp.
593     (when (> (fd-stream-ibuf-tail stream)
594     (fd-stream-ibuf-head stream))
595     (file-position stream (file-position stream)))
596 ram 1.1 (let* ((len (fd-stream-obuf-length stream))
597     (tail (fd-stream-obuf-tail stream))
598     (space (- len tail))
599     (bytes (- end start))
600     (newtail (+ tail bytes)))
601     (cond ((minusp bytes) ; Error case
602     (cerror "Just go on as if nothing happened..."
603     "~S called with :END before :START!"
604     'output-raw-bytes))
605     ((zerop bytes)) ; Easy case
606     ((<= bytes space)
607 wlott 1.5 (if (system-area-pointer-p thing)
608     (system-area-copy thing
609     (* start vm:byte-bits)
610     (fd-stream-obuf-sap stream)
611     (* tail vm:byte-bits)
612     (* bytes vm:byte-bits))
613     (copy-to-system-area thing
614     (+ (* start vm:byte-bits)
615     (* vm:vector-data-offset vm:word-bits))
616     (fd-stream-obuf-sap stream)
617     (* tail vm:byte-bits)
618     (* bytes vm:byte-bits)))
619 ram 1.1 (setf (fd-stream-obuf-tail stream) newtail))
620     ((<= bytes len)
621     (flush-output-buffer stream)
622 wlott 1.5 (if (system-area-pointer-p thing)
623     (system-area-copy thing
624     (* start vm:byte-bits)
625     (fd-stream-obuf-sap stream)
626     0
627     (* bytes vm:byte-bits))
628     (copy-to-system-area thing
629     (+ (* start vm:byte-bits)
630     (* vm:vector-data-offset vm:word-bits))
631     (fd-stream-obuf-sap stream)
632     0
633     (* bytes vm:byte-bits)))
634 ram 1.1 (setf (fd-stream-obuf-tail stream) bytes))
635     (t
636     (flush-output-buffer stream)
637     (do-output stream thing start end nil))))))
638    
639     ;;; FD-SOUT -- internal
640     ;;;
641     ;;; Routine to use to output a string. If the stream is unbuffered, slam
642     ;;; the string down the file descriptor, otherwise use OUTPUT-RAW-BYTES to
643     ;;; buffer the string. Update charpos by checking to see where the last newline
644     ;;; was.
645     ;;;
646     ;;; Note: some bozos (the FASL dumper) call write-string with things other
647     ;;; than strings. Therefore, we must make sure we have a string before calling
648     ;;; position on it.
649 rtoy 1.86 ;;;
650    
651     (stream::def-ef-macro ef-sout (extfmt lisp stream::+ef-max+ stream::+ef-sout+)
652     `(lambda (stream string start end)
653     (declare (type fd-stream stream)
654     (type simple-string string)
655     (type index start end)
656     (optimize (speed 3) (space 0) (safety 0) (debug 0)))
657     ;; If there is any input read from UNIX but not
658     ;; supplied to the user of the stream, reposition
659     ;; to the real file position as seen from Lisp.
660     ;; (maybe the caller should do this?)
661     (when (> (fd-stream-ibuf-tail stream)
662     (fd-stream-ibuf-head stream))
663     (file-position stream (file-position stream)))
664     (let* ((sap (fd-stream-obuf-sap stream))
665     (len (fd-stream-obuf-length stream))
666     (tail (fd-stream-obuf-tail stream)))
667     (declare (type sys:system-area-pointer sap) (type index len tail))
668 rtoy 1.89 (dotimes (i (- end start))
669     (stream::char-to-octets ,extfmt
670     (schar string (+ i start))
671     (fd-stream-co-state stream)
672     (lambda (byte)
673     (when (= tail len)
674     (do-output stream sap 0 tail t)
675     (setq sap (fd-stream-obuf-sap stream)
676     tail 0))
677     (setf (bref sap (1- (incf tail))) byte))))
678 rtoy 1.86 (setf (fd-stream-obuf-tail stream) tail))))
679    
680    
681     #-unicode
682 ram 1.1 (defun fd-sout (stream thing start end)
683     (let ((start (or start 0))
684 ram 1.14 (end (or end (length (the vector thing)))))
685 dtc 1.51 (declare (type index start end))
686 ram 1.1 (if (stringp thing)
687 wlott 1.5 (let ((last-newline (and (find #\newline (the simple-string thing)
688     :start start :end end)
689     (position #\newline (the simple-string thing)
690     :from-end t
691     :start start
692     :end end))))
693     (ecase (fd-stream-buffering stream)
694     (:full
695     (output-raw-bytes stream thing start end))
696     (:line
697     (output-raw-bytes stream thing start end)
698     (when last-newline
699     (flush-output-buffer stream)))
700     (:none
701     (do-output stream thing start end nil)))
702     (if last-newline
703     (setf (fd-stream-char-pos stream)
704     (- end last-newline 1))
705     (incf (fd-stream-char-pos stream)
706     (- end start))))
707 ram 1.1 (ecase (fd-stream-buffering stream)
708 wlott 1.5 ((:line :full)
709 ram 1.1 (output-raw-bytes stream thing start end))
710     (:none
711 wlott 1.5 (do-output stream thing start end nil))))))
712 ram 1.1
713 rtoy 1.86 #+unicode
714 rtoy 1.89 ;; Temporary. The final version is defined in fd-stream-extfmt.lisp
715 rtoy 1.86 (defun fd-sout (stream thing start end)
716     (declare (type string thing))
717     (let ((start (or start 0))
718     (end (or end (length (the vector thing)))))
719     (declare (type index start end))
720     (cond
721     ((stringp thing) ; FIXME - remove this test
722     (let ((out (fd-stream-out stream)))
723     (do ((index start (+ index 1)))
724     ((>= index end))
725     (funcall out stream (elt thing index))))))))
726    
727 rtoy 1.79 (defmacro output-wrapper ((stream size buffering) &body body)
728     (let ((stream-var (gensym)))
729     `(let ((,stream-var ,stream))
730     ,(unless (eq (car buffering) :none)
731     `(when (< (fd-stream-obuf-length ,stream-var)
732     (+ (fd-stream-obuf-tail ,stream-var)
733     ,size))
734     (flush-output-buffer ,stream-var)))
735     ,(unless (eq (car buffering) :none)
736     `(when (> (fd-stream-ibuf-tail ,stream-var)
737     (fd-stream-ibuf-head ,stream-var))
738     (file-position ,stream-var (file-position ,stream-var))))
739    
740     ,@body
741     (incf (fd-stream-obuf-tail ,stream-var) ,size)
742     ,(ecase (car buffering)
743     (:none
744     `(flush-output-buffer ,stream-var))
745     (:line
746     `(when (eq (char-code byte) (char-code #\Newline))
747     (flush-output-buffer ,stream-var)))
748     (:full))
749     (values))))
750    
751 ram 1.1 ;;; PICK-OUTPUT-ROUTINE -- internal
752     ;;;
753     ;;; Find an output routine to use given the type and buffering. Return as
754     ;;; multiple values the routine, the real type transfered, and the number of
755     ;;; bytes per element.
756     ;;;
757     (defun pick-output-routine (type buffering)
758     (dolist (entry *output-routines*)
759     (when (and (subtypep type (car entry))
760     (eq buffering (cadr entry)))
761 rtoy 1.79 (return-from pick-output-routine
762     (values (symbol-function (caddr entry))
763     (car entry)
764     (cadddr entry)))))
765     ;; KLUDGE: also see comments in PICK-INPUT-ROUTINE
766     (loop for i from 40 by 8 to max-stream-element-size ; ARB (KLUDGE)
767     if (subtypep type `(unsigned-byte ,i))
768     do (return-from pick-output-routine
769     (values
770     (ecase buffering
771     (:none
772     (lambda (stream byte)
773     (output-wrapper (stream (/ i 8) (:none))
774     (loop for j from 0 below (/ i 8)
775     do (setf (sap-ref-8
776     (fd-stream-obuf-sap stream)
777     (+ j (fd-stream-obuf-tail stream)))
778     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
779     (:full
780     (lambda (stream byte)
781     (output-wrapper (stream (/ i 8) (:full))
782     (loop for j from 0 below (/ i 8)
783     do (setf (sap-ref-8
784     (fd-stream-obuf-sap stream)
785     (+ j (fd-stream-obuf-tail stream)))
786     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
787     `(unsigned-byte ,i)
788     (/ i 8))))
789     (loop for i from 40 by 8 to max-stream-element-size ; ARB (KLUDGE)
790     if (subtypep type `(signed-byte ,i))
791     do (return-from pick-output-routine
792     (values
793     (ecase buffering
794     (:none
795     (lambda (stream byte)
796     (output-wrapper (stream (/ i 8) (:none))
797     (loop for j from 0 below (/ i 8)
798     do (setf (sap-ref-8
799     (fd-stream-obuf-sap stream)
800     (+ j (fd-stream-obuf-tail stream)))
801     (ldb (byte 8 (- i 8 (* j 8))) byte))))))
802     (:full
803     (lambda (stream byte)
804     (output-wrapper (stream (/ i 8) (:full))
805     (loop for j from 0 below (/ i 8)
806     do (setf (sap-ref-8
807     (fd-stream-obuf-sap stream)
808     (+ j (fd-stream-obuf-tail stream)))
809     (ldb (byte 8 (- i 8 (* j 8))) byte)))))))
810     `(signed-byte ,i)
811     (/ i 8)))))
812 ram 1.1
813     ;;;; Input routines and related noise.
814    
815     (defvar *input-routines* ()
816     "List of all available input routines. Each element is a list of the
817     element-type input, the function name, and the number of bytes per element.")
818    
819     ;;; DO-INPUT -- internal
820     ;;;
821     ;;; Fills the input buffer, and returns the first character. Throws to
822     ;;; eof-input-catcher if the eof was reached. Drops into system:server if
823     ;;; necessary.
824     ;;;
825     (defun do-input (stream)
826     (let ((fd (fd-stream-fd stream))
827     (ibuf-sap (fd-stream-ibuf-sap stream))
828     (buflen (fd-stream-ibuf-length stream))
829     (head (fd-stream-ibuf-head stream))
830 rtoy 1.86 (lcrs #-unicode 0
831     #+unicode (fd-stream-last-char-read-size stream))
832 ram 1.1 (tail (fd-stream-ibuf-tail stream)))
833 rtoy 1.86 (declare (type index head lcrs tail))
834 ram 1.1 (unless (zerop head)
835 ram 1.14 (cond ((eql head tail)
836 rtoy 1.86 (setf head lcrs)
837     (setf tail lcrs)
838     (setf (fd-stream-ibuf-head stream) lcrs)
839     (setf (fd-stream-ibuf-tail stream) lcrs))
840 ram 1.1 (t
841 rtoy 1.86 (decf tail (- head lcrs))
842     (system-area-copy ibuf-sap (* (- head lcrs) vm:byte-bits)
843 wlott 1.5 ibuf-sap 0 (* tail vm:byte-bits))
844 rtoy 1.86 (setf head lcrs)
845     (setf (fd-stream-ibuf-head stream) lcrs)
846 ram 1.1 (setf (fd-stream-ibuf-tail stream) tail))))
847     (setf (fd-stream-listen stream) nil)
848     (multiple-value-bind
849 dtc 1.41 (count errno)
850     (alien:with-alien ((read-fds (alien:struct unix:fd-set)))
851     (unix:fd-zero read-fds)
852     (unix:fd-set fd read-fds)
853     (unix:unix-fast-select (1+ fd) (alien:addr read-fds) nil nil 0 0))
854 dtc 1.49 ;; Wait if input is not available or if interrupted.
855     (when (or (eql count 0)
856     (and (not count) (eql errno unix:eintr)))
857     (unless #-mp (system:wait-until-fd-usable
858     fd :input (fd-stream-timeout stream))
859     #+mp (mp:process-wait-until-fd-usable
860     fd :input (fd-stream-timeout stream))
861     (error 'io-timeout :stream stream :direction :read))))
862 ram 1.1 (multiple-value-bind
863 dtc 1.42 (count errno)
864 wlott 1.19 (unix:unix-read fd
865 ram 1.1 (system:int-sap (+ (system:sap-int ibuf-sap) tail))
866     (- buflen tail))
867     (cond ((null count)
868 rtoy 1.81 ;; What kinds of errors do we want to look at and what do
869     ;; we want them to do?
870     (cond ((eql errno unix:ewouldblock)
871     (unless #-mp (system:wait-until-fd-usable
872     fd :input (fd-stream-timeout stream))
873     #+mp (mp:process-wait-until-fd-usable
874     fd :input (fd-stream-timeout stream))
875     (error 'io-timeout :stream stream :direction :read))
876     (do-input stream))
877     ((eql errno unix:econnreset)
878     (error 'socket-error
879     :format-control "Socket connection reset: ~A"
880     :format-arguments (list (unix:get-unix-error-msg errno))
881     :errno errno))
882     (t
883     (error "Error reading ~S: ~A"
884     stream
885     (unix:get-unix-error-msg errno)))))
886 ram 1.1 ((zerop count)
887 ram 1.12 (setf (fd-stream-listen stream) :eof)
888 ram 1.1 (throw 'eof-input-catcher nil))
889     (t
890     (incf (fd-stream-ibuf-tail stream) count))))))
891 rtoy 1.86
892 ram 1.1 ;;; INPUT-AT-LEAST -- internal
893     ;;;
894     ;;; Makes sure there are at least ``bytes'' number of bytes in the input
895     ;;; buffer. Keeps calling do-input until that condition is met.
896     ;;;
897     (defmacro input-at-least (stream bytes)
898     (let ((stream-var (gensym))
899     (bytes-var (gensym)))
900     `(let ((,stream-var ,stream)
901     (,bytes-var ,bytes))
902     (loop
903     (when (>= (- (fd-stream-ibuf-tail ,stream-var)
904     (fd-stream-ibuf-head ,stream-var))
905     ,bytes-var)
906     (return))
907     (do-input ,stream-var)))))
908    
909 rtoy 1.86 ;;; INPUT-WRAPPER -- internal
910 ram 1.1 ;;;
911 ram 1.24 ;;; Macro to wrap around all input routines to handle eof-error noise.
912 ram 1.1 ;;;
913 rtoy 1.82 (defmacro input-wrapper ((stream bytes eof-error eof-value &optional type) &body read-forms)
914 ram 1.1 (let ((stream-var (gensym))
915     (element-var (gensym)))
916     `(let ((,stream-var ,stream))
917 rtoy 1.86 (if (fd-stream-unread ,stream-var) ;;@@
918 ram 1.26 (prog1
919 rtoy 1.82 ,(if (eq type 'character)
920     `(fd-stream-unread ,stream-var)
921     `(char-code (fd-stream-unread ,stream-var)))
922 ram 1.26 (setf (fd-stream-unread ,stream-var) nil)
923     (setf (fd-stream-listen ,stream-var) nil))
924     (let ((,element-var
925     (catch 'eof-input-catcher
926     (input-at-least ,stream-var ,bytes)
927     ,@read-forms)))
928     (cond (,element-var
929     (incf (fd-stream-ibuf-head ,stream-var) ,bytes)
930     ,element-var)
931     (t
932     (eof-or-lose ,stream-var ,eof-error ,eof-value))))))))
933 ram 1.1
934     ;;; DEF-INPUT-ROUTINE -- internal
935     ;;;
936     ;;; Defines an input routine.
937     ;;;
938     (defmacro def-input-routine (name
939     (type size sap head)
940     &rest body)
941     `(progn
942     (defun ,name (stream eof-error eof-value)
943 rtoy 1.82 (input-wrapper (stream ,size eof-error eof-value ,type)
944 ram 1.1 (let ((,sap (fd-stream-ibuf-sap stream))
945     (,head (fd-stream-ibuf-head stream)))
946     ,@body)))
947     (setf *input-routines*
948     (nconc *input-routines*
949     (list (list ',type ',name ',size))))))
950    
951 wlott 1.6 ;;; INPUT-CHARACTER -- internal
952 ram 1.1 ;;;
953     ;;; Routine to use in stream-in slot for reading string chars.
954     ;;;
955 wlott 1.6 (def-input-routine input-character
956     (character 1 sap head)
957 wlott 1.5 (code-char (sap-ref-8 sap head)))
958 ram 1.1
959     ;;; INPUT-UNSIGNED-8BIT-BYTE -- internal
960     ;;;
961     ;;; Routine to read in an unsigned 8 bit number.
962     ;;;
963     (def-input-routine input-unsigned-8bit-byte
964     ((unsigned-byte 8) 1 sap head)
965 wlott 1.5 (sap-ref-8 sap head))
966 ram 1.1
967     ;;; INPUT-SIGNED-8BIT-BYTE -- internal
968     ;;;
969     ;;; Routine to read in a signed 8 bit number.
970     ;;;
971     (def-input-routine input-signed-8bit-number
972     ((signed-byte 8) 1 sap head)
973 wlott 1.5 (signed-sap-ref-8 sap head))
974 ram 1.1
975     ;;; INPUT-UNSIGNED-16BIT-BYTE -- internal
976     ;;;
977     ;;; Routine to read in an unsigned 16 bit number.
978     ;;;
979     (def-input-routine input-unsigned-16bit-byte
980     ((unsigned-byte 16) 2 sap head)
981 wlott 1.20 (sap-ref-16 sap head))
982 ram 1.1
983     ;;; INPUT-SIGNED-16BIT-BYTE -- internal
984     ;;;
985     ;;; Routine to read in a signed 16 bit number.
986     ;;;
987     (def-input-routine input-signed-16bit-byte
988     ((signed-byte 16) 2 sap head)
989 wlott 1.20 (signed-sap-ref-16 sap head))
990 ram 1.1
991     ;;; INPUT-UNSIGNED-32BIT-BYTE -- internal
992     ;;;
993     ;;; Routine to read in a unsigned 32 bit number.
994     ;;;
995     (def-input-routine input-unsigned-32bit-byte
996     ((unsigned-byte 32) 4 sap head)
997 wlott 1.20 (sap-ref-32 sap head))
998 ram 1.1
999     ;;; INPUT-SIGNED-32BIT-BYTE -- internal
1000     ;;;
1001     ;;; Routine to read in a signed 32 bit number.
1002     ;;;
1003     (def-input-routine input-signed-32bit-byte
1004     ((signed-byte 32) 4 sap head)
1005 wlott 1.20 (signed-sap-ref-32 sap head))
1006 ram 1.1
1007 rtoy 1.86 (stream::def-ef-macro ef-cin (extfmt lisp stream::+ef-max+ stream::+ef-cin+)
1008 rtoy 1.89 `(lambda (stream eof-error-p eof-value)
1009 rtoy 1.86 (declare (type fd-stream stream)
1010 rtoy 1.89 #|(optimize (speed 3) (space 0) (debug 0) (safety 0))|#)
1011     (let* ((head (fd-stream-ibuf-head stream))
1012     (ch (catch 'eof-input-catcher
1013     (stream::octets-to-char ,extfmt
1014     (fd-stream-oc-state stream)
1015     (fd-stream-last-char-read-size stream)
1016     ;;@@ Note: need proper EOF handling...
1017     (progn
1018     (when (= head (fd-stream-ibuf-tail stream))
1019     (let ((sofar (- head (fd-stream-ibuf-head
1020     stream))))
1021     (do-input stream)
1022     (setf head (+ (fd-stream-ibuf-head stream)
1023     sofar))))
1024     (bref (fd-stream-ibuf-sap stream)
1025     (1- (incf head))))
1026     (lambda (n) (decf head n))))))
1027     (declare (type index head))
1028     (if ch
1029     (progn
1030     (setf (fd-stream-ibuf-head stream) head)
1031     ch)
1032     (eof-or-lose stream eof-error-p eof-value)))))
1033 rtoy 1.86
1034     #+(or)
1035     (stream::def-ef-macro ef-sin (extfmt lisp stream::+ef-max+ stream::+ef-sin+)
1036     `(lambda (stream string char start end)
1037     (declare (type fd-stream stream)
1038     (type simple-string string)
1039     (type (or character null) char)
1040     (type index start end)
1041     (optimize (speed 3) (space 0) (debug 0) (safety 0)))
1042     (let ((sap (fd-stream-ibuf-sap stream))
1043     (head (fd-stream-ibuf-head stream))
1044     (tail (fd-stream-ibuf-tail stream))
1045     (curr start))
1046     (declare (type sys:system-area-pointer sap)
1047     (type index head tail curr))
1048     (loop
1049     ;;@@ Fix EOF handling
1050     (let* ((sz 0)
1051     (ch (catch 'eof-input-catcher
1052     (stream::octets-to-char ,extfmt
1053 rtoy 1.89 (fd-stream-oc-state stream)
1054     sz
1055     (progn
1056     (when (= head tail)
1057     (let ((sofar (- head
1058     (fd-stream-ibuf-head
1059     stream))))
1060     (do-input stream)
1061     (setq head
1062     (+ (fd-stream-ibuf-head
1063     stream)
1064     sofar)
1065     tail
1066     (fd-stream-ibuf-tail
1067     stream))))
1068     (bref sap (1- (incf head))))
1069     (lambda (n) (decf head n))))))
1070 rtoy 1.86 (declare (type index sz)
1071     (type (or null character) ch))
1072     (when (null ch)
1073     (return (values (- curr start) :eof)))
1074     (setf (fd-stream-last-char-read-size stream) sz)
1075     (incf (fd-stream-ibuf-head stream) sz)
1076     (when (and char (char= ch char))
1077     (return (values (- curr start) t)))
1078     (setf (schar string (1- (incf curr))) ch)
1079     (when (= curr end)
1080     (return (values (- curr start) nil))))))))
1081    
1082 ram 1.1 ;;; PICK-INPUT-ROUTINE -- internal
1083     ;;;
1084     ;;; Find an input routine to use given the type. Return as multiple values
1085     ;;; the routine, the real type transfered, and the number of bytes per element.
1086     ;;;
1087     (defun pick-input-routine (type)
1088     (dolist (entry *input-routines*)
1089     (when (subtypep type (car entry))
1090 rtoy 1.79 (return-from pick-input-routine
1091     (values (symbol-function (cadr entry))
1092     (car entry)
1093     (caddr entry)))))
1094     ;; FIXME: let's do it the hard way, then (but ignore things like
1095     ;; endianness, efficiency, and the necessary coupling between these
1096     ;; and the output routines). -- CSR, 2004-02-09
1097     (loop for i from 40 by 8 to max-stream-element-size ; ARB (well, KLUDGE really)
1098     if (subtypep type `(unsigned-byte ,i))
1099     do (return-from pick-input-routine
1100     (values
1101     (lambda (stream eof-error eof-value)
1102     (input-wrapper (stream (/ i 8) eof-error eof-value)
1103     (let ((sap (fd-stream-ibuf-sap stream))
1104     (head (fd-stream-ibuf-head stream)))
1105     (loop for j from 0 below (/ i 8)
1106     with result = 0
1107     do (setf result
1108     (+ (* 256 result)
1109     (sap-ref-8 sap (+ head j))))
1110     finally (return result)))))
1111     `(unsigned-byte ,i)
1112     (/ i 8))))
1113     (loop for i from 40 by 8 to max-stream-element-size ; ARB (well, KLUDGE really)
1114     if (subtypep type `(signed-byte ,i))
1115     do (return-from pick-input-routine
1116     (values
1117     (lambda (stream eof-error eof-value)
1118     (input-wrapper (stream (/ i 8) eof-error eof-value)
1119     (let ((sap (fd-stream-ibuf-sap stream))
1120     (head (fd-stream-ibuf-head stream)))
1121     (loop for j from 0 below (/ i 8)
1122     with result = 0
1123     do (setf result
1124     (+ (* 256 result)
1125     (sap-ref-8 sap (+ head j))))
1126 rtoy 1.80 finally (return (if (logbitp (1- i) result)
1127     (dpb result (byte i 0) -1)
1128     result))))))
1129 rtoy 1.79 `(signed-byte ,i)
1130     (/ i 8)))))
1131 ram 1.1
1132     ;;; STRING-FROM-SAP -- internal
1133     ;;;
1134     ;;; Returns a string constructed from the sap, start, and end.
1135     ;;;
1136     (defun string-from-sap (sap start end)
1137 ram 1.14 (declare (type index start end))
1138 ram 1.1 (let* ((length (- end start))
1139     (string (make-string length)))
1140 wlott 1.5 (copy-from-system-area sap (* start vm:byte-bits)
1141     string (* vm:vector-data-offset vm:word-bits)
1142     (* length vm:byte-bits))
1143 ram 1.1 string))
1144    
1145 ram 1.13 #|
1146 ram 1.1 ;;; FD-STREAM-READ-N-BYTES -- internal
1147     ;;;
1148 dtc 1.50 ;;; This version waits using server. I changed to the non-server version
1149     ;;; because it allows this method to be used by CLX w/o confusing serve-event.
1150     ;;; The non-server method is also significantly more efficient for large
1151     ;;; reads. -- Ram
1152     ;;;
1153 ram 1.1 ;;; The n-bin routine.
1154     ;;;
1155     (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p)
1156 dtc 1.50 (declare (type stream stream) (type index start requested))
1157 ram 1.1 (let* ((sap (fd-stream-ibuf-sap stream))
1158     (elsize (fd-stream-element-size stream))
1159     (offset (* elsize start))
1160     (bytes (* elsize requested))
1161 wlott 1.5 (result
1162     (catch 'eof-input-catcher
1163     (loop
1164     (input-at-least stream 1)
1165     (let* ((head (fd-stream-ibuf-head stream))
1166     (tail (fd-stream-ibuf-tail stream))
1167     (available (- tail head))
1168     (copy (min available bytes)))
1169     (if (typep buffer 'system-area-pointer)
1170     (system-area-copy sap (* head vm:byte-bits)
1171     buffer (* offset vm:byte-bits)
1172     (* copy vm:byte-bits))
1173     (copy-from-system-area sap (* head vm:byte-bits)
1174     buffer (+ (* offset vm:byte-bits)
1175     (* vm:vector-data-offset
1176     vm:word-bits))
1177     (* copy vm:byte-bits)))
1178     (incf (fd-stream-ibuf-head stream) copy)
1179     (incf offset copy)
1180     (decf bytes copy))
1181     (when (zerop bytes)
1182     (return requested))))))
1183 ram 1.26 (or result
1184     (eof-or-lose stream eof-error-p
1185     (- requested (/ bytes elsize))))))
1186 ram 1.13 |#
1187 ram 1.1
1188 ram 1.13
1189     ;;; FD-STREAM-READ-N-BYTES -- internal
1190     ;;;
1191 dtc 1.50 ;;; The N-Bin method for FD-STREAMs. This doesn't use the SERVER; it blocks
1192 rtoy 1.86 ;;; in UNIX-READ. This allows the method to be used to implement reading
1193 ram 1.13 ;;; for CLX. It is generally used where there is a definite amount of reading
1194 ram 1.14 ;;; to be done, so blocking isn't too problematical.
1195 ram 1.13 ;;;
1196     ;;; We copy buffered data into the buffer. If there is enough, just return.
1197     ;;; Otherwise, we see if the amount of additional data needed will fit in the
1198     ;;; stream buffer. If not, inhibit GCing (so we can have a SAP into the Buffer
1199     ;;; argument), and read directly into the user supplied buffer. Otherwise,
1200     ;;; read a buffer-full into the stream buffer and then copy the amount we need
1201     ;;; out.
1202     ;;;
1203     ;;; We loop doing the reads until we either get enough bytes or hit EOF. We
1204 ram 1.24 ;;; must loop when eof-errorp is T because some streams (like pipes) may return
1205     ;;; a partial amount without hitting EOF.
1206     ;;;
1207 ram 1.13 (defun fd-stream-read-n-bytes (stream buffer start requested eof-error-p)
1208     (declare (type stream stream) (type index start requested))
1209     (let* ((sap (fd-stream-ibuf-sap stream))
1210 ram 1.24 (offset start)
1211 ram 1.13 (head (fd-stream-ibuf-head stream))
1212     (tail (fd-stream-ibuf-tail stream))
1213     (available (- tail head))
1214 ram 1.24 (copy (min requested available)))
1215     (declare (type index offset head tail available copy))
1216 gerd 1.72 ;;
1217     ;; If something has been unread, put that at buffer + start,
1218     ;; and read the rest to start + 1.
1219 rtoy 1.86 (when (fd-stream-unread stream) ;;@@
1220 gerd 1.72 (etypecase buffer
1221     (system-area-pointer
1222     (assert (= 1 (fd-stream-element-size stream)))
1223     (setf (sap-ref-8 buffer start) (char-code (read-char stream))))
1224 rtoy 1.82 (string
1225     (setf (aref buffer start) (read-char stream)))
1226 gerd 1.72 (vector
1227 rtoy 1.82 (setf (aref buffer start) (char-code(read-char stream)))))
1228 gerd 1.72 (return-from fd-stream-read-n-bytes
1229     (1+ (fd-stream-read-n-bytes stream buffer (1+ start) (1- requested)
1230     eof-error-p))))
1231     ;;
1232 ram 1.13 (unless (zerop copy)
1233     (if (typep buffer 'system-area-pointer)
1234     (system-area-copy sap (* head vm:byte-bits)
1235     buffer (* offset vm:byte-bits)
1236     (* copy vm:byte-bits))
1237     (copy-from-system-area sap (* head vm:byte-bits)
1238     buffer (+ (* offset vm:byte-bits)
1239     (* vm:vector-data-offset
1240     vm:word-bits))
1241     (* copy vm:byte-bits)))
1242     (incf (fd-stream-ibuf-head stream) copy))
1243     (cond
1244 ram 1.24 ((or (= copy requested)
1245     (and (not eof-error-p) (/= copy 0)))
1246     copy)
1247     (t
1248 ram 1.13 (setf (fd-stream-ibuf-head stream) 0)
1249     (setf (fd-stream-ibuf-tail stream) 0)
1250     (setf (fd-stream-listen stream) nil)
1251 ram 1.24 (let ((now-needed (- requested copy))
1252 ram 1.13 (len (fd-stream-ibuf-length stream)))
1253     (declare (type index now-needed len))
1254     (cond
1255     ((> now-needed len)
1256 ram 1.32 ;;
1257     ;; If the desired amount is greater than the stream buffer size, then
1258     ;; read directly into the destination, incrementing the start
1259     ;; accordingly. In this case, we never leave anything in the stream
1260     ;; buffer.
1261 ram 1.13 (system:without-gcing
1262     (loop
1263     (multiple-value-bind
1264     (count err)
1265 wlott 1.19 (unix:unix-read (fd-stream-fd stream)
1266 ram 1.13 (sap+ (if (typep buffer 'system-area-pointer)
1267     buffer
1268     (vector-sap buffer))
1269     (+ offset copy))
1270     now-needed)
1271     (declare (type (or index null) count))
1272     (unless count
1273     (error "Error reading ~S: ~A" stream
1274 wlott 1.19 (unix:get-unix-error-msg err)))
1275 pw 1.48 (decf now-needed count)
1276 ram 1.33 (if eof-error-p
1277     (when (zerop count)
1278     (error 'end-of-file :stream stream))
1279     (return (- requested now-needed)))
1280 ram 1.13 (when (zerop now-needed) (return requested))
1281     (incf offset count)))))
1282     (t
1283 ram 1.32 ;;
1284     ;; If we want less than the buffer size, then loop trying to fill the
1285     ;; stream buffer and copying what we get into the destination. When
1286     ;; we have enough, we leave what's left in the stream buffer.
1287 ram 1.13 (loop
1288     (multiple-value-bind
1289     (count err)
1290 wlott 1.19 (unix:unix-read (fd-stream-fd stream) sap len)
1291 ram 1.13 (declare (type (or index null) count))
1292     (unless count
1293     (error "Error reading ~S: ~A" stream
1294 wlott 1.19 (unix:get-unix-error-msg err)))
1295 ram 1.33 (when (and eof-error-p (zerop count))
1296     (error 'end-of-file :stream stream))
1297    
1298 ram 1.13 (let* ((copy (min now-needed count))
1299     (copy-bits (* copy vm:byte-bits))
1300     (buffer-start-bits
1301     (* (+ offset available) vm:byte-bits)))
1302     (declare (type index copy copy-bits buffer-start-bits))
1303     (if (typep buffer 'system-area-pointer)
1304     (system-area-copy sap 0
1305     buffer buffer-start-bits
1306     copy-bits)
1307     (copy-from-system-area sap 0
1308     buffer (+ buffer-start-bits
1309     (* vm:vector-data-offset
1310     vm:word-bits))
1311     copy-bits))
1312 ram 1.32
1313 ram 1.13 (decf now-needed copy)
1314 ram 1.33 (when (or (zerop now-needed) (not eof-error-p))
1315 ram 1.32 (setf (fd-stream-ibuf-head stream) copy)
1316     (setf (fd-stream-ibuf-tail stream) count)
1317 ram 1.33 (return (- requested now-needed)))
1318 ram 1.24 (incf offset copy)))))))))))
1319 ram 1.13
1320 ram 1.1
1321     ;;;; Utility functions (misc routines, etc)
1322    
1323     ;;; SET-ROUTINES -- internal
1324     ;;;
1325 ram 1.24 ;;; Fill in the various routine slots for the given type. Input-p and
1326     ;;; output-p indicate what slots to fill. The buffering slot must be set prior
1327     ;;; to calling this routine.
1328 ram 1.1 ;;;
1329 rtoy 1.82
1330 rtoy 1.83 (defun set-routines (stream type input-p output-p buffer-p &key binary-stream-p)
1331 ram 1.1 (let ((target-type (case type
1332     ((:default unsigned-byte)
1333     '(unsigned-byte 8))
1334     (signed-byte
1335     '(signed-byte 8))
1336     (t
1337     type)))
1338     (input-type nil)
1339     (output-type nil)
1340     (input-size nil)
1341     (output-size nil))
1342    
1343 wlott 1.5 (when (fd-stream-obuf-sap stream)
1344     (push (fd-stream-obuf-sap stream) *available-buffers*)
1345     (setf (fd-stream-obuf-sap stream) nil))
1346     (when (fd-stream-ibuf-sap stream)
1347     (push (fd-stream-ibuf-sap stream) *available-buffers*)
1348     (setf (fd-stream-ibuf-sap stream) nil))
1349 rtoy 1.86
1350     #+unicode
1351     (when (null (fd-stream-external-format stream))
1352     (setf (fd-stream-external-format stream) :default))
1353 ram 1.1
1354     (when input-p
1355     (multiple-value-bind
1356     (routine type size)
1357     (pick-input-routine target-type)
1358     (unless routine
1359     (error "Could not find any input routine for ~S" target-type))
1360 wlott 1.5 (setf (fd-stream-ibuf-sap stream) (next-available-buffer))
1361     (setf (fd-stream-ibuf-length stream) bytes-per-buffer)
1362     (setf (fd-stream-ibuf-tail stream) 0)
1363 ram 1.1 (if (subtypep type 'character)
1364 ram 1.14 (setf (fd-stream-in stream) routine
1365 ram 1.24 (fd-stream-bin stream) #'ill-bin)
1366 rtoy 1.83 (setf (fd-stream-in stream) (if (and binary-stream-p
1367 rtoy 1.82 (eql size 1))
1368     (pick-input-routine 'character)
1369     #'ill-in)
1370 ram 1.24 (fd-stream-bin stream) routine))
1371 toy 1.58 (when (or (eql size 1)
1372     (eql size 2)
1373     (eql size 4))
1374     ;; Support for n-byte operations on 8-, 16-, and 32-bit streams
1375 ram 1.24 (setf (fd-stream-n-bin stream) #'fd-stream-read-n-bytes)
1376 toy 1.60 (when (and buffer-p (eql size 1)
1377 rtoy 1.91 (or
1378     ;; FIXME: Do this better. We want to check for
1379     ;; (unsigned-byte 8). The 8 is unnecessary
1380     ;; since we already have size = 1.
1381     (or (eq 'unsigned-byte (and (consp type) (car type)))
1382     (eq type :default))
1383     ;; Character streams with :iso8859-1
1384 rtoy 1.91.2.1.2.1 (and (eq type 'character))))
1385 toy 1.60 ;; We only create this buffer for streams of type
1386 rtoy 1.91 ;; (unsigned-byte 8) or character streams with an external
1387     ;; format of :iso8859-1. Because there's no buffer, the
1388 toy 1.60 ;; other element-types will dispatch to the appropriate
1389 rtoy 1.91 ;; input (output) routine in fast-read-byte/fast-read-char.
1390 rtoy 1.91.2.1.2.1 (when *enable-stream-buffer-p*
1391     (setf (lisp-stream-in-buffer stream)
1392     (make-array in-buffer-length
1393     :element-type '(unsigned-byte 8))))
1394     (when (and *enable-stream-buffer-p*
1395     (eq type 'character))
1396     ;; For character streams, we create the string-buffer
1397     ;; and indices so we can have fast character streams.
1398     ;; Also with character streams, the in-buffer index is
1399     ;; handled differently, so we need to initialize it.
1400     (setf (lisp-stream-string-buffer stream)
1401 rtoy 1.91.2.1.2.2 (make-string (1+ in-buffer-length)))
1402 rtoy 1.91.2.1.2.1 (setf (lisp-stream-string-buffer-len stream) 0)
1403     (setf (lisp-stream-string-index stream) 0))))
1404 ram 1.1 (setf input-size size)
1405     (setf input-type type)))
1406    
1407     (when output-p
1408     (multiple-value-bind
1409     (routine type size)
1410     (pick-output-routine target-type (fd-stream-buffering stream))
1411     (unless routine
1412     (error "Could not find any output routine for ~S buffered ~S."
1413     (fd-stream-buffering stream)
1414     target-type))
1415 wlott 1.5 (setf (fd-stream-obuf-sap stream) (next-available-buffer))
1416     (setf (fd-stream-obuf-length stream) bytes-per-buffer)
1417 ram 1.1 (setf (fd-stream-obuf-tail stream) 0)
1418     (if (subtypep type 'character)
1419     (setf (fd-stream-out stream) routine
1420     (fd-stream-bout stream) #'ill-bout)
1421     (setf (fd-stream-out stream)
1422     (or (if (eql size 1)
1423 wlott 1.16 (pick-output-routine 'base-char
1424 ram 1.1 (fd-stream-buffering stream)))
1425     #'ill-out)
1426     (fd-stream-bout stream) routine))
1427     (setf (fd-stream-sout stream)
1428 rtoy 1.91 (if (eql size 1) #'fd-sout #'ill-out))
1429 ram 1.1 (setf (fd-stream-char-pos stream) 0)
1430     (setf output-size size)
1431     (setf output-type type)))
1432    
1433     (when (and input-size output-size
1434 rtoy 1.86 (not (eql input-size output-size)))
1435 ram 1.1 (error "Element sizes for input (~S:~S) and output (~S:~S) differ?"
1436     input-type input-size
1437     output-type output-size))
1438     (setf (fd-stream-element-size stream)
1439     (or input-size output-size))
1440    
1441     (setf (fd-stream-element-type stream)
1442     (cond ((equal input-type output-type)
1443     input-type)
1444 dtc 1.39 ((null output-type)
1445     input-type)
1446     ((null input-type)
1447     output-type)
1448     ((subtypep input-type output-type)
1449 ram 1.1 input-type)
1450     ((subtypep output-type input-type)
1451     output-type)
1452     (t
1453     (error "Input type (~S) and output type (~S) are unrelated?"
1454     input-type
1455     output-type))))))
1456    
1457 toy 1.66 ;;; REVERT-FILE -- internal
1458     ;;;
1459 rtoy 1.84 ;;; Revert a file, if possible; otherwise do nothing. Used during
1460 toy 1.66 ;;; CLOSE when the abort flag is set.
1461     ;;;
1462     (defun revert-file (filename original)
1463     (declare (type simple-base-string filename)
1464     (type (or simple-base-string null) original))
1465 rtoy 1.84 (when original
1466     (multiple-value-bind (okay err)
1467     (unix:unix-rename original filename)
1468     (unless okay
1469 toy 1.66 (cerror "Go on as if nothing bad happened."
1470 emarsden 1.71 "Could not restore ~S to its original contents: ~A"
1471 toy 1.66 filename (unix:get-unix-error-msg err))))))
1472    
1473     ;;; DELETE-ORIGINAL -- internal
1474     ;;;
1475     ;;; Delete a backup file. Used during CLOSE.
1476     ;;;
1477     (defun delete-original (filename original)
1478     (declare (type simple-base-string filename)
1479     (type (or simple-base-string null) original))
1480     (when original
1481     (multiple-value-bind (okay err) (unix:unix-unlink original)
1482     (unless okay
1483     (cerror "Go on as if nothing bad happened."
1484     "Could not delete ~S during close of ~S: ~A"
1485 emarsden 1.69 original filename (unix:get-unix-error-msg err))))))
1486 toy 1.66
1487 ram 1.1 ;;; FD-STREAM-MISC-ROUTINE -- input
1488     ;;;
1489     ;;; Handle the various misc operations on fd-stream.
1490     ;;;
1491     (defun fd-stream-misc-routine (stream operation &optional arg1 arg2)
1492 ram 1.24 (declare (ignore arg2))
1493 ram 1.1 (case operation
1494 ram 1.24 (:listen
1495 ram 1.1 (or (not (eql (fd-stream-ibuf-head stream)
1496     (fd-stream-ibuf-tail stream)))
1497     (fd-stream-listen stream)
1498     (setf (fd-stream-listen stream)
1499 dtc 1.41 (eql (alien:with-alien ((read-fds (alien:struct unix:fd-set)))
1500     (unix:fd-zero read-fds)
1501     (unix:fd-set (fd-stream-fd stream) read-fds)
1502     (unix:unix-fast-select (1+ (fd-stream-fd stream))
1503     (alien:addr read-fds) nil nil
1504     0 0))
1505 ram 1.13 1))))
1506 ram 1.1 (:unread
1507 rtoy 1.86 #-unicode
1508 wlott 1.5 (setf (fd-stream-unread stream) arg1)
1509 rtoy 1.86 #+unicode
1510 rtoy 1.91.2.1.2.1 (cond ((lisp-stream-string-buffer stream)
1511     (if (zerop (lisp-stream-string-index stream))
1512     (setf (fd-stream-unread stream) arg1)
1513     (decf (lisp-stream-string-index stream))))
1514     (t
1515     (if (zerop (fd-stream-last-char-read-size stream))
1516     (setf (fd-stream-unread stream) arg1)
1517     (decf (fd-stream-ibuf-head stream)
1518     (fd-stream-last-char-read-size stream)))))
1519 rtoy 1.86 ;; Paul says:
1520     ;;
1521     ;; Not needed for unicode when unreading is implemented by backing up in
1522     ;; the buffer (e.g., with last-char-read-size...)
1523     ;;
1524     ;; (AFAICS there's nothing wrong with setting it there, but it
1525     ;; screws up read-interactive in my toplevel command thing -
1526     ;; leaves it expecting to read arguments when it shouldn't,
1527     ;; because LISTEN returns T when there's no input pending, but I
1528     ;; don't understand why...)
1529     #-unicode
1530 wlott 1.5 (setf (fd-stream-listen stream) t))
1531 ram 1.1 (:close
1532     (cond (arg1
1533     ;; We got us an abort on our hands.
1534 dtc 1.40 (when (fd-stream-handler stream)
1535     (system:remove-fd-handler (fd-stream-handler stream))
1536     (setf (fd-stream-handler stream) nil))
1537 toy 1.66 (when (and (fd-stream-file stream) (fd-stream-obuf-sap stream))
1538     (revert-file (fd-stream-file stream)
1539     (fd-stream-original stream))))
1540 ram 1.1 (t
1541 rtoy 1.90 #+(and unicode (not unicode-bootstrap))
1542     (when (and (output-stream-p stream)
1543     (eq (stream-element-type stream) 'character))
1544     ;; For output character streams, we need to flush out
1545     ;; any state that the external format might have.
1546     #+nil (format *debug-io* "state = ~S~%" (fd-stream-co-state stream))
1547     (funcall (ef-flush (fd-stream-external-format stream))
1548     stream))
1549 ram 1.1 (fd-stream-misc-routine stream :finish-output)
1550 toy 1.66 (when (fd-stream-delete-original stream)
1551     (delete-original (fd-stream-file stream)
1552     (fd-stream-original stream)))))
1553 wlott 1.17 (when (fboundp 'cancel-finalization)
1554     (cancel-finalization stream))
1555 wlott 1.19 (unix:unix-close (fd-stream-fd stream))
1556 wlott 1.5 (when (fd-stream-obuf-sap stream)
1557     (push (fd-stream-obuf-sap stream) *available-buffers*)
1558     (setf (fd-stream-obuf-sap stream) nil))
1559     (when (fd-stream-ibuf-sap stream)
1560     (push (fd-stream-ibuf-sap stream) *available-buffers*)
1561     (setf (fd-stream-ibuf-sap stream) nil))
1562 ram 1.1 (lisp::set-closed-flame stream))
1563 wlott 1.6 (:clear-input
1564 rtoy 1.86 (setf (fd-stream-unread stream) nil) ;;@@
1565     #+unicode (setf (fd-stream-last-char-read-size stream) 0)
1566 wlott 1.6 (setf (fd-stream-ibuf-head stream) 0)
1567     (setf (fd-stream-ibuf-tail stream) 0)
1568 ram 1.38 (catch 'eof-input-catcher
1569     (loop
1570 dtc 1.49 (multiple-value-bind
1571     (count errno)
1572     (alien:with-alien ((read-fds (alien:struct unix:fd-set)))
1573     (unix:fd-zero read-fds)
1574     (unix:fd-set (fd-stream-fd stream) read-fds)
1575     (unix:unix-fast-select (1+ (fd-stream-fd stream))
1576     (alien:addr read-fds) nil nil 0 0))
1577 ram 1.38 (cond ((eql count 1)
1578     (do-input stream)
1579     (setf (fd-stream-ibuf-head stream) 0)
1580     (setf (fd-stream-ibuf-tail stream) 0))
1581 dtc 1.49 ((and (not count) (eql errno unix:eintr)))
1582 ram 1.38 (t
1583     (return t)))))))
1584 ram 1.1 (:force-output
1585     (flush-output-buffer stream))
1586     (:finish-output
1587     (flush-output-buffer stream)
1588     (do ()
1589     ((null (fd-stream-output-later stream)))
1590     (system:serve-all-events)))
1591     (:element-type
1592     (fd-stream-element-type stream))
1593 ram 1.22 (:interactive-p
1594     (unix:unix-isatty (fd-stream-fd stream)))
1595 ram 1.1 (:line-length
1596     80)
1597     (:charpos
1598     (fd-stream-char-pos stream))
1599     (:file-length
1600 pw 1.56 (unless (fd-stream-file stream)
1601     (error 'simple-type-error
1602     :datum stream
1603     :expected-type 'file-stream
1604     :format-control "~s is not a stream associated with a file."
1605     :format-arguments (list stream)))
1606 ram 1.1 (multiple-value-bind
1607     (okay dev ino mode nlink uid gid rdev size
1608     atime mtime ctime blksize blocks)
1609 wlott 1.19 (unix:unix-fstat (fd-stream-fd stream))
1610 ram 1.1 (declare (ignore ino nlink uid gid rdev
1611     atime mtime ctime blksize blocks))
1612     (unless okay
1613 pmai 1.61 (error 'simple-file-error
1614     :format-control "Error fstating ~S: ~A"
1615     :format-arguments (list stream (unix:get-unix-error-msg dev))))
1616 dtc 1.51 (if (zerop mode)
1617 ram 1.23 nil
1618 toy 1.64 (values (truncate size (fd-stream-element-size stream))))))
1619 ram 1.1 (:file-position
1620 ram 1.29 (fd-stream-file-position stream arg1))))
1621 ram 1.1
1622 ram 1.28
1623 ram 1.1 ;;; FD-STREAM-FILE-POSITION -- internal.
1624     ;;;
1625     (defun fd-stream-file-position (stream &optional newpos)
1626 ram 1.14 (declare (type fd-stream stream)
1627 dtc 1.51 (type (or (integer 0) (member nil :start :end)) newpos))
1628 ram 1.1 (if (null newpos)
1629     (system:without-interrupts
1630 dtc 1.51 ;; First, find the position of the UNIX file descriptor in the file.
1631 ram 1.1 (multiple-value-bind
1632 dtc 1.51 (posn errno)
1633 wlott 1.19 (unix:unix-lseek (fd-stream-fd stream) 0 unix:l_incr)
1634 dtc 1.51 (declare (type (or (integer 0) null) posn))
1635     (cond (posn
1636 ram 1.1 ;; Adjust for buffered output:
1637     ;; If there is any output buffered, the *real* file position
1638     ;; will be larger than reported by lseek because lseek
1639 toy 1.70 ;; obviously cannot take into account output we have not
1640 ram 1.1 ;; sent yet.
1641     (dolist (later (fd-stream-output-later stream))
1642 ram 1.14 (incf posn (- (the index (caddr later))
1643     (the index (cadr later)))))
1644 ram 1.1 (incf posn (fd-stream-obuf-tail stream))
1645     ;; Adjust for unread input:
1646     ;; If there is any input read from UNIX but not supplied to
1647     ;; the user of the stream, the *real* file position will
1648     ;; smaller than reported, because we want to look like the
1649     ;; unread stuff is still available.
1650     (decf posn (- (fd-stream-ibuf-tail stream)
1651     (fd-stream-ibuf-head stream)))
1652 rtoy 1.86 (when (fd-stream-unread stream) ;;@@
1653 ram 1.1 (decf posn))
1654     ;; Divide bytes by element size.
1655 ram 1.14 (truncate posn (fd-stream-element-size stream)))
1656 wlott 1.19 ((eq errno unix:espipe)
1657 ram 1.1 nil)
1658     (t
1659     (system:with-interrupts
1660     (error "Error lseek'ing ~S: ~A"
1661     stream
1662 wlott 1.19 (unix:get-unix-error-msg errno)))))))
1663 dtc 1.51 (let ((offset 0)
1664     origin)
1665     (declare (type (integer 0) offset))
1666 ram 1.1 ;; Make sure we don't have any output pending, because if we move the
1667     ;; file pointer before writing this stuff, it will be written in the
1668     ;; wrong location.
1669     (flush-output-buffer stream)
1670     (do ()
1671     ((null (fd-stream-output-later stream)))
1672     (system:serve-all-events))
1673 ram 1.4 ;; Clear out any pending input to force the next read to go to the
1674     ;; disk.
1675 rtoy 1.86 (setf (fd-stream-unread stream) nil) ;;@@
1676     #+unicode (setf (fd-stream-last-char-read-size stream) 0)
1677 ram 1.4 (setf (fd-stream-ibuf-head stream) 0)
1678     (setf (fd-stream-ibuf-tail stream) 0)
1679 dtc 1.51 ;; Trash cached value for listen, so that we check next time.
1680 wlott 1.5 (setf (fd-stream-listen stream) nil)
1681 ram 1.4 ;; Now move it.
1682 ram 1.1 (cond ((eq newpos :start)
1683 dtc 1.51 (setf offset 0
1684     origin unix:l_set))
1685 ram 1.1 ((eq newpos :end)
1686 dtc 1.51 (setf offset 0
1687     origin unix:l_xtnd))
1688     ((typep newpos '(integer 0))
1689 ram 1.1 (setf offset (* newpos (fd-stream-element-size stream))
1690 wlott 1.19 origin unix:l_set))
1691 ram 1.1 (t
1692     (error "Invalid position given to file-position: ~S" newpos)))
1693     (multiple-value-bind
1694     (posn errno)
1695 wlott 1.19 (unix:unix-lseek (fd-stream-fd stream) offset origin)
1696 dtc 1.51 (cond (posn
1697 ram 1.1 t)
1698 wlott 1.19 ((eq errno unix:espipe)
1699 ram 1.1 nil)
1700     (t
1701     (error "Error lseek'ing ~S: ~A"
1702     stream
1703 wlott 1.19 (unix:get-unix-error-msg errno))))))))
1704 ram 1.1
1705    
1706    
1707     ;;;; Creation routines (MAKE-FD-STREAM and OPEN)
1708    
1709     ;;; MAKE-FD-STREAM -- Public.
1710     ;;;
1711     ;;; Returns a FD-STREAM on the given file.
1712     ;;;
1713     (defun make-fd-stream (fd
1714     &key
1715     (input nil input-p)
1716     (output nil output-p)
1717 wlott 1.16 (element-type 'base-char)
1718 ram 1.1 (buffering :full)
1719 ram 1.15 timeout
1720 ram 1.1 file
1721     original
1722     delete-original
1723 ram 1.28 pathname
1724 ram 1.24 input-buffer-p
1725 ram 1.1 (name (if file
1726     (format nil "file ~S" file)
1727 wlott 1.17 (format nil "descriptor ~D" fd)))
1728 rtoy 1.83 auto-close
1729 rtoy 1.86 (external-format :default)
1730 rtoy 1.83 binary-stream-p)
1731 ram 1.15 (declare (type index fd) (type (or index null) timeout)
1732     (type (member :none :line :full) buffering))
1733     "Create a stream for the given unix file descriptor.
1734     If input is non-nil, allow input operations.
1735     If output is non-nil, allow output operations.
1736     If neither input nor output are specified, default to allowing input.
1737     Element-type indicates the element type to use (as for open).
1738     Buffering indicates the kind of buffering to use.
1739     Timeout (if true) is the number of seconds to wait for input. If NIL (the
1740     default), then wait forever. When we time out, we signal IO-TIMEOUT.
1741     File is the name of the file (will be returned by PATHNAME).
1742     Name is used to identify the stream when printed."
1743 ram 1.1 (cond ((not (or input-p output-p))
1744     (setf input t))
1745     ((not (or input output))
1746     (error "File descriptor must be opened either for input or output.")))
1747 rtoy 1.83 (let ((stream (if binary-stream-p
1748     (%make-binary-text-stream :fd fd
1749     :name name
1750     :file file
1751     :original original
1752     :delete-original delete-original
1753     :pathname pathname
1754     :buffering buffering
1755     :timeout timeout)
1756     (%make-fd-stream :fd fd
1757     :name name
1758     :file file
1759     :original original
1760     :delete-original delete-original
1761     :pathname pathname
1762     :buffering buffering
1763     :timeout timeout))))
1764 rtoy 1.91 ;; FIXME: setting the external format here should be better
1765     ;; integrated into set-routines. We do it before so that
1766     ;; set-routines can create an in-buffer if appropriate. But we
1767     ;; need to do it after to put the correct input routines for the
1768     ;; external format.
1769     ;;
1770     ;;#-unicode-bootstrap ; fails in stream-reinit otherwise
1771     #+(and unicode (not unicode-bootstrap))
1772     (setf (stream-external-format stream) external-format)
1773 rtoy 1.83 (set-routines stream element-type input output input-buffer-p
1774     :binary-stream-p binary-stream-p)
1775 rtoy 1.86 #+(and unicode (not unicode-bootstrap))
1776     (setf (stream-external-format stream) external-format)
1777 wlott 1.17 (when (and auto-close (fboundp 'finalize))
1778     (finalize stream
1779     #'(lambda ()
1780 wlott 1.19 (unix:unix-close fd)
1781 toy 1.70 (format *terminal-io* "** Closed ~A~%" name)
1782     (when original
1783     (revert-file file original)))))
1784 ram 1.1 stream))
1785    
1786 ram 1.24
1787 toy 1.66 ;;; PICK-BACKUP-NAME -- internal
1788 ram 1.1 ;;;
1789     ;;; Pick a name to use for the backup file.
1790     ;;;
1791     (defvar *backup-extension* ".BAK"
1792     "This is a string that OPEN tacks on the end of a file namestring to produce
1793     a name for the :if-exists :rename-and-delete and :rename options. Also,
1794     this can be a function that takes a namestring and returns a complete
1795     namestring.")
1796     ;;;
1797     (defun pick-backup-name (name)
1798 ram 1.14 (declare (type simple-string name))
1799     (let ((ext *backup-extension*))
1800     (etypecase ext
1801     (simple-string (concatenate 'simple-string name ext))
1802     (function (funcall ext name)))))
1803 ram 1.1
1804 toy 1.65 ;;; NEXT-VERSION -- internal
1805     ;;;
1806     ;;; Find the next available versioned name for a file.
1807     ;;;
1808     (defun next-version (name)
1809     (declare (type simple-string name))
1810     (let* ((sep (position #\/ name :from-end t))
1811     (base (if sep (subseq name 0 (1+ sep)) ""))
1812     (dir (unix:open-dir base)))
1813     (multiple-value-bind (name type version)
1814     (extract-name-type-and-version name (if sep (1+ sep) 0) (length name))
1815     (let ((version (if (symbolp version) 1 (1+ version)))
1816 toy 1.67 (match (if type
1817     (concatenate 'string name "." type ".~")
1818     (concatenate 'string name ".~"))))
1819 toy 1.65 (when dir
1820     (unwind-protect
1821     (loop
1822     (let ((name (unix:read-dir dir)))
1823     (cond ((null name) (return))
1824     ((and (> (length name) (length match))
1825     (string= name match :end1 (length match)))
1826     (multiple-value-bind (v e)
1827     (parse-integer name :start (length match)
1828     :junk-allowed t)
1829     (when (and v
1830     (= (length name) (1+ e))
1831     (char= (schar name e) #\~))
1832     (setq version (max version (1+ v)))))))))
1833     (unix:close-dir dir)))
1834     (concatenate 'string base
1835     match (quick-integer-to-string version) "~")))))
1836    
1837 ram 1.1 ;;; ASSURE-ONE-OF -- internal
1838     ;;;
1839     ;;; Assure that the given arg is one of the given list of valid things.
1840     ;;; Allow the user to fix any problems.
1841     ;;;
1842     (defun assure-one-of (item list what)
1843     (unless (member item list)
1844     (loop
1845     (cerror "Enter new value for ~*~S"
1846     "~S is invalid for ~S. Must be one of~{ ~S~}"
1847     item
1848     what
1849     list)
1850 ram 1.14 (format (the stream *query-io*) "Enter new value for ~S: " what)
1851 ram 1.1 (force-output *query-io*)
1852     (setf item (read *query-io*))
1853     (when (member item list)
1854     (return))))
1855     item)
1856    
1857 ram 1.14 ;;; DO-OLD-RENAME -- Internal
1858     ;;;
1859     ;;; Rename Namestring to Original. First, check if we have write access,
1860     ;;; since we don't want to trash unwritable files even if we technically can.
1861 toy 1.70 ;;; We return true if we succeed in renaming.
1862 ram 1.14 ;;;
1863     (defun do-old-rename (namestring original)
1864 wlott 1.19 (unless (unix:unix-access namestring unix:w_ok)
1865 ram 1.14 (cerror "Try to rename it anyway." "File ~S is not writable." namestring))
1866     (multiple-value-bind
1867     (okay err)
1868 wlott 1.19 (unix:unix-rename namestring original)
1869 ram 1.14 (cond (okay t)
1870     (t
1871     (cerror "Use :SUPERSEDE instead."
1872     "Could not rename ~S to ~S: ~A."
1873     namestring
1874     original
1875 wlott 1.19 (unix:get-unix-error-msg err))
1876 ram 1.14 nil))))
1877    
1878 toy 1.66 ;;; FD-OPEN -- Internal
1879 pw 1.57 ;;;
1880 toy 1.66 ;;; Open a file.
1881 pw 1.57 ;;;
1882 toy 1.66 (defun fd-open (pathname direction if-exists if-exists-given
1883     if-does-not-exist if-does-not-exist-given)
1884     (declare (type pathname pathname)
1885     (type (member :input :output :io :probe) direction)
1886     (type (member :error :new-version :rename :rename-and-delete
1887     :overwrite :append :supersede nil) if-exists)
1888     (type (member :error :create nil) if-does-not-exist))
1889     (multiple-value-bind (input output mask)
1890     (ecase direction
1891     (:input (values t nil unix:o_rdonly))
1892     (:output (values nil t unix:o_wronly))
1893     (:io (values t t unix:o_rdwr))
1894     (:probe (values t nil unix:o_rdonly)))
1895     (declare (type index mask))
1896 emarsden 1.76 ;; Process if-exists argument if we are doing any output.
1897     (cond (output
1898     (unless if-exists-given
1899     (setf if-exists
1900     (if (eq (pathname-version pathname) :newest)
1901     :new-version
1902     :error)))
1903     (case if-exists
1904     ((:error nil)
1905     (setf mask (logior mask unix:o_excl)))
1906     ((:new-version :rename :rename-and-delete)
1907     (setf mask (logior mask unix:o_creat)))
1908     (:supersede
1909     (setf mask (logior mask unix:o_trunc)))))
1910     (t
1911     (setf if-exists nil))) ; :ignore-this-arg
1912    
1913     (unless if-does-not-exist-given
1914     (setf if-does-not-exist
1915     (cond ((eq direction :input) :error)
1916     ((and output
1917     (member if-exists '(:overwrite :append)))
1918     :error)
1919     ((eq direction :probe)
1920     nil)
1921     (t
1922     :create))))
1923     (if (eq if-does-not-exist :create)
1924     (setf mask (logior mask unix:o_creat)))
1925    
1926 toy 1.66 (let ((name (cond ((unix-namestring pathname input))
1927     ((and input (eq if-does-not-exist :create))
1928     (unix-namestring pathname nil)))))
1929     (let ((original (cond ((eq if-exists :new-version)
1930     (next-version name))
1931     ((member if-exists '(:rename :rename-and-delete))
1932     (pick-backup-name name))))
1933     (delete-original (eq if-exists :rename-and-delete))
1934     (mode #o666))
1935     (when original
1936     ;; We are doing a :rename or :rename-and-delete.
1937     ;; Determine if the file already exists, make sure the original
1938     ;; file is not a directory and keep the mode
1939     (let ((exists
1940     (and name
1941     (multiple-value-bind
1942     (okay err/dev inode orig-mode)
1943     (unix:unix-stat name)
1944     (declare (ignore inode)
1945     (type (or index null) orig-mode))
1946     (cond
1947     (okay
1948     (when (and output (= (logand orig-mode #o170000)
1949     #o40000))
1950     (error 'simple-file-error
1951     :pathname pathname
1952     :format-control
1953     "Cannot open ~S for output: Is a directory."
1954     :format-arguments (list name)))
1955     (setf mode (logand orig-mode #o777))
1956     t)
1957     ((eql err/dev unix:enoent)
1958     nil)
1959     (t
1960     (error 'simple-file-error
1961     :pathname pathname
1962     :format-control "Cannot find ~S: ~A"
1963     :format-arguments
1964     (list name
1965     (unix:get-unix-error-msg err/dev)))))))))
1966     (unless (and exists
1967     (do-old-rename name original))
1968     (setf original nil)
1969     (setf delete-original nil)
1970     ;; In order to use SUPERSEDE instead, we have
1971     ;; to make sure unix:o_creat corresponds to
1972     ;; if-does-not-exist. unix:o_creat was set
1973     ;; before because of if-exists being :rename.
1974     (unless (eq if-does-not-exist :create)
1975     (setf mask (logior (logandc2 mask unix:o_creat)
1976     unix:o_trunc)))
1977     (setf if-exists :supersede))))
1978    
1979     ;; Okay, now we can try the actual open.
1980     (loop
1981     (multiple-value-bind (fd errno)
1982     (if name
1983     (unix:unix-open name mask mode)
1984     (values nil unix:enoent))
1985     (cond ((fixnump fd)
1986 toy 1.68 (when (eq if-exists :append)
1987     (unix:unix-lseek fd 0 unix:l_xtnd)) ; SEEK_END
1988 toy 1.66 (return (values fd name original delete-original)))
1989     ((eql errno unix:enoent)
1990     (case if-does-not-exist
1991     (:error
1992     (cerror "Return NIL."
1993     'simple-file-error
1994     :pathname pathname
1995     :format-control "Error opening ~S, ~A."
1996     :format-arguments
1997     (list pathname
1998     (unix:get-unix-error-msg errno))))
1999     (:create
2000     (cerror "Return NIL."
2001     'simple-file-error
2002     :pathname pathname
2003     :format-control
2004     "Error creating ~S, path does not exist."
2005     :format-arguments (list pathname))))
2006     (return nil))
2007     ((eql errno unix:eexist)
2008     (unless (eq nil if-exists)
2009     (cerror "Return NIL."
2010     'simple-file-error
2011     :pathname pathname
2012     :format-control "Error opening ~S, ~A."
2013     :format-arguments
2014     (list pathname
2015     (unix:get-unix-error-msg errno))))
2016     (return nil))
2017     ((eql errno unix:eacces)
2018     (cerror "Try again."
2019     'simple-file-error
2020     :pathname pathname
2021     :format-control "Error opening ~S, ~A."
2022     :format-arguments
2023     (list pathname
2024     (unix:get-unix-error-msg errno))))
2025     (t
2026     (cerror "Return NIL."
2027     'simple-file-error
2028     :pathname pathname
2029     :format-control "Error opening ~S, ~A."
2030     :format-arguments
2031     (list pathname
2032     (unix:get-unix-error-msg errno)))
2033     (return nil)))))))))
2034    
2035     ;;; OPEN-FD-STREAM -- Internal
2036     ;;;
2037     ;;; Open an fd-stream connected to a file.
2038     ;;;
2039     (defun open-fd-stream (pathname &key (direction :input)
2040     (element-type 'base-char)
2041     (if-exists nil if-exists-given)
2042     (if-does-not-exist nil if-does-not-exist-given)
2043 rtoy 1.83 (external-format :default)
2044     class)
2045 toy 1.66 (declare (type pathname pathname)
2046     (type (member :input :output :io :probe) direction)
2047     (type (member :error :new-version :rename :rename-and-delete
2048     :overwrite :append :supersede nil) if-exists)
2049 rtoy 1.86 (type (member :error :create nil) if-does-not-exist