1/* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements.  See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License.  You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package java.nio;
18
19import java.io.Closeable;
20import java.io.FileDescriptor;
21import java.io.IOException;
22import java.nio.channels.ClosedChannelException;
23import java.nio.channels.FileChannel;
24import java.util.Set;
25
26import static android.system.OsConstants.*;
27import sun.misc.Cleaner;
28import sun.nio.ch.DirectBuffer;
29import sun.nio.ch.FileChannelImpl;
30
31/**
32 * @hide internal use only
33 */
34public final class NioUtils {
35    private NioUtils() {
36    }
37
38    public static void freeDirectBuffer(ByteBuffer buffer) {
39        if (buffer == null) {
40            return;
41        }
42
43        DirectByteBuffer dbb = (DirectByteBuffer) buffer;
44        // Run the cleaner early, if one is defined.
45        if (dbb.cleaner != null) {
46            dbb.cleaner.clean();
47        }
48
49        dbb.memoryRef.free();
50    }
51
52    /**
53     * Returns the int file descriptor from within the given FileChannel 'fc'.
54     */
55    public static FileDescriptor getFD(FileChannel fc) {
56        return ((FileChannelImpl) fc).fd;
57    }
58
59    /**
60     * Helps bridge between io and nio.
61     */
62    public static FileChannel newFileChannel(Closeable ioObject, FileDescriptor fd, int mode) {
63        boolean readable = (mode & (O_RDONLY | O_RDWR | O_SYNC)) != 0;
64        boolean writable = (mode & (O_WRONLY | O_RDWR | O_SYNC)) != 0;
65        boolean append = (mode & O_APPEND) != 0;
66        return FileChannelImpl.open(fd, null, readable, writable, append, ioObject);
67    }
68
69    /**
70     * Exposes the array backing a non-direct ByteBuffer, even if the ByteBuffer is read-only.
71     * Normally, attempting to access the array backing a read-only buffer throws.
72     */
73    public static byte[] unsafeArray(ByteBuffer b) {
74        return b.array();
75    }
76
77    /**
78     * Exposes the array offset for the array backing a non-direct ByteBuffer,
79     * even if the ByteBuffer is read-only.
80     */
81    public static int unsafeArrayOffset(ByteBuffer b) {
82        return b.arrayOffset();
83    }
84}
85