mmapped_buffer.h revision c0c674cdc0721a374e140ad5ee1409c0498b3262
1/*
2 * Copyright (C) 2013, 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
17#ifndef LATINIME_MMAPPED_BUFFER_H
18#define LATINIME_MMAPPED_BUFFER_H
19
20#include <cstdint>
21#include <memory>
22
23#include "defines.h"
24#include "utils/byte_array_view.h"
25
26namespace latinime {
27
28class MmappedBuffer {
29 public:
30    typedef std::unique_ptr<const MmappedBuffer> MmappedBufferPtr;
31
32    static MmappedBufferPtr openBuffer(const char *const path,
33            const int bufferOffset, const int bufferSize, const bool isUpdatable);
34
35    // Mmap entire file.
36    static MmappedBufferPtr openBuffer(const char *const path, const bool isUpdatable);
37
38    static MmappedBufferPtr openBuffer(const char *const dirPath, const char *const fileName,
39            const bool isUpdatable);
40
41    ~MmappedBuffer();
42
43    ReadWriteByteArrayView getReadWriteByteArrayView() const {
44        return mByteArrayView;
45    }
46
47    ReadOnlyByteArrayView getReadOnlyByteArrayView() const {
48        return mByteArrayView.getReadOnlyView();
49    }
50
51    AK_FORCE_INLINE bool isUpdatable() const {
52        return mIsUpdatable;
53    }
54
55 private:
56    AK_FORCE_INLINE MmappedBuffer(uint8_t *const buffer, const int bufferSize,
57            void *const mmappedBuffer, const int alignedSize, const int mmapFd,
58            const bool isUpdatable)
59            : mByteArrayView(buffer, bufferSize), mMmappedBuffer(mmappedBuffer),
60              mAlignedSize(alignedSize), mMmapFd(mmapFd), mIsUpdatable(isUpdatable) {}
61
62    // Empty file. We have to handle an empty file as a valid part of a dictionary.
63    AK_FORCE_INLINE MmappedBuffer(const bool isUpdatable)
64            : mByteArrayView(), mMmappedBuffer(nullptr), mAlignedSize(0),
65              mMmapFd(0), mIsUpdatable(isUpdatable) {}
66
67    DISALLOW_IMPLICIT_CONSTRUCTORS(MmappedBuffer);
68
69    const ReadWriteByteArrayView mByteArrayView;
70    void *const mMmappedBuffer;
71    const int mAlignedSize;
72    const int mMmapFd;
73    const bool mIsUpdatable;
74};
75}
76#endif /* LATINIME_MMAPPED_BUFFER_H */
77