1 /* 2 * Copyright 2022 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * 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 package com.google.android.libraries.mobiledatadownload.file.openers; 17 18 import com.google.android.libraries.mobiledatadownload.file.OpenContext; 19 import com.google.android.libraries.mobiledatadownload.file.Opener; 20 import com.google.android.libraries.mobiledatadownload.file.common.FileChannelConvertible; 21 import com.google.android.libraries.mobiledatadownload.file.common.UnsupportedFileStorageOperation; 22 import java.io.IOException; 23 import java.io.InputStream; 24 import java.nio.MappedByteBuffer; 25 import java.nio.channels.FileChannel; 26 import java.nio.channels.FileChannel.MapMode; 27 28 /** 29 * Opener that maps a file directly into memory (read only). 30 * 31 * <p>Warning: MappedByteBuffer is known to suffer from poor garbage collection; see {@link 32 * <internal>}. 33 * 34 * <p>Usage: <code> 35 * MappedByteBuffer buffer = storage.open(uri, MappedByteBufferOpener.create()); 36 * </code> 37 */ 38 public final class MappedByteBufferOpener implements Opener<MappedByteBuffer> { 39 MappedByteBufferOpener()40 private MappedByteBufferOpener() {} 41 createForRead()42 public static MappedByteBufferOpener createForRead() { 43 return new MappedByteBufferOpener(); 44 } 45 46 @Override open(OpenContext openContext)47 public MappedByteBuffer open(OpenContext openContext) throws IOException { 48 // FileChannelConvertible (vs ReadFileOpener) allows this opener to be used over IPC. 49 try (InputStream stream = ReadStreamOpener.create().open(openContext)) { 50 if (stream instanceof FileChannelConvertible) { 51 FileChannel fileChannel = ((FileChannelConvertible) stream).toFileChannel(); 52 return fileChannel.map(MapMode.READ_ONLY, 0, fileChannel.size()); 53 } 54 throw new UnsupportedFileStorageOperation( 55 "URI not convertible to FileChannel for mapping: " + openContext.originalUri()); 56 } 57 } 58 } 59