(defun non-block-read-byte (stream) "read byte that is non blocking, if there is nothing to read it simply returns nil" (declare (optimize (speed 3)(safety 0)) (type stream stream)) (the (or u-byte boolean) (and (the boolean (listen stream)) (let ((byte (the u-byte (read-byte stream t)))) (the u-byte byte))))) (defconstant +sleep-time+ (the single-float 0.001)) (defconstant +timeout+ (the u-byte 5)) (defconstant +increment+ (the fixnum (ceiling (/ +timeout+ +sleep-time+)))) (defun timed-non-block-read-byte (stream) "This is a non blocking version of read byte which is timed. loops +increment+ amount of times and checks if there is anything on the stream to be read, if not it'll sleep for +sleep-time+ if it eventually finds something to read it'll read and then return that byte. if it reaches the timeout it'll signal an error" (declare (optimize (speed 3)(safety 0))) (declare (type stream stream)) (let ((byte (the (or u-byte boolean) (non-block-read-byte stream)))) (or byte (the u-byte (loop :for x fixnum :from 1 :to +increment+ :for byte? := (the (or boolean u-byte) (non-block-read-byte stream)) :then (the (or u-byte boolean) (non-block-read-byte stream)) :if byte? :do (return byte?) :else :do (sleep +sleep-time+) :finally (error 'stream-error :stream stream)))))) (defun read-n-bytes (n stream) "Reads n bytes from stream and puts them into an array of length n and type unsigned-byte 8" (declare (optimize (speed 3)(safety 0)) (type fixnum n) (type stream stream)) (let ((data (the byte-array (make-array n :element-type 'u-byte)))) (declare (type byte-array data)) (dotimes (i n (the byte-array data)) (declare (type fixnum i) (type fixnum n)) (the u-byte (setf (aref data i) (the u-byte (timed-non-block-read-byte stream)))))))