Commit | Line | Data |
---|---|---|
f4a474e3 MAL |
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 | ||
f357bcd4 | 13 | package org.eclipse.tracecompass.internal.ctf.core; |
f4a474e3 MAL |
14 | |
15 | import java.io.IOException; | |
16 | import java.nio.ByteBuffer; | |
17 | import java.nio.channels.FileChannel; | |
18 | ||
f4a474e3 MAL |
19 | /** |
20 | * A common utility for mapping a ByteBuffer safely to work around a bug on | |
21 | * Windows which prevents deleting a file after it was mapped. On Windows, the | |
22 | * ByteBuffer will be allocated and the file will be read instead of being | |
23 | * mapped. | |
24 | * | |
25 | * http://bugs.java.com/view_bug.do?bug_id=4715154 | |
26 | */ | |
27 | public class SafeMappedByteBuffer { | |
28 | ||
882c5741 | 29 | private static final boolean IS_WIN32 = System.getProperty("os.name").startsWith("Windows"); //$NON-NLS-1$//$NON-NLS-2$ |
f4a474e3 | 30 | |
f068c622 MK |
31 | private SafeMappedByteBuffer(){} |
32 | ||
f4a474e3 MAL |
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); | |
b8db4083 | 54 | byteBuffer.flip(); |
f4a474e3 MAL |
55 | } else { |
56 | byteBuffer = fc.map(mode, position, size); | |
57 | } | |
58 | ||
59 | return byteBuffer; | |
60 | } | |
61 | } |