1/* -*- c-basic-offset: 2 -*- */
2/*
3 Copyright(C) 2011-2016 Brazil
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License version 2.1 as published by the Free Software Foundation.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17*/
18
19#pragma once
20
21#include "dat.hpp"
22
23namespace grn {
24namespace dat {
25
26// This class is used to detect an out-of-range access in debug mode.
27template <typename T>
28class GRN_DAT_API Array {
29 public:
30 Array() : ptr_(NULL), size_(0) {}
31 Array(void *ptr, UInt32 size) : ptr_(static_cast<T *>(ptr)), size_(size) {
32 GRN_DAT_DEBUG_THROW_IF((ptr == NULL) && (size != 0));
33 }
34 template <UInt32 U>
35 explicit Array(T (&array)[U]) : ptr_(array), size_(U) {}
36 ~Array() {}
37
38 const T &operator[](UInt32 i) const {
39 GRN_DAT_DEBUG_THROW_IF(i >= size_);
40 return ptr_[i];
41 }
42 T &operator[](UInt32 i) {
43 GRN_DAT_DEBUG_THROW_IF(i >= size_);
44 return ptr_[i];
45 }
46
47 const T *begin() const {
48 return ptr();
49 }
50 T *begin() {
51 return ptr();
52 }
53
54 const T *end() const {
55 return ptr() + size();
56 }
57 T *end() {
58 return ptr() + size();
59 }
60
61 void assign(void *ptr, UInt32 size) {
62 GRN_DAT_DEBUG_THROW_IF((ptr == NULL) && (size != 0));
63 ptr_ = static_cast<T *>(ptr);
64 size_ = size;
65 }
66 template <UInt32 U>
67 void assign(T (&array)[U]) {
68 assign(array, U);
69 }
70
71 void swap(Array *rhs) {
72 T * const temp_ptr = ptr_;
73 ptr_ = rhs->ptr_;
74 rhs->ptr_ = temp_ptr;
75
76 const UInt32 temp_size = size_;
77 size_ = rhs->size_;
78 rhs->size_ = temp_size;
79 }
80
81 T *ptr() const {
82 return ptr_;
83 }
84 UInt32 size() const {
85 return size_;
86 }
87
88 private:
89 T *ptr_;
90 UInt32 size_;
91
92 // Disallows copy and assignment.
93 Array(const Array &);
94 Array &operator=(const Array &);
95};
96
97} // namespace dat
98} // namespace grn
99