1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra. Eigen itself is part of the KDE project.
3//
4// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
5// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
6//
7// This Source Code Form is subject to the terms of the Mozilla
8// Public License v. 2.0. If a copy of the MPL was not distributed
9// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10
11// this hack is needed to make this file compiles with -pedantic (gcc)
12#ifdef __GNUC__
13#define throw(X)
14#endif
15// discard stack allocation as that too bypasses malloc
16#define EIGEN_STACK_ALLOCATION_LIMIT 0
17// any heap allocation will raise an assert
18#define EIGEN_NO_MALLOC
19
20#include "main.h"
21
22template<typename MatrixType> void nomalloc(const MatrixType& m)
23{
24  /* this test check no dynamic memory allocation are issued with fixed-size matrices
25  */
26
27  typedef typename MatrixType::Scalar Scalar;
28  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
29
30  int rows = m.rows();
31  int cols = m.cols();
32
33  MatrixType m1 = MatrixType::Random(rows, cols),
34             m2 = MatrixType::Random(rows, cols),
35             m3(rows, cols),
36             mzero = MatrixType::Zero(rows, cols),
37             identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
38                              ::Identity(rows, rows),
39             square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
40                              ::Random(rows, rows);
41  VectorType v1 = VectorType::Random(rows),
42             v2 = VectorType::Random(rows),
43             vzero = VectorType::Zero(rows);
44
45  Scalar s1 = ei_random<Scalar>();
46
47  int r = ei_random<int>(0, rows-1),
48      c = ei_random<int>(0, cols-1);
49
50  VERIFY_IS_APPROX((m1+m2)*s1,              s1*m1+s1*m2);
51  VERIFY_IS_APPROX((m1+m2)(r,c), (m1(r,c))+(m2(r,c)));
52  VERIFY_IS_APPROX(m1.cwise() * m1.block(0,0,rows,cols), m1.cwise() * m1);
53  VERIFY_IS_APPROX((m1*m1.transpose())*m2,  m1*(m1.transpose()*m2));
54}
55
56void test_eigen2_nomalloc()
57{
58  // check that our operator new is indeed called:
59  VERIFY_RAISES_ASSERT(MatrixXd dummy = MatrixXd::Random(3,3));
60  CALL_SUBTEST_1( nomalloc(Matrix<float, 1, 1>()) );
61  CALL_SUBTEST_2( nomalloc(Matrix4d()) );
62  CALL_SUBTEST_3( nomalloc(Matrix<float,32,32>()) );
63}
64