Debian Codegraph @

tools/swig/test/Farray.cxx

raw
1 #include "Farray.h"
2 #include <sstream>
3
4 // Size constructor
5 Farray::Farray(int nrows, int ncols) :
6 _nrows(nrows), _ncols(ncols), _buffer(0)
7 {
8 allocateMemory();
9 }
10
11 // Copy constructor
12 Farray::Farray(const Farray & source) :
13 _nrows(source._nrows), _ncols(source._ncols)
14 {
15 allocateMemory();
16 *this = source;
17 }
18
19 // Destructor
20 Farray::~Farray()
21 {
22 delete [] _buffer;
23 }
24
25 // Assignment operator
26 Farray & Farray::operator=(const Farray & source)
27 {
28 int nrows = _nrows < source._nrows ? _nrows : source._nrows;
29 int ncols = _ncols < source._ncols ? _ncols : source._ncols;
30 for (int i=0; i < nrows; ++i)
31 {
32 for (int j=0; j < ncols; ++j)
33 {
34 (*this)(i,j) = source(i,j);
35 }
36 }
37 return *this;
38 }
39
40 // Equals operator
41 bool Farray::operator==(const Farray & other) const
42 {
43 if (_nrows != other._nrows) return false;
44 if (_ncols != other._ncols) return false;
45 for (int i=0; i < _nrows; ++i)
46 {
47 for (int j=0; j < _ncols; ++j)
48 {
49 if ((*this)(i,j) != other(i,j)) return false;
50 }
51 }
52 return true;
53 }
54
55 // Length accessors
56 int Farray::nrows() const
57 {
58 return _nrows;
59 }
60
61 int Farray::ncols() const
62 {
63 return _ncols;
64 }
65
66 // Set item accessor
67 long & Farray::operator()(int i, int j)
68 {
69 if (i < 0 || i > _nrows) throw std::out_of_range("Farray row index out of range");
70 if (j < 0 || j > _ncols) throw std::out_of_range("Farray col index out of range");
71 return _buffer[offset(i,j)];
72 }
73
74 // Get item accessor
75 const long & Farray::operator()(int i, int j) const
76 {
77 if (i < 0 || i > _nrows) throw std::out_of_range("Farray row index out of range");
78 if (j < 0 || j > _ncols) throw std::out_of_range("Farray col index out of range");
79 return _buffer[offset(i,j)];
80 }
81
82 // String output
83 std::string Farray::asString() const
84 {
85 std::stringstream result;
86 result << "[ ";
87 for (int i=0; i < _nrows; ++i)
88 {
89 if (i > 0) result << " ";
90 result << "[";
91 for (int j=0; j < _ncols; ++j)
92 {
93 result << " " << (*this)(i,j);
94 if (j < _ncols-1) result << ",";
95 }
96 result << " ]";
97 if (i < _nrows-1) result << "," << std::endl;
98 }
99 result << " ]" << std::endl;
100 return result.str();
101 }
102
103 // Get view
104 void Farray::view(int* nrows, int* ncols, long** data) const
105 {
106 *nrows = _nrows;
107 *ncols = _ncols;
108 *data = _buffer;
109 }
110
111 // Private methods
112 void Farray::allocateMemory()
113 {
114 if (_nrows <= 0) throw std::invalid_argument("Farray nrows <= 0");
115 if (_ncols <= 0) throw std::invalid_argument("Farray ncols <= 0");
116 _buffer = new long[_nrows*_ncols];
117 }
118
119 inline int Farray::offset(int i, int j) const
120 {
121 return i + j * _nrows;
122 }