src/java.base/share/classes/sun/nio/ch/Util.java
changeset 47428 d72d7d55c765
parent 47216 71c04702a3d5
child 50719 106dc156ce6b
--- a/src/java.base/share/classes/sun/nio/ch/Util.java	Fri Oct 20 11:08:18 2017 -0700
+++ b/src/java.base/share/classes/sun/nio/ch/Util.java	Tue Oct 17 16:51:11 2017 -0700
@@ -37,7 +37,7 @@
 import java.util.Set;
 import jdk.internal.misc.Unsafe;
 import sun.security.action.GetPropertyAction;
-
+import java.io.IOException;
 
 public class Util {
 
@@ -237,6 +237,33 @@
     }
 
     /**
+     * Returns a temporary buffer of at least the given size and
+     * aligned to the alignment
+     */
+    public static ByteBuffer getTemporaryAlignedDirectBuffer(int size,
+                                                             int alignment) {
+        if (isBufferTooLarge(size)) {
+            return ByteBuffer.allocateDirect(size + alignment - 1)
+                    .alignedSlice(alignment);
+        }
+
+        BufferCache cache = bufferCache.get();
+        ByteBuffer buf = cache.get(size);
+        if (buf != null) {
+            if (buf.alignmentOffset(0, alignment) == 0) {
+                return buf;
+            }
+        } else {
+            if (!cache.isEmpty()) {
+                buf = cache.removeFirst();
+                free(buf);
+            }
+        }
+        return ByteBuffer.allocateDirect(size + alignment - 1)
+                .alignedSlice(alignment);
+    }
+
+    /**
      * Releases a temporary buffer by returning to the cache or freeing it.
      */
     public static void releaseTemporaryDirectBuffer(ByteBuffer buf) {
@@ -459,4 +486,37 @@
         }
         return dbb;
     }
+
+    static void checkBufferPositionAligned(ByteBuffer bb,
+                                                     int pos, int alignment)
+        throws IOException
+    {
+        if (bb.alignmentOffset(pos, alignment) != 0) {
+            throw new IOException("Current location of the bytebuffer ("
+                + pos + ") is not a multiple of the block size ("
+                + alignment + ")");
+        }
+    }
+
+    static void checkRemainingBufferSizeAligned(int rem,
+                                                          int alignment)
+        throws IOException
+    {
+        if (rem % alignment != 0) {
+            throw new IOException("Number of remaining bytes ("
+                + rem + ") is not a multiple of the block size ("
+                + alignment + ")");
+        }
+    }
+
+    static void checkChannelPositionAligned(long position,
+                                                      int alignment)
+        throws IOException
+    {
+        if (position % alignment != 0) {
+           throw new IOException("Channel position (" + position
+               + ") is not a multiple of the block size ("
+               + alignment + ")");
+        }
+    }
 }