;;AUTOLOAD: read-pending
;;AUTODOC: read-pending "read all available characters without blocking"
;;(read-pending [stream])
;;
;;Returns the available characters as a string or ""
;;If EOF is reached (even if some chars are returned), sets read-pending:EOF
;;to t, else ()

(defun read-pending (&optional (stream *standard-input*) &aux
    (result (copy ""))
    bytes
    (blocking (getn (stream-mode stream) :blocking))
  )
  (stream-mode stream :blocking ())
  (setq read-pending:EOF ())
  (while (and (not read-pending:EOF) (select stream :timeout 0))
    (if (/= "" (setq bytes (read-chars -1 stream)))
      (nconc result bytes)
      (setq read-pending:EOF t)
  ))
  (stream-mode stream :blocking blocking)
  result    
)

;;AUTOLOAD: write-pending
;;AUTODOC: write-pending "writes characters without blocking"
;;(write-pending string [ stream offset ] )
;;
;;Writes as much of string as possible without blocking
;;returns the new offset at which to start re-writing in string
;;sets write-pending:EOF to () if you need to write again, and to t if 
;;whole string has been written

(defun write-pending (string &optional (stream *standard-input*) (offset 0)
    &aux
    bytes
    (result (copy ""))
    (blocking (getn (stream-mode stream) :blocking))
  )
  (stream-mode stream :blocking ())
  (setq write-pending:EOF ())
  (while (and (not write-pending:EOF)
      (select :output stream :timeout 0))
    (if (/= 0 (setq bytes (write-chars string -1 stream offset)))
      (incf offset bytes)
      (setq write-pending:EOF t)
  ))
  (stream-mode stream :blocking blocking)
  offset
)
