Debian Codegraph @

tools/swig/test/Array1.cxx

raw
1 #include "Array1.h"
2 #include <iostream>
3 #include <sstream>
4
5 // Default/length/array constructor
6 Array1::Array1(int length, long* data) :
7 _ownData(false), _length(0), _buffer(0)
8 {
9 resize(length, data);
10 }
11
12 // Copy constructor
13 Array1::Array1(const Array1 & source) :
14 _length(source._length)
15 {
16 allocateMemory();
17 *this = source;
18 }
19
20 // Destructor
21 Array1::~Array1()
22 {
23 deallocateMemory();
24 }
25
26 // Assignment operator
27 Array1 & Array1::operator=(const Array1 & 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
38 bool Array1::operator==(const Array1 & 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
49 int Array1::length() const
50 {
51 return _length;
52 }
53
54 // Resize array
55 void Array1::resize(int length, long* data)
56 {
57 if (length < 0) throw std::invalid_argument("Array1 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
73 long & Array1::operator[](int i)
74 {
75 if (i < 0 || i >= _length) throw std::out_of_range("Array1 index out of range");
76 return _buffer[i];
77 }
78
79 // Get item accessor
80 const long & Array1::operator[](int i) const
81 {
82 if (i < 0 || i >= _length) throw std::out_of_range("Array1 index out of range");
83 return _buffer[i];
84 }
85
86 // String output
87 std::string Array1::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
101 void Array1::view(long** data, int* length) const
102 {
103 *data = _buffer;
104 *length = _length;
105 }
106
107 // Private methods
108 void Array1::allocateMemory()
109 {
110 if (_length == 0)
111 {
112 _ownData = false;
113 _buffer = 0;
114 }
115 else
116 {
117 _ownData = true;
118 _buffer = new long[_length];
119 }
120 }
121
122 void Array1::deallocateMemory()
123 {
124 if (_ownData && _length && _buffer)
125 {
126 delete [] _buffer;
127 }
128 _ownData = false;
129 _length = 0;
130 _buffer = 0;
131 }