1 #include "ArrayZ.h"
2 #include <iostream>
3 #include <sstream>
4
5 // Default/length/array constructor
ArrayZ(int length,std::complex<double> * data)6 ArrayZ::ArrayZ(int length, std::complex<double>* data) :
7 _ownData(false), _length(0), _buffer(0)
8 {
9 resize(length, data);
10 }
11
12 // Copy constructor
ArrayZ(const ArrayZ & source)13 ArrayZ::ArrayZ(const ArrayZ & source) :
14 _length(source._length)
15 {
16 allocateMemory();
17 *this = source;
18 }
19
20 // Destructor
~ArrayZ()21 ArrayZ::~ArrayZ()
22 {
23 deallocateMemory();
24 }
25
26 // Assignment operator
operator =(const ArrayZ & source)27 ArrayZ & ArrayZ::operator=(const ArrayZ & source)
28 {
29 int len = _length < source._length ? _length : source._length;
30 for (int i=0; i < len; ++i)
31 {
32 (*this)[i] = source[i];
33 }
34 return *this;
35 }
36
37 // Equals operator
operator ==(const ArrayZ & other) const38 bool ArrayZ::operator==(const ArrayZ & other) const
39 {
40 if (_length != other._length) return false;
41 for (int i=0; i < _length; ++i)
42 {
43 if ((*this)[i] != other[i]) return false;
44 }
45 return true;
46 }
47
48 // Length accessor
length() const49 int ArrayZ::length() const
50 {
51 return _length;
52 }
53
54 // Resize array
resize(int length,std::complex<double> * data)55 void ArrayZ::resize(int length, std::complex<double>* data)
56 {
57 if (length < 0) throw std::invalid_argument("ArrayZ length less than 0");
58 if (length == _length) return;
59 deallocateMemory();
60 _length = length;
61 if (!data)
62 {
63 allocateMemory();
64 }
65 else
66 {
67 _ownData = false;
68 _buffer = data;
69 }
70 }
71
72 // Set item accessor
operator [](int i)73 std::complex<double> & ArrayZ::operator[](int i)
74 {
75 if (i < 0 || i >= _length) throw std::out_of_range("ArrayZ index out of range");
76 return _buffer[i];
77 }
78
79 // Get item accessor
operator [](int i) const80 const std::complex<double> & ArrayZ::operator[](int i) const
81 {
82 if (i < 0 || i >= _length) throw std::out_of_range("ArrayZ index out of range");
83 return _buffer[i];
84 }
85
86 // String output
asString() const87 std::string ArrayZ::asString() const
88 {
89 std::stringstream result;
90 result << "[";
91 for (int i=0; i < _length; ++i)
92 {
93 result << " " << _buffer[i];
94 if (i < _length-1) result << ",";
95 }
96 result << " ]";
97 return result.str();
98 }
99
100 // Get view
view(std::complex<double> ** data,int * length) const101 void ArrayZ::view(std::complex<double>** data, int* length) const
102 {
103 *data = _buffer;
104 *length = _length;
105 }
106
107 // Private methods
allocateMemory()108 void ArrayZ::allocateMemory()
109 {
110 if (_length == 0)
111 {
112 _ownData = false;
113 _buffer = 0;
114 }
115 else
116 {
117 _ownData = true;
118 _buffer = new std::complex<double>[_length];
119 }
120 }
121
deallocateMemory()122 void ArrayZ::deallocateMemory()
123 {
124 if (_ownData && _length && _buffer)
125 {
126 delete [] _buffer;
127 }
128 _ownData = false;
129 _length = 0;
130 _buffer = 0;
131 }
132