ctf: Provide a utility for "safe" mapping of a ByteBuffer
[deliverable/tracecompass.git] / org.eclipse.linuxtools.ctf.core / src / org / eclipse / linuxtools / internal / ctf / core / SafeMappedByteBuffer.java
1 /*******************************************************************************
2 * Copyright (c) 2014 Ericsson
3 *
4 * All rights reserved. This program and the accompanying materials are made
5 * available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Marc-Andre Laperle - Initial API and implementation
11 *******************************************************************************/
12
13 package org.eclipse.linuxtools.internal.ctf.core;
14
15 import java.io.IOException;
16 import java.nio.ByteBuffer;
17 import java.nio.channels.FileChannel;
18
19 import org.eclipse.core.runtime.Platform;
20
21 /**
22 * A common utility for mapping a ByteBuffer safely to work around a bug on
23 * Windows which prevents deleting a file after it was mapped. On Windows, the
24 * ByteBuffer will be allocated and the file will be read instead of being
25 * mapped.
26 *
27 * http://bugs.java.com/view_bug.do?bug_id=4715154
28 */
29 public class SafeMappedByteBuffer {
30
31 private static final boolean IS_WIN32 = Platform.OS_WIN32.equals(Platform.getOS());
32
33 /**
34 * Maps a region of this channel's file directly into memory. On Windows,
35 * this will allocate a new ByteBuffer and read the file.
36 *
37 * @param fc
38 * the file channel
39 * @param mode
40 * the mapping mode
41 * @param position
42 * the position within the file
43 * @param size
44 * the size of the region to be mapped (or read)
45 * @return the mapped ByteBuffer
46 * @throws IOException
47 * on FileChannel operations failures
48 */
49 public static ByteBuffer map(FileChannel fc, FileChannel.MapMode mode, long position, long size) throws IOException {
50 ByteBuffer byteBuffer;
51 if (IS_WIN32) {
52 byteBuffer = ByteBuffer.allocate((int) size);
53 fc.read(byteBuffer, position);
54 } else {
55 byteBuffer = fc.map(mode, position, size);
56 }
57
58 return byteBuffer;
59 }
60 }
This page took 0.051277 seconds and 6 git commands to generate.