import "Stream" importJava "java.io.InputStream" where """Reads bytes from the stream to a mutable vector. The maximum number of bytes read is the dimension of the vector. Returns the actual number of bytes read or -1, if the stream has finished.""" @JavaName read readBytesM :: InputStream -> MVector Byte -> Integer """Reads a range of bytes from the stream to a mutable vector. The first integer is the offset the second integer is the maximum length of the range. Returns the actual number of bytes read or -1, if the stream has finished.""" @JavaName read readRangeOfBytesM :: InputStream -> MVector Byte -> Integer -> Integer -> Integer """Reads bytes from the stream. The integer parameter is the maximum number of bytes. Returns Nothing if stream has finished or a vector of bytes read.""" readBytes :: InputStream -> Integer -> Maybe (Vector Byte) readBytes stream length = if count == (-1) then Nothing else if count == length then Just (freezeMVector result) else Just (take count (freezeMVector result)) where result = createMVector length count = readBytesM stream result importJava "java.io.OutputStream" where """Writes given vector of bytes to output stream.""" @JavaName write writeBytes :: OutputStream -> Vector Byte -> () @JavaName write writeBytesM :: OutputStream -> MVector Byte -> () """Writes a range of bytes from the vector to output stream. The first integer is the offset the second integer is the length of the range.""" @JavaName write writeRangeOfBytes :: OutputStream -> Vector Byte -> Integer -> Integer -> () @JavaName write writeRangeOfBytesM :: OutputStream -> MVector Byte -> Integer -> Integer -> () """Copy all available bytes from output stream to input stream.""" copyAllBytes :: OutputStream -> InputStream -> () copyAllBytes output input = loop () where buffer = createMVector 4096 loop () = let count = readBytesM input buffer in if count == (-1) then () else do writeRangeOfBytesM output buffer 0 count loop ()