我在clojure.java.io/copy函数的实现中发现了奇怪的行为
https://github.com/clojure/clojure/blob/ee1b606ad066ac8df2efd4a6b8d0d365c206f5bf/src/clj/clojure/java/io.clj#L391
(defn copy
"Copies input to output. Returns nil or throws IOException.
Input may be an InputStream, Reader, File, byte[], char[], or String.
Output may be an OutputStream, Writer, or File.
Options are key/value pairs and may be one of
:buffer-size buffer size to use, default is 1024.
:encoding encoding to use if converting between
byte and char streams.
Does not close any streams except those it opens itself
(on a File)."
{:added "1.2"}
[input output & opts]
(do-copy input output (when opts (apply hash-map opts))))
实际的复制在这里实现,当从InputStream复制到OutputStream时。
https://github.com/clojure/clojure/blob/ee1b606ad066ac8df2efd4a6b8d0d365c206f5bf/src/clj/clojure/java/io.clj#L306
(defmethod do-copy [InputStream OutputStream] [^InputStream input ^OutputStream output opts]
(let [buffer (make-array Byte/TYPE (buffer-size opts))]
(loop []
(let [size (.read input buffer)] ;;; XXX point 1
(when (pos? size) ;;; XXX point 2
(do (.write output buffer 0 size)
(recur)))))))
这是点1处的.read函数https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read(byte[])
Java文档中声明如下
从输入流中读取一些字节数并将它们存储到缓冲区数组b中。实际读取的字节数作为一个整数返回。该方法在输入数据可用、检测到文件尾或抛出异常时阻塞。
如果b的长度为零,则不读取任何字节数,并返回0;否则,尝试读取至少一个字节。如果因为流位于文件末尾而没有字节可用,则返回-1;否则,至少读取一个字节并将其存储到b中。
这意味着返回值-1意味着流结束,而返回值0不代表流结束。然而,在上述代码的点2中,当.read返回小于1的值时,停止递归。
现在考虑这样一个情况,.read在连续调用中返回以下序列值
1024, 0, 1024, 201, -1
clojure.java/io仅在流有2249字节时复制了前1024字节。这是预期行为吗?点1的条件应该不是(not (neg? size))
吗?
我还在google groups上发起了这个问题的讨论:https://groups.google.com/forum/#!topic/clojure/XzpPPXXhgM4