int_array_view.h revision 03dc44f543795040a092723085fac1209103b7bd
1/*
2 * Copyright (C) 2014 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_INT_ARRAY_VIEW_H
18#define LATINIME_INT_ARRAY_VIEW_H
19
20#include <cstdint>
21#include <cstdlib>
22#include <vector>
23
24#include "defines.h"
25
26namespace latinime {
27
28/**
29 * Helper class used to provide a read-only view of a given range of integer array. This class
30 * does not take ownership of the underlying integer array but is designed to be a lightweight
31 * object that obeys value semantics.
32 *
33 * Example:
34 * <code>
35 * bool constinsX(IntArrayView view) {
36 *     for (size_t i = 0; i < view.size(); ++i) {
37 *         if (view[i] == 'X') {
38 *             return true;
39 *         }
40 *     }
41 *     return false;
42 * }
43 *
44 * const int codePointArray[] = { 'A', 'B', 'X', 'Z' };
45 * auto view = IntArrayView(codePointArray, NELEMS(codePointArray));
46 * const bool hasX = constinsX(view);
47 * </code>
48 */
49class IntArrayView {
50 public:
51    IntArrayView() : mPtr(nullptr), mSize(0) {}
52
53    IntArrayView(const int *const ptr, const size_t size)
54            : mPtr(ptr), mSize(size) {}
55
56    explicit IntArrayView(const std::vector<int> &vector)
57            : mPtr(vector.data()), mSize(vector.size()) {}
58
59    AK_FORCE_INLINE int operator[](const size_t index) const {
60        ASSERT(index < mSize);
61        return mPtr[index];
62    }
63
64    AK_FORCE_INLINE bool empty() const {
65        return size() == 0;
66    }
67
68    AK_FORCE_INLINE size_t size() const {
69        return mSize;
70    }
71
72    AK_FORCE_INLINE const int *data() const {
73        return mPtr;
74    }
75
76    AK_FORCE_INLINE const int *begin() const {
77        return mPtr;
78    }
79
80    AK_FORCE_INLINE const int *end() const {
81        return mPtr + mSize;
82    }
83
84 private:
85    DISALLOW_ASSIGNMENT_OPERATOR(IntArrayView);
86
87    const int *const mPtr;
88    const size_t mSize;
89};
90
91using WordIdArrayView = IntArrayView;
92
93} // namespace latinime
94#endif // LATINIME_MEMORY_VIEW_H
95