1 // Copyright 2016 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #pragma once
6 
7 #include <zircon/assert.h>
8 #include <fbl/macros.h>
9 
10 namespace fbl {
11 
12 template <typename T>
13 class Array {
14 public:
Array()15     constexpr Array() : ptr_(nullptr), count_(0U) {}
Array(decltype (nullptr))16     constexpr Array(decltype(nullptr)) : Array() {}
17 
Array(T * array,size_t count)18     Array(T* array, size_t count) : ptr_(array), count_(count) {}
19 
Array(Array && other)20     Array(Array&& other) : ptr_(nullptr), count_(other.count_) {
21         ptr_ = other.release();
22     }
23 
size()24     size_t size() const {
25         return count_;
26     }
27 
~Array()28     ~Array() {
29         reset();
30     }
31 
32     Array& operator=(Array&& o) {
33         auto count = o.count_;
34         reset(o.release(), count);
35         return *this;
36     }
37 
38     // move semantics only
39     DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(Array);
40 
release()41     T* release() {
42         T* t = ptr_;
43         ptr_ = nullptr;
44         count_ = 0;
45         return t;
46     }
47 
reset()48     void reset() {
49         reset(nullptr, 0U);
50     }
51 
reset(T * t,size_t count)52     void reset(T* t, size_t count) {
53         T* ptr = ptr_;
54         ptr_ = t;
55         count_ = count;
56         delete[] ptr;
57     }
58 
swap(Array & other)59     void swap(Array& other) {
60         T* t = ptr_;
61         ptr_ = other.ptr_;
62         other.ptr_ = t;
63         size_t c = count_;
64         count_ = other.count_;
65         other.count_ = c;
66     }
67 
get()68     T* get() const {
69         return ptr_;
70     }
71 
72     explicit operator bool() const {
73         return static_cast<bool>(ptr_);
74     }
75 
76     T& operator[](size_t i) const {
77         ZX_DEBUG_ASSERT(i < count_);
78         return ptr_[i];
79     }
80 
begin()81     T* begin() const {
82         return ptr_;
83     }
84 
end()85     T* end() const {
86         return &ptr_[count_];
87     }
88 
89 private:
90     T* ptr_;
91     size_t count_;
92 };
93 
94 }  // namespace fbl
95