1/*
2 * Copyright (C) 2011 The Android Open Source Project
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
17package com.android.inputmethod.latin;
18
19import com.android.inputmethod.latin.common.FileUtils;
20
21import java.io.File;
22
23/**
24 * Immutable class to hold the address of an asset.
25 * As opposed to a normal file, an asset is usually represented as a contiguous byte array in
26 * the package file. Open it correctly thus requires the name of the package it is in, but
27 * also the offset in the file and the length of this data. This class encapsulates these three.
28 */
29public final class AssetFileAddress {
30    public final String mFilename;
31    public final long mOffset;
32    public final long mLength;
33
34    public AssetFileAddress(final String filename, final long offset, final long length) {
35        mFilename = filename;
36        mOffset = offset;
37        mLength = length;
38    }
39
40    public static AssetFileAddress makeFromFile(final File file) {
41        if (!file.isFile()) return null;
42        return new AssetFileAddress(file.getAbsolutePath(), 0L, file.length());
43    }
44
45    public static AssetFileAddress makeFromFileName(final String filename) {
46        if (null == filename) return null;
47        return makeFromFile(new File(filename));
48    }
49
50    public static AssetFileAddress makeFromFileNameAndOffset(final String filename,
51            final long offset, final long length) {
52        if (null == filename) return null;
53        final File f = new File(filename);
54        if (!f.isFile()) return null;
55        return new AssetFileAddress(filename, offset, length);
56    }
57
58    public boolean pointsToPhysicalFile() {
59        return 0 == mOffset;
60    }
61
62    public void deleteUnderlyingFile() {
63        FileUtils.deleteRecursively(new File(mFilename));
64    }
65
66    @Override
67    public String toString() {
68        return String.format("%s (offset=%d, length=%d)", mFilename, mOffset, mLength);
69    }
70}
71