Github user srowen commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15408#discussion_r82737052
  
    --- Diff: 
core/src/main/java/org/apache/spark/io/NioBufferedFileInputStream.java ---
    @@ -0,0 +1,129 @@
    +/*
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +package org.apache.spark.io;
    +
    +import org.apache.spark.storage.StorageUtils;
    +
    +import java.io.File;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.nio.ByteBuffer;
    +import java.nio.channels.FileChannel;
    +import java.nio.file.StandardOpenOption;
    +
    +/**
    + * {@link InputStream} implementation which uses direct buffer
    + * to read a file to avoid extra copy of data between Java and
    + * native memory which happens when using {@link 
java.io.BufferedInputStream}.
    + * Unfortunately, this is not something already available in JDK,
    + * {@link sun.nio.ch.ChannelInputStream} supports reading a file using nio,
    + * but does not support buffering.
    + *
    + * TODO: support {@link #mark(int)}/{@link #reset()}
    + *
    + */
    +public final class NioBufferedFileInputStream extends InputStream {
    +
    +  private static int DEFAULT_BUFFER_SIZE_BYTES = 8192;
    +
    +  private final ByteBuffer byteBuffer;
    +
    +  private final FileChannel fileChannel;
    +
    +  public NioBufferedFileInputStream(File file, int bufferSizeInBytes) 
throws IOException {
    +    byteBuffer = ByteBuffer.allocateDirect(bufferSizeInBytes);
    +    fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.READ);
    +    byteBuffer.flip();
    +  }
    +
    +  public NioBufferedFileInputStream(File file) throws IOException {
    +    this(file, DEFAULT_BUFFER_SIZE_BYTES);
    +  }
    +
    +  /**
    +   * Checks weather data is left to be read from the input stream.
    +   * @return true if data is left, false otherwise
    +   * @throws IOException
    +   */
    +  private boolean refill() throws IOException {
    +    if (!byteBuffer.hasRemaining()) {
    +      byteBuffer.clear();
    +      int nRead = fileChannel.read(byteBuffer);
    +      if (nRead <= 0) {
    --- End diff --
    
    It could be 0 forever though (dunno, FS error?) and then this creates an 
infinite loop. I went hunting through the SDK for some examples of dealing with 
this, because this has always been a tricky part of even `InputStream`.
    
    `java.nio.Files`:
    
    ```
        private static long copy(InputStream source, OutputStream sink)
            throws IOException
        {
            long nread = 0L;
            byte[] buf = new byte[BUFFER_SIZE];
            int n;
            while ((n = source.read(buf)) > 0) {
                sink.write(buf, 0, n);
                nread += n;
            }
            return nread;
        }
    
    ...
    
        private static byte[] read(InputStream source, int initialSize) throws 
IOException {
            int capacity = initialSize;
            byte[] buf = new byte[capacity];
            int nread = 0;
            int n;
            for (;;) {
                // read to EOF which may read more or less than initialSize 
(eg: file
                // is truncated while we are reading)
                while ((n = source.read(buf, nread, capacity - nread)) > 0)
                    nread += n;
    
                // if last call to source.read() returned -1, we are done
                // otherwise, try to read one more byte; if that failed we're 
done too
                if (n < 0 || (n = source.read()) < 0)
                    break;
    
                // one more byte was read; need to allocate a larger buffer
                if (capacity <= MAX_BUFFER_SIZE - capacity) {
                    capacity = Math.max(capacity << 1, BUFFER_SIZE);
                } else {
                    if (capacity == MAX_BUFFER_SIZE)
                        throw new OutOfMemoryError("Required array size too 
large");
                    capacity = MAX_BUFFER_SIZE;
                }
                buf = Arrays.copyOf(buf, capacity);
                buf[nread++] = (byte)n;
            }
            return (capacity == nread) ? buf : Arrays.copyOf(buf, nread);
        }
    ```
    
    The first instance seems to assume that 0 bytes means it should stop.
    In the second instance it forces the `InputStream` to give a definitive 
answer by trying to read just 1 byte. That isn't available with `FileChannel` 
though, unfortunately.
    
    Now `com.google.common.io.ByteStreams`:
    
    ```
      public static long copy(InputStream from, OutputStream to)
          throws IOException {
        checkNotNull(from);
        checkNotNull(to);
        byte[] buf = new byte[BUF_SIZE];
        long total = 0;
        while (true) {
          int r = from.read(buf);
          if (r == -1) {
            break;
          }
          to.write(buf, 0, r);
          total += r;
        }
        return total;
      }
    
      public static int read(InputStream in, byte[] b, int off, int len)
          throws IOException {
        checkNotNull(in);
        checkNotNull(b);
        if (len < 0) {
          throw new IndexOutOfBoundsException("len is negative");
        }
        int total = 0;
        while (total < len) {
          int result = in.read(b, off + total, len - total);
          if (result == -1) {
            break;
          }
          total += result;
        }
        return total;
      }
    ```
    
    Guava will only stop when it sees -1.
    
    Aside from the JDK copy method, all of these do _not_ think that 0 means 
reading can stop. I'd change my answer then, yes, to reading in a loop until -1 
is observed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastruct...@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org
For additional commands, e-mail: reviews-h...@spark.apache.org

Reply via email to