text
stringlengths
54
60.6k
<commit_before>// /////////////////////////////////////////////////////////////////////////// // tenh/utility/optimization.hpp by Victor Dods, created 2013/12/09 // Copyright Leap Motion Inc. // /////////////////////////////////////////////////////////////////////////// #ifndef TENH_UTILITY_OPTIMIZATION_HPP_ #define TENH_UTILITY_OPTIMIZATION_HPP_ #include "tenh/core.hpp" #include <iostream> #include "tenh/implementation/vector.hpp" #include "tenh/implementation/vee.hpp" namespace Tenh { // adaptive minimization which uses, in order of availability/preference, // 1. Newton's method, 2. conjugate gradient, and 3. gradient descent. template <typename InnerProductId_, typename ObjectiveFunction_, typename BasedVectorSpace_, typename Scalar_> ImplementationOf_t<BasedVectorSpace_,Scalar_> minimize (ObjectiveFunction_ const &func, ImplementationOf_t<BasedVectorSpace_,Scalar_> const &guess, Scalar_ const tolerance) { typedef ImplementationOf_t<BasedVectorSpace_, Scalar_> VectorType; typedef InnerProductId_ InnerProductType; typedef typename InnerProduct_f<BasedVectorSpace_, InnerProductType, Scalar_>::T VectorInnerProductType; typedef ImplementationOf_t<typename DualOf_f<BasedVectorSpace_>::T, Scalar_> CoVectorType; typedef typename InnerProduct_f<typename DualOf_f<BasedVectorSpace_>::T, InnerProductType, Scalar_>::T CoVectorInnerProductType; typedef SymmetricPowerOfBasedVectorSpace_c<2, BasedVectorSpace_> Sym2; typedef typename ObjectiveFunction_::D2 HessianType; typedef ImplementationOf_t<SymmetricPowerOfBasedVectorSpace_c<2, BasedVectorSpace_>, Scalar_> HessianInverseType; STATIC_ASSERT_TYPES_ARE_EQUAL(VectorType, typename ObjectiveFunction_::V); STATIC_ASSERT_TYPES_ARE_EQUAL(Scalar_, typename ObjectiveFunction_::Out); static int const LINE_SEARCH_SAMPLE_COUNT = 20; static Scalar_ const STEP_SCALE = Scalar_(1.0); static Scalar_ const MAX_STEP_SIZE = Scalar_(-1.0); static int const MAX_ITERATION_COUNT = 200; static Scalar_ const GRADIENT_DESCENT_STEP_SIZE = Scalar_(1.0); static bool const PRINT_DEBUG_OUTPUT = true; static Scalar_ const EPSILON = 1e-5; VectorInnerProductType vector_innerproduct; CoVectorInnerProductType covector_innerproduct; AbstractIndex_c<'a'> a; AbstractIndex_c<'b'> b; AbstractIndex_c<'c'> c; AbstractIndex_c<'i'> i; AbstractIndex_c<'j'> j; AbstractIndex_c<'k'> k; AbstractIndex_c<'l'> l; VectorType current_approximation = guess; int iteration_count = 0; int gradient_descent = 0; int conjugate_gradient = 0; int newtons_method = 0; bool tolerance_was_attained = false; while (iteration_count < MAX_ITERATION_COUNT) { Scalar_ current_value = func.function(current_approximation); CoVectorType g = func.D_function(current_approximation); Scalar_ g_squared_norm = g(i)*covector_innerproduct(a).split(a,i|j)*g(j); Scalar_ g_norm = std::sqrt(g_squared_norm); if (PRINT_DEBUG_OUTPUT) { std::cout << current_approximation << " " << g_norm << std::endl; } if (g_norm <= tolerance) { tolerance_was_attained = true; break; } HessianType h(func.D2_function(current_approximation)); HessianInverseType hinv(Static<WithoutInitialization>::SINGLETON); VectorType step(Static<WithoutInitialization>::SINGLETON); Scalar_ d; if (invert_2tensor(h, hinv)) { step(i).no_alias() = hinv(a).split(a,i|j) * -g(j); d = h(a)*(step(i)*step(j)).bundle(i|j,Sym2(),a); } else { d = 5; // bigger than EPSILON. } if (d < EPSILON) // h isn't postive definite along step so fall back to conjugate gradient { VectorType v(Static<WithoutInitialization>::SINGLETON); v(j).no_alias() = g(i) * covector_innerproduct(a).split(a,i|j); // d = g(i)*v(i); d = v(i) * h(b).split(b,i|j) * v(j); if (d < EPSILON) // h isn't positive definite along g either, gradient descent { if (PRINT_DEBUG_OUTPUT) { std::cout << "Doing Gradient descent." << std::endl; ++gradient_descent; } step(i).no_alias() = -GRADIENT_DESCENT_STEP_SIZE * g(i) / g_norm; } else // h is positive definite along g, use conjugate gradient { if (PRINT_DEBUG_OUTPUT) { std::cout << "Using conjugate gradient." << std::endl; ++conjugate_gradient; } //Scalar_ v_squared_norm = v(i)*vector_innerproduct(a).split(a,i|j)*v(j); //Scalar_ v_norm = std::sqrt(v_squared_norm); // step(i).no_alias() = -g_squared_norm / v_squared_norm * v(i); step(i).no_alias() = (-g_squared_norm / (Scalar_(2) * d)) * v(i); } } else // h is positive definite along step, use it as is. { if (PRINT_DEBUG_OUTPUT) { std::cout << "Newton's method." << std::endl; ++newtons_method; } } step(i).no_alias() = STEP_SCALE * step(i); Scalar_ step_norm = std::sqrt(vector_innerproduct(a).split(a,i|j)*step(i)*step(j)); if (MAX_STEP_SIZE > 0 && step_norm > MAX_STEP_SIZE) { step(i).no_alias() = MAX_STEP_SIZE * step(i) / step_norm; } VectorType line_search_step(Static<WithoutInitialization>::SINGLETON); VectorType partial_step(fill_with<Scalar_>(0)); line_search_step(i).no_alias() = step(i) / LINE_SEARCH_SAMPLE_COUNT; for (int it = 0; it < LINE_SEARCH_SAMPLE_COUNT; ++it) { VectorType x(Static<WithoutInitialization>::SINGLETON); partial_step(i).no_alias() += line_search_step(i); x(i).no_alias() = current_approximation(i) + partial_step(i); Scalar_ next_value = func.function(x); if (next_value > current_value) { step = partial_step; std::cout << "used " << it << " steps in line search\n"; break; } current_value = next_value; } current_approximation(i) += step(i); ++iteration_count; } if (PRINT_DEBUG_OUTPUT) { std::cout << "optimize took " << iteration_count << " steps " << newtons_method << " were Newton's method, " << conjugate_gradient << " were conjugate gradient, and " << gradient_descent << " were gradient descent." << std::endl; } return current_approximation; } } // end of namespace Tenh #endif // TENH_UTILITY_OPTIMIZATION_HPP_ <commit_msg>Various minor changes to minimize.<commit_after>// /////////////////////////////////////////////////////////////////////////// // tenh/utility/optimization.hpp by Victor Dods, created 2013/12/09 // Copyright Leap Motion Inc. // /////////////////////////////////////////////////////////////////////////// #ifndef TENH_UTILITY_OPTIMIZATION_HPP_ #define TENH_UTILITY_OPTIMIZATION_HPP_ #include "tenh/core.hpp" #include <iostream> #include "tenh/implementation/vector.hpp" #include "tenh/implementation/vee.hpp" namespace Tenh { // adaptive minimization which uses, in order of availability/preference, // 1. Newton's method, 2. conjugate gradient, and 3. gradient descent. template <typename InnerProductId_, typename ObjectiveFunction_, typename BasedVectorSpace_, typename Scalar_> ImplementationOf_t<BasedVectorSpace_,Scalar_> minimize (ObjectiveFunction_ const &func, ImplementationOf_t<BasedVectorSpace_,Scalar_> const &guess, Scalar_ const tolerance) { typedef ImplementationOf_t<BasedVectorSpace_, Scalar_> VectorType; typedef typename InnerProduct_f<BasedVectorSpace_, InnerProductId_, Scalar_>::T VectorInnerProductType; typedef ImplementationOf_t<typename DualOf_f<BasedVectorSpace_>::T, Scalar_> CoVectorType; typedef typename InnerProduct_f<typename DualOf_f<BasedVectorSpace_>::T, InnerProductId_, Scalar_>::T CoVectorInnerProductType; typedef SymmetricPowerOfBasedVectorSpace_c<2, BasedVectorSpace_> Sym2; typedef typename ObjectiveFunction_::D2 HessianType; typedef ImplementationOf_t<SymmetricPowerOfBasedVectorSpace_c<2, BasedVectorSpace_>, Scalar_> HessianInverseType; STATIC_ASSERT_TYPES_ARE_EQUAL(VectorType, typename ObjectiveFunction_::V); STATIC_ASSERT_TYPES_ARE_EQUAL(Scalar_, typename ObjectiveFunction_::Out); static int const LINE_SEARCH_SAMPLE_COUNT = 800; static Scalar_ const STEP_SCALE = Scalar_(1.0); static Scalar_ const MAX_STEP_SIZE = Scalar_(-1.0); static int const MAX_ITERATION_COUNT = 20; static Scalar_ const GRADIENT_DESCENT_STEP_SIZE = Scalar_(1.0); static bool const PRINT_DEBUG_OUTPUT = true; static Scalar_ const EPSILON = 1e-5; VectorInnerProductType vector_innerproduct; CoVectorInnerProductType covector_innerproduct; AbstractIndex_c<'a'> a; AbstractIndex_c<'b'> b; AbstractIndex_c<'c'> c; AbstractIndex_c<'i'> i; AbstractIndex_c<'j'> j; AbstractIndex_c<'k'> k; AbstractIndex_c<'l'> l; VectorType current_approximation = guess; int iteration_count = 0; int gradient_descent = 0; int conjugate_gradient = 0; int newtons_method = 0; bool tolerance_was_attained = false; while (iteration_count < MAX_ITERATION_COUNT) { Scalar_ current_value = func.function(current_approximation); CoVectorType g = func.D_function(current_approximation); Scalar_ g_squared_norm = g(i)*covector_innerproduct(a).split(a,i|j)*g(j); Scalar_ g_norm = std::sqrt(g_squared_norm); if (PRINT_DEBUG_OUTPUT) { std::cout << current_approximation << "\n" << g << " " << g_norm << " " << current_value << std::endl; } if (g_norm <= tolerance) { tolerance_was_attained = true; break; } HessianType h(func.D2_function(current_approximation)); HessianInverseType hinv(Static<WithoutInitialization>::SINGLETON); VectorType step(Static<WithoutInitialization>::SINGLETON); Scalar_ d; if (invert_2tensor(h, hinv)) { step(i).no_alias() = hinv(a).split(a,i|j) * -g(j); d = h(a)*(step(i)*step(j)).bundle(i|j,Sym2(),a); } else { d = 5; // bigger than EPSILON. } if (d < EPSILON) // h isn't postive definite along step so fall back to conjugate gradient { VectorType v(Static<WithoutInitialization>::SINGLETON); v(j).no_alias() = g(i) * covector_innerproduct(a).split(a,i|j); // d = g(i)*v(i); d = v(i) * h(b).split(b,i|j) * v(j); if (d < EPSILON) // h isn't positive definite along g either, gradient descent { if (PRINT_DEBUG_OUTPUT) { std::cout << "Doing Gradient descent." << std::endl; ++gradient_descent; } step(i).no_alias() = -GRADIENT_DESCENT_STEP_SIZE * g(i) / g_norm; } else // h is positive definite along g, use conjugate gradient { if (PRINT_DEBUG_OUTPUT) { std::cout << "Using conjugate gradient." << std::endl; ++conjugate_gradient; } //Scalar_ v_squared_norm = v(i)*vector_innerproduct(a).split(a,i|j)*v(j); //Scalar_ v_norm = std::sqrt(v_squared_norm); // step(i).no_alias() = -g_squared_norm / v_squared_norm * v(i); step(i).no_alias() = (-g_squared_norm / d) * v(i); } } else // h is positive definite along step, use it as is. { if (PRINT_DEBUG_OUTPUT) { std::cout << "Newton's method." << std::endl << h(a).split(a,i|j) << std::endl; ++newtons_method; } } step(i).no_alias() = STEP_SCALE * step(i); Scalar_ step_norm = std::sqrt(vector_innerproduct(a).split(a,i|j)*step(i)*step(j)); if (MAX_STEP_SIZE > 0 && step_norm > MAX_STEP_SIZE) { if (PRINT_DEBUG_OUTPUT) { std::cout << "Clamping step length to " << MAX_STEP_SIZE << std::endl; } step(i).no_alias() = MAX_STEP_SIZE * step(i) / step_norm; } VectorType line_search_step(Static<WithoutInitialization>::SINGLETON); VectorType partial_step(fill_with<Scalar_>(0)); VectorType x(Static<WithoutInitialization>::SINGLETON); line_search_step(i).no_alias() = step(i) / LINE_SEARCH_SAMPLE_COUNT; int it; for (it = 0; it < LINE_SEARCH_SAMPLE_COUNT; ++it) { partial_step(i).no_alias() += line_search_step(i); x(i).no_alias() = current_approximation(i) + partial_step(i); Scalar_ next_value = func.function(x); if (next_value > current_value) { current_value = next_value; step = partial_step; break; } current_value = next_value; } if (PRINT_DEBUG_OUTPUT) { std::cout << "used " << it << " steps in line search\n"; } if (it != 0 && it != LINE_SEARCH_SAMPLE_COUNT) { std::cout << "Did a partial line search\n"; } current_approximation(i) += step(i); ++iteration_count; } if (PRINT_DEBUG_OUTPUT) { std::cout << "optimize took " << iteration_count << " steps " << newtons_method << " were Newton's method, " << conjugate_gradient << " were conjugate gradient, and " << gradient_descent << " were gradient descent." << std::endl; } return current_approximation; } } // end of namespace Tenh #endif // TENH_UTILITY_OPTIMIZATION_HPP_ <|endoftext|>
<commit_before>/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkByteSwapper_hxx #define itkByteSwapper_hxx #include <memory> #include <cstring> namespace itk { // The following are the public methods -------------------------------- // // Machine definitions #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> bool ByteSwapper<T>::SystemIsBigEndian() { return true; } template <typename T> bool ByteSwapper<T>::SystemIsLittleEndian() { return false; } #else template <typename T> bool ByteSwapper<T>::SystemIsBigEndian() { return false; } template <typename T> bool ByteSwapper<T>::SystemIsLittleEndian() { return true; } #endif //------Big Endian methods---------------------------------------------- // Use different swap methods based on type #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapFromSystemToBigEndian(T *) {} #else template <typename T> void ByteSwapper<T>::SwapFromSystemToBigEndian(T * p) { switch (sizeof(T)) { case 1: return; case 2: Self::Swap2(p); return; case 4: Self::Swap4(p); return; case 8: Self::Swap8(p); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #endif #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapRangeFromSystemToBigEndian(T *, BufferSizeType) { // nothing needs to be done here... } #else # ifdef __INTEL_COMPILER # pragma warning disable 280 // remark #280: selector expression is constant # endif template <typename T> void ByteSwapper<T>::SwapRangeFromSystemToBigEndian(T * p, BufferSizeType num) { switch (sizeof(T)) { case 1: return; case 2: Self::Swap2Range(p, num); return; case 4: Self::Swap4Range(p, num); return; case 8: Self::Swap8Range(p, num); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #endif #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapWriteRangeFromSystemToBigEndian(T * p, int num, OStreamType * fp) { num *= sizeof(T); fp->write((char *)p, num); } #else template <typename T> void ByteSwapper<T>::SwapWriteRangeFromSystemToBigEndian(T * p, int num, OStreamType * fp) { switch (sizeof(T)) { case 1: return; case 2: Self::SwapWrite2Range(p, num, fp); return; case 4: Self::SwapWrite4Range(p, num, fp); return; case 8: Self::SwapWrite8Range(p, num, fp); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #endif //------Little Endian methods---------------------------------------------- #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapFromSystemToLittleEndian(T * p) { switch (sizeof(T)) { case 1: return; case 2: Self::Swap2(p); return; case 4: Self::Swap4(p); return; case 8: Self::Swap8(p); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #else template <typename T> void ByteSwapper<T>::SwapFromSystemToLittleEndian(T *) {} #endif #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapRangeFromSystemToLittleEndian(T * p, BufferSizeType num) { switch (sizeof(T)) { case 1: return; case 2: Self::Swap2Range(p, num); return; case 4: Self::Swap4Range(p, num); return; case 8: Self::Swap8Range(p, num); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #else template <typename T> void ByteSwapper<T>::SwapRangeFromSystemToLittleEndian(T *, BufferSizeType) {} #endif #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapWriteRangeFromSystemToLittleEndian(T * p, int num, OStreamType * fp) { switch (sizeof(T)) { case 1: return; case 2: Self::SwapWrite2Range(p, num, fp); return; case 4: Self::SwapWrite4Range(p, num, fp); return; case 8: Self::SwapWrite8Range(p, num, fp); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #else template <typename T> void ByteSwapper<T>::SwapWriteRangeFromSystemToLittleEndian(T * p, int num, OStreamType * fp) { num *= sizeof(T); fp->write((char *)p, num); } #endif // The following are the protected methods ------------------------- // //------2-byte methods---------------------------------------------- // Swap 2 byte word. template <typename T> void ByteSwapper<T>::Swap2(void * pin) { auto * p = static_cast<unsigned short *>(pin); const unsigned short h1 = (*p) << static_cast<short unsigned int>(8); const unsigned short h2 = (*p) >> static_cast<short unsigned int>(8); *p = h1 | h2; } // Swap bunch of bytes. Num is the number of two byte words to swap. template <typename T> void ByteSwapper<T>::Swap2Range(void * ptr, BufferSizeType num) { auto * pos = static_cast<char *>(ptr); for (BufferSizeType i = 0; i < num; ++i) { const char one_byte = pos[0]; pos[0] = pos[1]; pos[1] = one_byte; pos = pos + 2; } } // Swap bunch of bytes. Num is the number of four byte words to swap. template <typename T> void ByteSwapper<T>::SwapWrite2Range(void * ptr, BufferSizeType num, OStreamType * fp) { BufferSizeType chunkSize = 1000000; if (num < chunkSize) { chunkSize = num; } auto * cpy = new char[chunkSize * 2]; while (num) { memcpy(cpy, ptr, chunkSize * 2); Self::Swap2Range(cpy, num); fp->write((char *)cpy, static_cast<std::streamsize>(2 * chunkSize)); ptr = (char *)ptr + chunkSize * 2; num -= chunkSize; if (num < chunkSize) { chunkSize = num; } } delete[] cpy; } //------4-byte methods---------------------------------------------- // Swap four byte word. template <typename T> void ByteSwapper<T>::Swap4(void * ptr) { char one_byte; auto * p = static_cast<char *>(ptr); one_byte = p[0]; p[0] = p[3]; p[3] = one_byte; one_byte = p[1]; p[1] = p[2]; p[2] = one_byte; } // Swap bunch of bytes. Num is the number of four byte words to swap. template <typename T> void ByteSwapper<T>::Swap4Range(void * ptr, BufferSizeType num) { auto * pos = static_cast<char *>(ptr); for (BufferSizeType i = 0; i < num; ++i) { Self::Swap4(pos); pos = pos + 4; } } // Swap bunch of bytes. Num is the number of four byte words to swap. template <typename T> void ByteSwapper<T>::SwapWrite4Range(void * ptr, BufferSizeType num, OStreamType * fp) { BufferSizeType chunkSize = 1000000; if (num < chunkSize) { chunkSize = num; } auto * cpy = new char[chunkSize * 4]; while (num) { memcpy(cpy, ptr, chunkSize * 4); Self::Swap4Range(cpy, num); fp->write((char *)cpy, static_cast<std::streamsize>(4 * chunkSize)); ptr = (char *)ptr + chunkSize * 4; num -= chunkSize; if (num < chunkSize) { chunkSize = num; } } delete[] cpy; } //------8-byte methods---------------------------------------------- // Swap 8 byte double precision template <typename T> void ByteSwapper<T>::Swap8(void * ptr) { char one_byte; auto * p = static_cast<char *>(ptr); one_byte = p[0]; p[0] = p[7]; p[7] = one_byte; one_byte = p[1]; p[1] = p[6]; p[6] = one_byte; one_byte = p[2]; p[2] = p[5]; p[5] = one_byte; one_byte = p[3]; p[3] = p[4]; p[4] = one_byte; } // Swap bunch of bytes. Num is the number of eight byte words to swap. template <typename T> void ByteSwapper<T>::Swap8Range(void * ptr, BufferSizeType num) { auto * pos = static_cast<char *>(ptr); for (BufferSizeType i = 0; i < num; ++i) { Self::Swap8(pos); pos = pos + 8; } } // Swap bunch of bytes. Num is the number of four byte words to swap. template <typename T> void ByteSwapper<T>::SwapWrite8Range(void * ptr, BufferSizeType num, OStreamType * fp) { BufferSizeType chunkSize = 1000000; if (num < chunkSize) { chunkSize = num; } auto * cpy = new char[chunkSize * 8]; while (num) { memcpy(cpy, ptr, chunkSize * 8); Self::Swap8Range(cpy, chunkSize); fp->write((char *)cpy, static_cast<std::streamsize>(8 * chunkSize)); ptr = (char *)ptr + chunkSize * 8; num -= chunkSize; if (num < chunkSize) { chunkSize = num; } } delete[] cpy; } } // end namespace itk #endif <commit_msg>STYLE: Use `unique_ptr` in "SwapWrite" member functions of `ByteSwapper`<commit_after>/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkByteSwapper_hxx #define itkByteSwapper_hxx #include <memory> #include <cstring> namespace itk { // The following are the public methods -------------------------------- // // Machine definitions #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> bool ByteSwapper<T>::SystemIsBigEndian() { return true; } template <typename T> bool ByteSwapper<T>::SystemIsLittleEndian() { return false; } #else template <typename T> bool ByteSwapper<T>::SystemIsBigEndian() { return false; } template <typename T> bool ByteSwapper<T>::SystemIsLittleEndian() { return true; } #endif //------Big Endian methods---------------------------------------------- // Use different swap methods based on type #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapFromSystemToBigEndian(T *) {} #else template <typename T> void ByteSwapper<T>::SwapFromSystemToBigEndian(T * p) { switch (sizeof(T)) { case 1: return; case 2: Self::Swap2(p); return; case 4: Self::Swap4(p); return; case 8: Self::Swap8(p); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #endif #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapRangeFromSystemToBigEndian(T *, BufferSizeType) { // nothing needs to be done here... } #else # ifdef __INTEL_COMPILER # pragma warning disable 280 // remark #280: selector expression is constant # endif template <typename T> void ByteSwapper<T>::SwapRangeFromSystemToBigEndian(T * p, BufferSizeType num) { switch (sizeof(T)) { case 1: return; case 2: Self::Swap2Range(p, num); return; case 4: Self::Swap4Range(p, num); return; case 8: Self::Swap8Range(p, num); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #endif #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapWriteRangeFromSystemToBigEndian(T * p, int num, OStreamType * fp) { num *= sizeof(T); fp->write((char *)p, num); } #else template <typename T> void ByteSwapper<T>::SwapWriteRangeFromSystemToBigEndian(T * p, int num, OStreamType * fp) { switch (sizeof(T)) { case 1: return; case 2: Self::SwapWrite2Range(p, num, fp); return; case 4: Self::SwapWrite4Range(p, num, fp); return; case 8: Self::SwapWrite8Range(p, num, fp); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #endif //------Little Endian methods---------------------------------------------- #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapFromSystemToLittleEndian(T * p) { switch (sizeof(T)) { case 1: return; case 2: Self::Swap2(p); return; case 4: Self::Swap4(p); return; case 8: Self::Swap8(p); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #else template <typename T> void ByteSwapper<T>::SwapFromSystemToLittleEndian(T *) {} #endif #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapRangeFromSystemToLittleEndian(T * p, BufferSizeType num) { switch (sizeof(T)) { case 1: return; case 2: Self::Swap2Range(p, num); return; case 4: Self::Swap4Range(p, num); return; case 8: Self::Swap8Range(p, num); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #else template <typename T> void ByteSwapper<T>::SwapRangeFromSystemToLittleEndian(T *, BufferSizeType) {} #endif #ifdef CMAKE_WORDS_BIGENDIAN template <typename T> void ByteSwapper<T>::SwapWriteRangeFromSystemToLittleEndian(T * p, int num, OStreamType * fp) { switch (sizeof(T)) { case 1: return; case 2: Self::SwapWrite2Range(p, num, fp); return; case 4: Self::SwapWrite4Range(p, num, fp); return; case 8: Self::SwapWrite8Range(p, num, fp); return; default: itkGenericExceptionMacro(<< "Cannot swap number of bytes requested"); } } #else template <typename T> void ByteSwapper<T>::SwapWriteRangeFromSystemToLittleEndian(T * p, int num, OStreamType * fp) { num *= sizeof(T); fp->write((char *)p, num); } #endif // The following are the protected methods ------------------------- // //------2-byte methods---------------------------------------------- // Swap 2 byte word. template <typename T> void ByteSwapper<T>::Swap2(void * pin) { auto * p = static_cast<unsigned short *>(pin); const unsigned short h1 = (*p) << static_cast<short unsigned int>(8); const unsigned short h2 = (*p) >> static_cast<short unsigned int>(8); *p = h1 | h2; } // Swap bunch of bytes. Num is the number of two byte words to swap. template <typename T> void ByteSwapper<T>::Swap2Range(void * ptr, BufferSizeType num) { auto * pos = static_cast<char *>(ptr); for (BufferSizeType i = 0; i < num; ++i) { const char one_byte = pos[0]; pos[0] = pos[1]; pos[1] = one_byte; pos = pos + 2; } } // Swap bunch of bytes. Num is the number of four byte words to swap. template <typename T> void ByteSwapper<T>::SwapWrite2Range(void * ptr, BufferSizeType num, OStreamType * fp) { BufferSizeType chunkSize = 1000000; if (num < chunkSize) { chunkSize = num; } const std::unique_ptr<char[]> cpy(new char[chunkSize * 2]); while (num) { memcpy(cpy.get(), ptr, chunkSize * 2); Self::Swap2Range(cpy.get(), num); fp->write(cpy.get(), static_cast<std::streamsize>(2 * chunkSize)); ptr = (char *)ptr + chunkSize * 2; num -= chunkSize; if (num < chunkSize) { chunkSize = num; } } } //------4-byte methods---------------------------------------------- // Swap four byte word. template <typename T> void ByteSwapper<T>::Swap4(void * ptr) { char one_byte; auto * p = static_cast<char *>(ptr); one_byte = p[0]; p[0] = p[3]; p[3] = one_byte; one_byte = p[1]; p[1] = p[2]; p[2] = one_byte; } // Swap bunch of bytes. Num is the number of four byte words to swap. template <typename T> void ByteSwapper<T>::Swap4Range(void * ptr, BufferSizeType num) { auto * pos = static_cast<char *>(ptr); for (BufferSizeType i = 0; i < num; ++i) { Self::Swap4(pos); pos = pos + 4; } } // Swap bunch of bytes. Num is the number of four byte words to swap. template <typename T> void ByteSwapper<T>::SwapWrite4Range(void * ptr, BufferSizeType num, OStreamType * fp) { BufferSizeType chunkSize = 1000000; if (num < chunkSize) { chunkSize = num; } const std::unique_ptr<char[]> cpy(new char[chunkSize * 4]); while (num) { memcpy(cpy.get(), ptr, chunkSize * 4); Self::Swap4Range(cpy.get(), num); fp->write(cpy.get(), static_cast<std::streamsize>(4 * chunkSize)); ptr = (char *)ptr + chunkSize * 4; num -= chunkSize; if (num < chunkSize) { chunkSize = num; } } } //------8-byte methods---------------------------------------------- // Swap 8 byte double precision template <typename T> void ByteSwapper<T>::Swap8(void * ptr) { char one_byte; auto * p = static_cast<char *>(ptr); one_byte = p[0]; p[0] = p[7]; p[7] = one_byte; one_byte = p[1]; p[1] = p[6]; p[6] = one_byte; one_byte = p[2]; p[2] = p[5]; p[5] = one_byte; one_byte = p[3]; p[3] = p[4]; p[4] = one_byte; } // Swap bunch of bytes. Num is the number of eight byte words to swap. template <typename T> void ByteSwapper<T>::Swap8Range(void * ptr, BufferSizeType num) { auto * pos = static_cast<char *>(ptr); for (BufferSizeType i = 0; i < num; ++i) { Self::Swap8(pos); pos = pos + 8; } } // Swap bunch of bytes. Num is the number of four byte words to swap. template <typename T> void ByteSwapper<T>::SwapWrite8Range(void * ptr, BufferSizeType num, OStreamType * fp) { BufferSizeType chunkSize = 1000000; if (num < chunkSize) { chunkSize = num; } const std::unique_ptr<char[]> cpy(new char[chunkSize * 8]); while (num) { memcpy(cpy.get(), ptr, chunkSize * 8); Self::Swap8Range(cpy.get(), chunkSize); fp->write(cpy.get(), static_cast<std::streamsize>(8 * chunkSize)); ptr = (char *)ptr + chunkSize * 8; num -= chunkSize; if (num < chunkSize) { chunkSize = num; } } } } // end namespace itk #endif <|endoftext|>
<commit_before>/* Copyright (c) 2015 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam */ #include "library/defeq_simplifier.h" #include "util/interrupt.h" #include "util/sexpr/option_declarations.h" #include "kernel/expr_maps.h" #include "kernel/instantiate.h" #include "kernel/abstract.h" #include "library/trace.h" #include "library/tmp_type_context.h" #include "library/normalize.h" #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_SIMP_ROUNDS #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_SIMP_ROUNDS 1000 #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_REWRITE_ROUNDS #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_REWRITE_ROUNDS 1000 #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_TOP_DOWN #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_TOP_DOWN false #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXHAUSTIVE #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXHAUSTIVE true #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_MEMOIZE #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_MEMOIZE true #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXPAND_MACROS #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXPAND_MACROS false #endif namespace lean { /* Options */ static name * g_simplify_max_simp_rounds = nullptr; static name * g_simplify_max_rewrite_rounds = nullptr; static name * g_simplify_top_down = nullptr; static name * g_simplify_exhaustive = nullptr; static name * g_simplify_memoize = nullptr; static name * g_simplify_expand_macros = nullptr; static unsigned get_simplify_max_simp_rounds(options const & o) { return o.get_unsigned(*g_simplify_max_simp_rounds, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_SIMP_ROUNDS); } static unsigned get_simplify_max_rewrite_rounds(options const & o) { return o.get_unsigned(*g_simplify_max_rewrite_rounds, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_REWRITE_ROUNDS); } static bool get_simplify_top_down(options const & o) { return o.get_bool(*g_simplify_top_down, LEAN_DEFAULT_DEFEQ_SIMPLIFY_TOP_DOWN); } static bool get_simplify_exhaustive(options const & o) { return o.get_bool(*g_simplify_exhaustive, LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXHAUSTIVE); } static bool get_simplify_memoize(options const & o) { return o.get_bool(*g_simplify_memoize, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MEMOIZE); } static bool get_simplify_expand_macros(options const & o) { return o.get_bool(*g_simplify_expand_macros, LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXPAND_MACROS); } /* Main simplifier class */ class defeq_simplify_fn { tmp_type_context m_tmp_tctx; defeq_simp_lemmas m_simp_lemmas; unsigned m_num_simp_rounds{0}; unsigned m_num_rewrite_rounds{0}; options const & m_options; /* Options */ unsigned m_max_simp_rounds; unsigned m_max_rewrite_rounds; bool m_top_down; bool m_exhaustive; bool m_memoize; bool m_expand_macros; /* Cache */ expr_struct_map<expr> m_cache; optional<expr> cache_lookup(expr const & e) { auto it = m_cache.find(e); if (it == m_cache.end()) return none_expr(); else return some_expr(it->second); } void cache_save(expr const & e, expr const & e_simp) { m_cache.insert(mk_pair(e, e_simp)); } /* Simplification */ expr defeq_simplify(expr const & _e) { expr e = _e; lean_trace_inc_depth("defeq_simplifier"); lean_trace_d("defeq_simplifier", tout() << e << "\n";); while (true) { expr e_start = e; check_system("defeq_simplifier"); m_num_simp_rounds++; if (m_num_simp_rounds > m_max_simp_rounds) throw exception("defeq_simplifier failed, maximum number of simp rounds exceeded"); if (m_memoize) { if (auto it = cache_lookup(e)) return *it; } if (m_top_down) e = rewrite(whnf_eta(e)); e = whnf_eta(e); switch (e.kind()) { case expr_kind::Local: case expr_kind::Meta: case expr_kind::Sort: case expr_kind::Constant: break; case expr_kind::Var: lean_unreachable(); case expr_kind::Macro: if (m_expand_macros) { if (auto m = m_tmp_tctx.expand_macro(e)) e = defeq_simplify(whnf_eta(*m)); } break; case expr_kind::Lambda: case expr_kind::Pi: e = defeq_simplify_binding(e); break; case expr_kind::App: e = defeq_simplify_app(e); break; } if (!m_top_down) e = rewrite(whnf_eta(e)); if (!m_exhaustive || e == e_start) break; } if (m_memoize) cache_save(_e, e); return e; } expr defeq_simplify_binding(expr const & e) { expr d = defeq_simplify(binding_domain(e)); expr l = m_tmp_tctx.mk_tmp_local(binding_name(e), d, binding_info(e)); expr b = abstract(defeq_simplify(instantiate(binding_body(e), l)), l); return update_binding(e, d, b); } expr defeq_simplify_app(expr const & e) { buffer<expr> args; expr f = defeq_simplify(get_app_args(e, args)); for (unsigned i = 0; i < args.size(); ++i) args[i] = defeq_simplify(args[i]); return mk_app(f, args); } /* Rewriting */ expr rewrite(expr const & _e) { expr e = _e; while (true) { check_system("defeq_simplifier"); m_num_rewrite_rounds++; if (m_num_rewrite_rounds > m_max_rewrite_rounds) throw exception("defeq_simplifier failed, maximum number of rewrite rounds exceeded"); list<defeq_simp_lemma> const * simp_lemmas_ptr = m_simp_lemmas.find(e); if (!simp_lemmas_ptr) return e; buffer<defeq_simp_lemma> simp_lemmas; to_buffer(*simp_lemmas_ptr, simp_lemmas); expr e_start = e; for (defeq_simp_lemma const & sl : simp_lemmas) e = rewrite(e, sl); if (e == e_start) break; } return e; } expr rewrite(expr const & e, defeq_simp_lemma const & sl) { tmp_type_context tmp_tctx(m_tmp_tctx.env(), m_options); tmp_tctx.clear(); tmp_tctx.set_next_uvar_idx(sl.get_num_umeta()); tmp_tctx.set_next_mvar_idx(sl.get_num_emeta()); if (!tmp_tctx.is_def_eq(e, sl.get_lhs())) return e; lean_trace(name({"defeq_simplifier", "rewrite"}), expr new_lhs = tmp_tctx.instantiate_uvars_mvars(sl.get_lhs()); expr new_rhs = tmp_tctx.instantiate_uvars_mvars(sl.get_rhs()); tout() << "(" << sl.get_id() << ") " << "[" << new_lhs << " --> " << new_rhs << "]\n";); if (!instantiate_emetas(tmp_tctx, sl.get_emetas(), sl.get_instances())) return e; for (unsigned i = 0; i < sl.get_num_umeta(); i++) { if (!tmp_tctx.is_uvar_assigned(i)) return e; } expr new_rhs = tmp_tctx.instantiate_uvars_mvars(sl.get_rhs()); return new_rhs; } bool instantiate_emetas(tmp_type_context & tmp_tctx, list<expr> const & _emetas, list<bool> const & _instances) { buffer<expr> emetas; buffer<bool> instances; to_buffer(_emetas, emetas); to_buffer(_instances, instances); lean_assert(emetas.size() == instances.size()); for (unsigned i = 0; i < emetas.size(); ++i) { expr m = emetas[i]; unsigned mvar_idx = emetas.size() - 1 - i; expr m_type = tmp_tctx.instantiate_uvars_mvars(tmp_tctx.infer(m)); lean_assert(!has_metavar(m_type)); if (tmp_tctx.is_mvar_assigned(mvar_idx)) continue; if (instances[i]) { if (auto v = tmp_tctx.mk_class_instance(m_type)) { if (!tmp_tctx.assign(m, *v)) { lean_trace(name({"defeq_simplifier", "failure"}), tout() << "unable to assign instance for: " << m_type << "\n";); return false; } else { lean_assert(tmp_tctx.is_mvar_assigned(mvar_idx)); continue; } } else { lean_trace(name({"defeq_simplifier", "failure"}), tout() << "unable to synthesize instance for: " << m_type << "\n";); return false; } } else { lean_trace(name({"defeq_simplifier", "failure"}), tout() << "failed to assign: " << m << " : " << m_type << "\n";); return false; } } return true; } expr whnf_eta(expr const & e) { return try_eta(m_tmp_tctx.whnf(e)); } public: defeq_simplify_fn(environment const & env, options const & o, defeq_simp_lemmas const & simp_lemmas): m_tmp_tctx(env, o), m_simp_lemmas(simp_lemmas), m_options(o), m_max_simp_rounds(get_simplify_max_simp_rounds(o)), m_max_rewrite_rounds(get_simplify_max_rewrite_rounds(o)), m_top_down(get_simplify_top_down(o)), m_exhaustive(get_simplify_exhaustive(o)), m_memoize(get_simplify_memoize(o)), m_expand_macros(get_simplify_expand_macros(o)) {} expr operator()(expr const & e) { return defeq_simplify(e); } }; /* Setup and teardown */ void initialize_defeq_simplifier() { register_trace_class("defeq_simplifier"); register_trace_class(name({"defeq_simplifier", "rewrite"})); register_trace_class(name({"defeq_simplifier", "failure"})); g_simplify_max_simp_rounds = new name{"defeq_simplify", "max_simp_rounds"}; g_simplify_max_rewrite_rounds = new name{"defeq_simplify", "max_rewrite_rounds"}; g_simplify_top_down = new name{"defeq_simplify", "top_down"}; g_simplify_exhaustive = new name{"defeq_simplify", "exhaustive"}; g_simplify_memoize = new name{"defeq_simplify", "memoize"}; g_simplify_expand_macros = new name{"defeq_simplify", "expand_macros"}; register_unsigned_option(*g_simplify_max_simp_rounds, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_SIMP_ROUNDS, "(defeq_simplify) max allowed simplification rounds"); register_unsigned_option(*g_simplify_max_rewrite_rounds, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_REWRITE_ROUNDS, "(defeq_simplify) max allowed rewrite rounds"); register_bool_option(*g_simplify_top_down, LEAN_DEFAULT_DEFEQ_SIMPLIFY_TOP_DOWN, "(defeq_simplify) use top-down rewriting instead of bottom-up"); register_bool_option(*g_simplify_exhaustive, LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXHAUSTIVE, "(defeq_simplify) simplify exhaustively"); register_bool_option(*g_simplify_memoize, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MEMOIZE, "(defeq_simplify) memoize simplifications"); register_bool_option(*g_simplify_expand_macros, LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXPAND_MACROS, "(defeq_simplify) expand macros"); } void finalize_defeq_simplifier() { delete g_simplify_expand_macros; delete g_simplify_memoize; delete g_simplify_exhaustive; delete g_simplify_top_down; delete g_simplify_max_rewrite_rounds; delete g_simplify_max_simp_rounds; } /* Entry point */ expr defeq_simplify(environment const & env, options const & o, defeq_simp_lemmas const & simp_lemmas, expr const & e) { return defeq_simplify_fn(env, o, simp_lemmas)(e); } } <commit_msg>feat(library/defeq_simplifier): no need to reverse args<commit_after>/* Copyright (c) 2015 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam */ #include "library/defeq_simplifier.h" #include "util/interrupt.h" #include "util/sexpr/option_declarations.h" #include "kernel/expr_maps.h" #include "kernel/instantiate.h" #include "kernel/abstract.h" #include "library/trace.h" #include "library/tmp_type_context.h" #include "library/normalize.h" #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_SIMP_ROUNDS #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_SIMP_ROUNDS 1000 #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_REWRITE_ROUNDS #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_REWRITE_ROUNDS 1000 #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_TOP_DOWN #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_TOP_DOWN false #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXHAUSTIVE #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXHAUSTIVE true #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_MEMOIZE #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_MEMOIZE true #endif #ifndef LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXPAND_MACROS #define LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXPAND_MACROS false #endif namespace lean { /* Options */ static name * g_simplify_max_simp_rounds = nullptr; static name * g_simplify_max_rewrite_rounds = nullptr; static name * g_simplify_top_down = nullptr; static name * g_simplify_exhaustive = nullptr; static name * g_simplify_memoize = nullptr; static name * g_simplify_expand_macros = nullptr; static unsigned get_simplify_max_simp_rounds(options const & o) { return o.get_unsigned(*g_simplify_max_simp_rounds, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_SIMP_ROUNDS); } static unsigned get_simplify_max_rewrite_rounds(options const & o) { return o.get_unsigned(*g_simplify_max_rewrite_rounds, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_REWRITE_ROUNDS); } static bool get_simplify_top_down(options const & o) { return o.get_bool(*g_simplify_top_down, LEAN_DEFAULT_DEFEQ_SIMPLIFY_TOP_DOWN); } static bool get_simplify_exhaustive(options const & o) { return o.get_bool(*g_simplify_exhaustive, LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXHAUSTIVE); } static bool get_simplify_memoize(options const & o) { return o.get_bool(*g_simplify_memoize, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MEMOIZE); } static bool get_simplify_expand_macros(options const & o) { return o.get_bool(*g_simplify_expand_macros, LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXPAND_MACROS); } /* Main simplifier class */ class defeq_simplify_fn { tmp_type_context m_tmp_tctx; defeq_simp_lemmas m_simp_lemmas; unsigned m_num_simp_rounds{0}; unsigned m_num_rewrite_rounds{0}; options const & m_options; /* Options */ unsigned m_max_simp_rounds; unsigned m_max_rewrite_rounds; bool m_top_down; bool m_exhaustive; bool m_memoize; bool m_expand_macros; /* Cache */ expr_struct_map<expr> m_cache; optional<expr> cache_lookup(expr const & e) { auto it = m_cache.find(e); if (it == m_cache.end()) return none_expr(); else return some_expr(it->second); } void cache_save(expr const & e, expr const & e_simp) { m_cache.insert(mk_pair(e, e_simp)); } /* Simplification */ expr defeq_simplify(expr const & _e) { expr e = _e; lean_trace_inc_depth("defeq_simplifier"); lean_trace_d("defeq_simplifier", tout() << e << "\n";); while (true) { expr e_start = e; check_system("defeq_simplifier"); m_num_simp_rounds++; if (m_num_simp_rounds > m_max_simp_rounds) throw exception("defeq_simplifier failed, maximum number of simp rounds exceeded"); if (m_memoize) { if (auto it = cache_lookup(e)) return *it; } if (m_top_down) e = rewrite(whnf_eta(e)); e = whnf_eta(e); switch (e.kind()) { case expr_kind::Local: case expr_kind::Meta: case expr_kind::Sort: case expr_kind::Constant: break; case expr_kind::Var: lean_unreachable(); case expr_kind::Macro: if (m_expand_macros) { if (auto m = m_tmp_tctx.expand_macro(e)) e = defeq_simplify(whnf_eta(*m)); } break; case expr_kind::Lambda: case expr_kind::Pi: e = defeq_simplify_binding(e); break; case expr_kind::App: e = defeq_simplify_app(e); break; } if (!m_top_down) e = rewrite(whnf_eta(e)); if (!m_exhaustive || e == e_start) break; } if (m_memoize) cache_save(_e, e); return e; } expr defeq_simplify_binding(expr const & e) { expr d = defeq_simplify(binding_domain(e)); expr l = m_tmp_tctx.mk_tmp_local(binding_name(e), d, binding_info(e)); expr b = abstract(defeq_simplify(instantiate(binding_body(e), l)), l); return update_binding(e, d, b); } expr defeq_simplify_app(expr const & e) { buffer<expr> rev_args; expr f = defeq_simplify(get_app_rev_args(e, rev_args)); for (unsigned i = 0; i < rev_args.size(); ++i) rev_args[i] = defeq_simplify(rev_args[i]); return mk_rev_app(f, rev_args); } /* Rewriting */ expr rewrite(expr const & _e) { expr e = _e; while (true) { check_system("defeq_simplifier"); m_num_rewrite_rounds++; if (m_num_rewrite_rounds > m_max_rewrite_rounds) throw exception("defeq_simplifier failed, maximum number of rewrite rounds exceeded"); list<defeq_simp_lemma> const * simp_lemmas_ptr = m_simp_lemmas.find(e); if (!simp_lemmas_ptr) return e; buffer<defeq_simp_lemma> simp_lemmas; to_buffer(*simp_lemmas_ptr, simp_lemmas); expr e_start = e; for (defeq_simp_lemma const & sl : simp_lemmas) e = rewrite(e, sl); if (e == e_start) break; } return e; } expr rewrite(expr const & e, defeq_simp_lemma const & sl) { tmp_type_context tmp_tctx(m_tmp_tctx.env(), m_options); tmp_tctx.clear(); tmp_tctx.set_next_uvar_idx(sl.get_num_umeta()); tmp_tctx.set_next_mvar_idx(sl.get_num_emeta()); if (!tmp_tctx.is_def_eq(e, sl.get_lhs())) return e; lean_trace(name({"defeq_simplifier", "rewrite"}), expr new_lhs = tmp_tctx.instantiate_uvars_mvars(sl.get_lhs()); expr new_rhs = tmp_tctx.instantiate_uvars_mvars(sl.get_rhs()); tout() << "(" << sl.get_id() << ") " << "[" << new_lhs << " --> " << new_rhs << "]\n";); if (!instantiate_emetas(tmp_tctx, sl.get_emetas(), sl.get_instances())) return e; for (unsigned i = 0; i < sl.get_num_umeta(); i++) { if (!tmp_tctx.is_uvar_assigned(i)) return e; } expr new_rhs = tmp_tctx.instantiate_uvars_mvars(sl.get_rhs()); return new_rhs; } bool instantiate_emetas(tmp_type_context & tmp_tctx, list<expr> const & _emetas, list<bool> const & _instances) { buffer<expr> emetas; buffer<bool> instances; to_buffer(_emetas, emetas); to_buffer(_instances, instances); lean_assert(emetas.size() == instances.size()); for (unsigned i = 0; i < emetas.size(); ++i) { expr m = emetas[i]; unsigned mvar_idx = emetas.size() - 1 - i; expr m_type = tmp_tctx.instantiate_uvars_mvars(tmp_tctx.infer(m)); lean_assert(!has_metavar(m_type)); if (tmp_tctx.is_mvar_assigned(mvar_idx)) continue; if (instances[i]) { if (auto v = tmp_tctx.mk_class_instance(m_type)) { if (!tmp_tctx.assign(m, *v)) { lean_trace(name({"defeq_simplifier", "failure"}), tout() << "unable to assign instance for: " << m_type << "\n";); return false; } else { lean_assert(tmp_tctx.is_mvar_assigned(mvar_idx)); continue; } } else { lean_trace(name({"defeq_simplifier", "failure"}), tout() << "unable to synthesize instance for: " << m_type << "\n";); return false; } } else { lean_trace(name({"defeq_simplifier", "failure"}), tout() << "failed to assign: " << m << " : " << m_type << "\n";); return false; } } return true; } expr whnf_eta(expr const & e) { return try_eta(m_tmp_tctx.whnf(e)); } public: defeq_simplify_fn(environment const & env, options const & o, defeq_simp_lemmas const & simp_lemmas): m_tmp_tctx(env, o), m_simp_lemmas(simp_lemmas), m_options(o), m_max_simp_rounds(get_simplify_max_simp_rounds(o)), m_max_rewrite_rounds(get_simplify_max_rewrite_rounds(o)), m_top_down(get_simplify_top_down(o)), m_exhaustive(get_simplify_exhaustive(o)), m_memoize(get_simplify_memoize(o)), m_expand_macros(get_simplify_expand_macros(o)) {} expr operator()(expr const & e) { return defeq_simplify(e); } }; /* Setup and teardown */ void initialize_defeq_simplifier() { register_trace_class("defeq_simplifier"); register_trace_class(name({"defeq_simplifier", "rewrite"})); register_trace_class(name({"defeq_simplifier", "failure"})); g_simplify_max_simp_rounds = new name{"defeq_simplify", "max_simp_rounds"}; g_simplify_max_rewrite_rounds = new name{"defeq_simplify", "max_rewrite_rounds"}; g_simplify_top_down = new name{"defeq_simplify", "top_down"}; g_simplify_exhaustive = new name{"defeq_simplify", "exhaustive"}; g_simplify_memoize = new name{"defeq_simplify", "memoize"}; g_simplify_expand_macros = new name{"defeq_simplify", "expand_macros"}; register_unsigned_option(*g_simplify_max_simp_rounds, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_SIMP_ROUNDS, "(defeq_simplify) max allowed simplification rounds"); register_unsigned_option(*g_simplify_max_rewrite_rounds, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MAX_REWRITE_ROUNDS, "(defeq_simplify) max allowed rewrite rounds"); register_bool_option(*g_simplify_top_down, LEAN_DEFAULT_DEFEQ_SIMPLIFY_TOP_DOWN, "(defeq_simplify) use top-down rewriting instead of bottom-up"); register_bool_option(*g_simplify_exhaustive, LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXHAUSTIVE, "(defeq_simplify) simplify exhaustively"); register_bool_option(*g_simplify_memoize, LEAN_DEFAULT_DEFEQ_SIMPLIFY_MEMOIZE, "(defeq_simplify) memoize simplifications"); register_bool_option(*g_simplify_expand_macros, LEAN_DEFAULT_DEFEQ_SIMPLIFY_EXPAND_MACROS, "(defeq_simplify) expand macros"); } void finalize_defeq_simplifier() { delete g_simplify_expand_macros; delete g_simplify_memoize; delete g_simplify_exhaustive; delete g_simplify_top_down; delete g_simplify_max_rewrite_rounds; delete g_simplify_max_simp_rounds; } /* Entry point */ expr defeq_simplify(environment const & env, options const & o, defeq_simp_lemmas const & simp_lemmas, expr const & e) { return defeq_simplify_fn(env, o, simp_lemmas)(e); } } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2006 Christian Gehl * Written (W) 2006-2009 Soeren Sonnenburg * Written (W) 2011 Sergey Lisitsyn * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include "classifier/KNN.h" #include "features/Labels.h" #include "lib/Mathematics.h" #include "lib/Signal.h" using namespace shogun; CKNN::CKNN() : CDistanceMachine(), m_k(3), num_classes(0), num_train_labels(0), train_labels(NULL), m_q(1.0) { } CKNN::CKNN(int32_t k_, CDistance* d, CLabels* trainlab) : CDistanceMachine(), m_k(k_), num_classes(0), train_labels(NULL), m_q(1.0) { ASSERT(d); ASSERT(trainlab); set_distance(d); set_labels(trainlab); num_train_labels=trainlab->get_num_labels(); } CKNN::~CKNN() { delete[] train_labels; } bool CKNN::train(CFeatures* data) { ASSERT(labels); ASSERT(distance); if (data) { if (labels->get_num_labels() != data->get_num_vectors()) SG_ERROR("Number of training vectors does not match number of labels\n"); distance->init(data, data); } train_labels=labels->get_int_labels(num_train_labels); ASSERT(train_labels); ASSERT(num_train_labels>0); int32_t max_class=train_labels[0]; int32_t min_class=train_labels[0]; int32_t i; for (i=1; i<num_train_labels; i++) { max_class=CMath::max(max_class, train_labels[i]); min_class=CMath::min(min_class, train_labels[i]); } for (i=0; i<num_train_labels; i++) train_labels[i]-=min_class; min_label=min_class; num_classes=max_class-min_class+1; SG_INFO( "num_classes: %d (%+d to %+d) num_train: %d\n", num_classes, min_class, max_class, num_train_labels); return true; } CLabels* CKNN::classify() { ASSERT(num_classes>0); ASSERT(distance); ASSERT(distance->get_num_vec_rhs()); int32_t num_lab=distance->get_num_vec_rhs(); ASSERT(m_k<=num_lab); CLabels* output=new CLabels(num_lab); //distances to train data and working buffer of train_labels float64_t* dists=new float64_t[num_train_labels]; int32_t* train_lab=new int32_t[num_train_labels]; ASSERT(dists); ASSERT(train_lab); SG_INFO( "%d test examples\n", num_lab); CSignal::clear_cancel(); ///histogram of classes and returned output float64_t* classes=new float64_t[num_classes]; ASSERT(classes); for (int32_t i=0; i<num_lab && (!CSignal::cancel_computations()); i++) { SG_PROGRESS(i, 0, num_lab); // lhs idx 1..n and rhs idx i distances_lhs(dists,0,num_train_labels-1,i); int32_t j; for (j=0; j<num_train_labels; j++) train_lab[j]=train_labels[j]; //sort the distance vector for test example j to all train examples //classes[1..k] then holds the classes for minimum distance CMath::qsort_index(dists, train_lab, num_train_labels); //compute histogram of class outputs of the first k nearest neighbours for (j=0; j<num_classes; j++) classes[j]=0.0; float64_t multiplier = m_q; for (j=0; j<m_k; j++) { classes[train_lab[j]]+= multiplier; multiplier*= multiplier; } //choose the class that got 'outputted' most often int32_t out_idx=0; int32_t out_max=0; for (j=0; j<num_classes; j++) { if (out_max< classes[j]) { out_idx= j; out_max= classes[j]; } } output->set_label(i, out_idx+min_label); } delete[] classes; delete[] dists; delete[] train_lab; return output; } CLabels* CKNN::classify(CFeatures* data) { init_distance(data); // redirecting to fast (without sorting) classify if k==1 if (m_k == 1) return classify_NN(); return classify(); } CLabels* CKNN::classify_NN() { ASSERT(distance); ASSERT(num_classes>0); int32_t num_lab = distance->get_num_vec_rhs(); ASSERT(num_lab); CLabels* output = new CLabels(num_lab); float64_t* distances = new float64_t[num_train_labels]; ASSERT(distances); SG_INFO("%d test examples\n", num_lab); CSignal::clear_cancel(); // for each test example for (int32_t i=0; i<num_lab && (!CSignal::cancel_computations()); i++) { SG_PROGRESS(i,0,num_lab); // get distances from i-th test example to 0..num_train_labels-1 train examples distances_lhs(distances,0,num_train_labels-1,i); int32_t j; // assuming 0th train examples as nearest to i-th test example int32_t out_idx = 0; float64_t min_dist = distances[0]; // searching for nearest neighbor by comparing distances for (j=0; j<num_train_labels; j++) { if (distances[j]<min_dist) { min_dist = distances[j]; out_idx = j; } } // label i-th test example with label of nearest neighbor with out_idx index output->set_label(i,train_labels[out_idx]+min_label); } delete [] distances; return output; } void CKNN::classify_for_multiple_k(int32_t** dst, int32_t* num_vec, int32_t* k_out) { ASSERT(dst); ASSERT(k_out); ASSERT(num_vec); ASSERT(num_classes>0); ASSERT(distance); ASSERT(distance->get_num_vec_rhs()); int32_t num_lab=distance->get_num_vec_rhs(); ASSERT(m_k<=num_lab); int32_t* output=(int32_t*) malloc(sizeof(int32_t)*m_k*num_lab); //distances to train data and working buffer of train_labels float64_t* dists=new float64_t[num_train_labels]; int32_t* train_lab=new int32_t[num_train_labels]; ///histogram of classes and returned output int32_t* classes=new int32_t[num_classes]; SG_INFO( "%d test examples\n", num_lab); CSignal::clear_cancel(); for (int32_t i=0; i<num_lab && (!CSignal::cancel_computations()); i++) { SG_PROGRESS(i, 0, num_lab); // lhs idx 1..n and rhs idx i distances_lhs(dists,0,num_train_labels-1,i); for (int32_t j=0; j<num_train_labels; j++) train_lab[j]=train_labels[j]; //sort the distance vector for test example j to all train examples //classes[1..k] then holds the classes for minimum distance CMath::qsort_index(dists, train_lab, num_train_labels); //compute histogram of class outputs of the first k nearest neighbours for (int32_t j=0; j<num_classes; j++) classes[j]=0; for (int32_t j=0; j<m_k; j++) { classes[train_lab[j]]++; //choose the class that got 'outputted' most often int32_t out_idx=0; int32_t out_max=0; for (int32_t c=0; c<num_classes; c++) { if (out_max< classes[c]) { out_idx= c; out_max= classes[c]; } } output[j*num_lab+i]=out_idx+min_label; } } delete[] dists; delete[] train_lab; delete[] classes; *dst=output; *k_out=m_k; *num_vec=num_lab; } void CKNN::init_distance(CFeatures* data) { if (!distance) SG_ERROR("No distance assigned!\n"); CFeatures* lhs=distance->get_lhs(); if (!lhs || !lhs->get_num_vectors()) { SG_UNREF(lhs); SG_ERROR("No vectors on left hand side\n"); } distance->init(lhs, data); SG_UNREF(lhs); } bool CKNN::load(FILE* srcfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } bool CKNN::save(FILE* dstfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } <commit_msg>Removed _ from k_. (Commit the Great)<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2006 Christian Gehl * Written (W) 2006-2009 Soeren Sonnenburg * Written (W) 2011 Sergey Lisitsyn * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include "classifier/KNN.h" #include "features/Labels.h" #include "lib/Mathematics.h" #include "lib/Signal.h" using namespace shogun; CKNN::CKNN() : CDistanceMachine(), m_k(3), num_classes(0), num_train_labels(0), train_labels(NULL), m_q(1.0) { } CKNN::CKNN(int32_t k, CDistance* d, CLabels* trainlab) : CDistanceMachine(), m_k(k), num_classes(0), train_labels(NULL), m_q(1.0) { ASSERT(d); ASSERT(trainlab); set_distance(d); set_labels(trainlab); num_train_labels=trainlab->get_num_labels(); } CKNN::~CKNN() { delete[] train_labels; } bool CKNN::train(CFeatures* data) { ASSERT(labels); ASSERT(distance); if (data) { if (labels->get_num_labels() != data->get_num_vectors()) SG_ERROR("Number of training vectors does not match number of labels\n"); distance->init(data, data); } train_labels=labels->get_int_labels(num_train_labels); ASSERT(train_labels); ASSERT(num_train_labels>0); int32_t max_class=train_labels[0]; int32_t min_class=train_labels[0]; int32_t i; for (i=1; i<num_train_labels; i++) { max_class=CMath::max(max_class, train_labels[i]); min_class=CMath::min(min_class, train_labels[i]); } for (i=0; i<num_train_labels; i++) train_labels[i]-=min_class; min_label=min_class; num_classes=max_class-min_class+1; SG_INFO( "num_classes: %d (%+d to %+d) num_train: %d\n", num_classes, min_class, max_class, num_train_labels); return true; } CLabels* CKNN::classify() { ASSERT(num_classes>0); ASSERT(distance); ASSERT(distance->get_num_vec_rhs()); int32_t num_lab=distance->get_num_vec_rhs(); ASSERT(m_k<=num_lab); CLabels* output=new CLabels(num_lab); //distances to train data and working buffer of train_labels float64_t* dists=new float64_t[num_train_labels]; int32_t* train_lab=new int32_t[num_train_labels]; ASSERT(dists); ASSERT(train_lab); SG_INFO( "%d test examples\n", num_lab); CSignal::clear_cancel(); ///histogram of classes and returned output float64_t* classes=new float64_t[num_classes]; ASSERT(classes); for (int32_t i=0; i<num_lab && (!CSignal::cancel_computations()); i++) { SG_PROGRESS(i, 0, num_lab); // lhs idx 1..n and rhs idx i distances_lhs(dists,0,num_train_labels-1,i); int32_t j; for (j=0; j<num_train_labels; j++) train_lab[j]=train_labels[j]; //sort the distance vector for test example j to all train examples //classes[1..k] then holds the classes for minimum distance CMath::qsort_index(dists, train_lab, num_train_labels); //compute histogram of class outputs of the first k nearest neighbours for (j=0; j<num_classes; j++) classes[j]=0.0; float64_t multiplier = m_q; for (j=0; j<m_k; j++) { classes[train_lab[j]]+= multiplier; multiplier*= multiplier; } //choose the class that got 'outputted' most often int32_t out_idx=0; int32_t out_max=0; for (j=0; j<num_classes; j++) { if (out_max< classes[j]) { out_idx= j; out_max= classes[j]; } } output->set_label(i, out_idx+min_label); } delete[] classes; delete[] dists; delete[] train_lab; return output; } CLabels* CKNN::classify(CFeatures* data) { init_distance(data); // redirecting to fast (without sorting) classify if k==1 if (m_k == 1) return classify_NN(); return classify(); } CLabels* CKNN::classify_NN() { ASSERT(distance); ASSERT(num_classes>0); int32_t num_lab = distance->get_num_vec_rhs(); ASSERT(num_lab); CLabels* output = new CLabels(num_lab); float64_t* distances = new float64_t[num_train_labels]; ASSERT(distances); SG_INFO("%d test examples\n", num_lab); CSignal::clear_cancel(); // for each test example for (int32_t i=0; i<num_lab && (!CSignal::cancel_computations()); i++) { SG_PROGRESS(i,0,num_lab); // get distances from i-th test example to 0..num_train_labels-1 train examples distances_lhs(distances,0,num_train_labels-1,i); int32_t j; // assuming 0th train examples as nearest to i-th test example int32_t out_idx = 0; float64_t min_dist = distances[0]; // searching for nearest neighbor by comparing distances for (j=0; j<num_train_labels; j++) { if (distances[j]<min_dist) { min_dist = distances[j]; out_idx = j; } } // label i-th test example with label of nearest neighbor with out_idx index output->set_label(i,train_labels[out_idx]+min_label); } delete [] distances; return output; } void CKNN::classify_for_multiple_k(int32_t** dst, int32_t* num_vec, int32_t* k_out) { ASSERT(dst); ASSERT(k_out); ASSERT(num_vec); ASSERT(num_classes>0); ASSERT(distance); ASSERT(distance->get_num_vec_rhs()); int32_t num_lab=distance->get_num_vec_rhs(); ASSERT(m_k<=num_lab); int32_t* output=(int32_t*) malloc(sizeof(int32_t)*m_k*num_lab); //distances to train data and working buffer of train_labels float64_t* dists=new float64_t[num_train_labels]; int32_t* train_lab=new int32_t[num_train_labels]; ///histogram of classes and returned output int32_t* classes=new int32_t[num_classes]; SG_INFO( "%d test examples\n", num_lab); CSignal::clear_cancel(); for (int32_t i=0; i<num_lab && (!CSignal::cancel_computations()); i++) { SG_PROGRESS(i, 0, num_lab); // lhs idx 1..n and rhs idx i distances_lhs(dists,0,num_train_labels-1,i); for (int32_t j=0; j<num_train_labels; j++) train_lab[j]=train_labels[j]; //sort the distance vector for test example j to all train examples //classes[1..k] then holds the classes for minimum distance CMath::qsort_index(dists, train_lab, num_train_labels); //compute histogram of class outputs of the first k nearest neighbours for (int32_t j=0; j<num_classes; j++) classes[j]=0; for (int32_t j=0; j<m_k; j++) { classes[train_lab[j]]++; //choose the class that got 'outputted' most often int32_t out_idx=0; int32_t out_max=0; for (int32_t c=0; c<num_classes; c++) { if (out_max< classes[c]) { out_idx= c; out_max= classes[c]; } } output[j*num_lab+i]=out_idx+min_label; } } delete[] dists; delete[] train_lab; delete[] classes; *dst=output; *k_out=m_k; *num_vec=num_lab; } void CKNN::init_distance(CFeatures* data) { if (!distance) SG_ERROR("No distance assigned!\n"); CFeatures* lhs=distance->get_lhs(); if (!lhs || !lhs->get_num_vectors()) { SG_UNREF(lhs); SG_ERROR("No vectors on left hand side\n"); } distance->init(lhs, data); SG_UNREF(lhs); } bool CKNN::load(FILE* srcfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } bool CKNN::save(FILE* dstfile) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } <|endoftext|>
<commit_before>#include <iostream> #include <sauce/sauce.h> /** * The purpose of this test is to enforce ansi c++ compatibility within the source. * * It does so by first pulling in all desired includes, instantiating templates and then asserting * that it was compiled with -ansi. */ using ::sauce::AbstractProvider; using ::sauce::Binder; using ::sauce::Injector; using ::sauce::Modules; using ::sauce::Named; struct Animal { virtual std::string says() = 0; }; struct Cat: Animal { std::string says() { return "Meow"; } }; struct LieutenantShinysides {}; struct Fish: Animal { std::string says() { return "Blub blub"; } }; struct Meatloaf {}; struct Cow: Animal { std::string says() { return "Moo"; } }; struct CowProvider: AbstractProvider<Animal> { Animal * provide() { return new Cow(); } void dispose(Animal * cow) { delete cow; } }; struct Pond { sauce::shared_ptr<Animal> animal; Pond(sauce::shared_ptr<Animal> animal): animal(animal) {} }; void AnimalModule(Binder & binder) { binder.bind<Animal>().to<Cat()>(); binder.bind<Animal>().named<LieutenantShinysides>().to<Fish()>(); binder.bind<Animal>().named<Meatloaf>().toProvider<CowProvider()>(); binder.bind<Pond>().to<Pond(Named<Animal, LieutenantShinysides>)>(); } int main() { sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector()); #ifdef __STRICT_ANSI__ return 0; #else std::cerr << "This file was not compiled with -ansi." << std::endl; return 1; #endif } <commit_msg>And a little more.<commit_after>#include <iostream> #include <sauce/sauce.h> /** * The purpose of this test is to enforce ansi c++ compatibility within the source. * * It does so by first pulling in all desired includes, instantiating templates and then asserting * that it was compiled with -ansi. */ using ::sauce::AbstractProvider; using ::sauce::Binder; using ::sauce::Injector; using ::sauce::Modules; using ::sauce::Named; using ::sauce::Provider; struct Animal { virtual std::string says() = 0; }; struct Cat: Animal { std::string says() { return "Meow"; } }; struct LieutenantShinysides {}; struct Fish: Animal { std::string says() { return "Blub blub"; } }; struct Meatloaf {}; struct Cow: Animal { std::string says() { return "Moo"; } }; struct CowProvider: AbstractProvider<Animal> { Animal * provide() { return new Cow(); } void dispose(Animal * cow) { delete cow; } }; struct Pond { sauce::shared_ptr<Animal> animal; Pond(sauce::shared_ptr<Animal> animal): animal(animal) {} }; void AnimalModule(Binder & binder) { binder.bind<Animal>().to<Cat()>(); binder.bind<Animal>().named<LieutenantShinysides>().to<Fish()>(); binder.bind<Animal>().named<Meatloaf>().toProvider<CowProvider()>(); binder.bind<Pond>().to<Pond(Named<Animal, LieutenantShinysides>)>(); } int main() { sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector()); sauce::shared_ptr<Provider<Animal> > animalProvider = injector->get<Provider<Animal> >(); sauce::shared_ptr<Provider<Named<Animal, LieutenantShinysides> > > namedImplicitProvider = injector->get<Provider<Named<Animal, LieutenantShinysides> > >(); sauce::shared_ptr<Provider<Named<Animal, Meatloaf> > > namedExplicitProvider = injector->get<Provider<Named<Animal, Meatloaf> > >(); #ifdef __STRICT_ANSI__ return 0; #else std::cerr << "This file was not compiled with -ansi." << std::endl; return 1; #endif } <|endoftext|>
<commit_before>#include <boost/archive/polymorphic_iarchive.hpp> #include <boost/archive/polymorphic_oarchive.hpp> #include <boost/serialization/export.hpp> #include <boost/lexical_cast.hpp> #include "watcherColors.h" #include <string> using namespace boost; using namespace std; BOOST_CLASS_EXPORT_GUID(watcher::event::Color, "watcher::event::Color"); namespace watcher { namespace event { INIT_LOGGER(Color, "Color"); const Color Color::black(0x00, 0x00, 0x00, 0x00); const Color Color::white(0xff, 0xff, 0xff, 0x00); const Color Color::violet(0xee, 0x82, 0xee, 0x00); const Color Color::indigo(0x4b, 0x00, 0x82, 0x00); const Color Color::blue(0x00, 0x00, 0xff, 0x00); const Color Color::green(0x00, 0x80, 0x00, 0x00); const Color Color::yellow(0xff, 0xff, 0x00, 0x00); const Color Color::orange(0xff, 0xa5, 0x00, 0x00); const Color Color::red(0xff, 0x00, 0x00, 0x00); const Color Color::darkblue(0x00, 0x00, 0x8b, 0x00); const Color Color::magenta(0xff, 0x00, 0xff, 0x00); const Color Color::gold(0xff, 0xd7, 0xff, 0x00); const Color Color::turquoise(0x40, 0xe0, 0xd0, 0x00); const Color Color::brown(0xa5, 0x2a, 0x2a, 0x00); const Color Color::deeppink(0xff, 0x14, 0x93, 0x00); Color::Color() : r(0), g(0), b(0), a(0) { TRACE_ENTER(); TRACE_EXIT(); } Color::Color(unsigned char R, unsigned char G, unsigned char B, unsigned char A) : r(R), g(G), b(B), a(A) { TRACE_ENTER(); TRACE_EXIT(); } Color::Color(const uint32_t &color) : r(0), g(0), b(0), a(0) { TRACE_ENTER(); r=color>>24; g=color>>16; b=color>>8; a=color; TRACE_EXIT(); } Color::Color(const Color &other) : r(other.r), g(other.g), b(other.b), a(other.a) { TRACE_ENTER(); TRACE_EXIT(); } Color::~Color() { TRACE_ENTER(); TRACE_EXIT(); } bool Color::fromString(const std::string &color) { if (color=="black") *this=Color::black; else if(color=="white") *this=Color::white; else if(color=="violet") *this=Color::violet; else if(color=="indigo") *this=Color::indigo; else if(color=="blue") *this=Color::blue; else if(color=="green") *this=Color::green; else if(color=="yellow") *this=Color::yellow; else if(color=="orange") *this=Color::orange; else if(color=="red") *this=Color::red; else if(color=="darkblue") *this=Color::darkblue; else if(color=="gold") *this=Color::gold; else if(color=="turquoise") *this=Color::turquoise; else if(color=="brown") *this=Color::brown; else if(color=="deeppink") *this=Color::deeppink; else { // basic sanity checking, may be a better way to do this. if (color[0]!='0' && color[1]!='x' && color.length()!=10) { TRACE_EXIT_RET("false"); return false; } istringstream is(color); uint32_t vals; is >> hex >> vals; r=vals>>24; g=vals>>16; b=vals>>8; a=vals; } TRACE_EXIT_RET("true"); return true; } bool Color::operator==(const Color &other) const { TRACE_ENTER(); bool retVal= r==other.r && g==other.g && b==other.b && a==other.a; TRACE_EXIT_RET((retVal ? "true" : "false")); return retVal; } Color &Color::operator=(const Color &other) { TRACE_ENTER(); r=other.r; g=other.g; b=other.b; a=other.a; TRACE_EXIT(); return *this; } std::ostream &Color::toStream(std::ostream &out) const { TRACE_ENTER(); out << toString(*this); TRACE_EXIT(); return out; } ostream &operator<<(ostream &out, const Color &c) { TRACE_ENTER(); c.operator<<(out); TRACE_EXIT(); return out; } std::string Color::toString(const Color &c) { if (c==Color::black) return string("black"); else if (c==Color::white) return string("white"); else if (c==Color::violet) return string("violet"); else if (c==Color::indigo) return string("indigo"); else if (c==Color::blue) return string("blue"); else if (c==Color::green) return string("green"); else if (c==Color::yellow) return string("yellow"); else if (c==Color::orange) return string("orange"); else if (c==Color::red) return string("red"); else if (c==Color::darkblue) return string("darkblue"); else if (c==Color::magenta) return string("magenta"); else if (c==Color::gold) return string("gold"); else if (c==Color::turquoise) return string("turquoise"); else if (c==Color::brown) return string("brown"); else if (c==Color::deeppink) return string("deeppink"); else { char buf[12]; snprintf(buf, sizeof(buf), "0x%02x%02x%02x%02x", c.r, c.g, c.b, c.a); return string(buf); } } } } <commit_msg>Added #include <cstdio> for newer g++ that doesn't do the implicit include.<commit_after>#include <boost/archive/polymorphic_iarchive.hpp> #include <boost/archive/polymorphic_oarchive.hpp> #include <boost/serialization/export.hpp> #include <boost/lexical_cast.hpp> #include "watcherColors.h" #include <cstdio> #include <string> using namespace boost; using namespace std; BOOST_CLASS_EXPORT_GUID(watcher::event::Color, "watcher::event::Color"); namespace watcher { namespace event { INIT_LOGGER(Color, "Color"); const Color Color::black(0x00, 0x00, 0x00, 0x00); const Color Color::white(0xff, 0xff, 0xff, 0x00); const Color Color::violet(0xee, 0x82, 0xee, 0x00); const Color Color::indigo(0x4b, 0x00, 0x82, 0x00); const Color Color::blue(0x00, 0x00, 0xff, 0x00); const Color Color::green(0x00, 0x80, 0x00, 0x00); const Color Color::yellow(0xff, 0xff, 0x00, 0x00); const Color Color::orange(0xff, 0xa5, 0x00, 0x00); const Color Color::red(0xff, 0x00, 0x00, 0x00); const Color Color::darkblue(0x00, 0x00, 0x8b, 0x00); const Color Color::magenta(0xff, 0x00, 0xff, 0x00); const Color Color::gold(0xff, 0xd7, 0xff, 0x00); const Color Color::turquoise(0x40, 0xe0, 0xd0, 0x00); const Color Color::brown(0xa5, 0x2a, 0x2a, 0x00); const Color Color::deeppink(0xff, 0x14, 0x93, 0x00); Color::Color() : r(0), g(0), b(0), a(0) { TRACE_ENTER(); TRACE_EXIT(); } Color::Color(unsigned char R, unsigned char G, unsigned char B, unsigned char A) : r(R), g(G), b(B), a(A) { TRACE_ENTER(); TRACE_EXIT(); } Color::Color(const uint32_t &color) : r(0), g(0), b(0), a(0) { TRACE_ENTER(); r=color>>24; g=color>>16; b=color>>8; a=color; TRACE_EXIT(); } Color::Color(const Color &other) : r(other.r), g(other.g), b(other.b), a(other.a) { TRACE_ENTER(); TRACE_EXIT(); } Color::~Color() { TRACE_ENTER(); TRACE_EXIT(); } bool Color::fromString(const std::string &color) { if (color=="black") *this=Color::black; else if(color=="white") *this=Color::white; else if(color=="violet") *this=Color::violet; else if(color=="indigo") *this=Color::indigo; else if(color=="blue") *this=Color::blue; else if(color=="green") *this=Color::green; else if(color=="yellow") *this=Color::yellow; else if(color=="orange") *this=Color::orange; else if(color=="red") *this=Color::red; else if(color=="darkblue") *this=Color::darkblue; else if(color=="gold") *this=Color::gold; else if(color=="turquoise") *this=Color::turquoise; else if(color=="brown") *this=Color::brown; else if(color=="deeppink") *this=Color::deeppink; else { // basic sanity checking, may be a better way to do this. if (color[0]!='0' && color[1]!='x' && color.length()!=10) { TRACE_EXIT_RET("false"); return false; } istringstream is(color); uint32_t vals; is >> hex >> vals; r=vals>>24; g=vals>>16; b=vals>>8; a=vals; } TRACE_EXIT_RET("true"); return true; } bool Color::operator==(const Color &other) const { TRACE_ENTER(); bool retVal= r==other.r && g==other.g && b==other.b && a==other.a; TRACE_EXIT_RET((retVal ? "true" : "false")); return retVal; } Color &Color::operator=(const Color &other) { TRACE_ENTER(); r=other.r; g=other.g; b=other.b; a=other.a; TRACE_EXIT(); return *this; } std::ostream &Color::toStream(std::ostream &out) const { TRACE_ENTER(); out << toString(*this); TRACE_EXIT(); return out; } ostream &operator<<(ostream &out, const Color &c) { TRACE_ENTER(); c.operator<<(out); TRACE_EXIT(); return out; } std::string Color::toString(const Color &c) { if (c==Color::black) return string("black"); else if (c==Color::white) return string("white"); else if (c==Color::violet) return string("violet"); else if (c==Color::indigo) return string("indigo"); else if (c==Color::blue) return string("blue"); else if (c==Color::green) return string("green"); else if (c==Color::yellow) return string("yellow"); else if (c==Color::orange) return string("orange"); else if (c==Color::red) return string("red"); else if (c==Color::darkblue) return string("darkblue"); else if (c==Color::magenta) return string("magenta"); else if (c==Color::gold) return string("gold"); else if (c==Color::turquoise) return string("turquoise"); else if (c==Color::brown) return string("brown"); else if (c==Color::deeppink) return string("deeppink"); else { char buf[12]; snprintf(buf, sizeof(buf), "0x%02x%02x%02x%02x", c.r, c.g, c.b, c.a); return string(buf); } } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: calendar_gregorian.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2006-10-06 09:08:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _I18N_CALENDAR_GREGORIAN_HXX_ #define _I18N_CALENDAR_GREGORIAN_HXX_ #include "calendarImpl.hxx" #include "nativenumbersupplier.hxx" // External unicode includes (from icu) cause warning C4668 on Windows. // We want to minimize the patches to external headers, so the warnings are // disabled here instead of in the header file itself. #ifdef _MSC_VER #pragma warning(push, 1) #endif #include "unicode/calendar.h" #ifdef _MSC_VER #pragma warning(pop) #endif // ---------------------------------------------------- // class Calendar_gregorian // ---------------------------------------------------- namespace com { namespace sun { namespace star { namespace i18n { struct Era { sal_Int32 year; sal_Int32 month; sal_Int32 day; }; class Calendar_gregorian : public CalendarImpl { public: // Constructors Calendar_gregorian(); Calendar_gregorian(Era *_eraArray); /** * Destructor */ ~Calendar_gregorian(); // Methods virtual void SAL_CALL loadCalendar(const rtl::OUString& uniqueID, const com::sun::star::lang::Locale& rLocale) throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDateTime(double nTimeInDays) throw(com::sun::star::uno::RuntimeException); virtual double SAL_CALL getDateTime() throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL setValue( sal_Int16 nFieldIndex, sal_Int16 nValue ) throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getValue(sal_Int16 nFieldIndex) throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL addValue(sal_Int16 nFieldIndex, sal_Int32 nAmount) throw(com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isValid() throw (com::sun::star::uno::RuntimeException); virtual Calendar SAL_CALL getLoadedCalendar() throw(com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getUniqueID() throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getFirstDayOfWeek() throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL setFirstDayOfWeek(sal_Int16 nDay) throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL setMinimumNumberOfDaysForFirstWeek(sal_Int16 nDays) throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getMinimumNumberOfDaysForFirstWeek() throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getNumberOfMonthsInYear() throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getNumberOfDaysInWeek() throw(com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence < CalendarItem > SAL_CALL getMonths() throw(com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence < CalendarItem > SAL_CALL getDays() throw(com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getDisplayName(sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType) throw(com::sun::star::uno::RuntimeException); // Methods in XExtendedCalendar virtual rtl::OUString SAL_CALL getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) throw (com::sun::star::uno::RuntimeException); //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw(com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence < rtl::OUString > SAL_CALL getSupportedServiceNames() throw(com::sun::star::uno::RuntimeException); protected: Era *eraArray; icu::Calendar *body; NativeNumberSupplier aNatNum; const sal_Char* cCalendar; com::sun::star::lang::Locale aLocale; sal_uInt32 fieldSet; sal_Int16 fieldValue[CalendarFieldIndex::FIELD_COUNT]; sal_Int16 fieldSetValue[CalendarFieldIndex::FIELD_COUNT]; virtual void SAL_CALL mapToGregorian() throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL mapFromGregorian() throw(com::sun::star::uno::RuntimeException); void SAL_CALL getValue() throw(com::sun::star::uno::RuntimeException); private: // submit fieldValue array according to fieldSet, plus YMDhms if >=0 void SAL_CALL submitValues( sal_Int32 nYear, sal_Int32 nMonth, sal_Int32 nDay, sal_Int32 nHour, sal_Int32 nMinute, sal_Int32 nSecond, sal_Int32 nMilliSecond) throw(com::sun::star::uno::RuntimeException); void SAL_CALL setValue() throw(com::sun::star::uno::RuntimeException); void SAL_CALL init(Era *_eraArray) throw(com::sun::star::uno::RuntimeException); Calendar aCalendar; }; // ---------------------------------------------------- // class Calendar_hanja // ---------------------------------------------------- class Calendar_hanja : public Calendar_gregorian { public: // Constructors Calendar_hanja(); virtual void SAL_CALL loadCalendar(const rtl::OUString& uniqueID, const com::sun::star::lang::Locale& rLocale) throw(com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getDisplayName(sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType) throw(com::sun::star::uno::RuntimeException); }; // ---------------------------------------------------- // class Calendar_gengou // ---------------------------------------------------- class Calendar_gengou : public Calendar_gregorian { public: // Constructors Calendar_gengou(); }; // ---------------------------------------------------- // class Calendar_ROC // ---------------------------------------------------- class Calendar_ROC : public Calendar_gregorian { public: // Constructors Calendar_ROC(); }; // ---------------------------------------------------- // class Calendar_buddhist // ---------------------------------------------------- class Calendar_buddhist : public Calendar_gregorian { public: // Constructors Calendar_buddhist(); // Methods in XExtendedCalendar virtual rtl::OUString SAL_CALL getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) throw (com::sun::star::uno::RuntimeException); }; } } } } #endif <commit_msg>INTEGRATION: CWS i18n27 (1.11.22); FILE MERGED 2006/10/19 23:05:37 khong 1.11.22.2: #68819# fix a core dump 2006/10/10 20:05:55 khong 1.11.22.1: #i68819 move getValue from construct to loadCalendar<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: calendar_gregorian.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2006-11-06 14:39:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _I18N_CALENDAR_GREGORIAN_HXX_ #define _I18N_CALENDAR_GREGORIAN_HXX_ #include "calendarImpl.hxx" #include "nativenumbersupplier.hxx" // External unicode includes (from icu) cause warning C4668 on Windows. // We want to minimize the patches to external headers, so the warnings are // disabled here instead of in the header file itself. #ifdef _MSC_VER #pragma warning(push, 1) #endif #include "unicode/calendar.h" #ifdef _MSC_VER #pragma warning(pop) #endif // ---------------------------------------------------- // class Calendar_gregorian // ---------------------------------------------------- namespace com { namespace sun { namespace star { namespace i18n { struct Era { sal_Int32 year; sal_Int32 month; sal_Int32 day; }; class Calendar_gregorian : public CalendarImpl { public: // Constructors Calendar_gregorian(); Calendar_gregorian(Era *_eraArray); void SAL_CALL init(Era *_eraArray); /** * Destructor */ ~Calendar_gregorian(); // Methods virtual void SAL_CALL loadCalendar(const rtl::OUString& uniqueID, const com::sun::star::lang::Locale& rLocale) throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDateTime(double nTimeInDays) throw(com::sun::star::uno::RuntimeException); virtual double SAL_CALL getDateTime() throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL setValue( sal_Int16 nFieldIndex, sal_Int16 nValue ) throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getValue(sal_Int16 nFieldIndex) throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL addValue(sal_Int16 nFieldIndex, sal_Int32 nAmount) throw(com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isValid() throw (com::sun::star::uno::RuntimeException); virtual Calendar SAL_CALL getLoadedCalendar() throw(com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getUniqueID() throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getFirstDayOfWeek() throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL setFirstDayOfWeek(sal_Int16 nDay) throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL setMinimumNumberOfDaysForFirstWeek(sal_Int16 nDays) throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getMinimumNumberOfDaysForFirstWeek() throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getNumberOfMonthsInYear() throw(com::sun::star::uno::RuntimeException); virtual sal_Int16 SAL_CALL getNumberOfDaysInWeek() throw(com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence < CalendarItem > SAL_CALL getMonths() throw(com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence < CalendarItem > SAL_CALL getDays() throw(com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getDisplayName(sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType) throw(com::sun::star::uno::RuntimeException); // Methods in XExtendedCalendar virtual rtl::OUString SAL_CALL getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) throw (com::sun::star::uno::RuntimeException); //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw(com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence < rtl::OUString > SAL_CALL getSupportedServiceNames() throw(com::sun::star::uno::RuntimeException); protected: Era *eraArray; icu::Calendar *body; NativeNumberSupplier aNatNum; const sal_Char* cCalendar; com::sun::star::lang::Locale aLocale; sal_uInt32 fieldSet; sal_Int16 fieldValue[CalendarFieldIndex::FIELD_COUNT]; sal_Int16 fieldSetValue[CalendarFieldIndex::FIELD_COUNT]; virtual void SAL_CALL mapToGregorian() throw(com::sun::star::uno::RuntimeException); virtual void SAL_CALL mapFromGregorian() throw(com::sun::star::uno::RuntimeException); void SAL_CALL getValue() throw(com::sun::star::uno::RuntimeException); private: // submit fieldValue array according to fieldSet, plus YMDhms if >=0 void SAL_CALL submitValues( sal_Int32 nYear, sal_Int32 nMonth, sal_Int32 nDay, sal_Int32 nHour, sal_Int32 nMinute, sal_Int32 nSecond, sal_Int32 nMilliSecond) throw(com::sun::star::uno::RuntimeException); void SAL_CALL setValue() throw(com::sun::star::uno::RuntimeException); Calendar aCalendar; }; // ---------------------------------------------------- // class Calendar_hanja // ---------------------------------------------------- class Calendar_hanja : public Calendar_gregorian { public: // Constructors Calendar_hanja(); virtual void SAL_CALL loadCalendar(const rtl::OUString& uniqueID, const com::sun::star::lang::Locale& rLocale) throw(com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getDisplayName(sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType) throw(com::sun::star::uno::RuntimeException); }; // ---------------------------------------------------- // class Calendar_gengou // ---------------------------------------------------- class Calendar_gengou : public Calendar_gregorian { public: // Constructors Calendar_gengou(); }; // ---------------------------------------------------- // class Calendar_ROC // ---------------------------------------------------- class Calendar_ROC : public Calendar_gregorian { public: // Constructors Calendar_ROC(); }; // ---------------------------------------------------- // class Calendar_buddhist // ---------------------------------------------------- class Calendar_buddhist : public Calendar_gregorian { public: // Constructors Calendar_buddhist(); // Methods in XExtendedCalendar virtual rtl::OUString SAL_CALL getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode ) throw (com::sun::star::uno::RuntimeException); }; } } } } #endif <|endoftext|>
<commit_before>#include "catch.hpp" #include <limits> #include <vector> #include <random> #include <simdify/simd_types.hpp> #include <simdify/util/malloc.hpp> TEST_CASE("Ray-box intersection", "[perf]") { // allocate data struct RayBoxData { float minx[8]; float miny[8]; float minz[8]; float maxx[8]; float maxy[8]; float maxz[8]; }; const size_t numData = 1024; using vec_t = std::vector<RayBoxData, simd::aligned_allocator<RayBoxData, sizeof(__m256)>>; vec_t data(numData); enum class Result : char { fail = 13, win = 42 }; std::vector<Result> resultsNonSimd(8 * numData); std::vector<Result> resultsHandSimd(8 * numData); std::vector<Result> resultsLibSimd(8 * numData); // fill data std::random_device rd; std::minstd_rand re(rd()); std::normal_distribution<float> dist(0, 1); auto fill = [&dist, &re](float* data, size_t num) { for (size_t i = 0; i < num; ++i) { *(data++) = dist(re); } }; const size_t numFloats = (sizeof(RayBoxData) / sizeof(float)) * numData; fill((float*)(data.data()), numFloats); // common pre-calculations auto gamma = [](int n) { float eps2 = static_cast<float>(std::numeric_limits<float>::epsilon() * 0.5); return (n * eps2) / (1 - n * eps2); }; struct Vec3f { float x, y, z; }; const float robustFactor = 1 + 2 * gamma(3); const Vec3f invDir = { dist(re), dist(re), dist(re) }; const Vec3f rayOrigin = { dist(re), dist(re), dist(re) }; const float rayTMax = 100.f; const int dirIsNeg[3] = { (dist(re) > 0) ? 1 : 0, (dist(re) > 0) ? 1 : 0, (dist(re) > 0) ? 1 : 0 }; // non-SIMD implementation (for correctness checking) auto nonSimd = [&]() { auto resIt = resultsNonSimd.begin(); for (const auto& elem : data) { for (int i = 0; i < 8; ++i) { Vec3f bounds[2] = { { elem.minx[i], elem.miny[i], elem.minz[i] }, { elem.maxx[i], elem.maxy[i], elem.maxz[i] }, }; float tmin = (bounds[dirIsNeg[0]].x - rayOrigin.x) * invDir.x; float tmax = (bounds[1 - dirIsNeg[0]].x - rayOrigin.x) * invDir.x; float tminy = (bounds[dirIsNeg[1]].y - rayOrigin.y) * invDir.y; float tmaxy = (bounds[1 - dirIsNeg[1]].y - rayOrigin.y) * invDir.y; tmax *= robustFactor; tmaxy *= robustFactor; if (tmin > tmaxy || tminy > tmax) { *(resIt++) = Result::fail; continue; } if (tminy > tmin) tmin = tminy; if (tmaxy < tmax) tmax = tmaxy; float tminz = (bounds[dirIsNeg[2]].z - rayOrigin.z) * invDir.z; float tmaxz = (bounds[1 - dirIsNeg[2]].z - rayOrigin.z) * invDir.z; tmaxz *= robustFactor; if (tmin > tmaxz || tminz > tmax) { *(resIt++) = Result::fail; continue; } if (tminz > tmin) tmin = tminz; if (tmaxz < tmax) tmax = tmaxz; *(resIt++) = ((tmin < rayTMax) && (tmax > 0)) ? Result::win : Result::fail; } } }; // SIMD implementation by hand auto handSimd = [&]() { auto resIt = resultsHandSimd.begin(); for (const auto& elem : data) { __m256 tmin, tmax; { __m256 minx = _mm256_load_ps(elem.minx); __m256 maxx = _mm256_load_ps(elem.maxx); __m256 idirx = _mm256_broadcast_ss(&invDir.x); __m256 rayox = _mm256_broadcast_ss(&rayOrigin.x); tmin = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[0] ? maxx : minx, rayox), idirx); tmax = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[0] ? minx : maxx, rayox), idirx); } { __m256 tminy, tmaxy; { __m256 miny = _mm256_load_ps(elem.miny); __m256 maxy = _mm256_load_ps(elem.maxy); __m256 idiry = _mm256_broadcast_ss(&invDir.y); __m256 rayoy = _mm256_broadcast_ss(&rayOrigin.y); tminy = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[1] ? maxy : miny, rayoy), idiry); tmaxy = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[1] ? miny : maxy, rayoy), idiry); } __m256 factor = _mm256_broadcast_ss(&robustFactor); tmax = _mm256_mul_ps(tmax, factor); tmaxy = _mm256_mul_ps(tmaxy, factor); { __m256 fail = _mm256_or_ps(_mm256_cmp_ps(tmin, tmaxy, _CMP_GT_OQ), _mm256_cmp_ps(tminy, tmax, _CMP_GT_OQ)); fail = _mm256_and_ps(fail, _mm256_permute_ps(fail, _MM_SHUFFLE(2, 3, 0, 1))); fail = _mm256_and_ps(fail, _mm256_permute_ps(fail, _MM_SHUFFLE(1, 0, 3, 2))); fail = _mm256_and_ps(fail, _mm256_permute2f128_ps(fail, fail, _MM_SHUFFLE(0, 0, 0, 1))); float all_failed = _mm_cvtss_f32(_mm256_castps256_ps128(fail)); if (simd::tou(all_failed)) { // mark fail continue; } } tmin = _mm256_blendv_ps(tmin, tminy, _mm256_cmp_ps(tminy, tmin, _CMP_GT_OQ)); tmax = _mm256_blendv_ps(tmax, tmaxy, _mm256_cmp_ps(tmaxy, tmax, _CMP_LT_OQ)); } { __m256 tminz, tmaxz; { __m256 minz = _mm256_load_ps(elem.minz); __m256 maxz = _mm256_load_ps(elem.maxz); __m256 idirz = _mm256_broadcast_ss(&invDir.z); __m256 rayoz = _mm256_broadcast_ss(&rayOrigin.z); tminz = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[2] ? maxz : minz, rayoz), idirz); tmaxz = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[2] ? minz : maxz, rayoz), idirz); } __m256 factor = _mm256_broadcast_ss(&robustFactor); tmaxz = _mm256_mul_ps(tmaxz, factor); { __m256 fail = _mm256_or_ps(_mm256_cmp_ps(tmin, tmaxz, _CMP_GT_OQ), _mm256_cmp_ps(tminz, tmax, _CMP_GT_OQ)); fail = _mm256_and_ps(fail, _mm256_permute_ps(fail, _MM_SHUFFLE(2, 3, 0, 1))); fail = _mm256_and_ps(fail, _mm256_permute_ps(fail, _MM_SHUFFLE(1, 0, 3, 2))); fail = _mm256_and_ps(fail, _mm256_permute2f128_ps(fail, fail, _MM_SHUFFLE(0, 0, 0, 1))); float all_failed = _mm_cvtss_f32(_mm256_castps256_ps128(fail)); if (simd::tou(all_failed)) { // mark fail continue; } } tmin = _mm256_blendv_ps(tmin, tminz, _mm256_cmp_ps(tminz, tmin, _CMP_GT_OQ)); tmax = _mm256_blendv_ps(tmax, tmaxz, _mm256_cmp_ps(tmaxz, tmax, _CMP_LT_OQ)); } __m256 win = _mm256_and_ps(_mm256_cmp_ps(tmin, _mm256_broadcast_ss(&rayTMax), _CMP_LT_OQ), _mm256_cmp_ps(tmax, _mm256_setzero_ps(), _CMP_GT_OQ)); uint32_t uwin[8]; std::memcpy(uwin, &win, sizeof(__m256)); for (int i = 0; i < 8; ++i) { *(resIt++) = uwin[i] ? Result::win : Result::fail; } } }; } <commit_msg>Measure number of hits from both algorithms, should be equal<commit_after>#include "catch.hpp" #include <limits> #include <vector> #include <random> #include <simdify/simd_types.hpp> #include <simdify/util/malloc.hpp> TEST_CASE("Ray-box intersection", "[perf]") { // allocate data struct RayBoxData { float minx[8]; float miny[8]; float minz[8]; float maxx[8]; float maxy[8]; float maxz[8]; }; const size_t numData = 1024; using vec_t = std::vector<RayBoxData, simd::aligned_allocator<RayBoxData, sizeof(__m256)>>; vec_t data(numData); enum class Result : char { fail = 13, win = 42 }; std::vector<Result> resultsNonSimd(8 * numData); std::vector<Result> resultsHandSimd(8 * numData); std::vector<Result> resultsLibSimd(8 * numData); // fill data std::random_device rd; std::minstd_rand re(rd()); std::normal_distribution<float> dist(0, 1); auto fill = [&dist, &re](float* data, size_t num) { for (size_t i = 0; i < num; ++i) { *(data++) = dist(re); } }; const size_t numFloats = (sizeof(RayBoxData) / sizeof(float)) * numData; fill((float*)(data.data()), numFloats); // common pre-calculations auto gamma = [](int n) { float eps2 = static_cast<float>(std::numeric_limits<float>::epsilon() * 0.5); return (n * eps2) / (1 - n * eps2); }; struct Vec3f { float x, y, z; }; const float robustFactor = 1 + 2 * gamma(3); const Vec3f invDir = { dist(re), dist(re), dist(re) }; const Vec3f rayOrigin = { dist(re), dist(re), dist(re) }; const float rayTMax = 100.f; const int dirIsNeg[3] = { (dist(re) > 0) ? 1 : 0, (dist(re) > 0) ? 1 : 0, (dist(re) > 0) ? 1 : 0 }; // non-SIMD implementation (for correctness checking) auto nonSimd = [&]() { auto resIt = resultsNonSimd.begin(); for (const auto& elem : data) { for (int i = 0; i < 8; ++i) { Vec3f bounds[2] = { { elem.minx[i], elem.miny[i], elem.minz[i] }, { elem.maxx[i], elem.maxy[i], elem.maxz[i] }, }; float tmin = (bounds[dirIsNeg[0]].x - rayOrigin.x) * invDir.x; float tmax = (bounds[1 - dirIsNeg[0]].x - rayOrigin.x) * invDir.x; float tminy = (bounds[dirIsNeg[1]].y - rayOrigin.y) * invDir.y; float tmaxy = (bounds[1 - dirIsNeg[1]].y - rayOrigin.y) * invDir.y; tmax *= robustFactor; tmaxy *= robustFactor; if (tmin > tmaxy || tminy > tmax) { *(resIt++) = Result::fail; continue; } if (tminy > tmin) tmin = tminy; if (tmaxy < tmax) tmax = tmaxy; float tminz = (bounds[dirIsNeg[2]].z - rayOrigin.z) * invDir.z; float tmaxz = (bounds[1 - dirIsNeg[2]].z - rayOrigin.z) * invDir.z; tmaxz *= robustFactor; if (tmin > tmaxz || tminz > tmax) { *(resIt++) = Result::fail; continue; } if (tminz > tmin) tmin = tminz; if (tmaxz < tmax) tmax = tmaxz; *(resIt++) = ((tmin < rayTMax) && (tmax > 0)) ? Result::win : Result::fail; } } }; // SIMD implementation by hand auto handSimd = [&]() { auto resIt = resultsHandSimd.begin(); for (const auto& elem : data) { __m256 tmin, tmax; { __m256 minx = _mm256_load_ps(elem.minx); __m256 maxx = _mm256_load_ps(elem.maxx); __m256 idirx = _mm256_broadcast_ss(&invDir.x); __m256 rayox = _mm256_broadcast_ss(&rayOrigin.x); tmin = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[0] ? maxx : minx, rayox), idirx); tmax = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[0] ? minx : maxx, rayox), idirx); } { __m256 tminy, tmaxy; { __m256 miny = _mm256_load_ps(elem.miny); __m256 maxy = _mm256_load_ps(elem.maxy); __m256 idiry = _mm256_broadcast_ss(&invDir.y); __m256 rayoy = _mm256_broadcast_ss(&rayOrigin.y); tminy = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[1] ? maxy : miny, rayoy), idiry); tmaxy = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[1] ? miny : maxy, rayoy), idiry); } __m256 factor = _mm256_broadcast_ss(&robustFactor); tmax = _mm256_mul_ps(tmax, factor); tmaxy = _mm256_mul_ps(tmaxy, factor); { __m256 fail = _mm256_or_ps(_mm256_cmp_ps(tmin, tmaxy, _CMP_GT_OQ), _mm256_cmp_ps(tminy, tmax, _CMP_GT_OQ)); fail = _mm256_and_ps(fail, _mm256_permute_ps(fail, _MM_SHUFFLE(2, 3, 0, 1))); fail = _mm256_and_ps(fail, _mm256_permute_ps(fail, _MM_SHUFFLE(1, 0, 3, 2))); fail = _mm256_and_ps(fail, _mm256_permute2f128_ps(fail, fail, _MM_SHUFFLE(0, 0, 0, 1))); float all_failed = _mm_cvtss_f32(_mm256_castps256_ps128(fail)); if (simd::tou(all_failed)) { for (int i = 0; i < 8; ++i) { *(resIt++) = Result::fail; } continue; } } tmin = _mm256_blendv_ps(tmin, tminy, _mm256_cmp_ps(tminy, tmin, _CMP_GT_OQ)); tmax = _mm256_blendv_ps(tmax, tmaxy, _mm256_cmp_ps(tmaxy, tmax, _CMP_LT_OQ)); } { __m256 tminz, tmaxz; { __m256 minz = _mm256_load_ps(elem.minz); __m256 maxz = _mm256_load_ps(elem.maxz); __m256 idirz = _mm256_broadcast_ss(&invDir.z); __m256 rayoz = _mm256_broadcast_ss(&rayOrigin.z); tminz = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[2] ? maxz : minz, rayoz), idirz); tmaxz = _mm256_mul_ps(_mm256_sub_ps(dirIsNeg[2] ? minz : maxz, rayoz), idirz); } __m256 factor = _mm256_broadcast_ss(&robustFactor); tmaxz = _mm256_mul_ps(tmaxz, factor); { __m256 fail = _mm256_or_ps(_mm256_cmp_ps(tmin, tmaxz, _CMP_GT_OQ), _mm256_cmp_ps(tminz, tmax, _CMP_GT_OQ)); fail = _mm256_and_ps(fail, _mm256_permute_ps(fail, _MM_SHUFFLE(2, 3, 0, 1))); fail = _mm256_and_ps(fail, _mm256_permute_ps(fail, _MM_SHUFFLE(1, 0, 3, 2))); fail = _mm256_and_ps(fail, _mm256_permute2f128_ps(fail, fail, _MM_SHUFFLE(0, 0, 0, 1))); float all_failed = _mm_cvtss_f32(_mm256_castps256_ps128(fail)); if (simd::tou(all_failed)) { for (int i = 0; i < 8; ++i) { *(resIt++) = Result::fail; } continue; } } tmin = _mm256_blendv_ps(tmin, tminz, _mm256_cmp_ps(tminz, tmin, _CMP_GT_OQ)); tmax = _mm256_blendv_ps(tmax, tmaxz, _mm256_cmp_ps(tmaxz, tmax, _CMP_LT_OQ)); } __m256 win = _mm256_and_ps(_mm256_cmp_ps(tmin, _mm256_broadcast_ss(&rayTMax), _CMP_LT_OQ), _mm256_cmp_ps(tmax, _mm256_setzero_ps(), _CMP_GT_OQ)); uint32_t uwin[8]; std::memcpy(uwin, &win, sizeof(__m256)); for (int i = 0; i < 8; ++i) { *(resIt++) = uwin[i] ? Result::win : Result::fail; } } }; nonSimd(); handSimd(); auto cntWin = std::count(resultsNonSimd.begin(), resultsNonSimd.end(), Result::win); auto cntWin2 = std::count(resultsHandSimd.begin(), resultsHandSimd.end(), Result::win); return; } <|endoftext|>
<commit_before>/** * @file llfloaterevent.cpp * @brief Display for events in the finder * * $LicenseInfo:firstyear=2004&license=viewergpl$ * * Copyright (c) 2004-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llfloaterevent.h" #include "message.h" #include "llnotificationsutil.h" #include "llui.h" #include "llagent.h" #include "llviewerwindow.h" #include "llbutton.h" #include "llcachename.h" #include "llcommandhandler.h" // secondlife:///app/chat/ support #include "lleventflags.h" #include "lleventnotifier.h" #include "llexpandabletextbox.h" #include "llfloater.h" #include "llfloaterreg.h" #include "llfloaterworldmap.h" #include "llinventorymodel.h" #include "llsecondlifeurls.h" #include "llslurl.h" #include "lltextbox.h" #include "lltexteditor.h" #include "lluiconstants.h" #include "llviewercontrol.h" #include "llweb.h" #include "llworldmap.h" #include "llworldmapmessage.h" #include "lluictrlfactory.h" #include "lltrans.h" class LLEventHandler : public LLCommandHandler { public: // requires trusted browser to trigger LLEventHandler() : LLCommandHandler("event", UNTRUSTED_THROTTLE) { } bool handle(const LLSD& params, const LLSD& query_map, LLMediaCtrl* web) { if (params.size() < 1) { return false; } LLFloaterEvent* floater = LLFloaterReg::getTypedInstance<LLFloaterEvent>("event"); if (floater) { floater->setEventID(params[0].asInteger()); LLFloaterReg::showTypedInstance<LLFloaterEvent>("event"); return true; } return false; } }; LLEventHandler gEventHandler; LLFloaterEvent::LLFloaterEvent(const LLSD& key) : LLFloater(key), mEventID(0) { } LLFloaterEvent::~LLFloaterEvent() { } BOOL LLFloaterEvent::postBuild() { mTBName = getChild<LLTextBox>("event_name"); mTBCategory = getChild<LLTextBox>("event_category"); mTBDate = getChild<LLTextBox>("event_date"); mTBDuration = getChild<LLTextBox>("event_duration"); mTBDesc = getChild<LLExpandableTextBox>("event_desc"); mTBDesc->setEnabled(FALSE); mTBRunBy = getChild<LLTextBox>("event_runby"); mTBLocation = getChild<LLTextBox>("event_location"); mTBCover = getChild<LLTextBox>("event_cover"); mTeleportBtn = getChild<LLButton>( "teleport_btn"); mTeleportBtn->setClickedCallback(onClickTeleport, this); mMapBtn = getChild<LLButton>( "map_btn"); mMapBtn->setClickedCallback(onClickMap, this); mNotifyBtn = getChild<LLButton>( "notify_btn"); mNotifyBtn->setClickedCallback(onClickNotify, this); mCreateEventBtn = getChild<LLButton>( "create_event_btn"); mCreateEventBtn->setClickedCallback(onClickCreateEvent, this); mGodDeleteEventBtn = getChild<LLButton>( "god_delete_event_btn"); mGodDeleteEventBtn->setClickedCallback(boost::bind(&LLFloaterEvent::onClickDeleteEvent, this)); return TRUE; } void LLFloaterEvent::setEventID(const U32 event_id) { mEventID = event_id; // Should reset all of the panel state here resetInfo(); if (event_id != 0) { sendEventInfoRequest(); } } void LLFloaterEvent::onClickDeleteEvent() { LLMessageSystem* msg = gMessageSystem; msg->newMessageFast(_PREHASH_EventGodDelete); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID()); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); msg->nextBlockFast(_PREHASH_EventData); msg->addU32Fast(_PREHASH_EventID, mEventID); gAgent.sendReliableMessage(); } void LLFloaterEvent::sendEventInfoRequest() { LLMessageSystem *msg = gMessageSystem; msg->newMessageFast(_PREHASH_EventInfoRequest); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID() ); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID() ); msg->nextBlockFast(_PREHASH_EventData); msg->addU32Fast(_PREHASH_EventID, mEventID); gAgent.sendReliableMessage(); } //static void LLFloaterEvent::processEventInfoReply(LLMessageSystem *msg, void **) { // extract the agent id LLUUID agent_id; msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id ); LLFloaterEvent* floater = LLFloaterReg::getTypedInstance<LLFloaterEvent>("event"); if(floater) { floater->mEventInfo.unpack(msg); floater->mTBName->setText(floater->mEventInfo.mName); floater->mTBCategory->setText(floater->mEventInfo.mCategoryStr); floater->mTBDate->setText(floater->mEventInfo.mTimeStr); floater->mTBDesc->setText(floater->mEventInfo.mDesc); floater->mTBRunBy->setText(LLSLURL::buildCommand("agent", floater->mEventInfo.mRunByID, "inspect")); floater->mTBDuration->setText(llformat("%d:%.2d", floater->mEventInfo.mDuration / 60, floater->mEventInfo.mDuration % 60)); if (!floater->mEventInfo.mHasCover) { floater->mTBCover->setText(floater->getString("none")); } else { floater->mTBCover->setText(llformat("%d", floater->mEventInfo.mCover)); } F32 global_x = (F32)floater->mEventInfo.mPosGlobal.mdV[VX]; F32 global_y = (F32)floater->mEventInfo.mPosGlobal.mdV[VY]; S32 region_x = llround(global_x) % REGION_WIDTH_UNITS; S32 region_y = llround(global_y) % REGION_WIDTH_UNITS; S32 region_z = llround((F32)floater->mEventInfo.mPosGlobal.mdV[VZ]); std::string desc = floater->mEventInfo.mSimName + llformat(" (%d, %d, %d)", region_x, region_y, region_z); floater->mTBLocation->setText(desc); floater->childSetVisible("rating_icon_m", FALSE); floater->childSetVisible("rating_icon_r", FALSE); floater->childSetVisible("rating_icon_pg", FALSE); floater->childSetValue("rating_value", floater->getString("unknown")); //for some reason there's not adult flags for now, so see if region is adult and then //set flags LLWorldMapMessage::url_callback_t cb = boost::bind( &regionInfoCallback, floater->mEventInfo.mID, _1); LLWorldMapMessage::getInstance()->sendNamedRegionRequest(floater->mEventInfo.mSimName, cb, std::string("unused"), false); if (floater->mEventInfo.mUnixTime < time_corrected()) { floater->mNotifyBtn->setEnabled(FALSE); } else { floater->mNotifyBtn->setEnabled(TRUE); } if (gEventNotifier.hasNotification(floater->mEventInfo.mID)) { floater->mNotifyBtn->setLabel(floater->getString("dont_notify")); } else { floater->mNotifyBtn->setLabel(floater->getString("notify")); } floater->mMapBtn->setEnabled(TRUE); floater->mTeleportBtn->setEnabled(TRUE); } } //static void LLFloaterEvent::regionInfoCallback(U32 event_id, U64 region_handle) { LLSimInfo* sim_info = LLWorldMap::getInstance()->simInfoFromHandle(region_handle); LLFloaterEvent* floater = LLFloaterReg::getTypedInstance<LLFloaterEvent>("event"); if (sim_info && floater && (event_id == floater->getEventID())) { // update the event with the maturity info if (sim_info->isAdult()) { floater->childSetVisible("rating_icon_m", FALSE); floater->childSetVisible("rating_icon_r", TRUE); floater->childSetVisible("rating_icon_pg", FALSE); floater->childSetValue("rating_value", floater->getString("adult")); } else if (floater->mEventInfo.mEventFlags & EVENT_FLAG_MATURE) { floater->childSetVisible("rating_icon_m", TRUE); floater->childSetVisible("rating_icon_r", FALSE); floater->childSetVisible("rating_icon_pg", FALSE); floater->childSetValue("rating_value", floater->getString("moderate")); } else { floater->childSetVisible("rating_icon_m", FALSE); floater->childSetVisible("rating_icon_r", FALSE); floater->childSetVisible("rating_icon_pg", TRUE); floater->childSetValue("rating_value", floater->getString("general")); } } } void LLFloaterEvent::draw() { mGodDeleteEventBtn->setVisible(gAgent.isGodlike()); LLPanel::draw(); } void LLFloaterEvent::resetInfo() { mTBName->setText(LLStringUtil::null); mTBCategory->setText(LLStringUtil::null); mTBDate->setText(LLStringUtil::null); mTBDesc->setText(LLStringUtil::null); mTBDuration->setText(LLStringUtil::null); mTBCover->setText(LLStringUtil::null); mTBLocation->setText(LLStringUtil::null); mTBRunBy->setText(LLStringUtil::null); mNotifyBtn->setEnabled(FALSE); mMapBtn->setEnabled(FALSE); mTeleportBtn->setEnabled(FALSE); } // static void LLFloaterEvent::onClickTeleport(void* data) { LLFloaterEvent* self = (LLFloaterEvent*)data; LLFloaterWorldMap* worldmap_instance = LLFloaterWorldMap::getInstance(); if (!self->mEventInfo.mPosGlobal.isExactlyZero()&&worldmap_instance) { gAgent.teleportViaLocation(self->mEventInfo.mPosGlobal); worldmap_instance->trackLocation(self->mEventInfo.mPosGlobal); } } // static void LLFloaterEvent::onClickMap(void* data) { LLFloaterEvent* self = (LLFloaterEvent*)data; LLFloaterWorldMap* worldmap_instance = LLFloaterWorldMap::getInstance(); if (!self->mEventInfo.mPosGlobal.isExactlyZero()&&worldmap_instance) { worldmap_instance->trackLocation(self->mEventInfo.mPosGlobal); LLFloaterReg::showInstance("world_map", "center"); } } // static void LLFloaterEvent::onClickCreateEvent(void* data) { LLNotificationsUtil::add("PromptGoToEventsPage");//, LLSD(), LLSD(), callbackCreateEventWebPage); } // static void LLFloaterEvent::onClickNotify(void *data) { LLFloaterEvent* self = (LLFloaterEvent*)data; if (!gEventNotifier.hasNotification(self->mEventID)) { gEventNotifier.add(self->mEventInfo); self->mNotifyBtn->setLabel(self->getString("dont_notify")); } else { gEventNotifier.remove(self->mEventInfo.mID); self->mNotifyBtn->setLabel(self->getString("notify")); } } <commit_msg>Fixed EXT-6349(normal) - "More" link in event details window does nothing Deleted code that disables expandable textbox. Probably there was edit_box, some time ago, that was read-only.<commit_after>/** * @file llfloaterevent.cpp * @brief Display for events in the finder * * $LicenseInfo:firstyear=2004&license=viewergpl$ * * Copyright (c) 2004-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llfloaterevent.h" #include "message.h" #include "llnotificationsutil.h" #include "llui.h" #include "llagent.h" #include "llviewerwindow.h" #include "llbutton.h" #include "llcachename.h" #include "llcommandhandler.h" // secondlife:///app/chat/ support #include "lleventflags.h" #include "lleventnotifier.h" #include "llexpandabletextbox.h" #include "llfloater.h" #include "llfloaterreg.h" #include "llfloaterworldmap.h" #include "llinventorymodel.h" #include "llsecondlifeurls.h" #include "llslurl.h" #include "lltextbox.h" #include "lltexteditor.h" #include "lluiconstants.h" #include "llviewercontrol.h" #include "llweb.h" #include "llworldmap.h" #include "llworldmapmessage.h" #include "lluictrlfactory.h" #include "lltrans.h" class LLEventHandler : public LLCommandHandler { public: // requires trusted browser to trigger LLEventHandler() : LLCommandHandler("event", UNTRUSTED_THROTTLE) { } bool handle(const LLSD& params, const LLSD& query_map, LLMediaCtrl* web) { if (params.size() < 1) { return false; } LLFloaterEvent* floater = LLFloaterReg::getTypedInstance<LLFloaterEvent>("event"); if (floater) { floater->setEventID(params[0].asInteger()); LLFloaterReg::showTypedInstance<LLFloaterEvent>("event"); return true; } return false; } }; LLEventHandler gEventHandler; LLFloaterEvent::LLFloaterEvent(const LLSD& key) : LLFloater(key), mEventID(0) { } LLFloaterEvent::~LLFloaterEvent() { } BOOL LLFloaterEvent::postBuild() { mTBName = getChild<LLTextBox>("event_name"); mTBCategory = getChild<LLTextBox>("event_category"); mTBDate = getChild<LLTextBox>("event_date"); mTBDuration = getChild<LLTextBox>("event_duration"); mTBDesc = getChild<LLExpandableTextBox>("event_desc"); mTBRunBy = getChild<LLTextBox>("event_runby"); mTBLocation = getChild<LLTextBox>("event_location"); mTBCover = getChild<LLTextBox>("event_cover"); mTeleportBtn = getChild<LLButton>( "teleport_btn"); mTeleportBtn->setClickedCallback(onClickTeleport, this); mMapBtn = getChild<LLButton>( "map_btn"); mMapBtn->setClickedCallback(onClickMap, this); mNotifyBtn = getChild<LLButton>( "notify_btn"); mNotifyBtn->setClickedCallback(onClickNotify, this); mCreateEventBtn = getChild<LLButton>( "create_event_btn"); mCreateEventBtn->setClickedCallback(onClickCreateEvent, this); mGodDeleteEventBtn = getChild<LLButton>( "god_delete_event_btn"); mGodDeleteEventBtn->setClickedCallback(boost::bind(&LLFloaterEvent::onClickDeleteEvent, this)); return TRUE; } void LLFloaterEvent::setEventID(const U32 event_id) { mEventID = event_id; // Should reset all of the panel state here resetInfo(); if (event_id != 0) { sendEventInfoRequest(); } } void LLFloaterEvent::onClickDeleteEvent() { LLMessageSystem* msg = gMessageSystem; msg->newMessageFast(_PREHASH_EventGodDelete); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID()); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); msg->nextBlockFast(_PREHASH_EventData); msg->addU32Fast(_PREHASH_EventID, mEventID); gAgent.sendReliableMessage(); } void LLFloaterEvent::sendEventInfoRequest() { LLMessageSystem *msg = gMessageSystem; msg->newMessageFast(_PREHASH_EventInfoRequest); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID() ); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID() ); msg->nextBlockFast(_PREHASH_EventData); msg->addU32Fast(_PREHASH_EventID, mEventID); gAgent.sendReliableMessage(); } //static void LLFloaterEvent::processEventInfoReply(LLMessageSystem *msg, void **) { // extract the agent id LLUUID agent_id; msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id ); LLFloaterEvent* floater = LLFloaterReg::getTypedInstance<LLFloaterEvent>("event"); if(floater) { floater->mEventInfo.unpack(msg); floater->mTBName->setText(floater->mEventInfo.mName); floater->mTBCategory->setText(floater->mEventInfo.mCategoryStr); floater->mTBDate->setText(floater->mEventInfo.mTimeStr); floater->mTBDesc->setText(floater->mEventInfo.mDesc); floater->mTBRunBy->setText(LLSLURL::buildCommand("agent", floater->mEventInfo.mRunByID, "inspect")); floater->mTBDuration->setText(llformat("%d:%.2d", floater->mEventInfo.mDuration / 60, floater->mEventInfo.mDuration % 60)); if (!floater->mEventInfo.mHasCover) { floater->mTBCover->setText(floater->getString("none")); } else { floater->mTBCover->setText(llformat("%d", floater->mEventInfo.mCover)); } F32 global_x = (F32)floater->mEventInfo.mPosGlobal.mdV[VX]; F32 global_y = (F32)floater->mEventInfo.mPosGlobal.mdV[VY]; S32 region_x = llround(global_x) % REGION_WIDTH_UNITS; S32 region_y = llround(global_y) % REGION_WIDTH_UNITS; S32 region_z = llround((F32)floater->mEventInfo.mPosGlobal.mdV[VZ]); std::string desc = floater->mEventInfo.mSimName + llformat(" (%d, %d, %d)", region_x, region_y, region_z); floater->mTBLocation->setText(desc); floater->childSetVisible("rating_icon_m", FALSE); floater->childSetVisible("rating_icon_r", FALSE); floater->childSetVisible("rating_icon_pg", FALSE); floater->childSetValue("rating_value", floater->getString("unknown")); //for some reason there's not adult flags for now, so see if region is adult and then //set flags LLWorldMapMessage::url_callback_t cb = boost::bind( &regionInfoCallback, floater->mEventInfo.mID, _1); LLWorldMapMessage::getInstance()->sendNamedRegionRequest(floater->mEventInfo.mSimName, cb, std::string("unused"), false); if (floater->mEventInfo.mUnixTime < time_corrected()) { floater->mNotifyBtn->setEnabled(FALSE); } else { floater->mNotifyBtn->setEnabled(TRUE); } if (gEventNotifier.hasNotification(floater->mEventInfo.mID)) { floater->mNotifyBtn->setLabel(floater->getString("dont_notify")); } else { floater->mNotifyBtn->setLabel(floater->getString("notify")); } floater->mMapBtn->setEnabled(TRUE); floater->mTeleportBtn->setEnabled(TRUE); } } //static void LLFloaterEvent::regionInfoCallback(U32 event_id, U64 region_handle) { LLSimInfo* sim_info = LLWorldMap::getInstance()->simInfoFromHandle(region_handle); LLFloaterEvent* floater = LLFloaterReg::getTypedInstance<LLFloaterEvent>("event"); if (sim_info && floater && (event_id == floater->getEventID())) { // update the event with the maturity info if (sim_info->isAdult()) { floater->childSetVisible("rating_icon_m", FALSE); floater->childSetVisible("rating_icon_r", TRUE); floater->childSetVisible("rating_icon_pg", FALSE); floater->childSetValue("rating_value", floater->getString("adult")); } else if (floater->mEventInfo.mEventFlags & EVENT_FLAG_MATURE) { floater->childSetVisible("rating_icon_m", TRUE); floater->childSetVisible("rating_icon_r", FALSE); floater->childSetVisible("rating_icon_pg", FALSE); floater->childSetValue("rating_value", floater->getString("moderate")); } else { floater->childSetVisible("rating_icon_m", FALSE); floater->childSetVisible("rating_icon_r", FALSE); floater->childSetVisible("rating_icon_pg", TRUE); floater->childSetValue("rating_value", floater->getString("general")); } } } void LLFloaterEvent::draw() { mGodDeleteEventBtn->setVisible(gAgent.isGodlike()); LLPanel::draw(); } void LLFloaterEvent::resetInfo() { mTBName->setText(LLStringUtil::null); mTBCategory->setText(LLStringUtil::null); mTBDate->setText(LLStringUtil::null); mTBDesc->setText(LLStringUtil::null); mTBDuration->setText(LLStringUtil::null); mTBCover->setText(LLStringUtil::null); mTBLocation->setText(LLStringUtil::null); mTBRunBy->setText(LLStringUtil::null); mNotifyBtn->setEnabled(FALSE); mMapBtn->setEnabled(FALSE); mTeleportBtn->setEnabled(FALSE); } // static void LLFloaterEvent::onClickTeleport(void* data) { LLFloaterEvent* self = (LLFloaterEvent*)data; LLFloaterWorldMap* worldmap_instance = LLFloaterWorldMap::getInstance(); if (!self->mEventInfo.mPosGlobal.isExactlyZero()&&worldmap_instance) { gAgent.teleportViaLocation(self->mEventInfo.mPosGlobal); worldmap_instance->trackLocation(self->mEventInfo.mPosGlobal); } } // static void LLFloaterEvent::onClickMap(void* data) { LLFloaterEvent* self = (LLFloaterEvent*)data; LLFloaterWorldMap* worldmap_instance = LLFloaterWorldMap::getInstance(); if (!self->mEventInfo.mPosGlobal.isExactlyZero()&&worldmap_instance) { worldmap_instance->trackLocation(self->mEventInfo.mPosGlobal); LLFloaterReg::showInstance("world_map", "center"); } } // static void LLFloaterEvent::onClickCreateEvent(void* data) { LLNotificationsUtil::add("PromptGoToEventsPage");//, LLSD(), LLSD(), callbackCreateEventWebPage); } // static void LLFloaterEvent::onClickNotify(void *data) { LLFloaterEvent* self = (LLFloaterEvent*)data; if (!gEventNotifier.hasNotification(self->mEventID)) { gEventNotifier.add(self->mEventInfo); self->mNotifyBtn->setLabel(self->getString("dont_notify")); } else { gEventNotifier.remove(self->mEventInfo.mID); self->mNotifyBtn->setLabel(self->getString("notify")); } } <|endoftext|>
<commit_before>#include "LineElement.h" #include "LineLook.h" namespace map_server { void LineElement::load(void) { _loaded = true; auto cursor = _iMap->getConnectionPtr()->query("diaphnea.line_elements", MONGO_QUERY("_id" << _mongoId), 1); if (cursor->more()) { mongo::BSONObj dbElement = cursor->next(); loadCommon(dbElement); int lookId = dbElement.getIntField("look_id"); _look = dynamic_cast<const LineLook *>(_iMap->getLook(lookId)); std::vector<mongo::BSONElement> dbLineItems = dbElement.getField("items").Array(); int i, n = dbLineItems.size(); for (i = 0; i < n; ++i) { std::string itemId = dbLineItems[i].OID().toString(); LineItem *lineItem = _iMap->getLineItem(itemId); _itemVector.push_back(lineItem); } } } } <commit_msg>MapDataProcessing: Correction: Set line element look<commit_after>#include "LineElement.h" #include "LineItem.h" #include "LineLook.h" namespace map_server { void LineElement::load(void) { _loaded = true; auto cursor = _iMap->getConnectionPtr()->query("diaphnea.line_elements", MONGO_QUERY("_id" << _mongoId), 1); if (cursor->more()) { mongo::BSONObj dbElement = cursor->next(); loadCommon(dbElement); int lookId = dbElement.getIntField("look_id"); _look = dynamic_cast<const LineLook *>(_iMap->getLook(lookId)); std::vector<mongo::BSONElement> dbLineItems = dbElement.getField("items").Array(); int i, n = dbLineItems.size(); for (i = 0; i < n; ++i) { std::string itemId = dbLineItems[i].OID().toString(); LineItem *lineItem = _iMap->getLineItem(itemId); lineItem->setCurrentLook(_look->getLineLook()); _itemVector.push_back(lineItem); } } } } <|endoftext|>
<commit_before>/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* rodsAgent.c - The main code for rodsAgent */ #include <syslog.h> #include "rodsAgent.hpp" #include "reconstants.hpp" #include "rsApiHandler.hpp" #include "icatHighLevelRoutines.hpp" #include "miscServerFunct.hpp" #ifdef windows_platform #include "rsLog.hpp" static void NtAgentSetEnvsFromArgs( int ac, char **av ); #endif // =-=-=-=-=-=-=- #include "irods_dynamic_cast.hpp" #include "irods_signal.hpp" #include "irods_client_server_negotiation.hpp" #include "irods_network_factory.hpp" #include "irods_auth_object.hpp" #include "irods_auth_factory.hpp" #include "irods_auth_manager.hpp" #include "irods_auth_plugin.hpp" #include "irods_auth_constants.hpp" /* #define SERVER_DEBUG 1 */ int main( int argc, char *argv[] ) { int status; rsComm_t rsComm; char *tmpStr; ProcessType = AGENT_PT; //sleep(30); #ifdef RUN_SERVER_AS_ROOT #ifndef windows_platform if ( initServiceUser() < 0 ) { exit( 1 ); } #endif #endif #ifdef windows_platform iRODSNtAgentInit( argc, argv ); #endif #ifndef windows_platform signal( SIGINT, signalExit ); signal( SIGHUP, signalExit ); signal( SIGTERM, signalExit ); /* set to SIG_DFL as recommended by andy.salnikov so that system() * call returns real values instead of 1 */ signal( SIGCHLD, SIG_DFL ); signal( SIGUSR1, signalExit ); signal( SIGPIPE, rsPipSigalHandler ); // register irods signal handlers register_handlers(); #endif #ifndef windows_platform #ifdef SERVER_DEBUG if ( isPath( "/tmp/rodsdebug" ) ) { sleep( 20 ); } #endif #endif #ifdef SYS_TIMING rodsLogLevel( LOG_NOTICE ); printSysTiming( "irodsAgent", "exec", 1 ); #endif memset( &rsComm, 0, sizeof( rsComm ) ); status = initRsCommWithStartupPack( &rsComm, NULL ); // =-=-=-=-=-=-=- // manufacture a network object for comms irods::network_object_ptr net_obj; irods::error ret = irods::network_factory( &rsComm, net_obj ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } if ( status < 0 ) { sendVersion( net_obj, status, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } /* Handle option to log sql commands */ tmpStr = getenv( SP_LOG_SQL ); if ( tmpStr != NULL ) { #ifdef SYSLOG int j = atoi( tmpStr ); rodsLogSqlReq( j ); #else rodsLogSqlReq( 1 ); #endif } /* Set the logging level */ tmpStr = getenv( SP_LOG_LEVEL ); if ( tmpStr != NULL ) { int i; i = atoi( tmpStr ); rodsLogLevel( i ); } else { rodsLogLevel( LOG_NOTICE ); /* default */ } #ifdef SYSLOG /* Open a connection to syslog */ openlog( "rodsAgent", LOG_ODELAY | LOG_PID, LOG_DAEMON ); #endif status = getRodsEnv( &rsComm.myEnv ); if ( status < 0 ) { rodsLog( LOG_ERROR, "agentMain :: getRodsEnv failed" ); sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } #if RODS_CAT if ( strstr( rsComm.myEnv.rodsDebug, "CAT" ) != NULL ) { chlDebug( rsComm.myEnv.rodsDebug ); } #endif status = initAgent( RULE_ENGINE_TRY_CACHE, &rsComm ); #ifdef SYS_TIMING printSysTiming( "irodsAgent", "initAgent", 0 ); #endif if ( status < 0 ) { rodsLog( LOG_ERROR, "agentMain :: initAgent failed: %d", status ); sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } /* move configConnectControl behind initAgent for now. need zoneName if * the user does not specify one in the input */ initConnectControl(); if ( rsComm.clientUser.userName[0] != '\0' ) { status = chkAllowedUser( rsComm.clientUser.userName, rsComm.clientUser.rodsZone ); if ( status < 0 ) { sendVersion( net_obj, status, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } } // =-=-=-=-=-=-=- // handle negotiations with the client regarding TLS if requested std::string neg_results; ret = irods::client_server_negotiation_for_server( net_obj, neg_results ); if ( !ret.ok() || neg_results == irods::CS_NEG_FAILURE ) { irods::log( PASS( ret ) ); // =-=-=-=-=-=-=- // send a 'we failed to negotiate' message here?? // or use the error stack rule engine thingie irods::log( PASS( ret ) ); sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( ret.code() ); } else { // =-=-=-=-=-=-=- // copy negotiation results to comm for action by network objects strncpy( rsComm.negotiation_results, neg_results.c_str(), MAX_NAME_LEN ); //rsComm.ssl_do_accept = 1; } /* send the server version and atatus as part of the protocol. Put * rsComm.reconnPort as the status */ ret = sendVersion( net_obj, status, rsComm.reconnPort, rsComm.reconnAddr, rsComm.cookie ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } #ifdef SYS_TIMING printSysTiming( "irodsAgent", "sendVersion", 0 ); #endif logAgentProc( &rsComm ); bool done = true; while ( !done ) { sleep( 1 ); } // =-=-=-=-=-=-=- // call initialization for network plugin as negotiated irods::network_object_ptr new_net_obj; ret = irods::network_factory( &rsComm, new_net_obj ); if ( !ret.ok() ) { return ret.code(); } ret = sockAgentStart( new_net_obj ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); return ret.code(); } new_net_obj->to_server( &rsComm ); status = agentMain( &rsComm ); // =-=-=-=-=-=-=- // call initialization for network plugin as negotiated ret = sockAgentStop( new_net_obj ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); return ret.code(); } new_net_obj->to_server( &rsComm ); unregister_handlers(); cleanupAndExit( status ); return ( status ); } int agentMain( rsComm_t *rsComm ) { irods::error result = SUCCESS(); int status = 0; // =-=-=-=-=-=-=- // compiler backwards compatibility hack // see header file for more details irods::dynamic_cast_hack(); bool auth_done = false; while ( result.ok() && status >= 0 ) { if ( false && rsComm->gsiRequest == 1 ) { status = igsiServersideAuth( rsComm ) ; rsComm->gsiRequest = 0; } if ( false && rsComm->gsiRequest == 2 ) { status = ikrbServersideAuth( rsComm ) ; rsComm->gsiRequest = 0; } // According to jason in the case of install a special boot user is used and auth agent request is never called and that is // okay. To handle that we set default to the native auth scheme here. if ( rsComm->auth_scheme == NULL ) { rsComm->auth_scheme = strdup( "native" ); } if ( !auth_done ) { if ( true ) { std::stringstream msg; msg << "qqq - Beginning"; DEBUGMSG( msg.str() ); } // construct an auth object based on the scheme specified in the comm irods::auth_object_ptr auth_obj; irods::error ret = irods::auth_factory( rsComm->auth_scheme, &rsComm->rError, auth_obj ); if ( true ) { std::stringstream msg; msg << "qqq - Ending."; DEBUGMSG( msg.str() ); } if ( ( result = ASSERT_PASS( ret, "Failed to factory an auth object for scheme: \"%s\".", rsComm->auth_scheme ) ).ok() ) { irods::plugin_ptr ptr; ret = auth_obj->resolve( irods::AUTH_INTERFACE, ptr ); if ( ( result = ASSERT_PASS( ret, "Failed to resolve the auth plugin for scheme: \"%s\".", rsComm->auth_scheme ) ).ok() ) { irods::auth_ptr auth_plugin = boost::dynamic_pointer_cast< irods::auth >( ptr ); // Call agent start char* foo = ""; ret = auth_plugin->call <rsComm_t*, const char* > ( irods::AUTH_CLIENT_START, auth_obj, rsComm, foo ); result = ASSERT_PASS( ret, "Failed during auth plugin agent start for scheme: \"%s\".", rsComm->auth_scheme ); auth_done = true; } } } if ( result.ok() ) { if ( rsComm->ssl_do_accept ) { status = sslAccept( rsComm ); rsComm->ssl_do_accept = 0; } if ( rsComm->ssl_do_shutdown ) { status = sslShutdown( rsComm ); rsComm->ssl_do_shutdown = 0; } status = readAndProcClientMsg( rsComm, READ_HEADER_TIMEOUT ); if ( status < 0 ) { if ( status == DISCONN_STATUS ) { status = 0; break; } } } } if ( !result.ok() ) { irods::log( result ); status = result.code(); return status; } // =-=-=-=-=-=-=- // determine if we even need to connect, break the // infinite reconnect loop. if ( !resc_mgr.need_maintenance_operations() ) { return status; } // =-=-=-=-=-=-=- // find the icat host rodsServerHost_t *rodsServerHost = 0; status = getRcatHost( MASTER_RCAT, 0, &rodsServerHost ); if ( status < 0 ) { irods::log( ERROR( status, "getRcatHost failed." ) ); return status; } // =-=-=-=-=-=-=- // connect to the icat host status = svrToSvrConnect( rsComm, rodsServerHost ); if ( status < 0 ) { irods::log( ERROR( status, "svrToSvrConnect failed." ) ); return status; } // =-=-=-=-=-=-=- // call post disconnect maintenance operations before exit status = resc_mgr.call_maintenance_operations( rodsServerHost->conn ); return ( status ); } <commit_msg>[#1880] Added needed headers for run as root code<commit_after>/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* rodsAgent.c - The main code for rodsAgent */ #include <syslog.h> #include "rodsAgent.hpp" #include "reconstants.hpp" #include "rsApiHandler.hpp" #include "icatHighLevelRoutines.hpp" #include "miscServerFunct.hpp" #ifdef windows_platform #include "rsLog.hpp" static void NtAgentSetEnvsFromArgs( int ac, char **av ); #endif // =-=-=-=-=-=-=- #include "irods_dynamic_cast.hpp" #include "irods_signal.hpp" #include "irods_client_server_negotiation.hpp" #include "irods_network_factory.hpp" #include "irods_auth_object.hpp" #include "irods_auth_factory.hpp" #include "irods_auth_manager.hpp" #include "irods_auth_plugin.hpp" #include "irods_auth_constants.hpp" #include "irods_server_properties.hpp" #include "readServerConfig.hpp" /* #define SERVER_DEBUG 1 */ int main( int argc, char *argv[] ) { int status; rsComm_t rsComm; char *tmpStr; bool run_server_as_root = false; ProcessType = AGENT_PT; //sleep(30); irods::server_properties::getInstance().get_property<bool>(RUN_SERVER_AS_ROOT_KW, run_server_as_root); #ifndef windows_platform if (run_server_as_root) { if ( initServiceUser() < 0 ) { exit( 1 ); } } #endif #ifdef windows_platform iRODSNtAgentInit( argc, argv ); #endif #ifndef windows_platform signal( SIGINT, signalExit ); signal( SIGHUP, signalExit ); signal( SIGTERM, signalExit ); /* set to SIG_DFL as recommended by andy.salnikov so that system() * call returns real values instead of 1 */ signal( SIGCHLD, SIG_DFL ); signal( SIGUSR1, signalExit ); signal( SIGPIPE, rsPipSigalHandler ); // register irods signal handlers register_handlers(); #endif #ifndef windows_platform #ifdef SERVER_DEBUG if ( isPath( "/tmp/rodsdebug" ) ) { sleep( 20 ); } #endif #endif #ifdef SYS_TIMING rodsLogLevel( LOG_NOTICE ); printSysTiming( "irodsAgent", "exec", 1 ); #endif memset( &rsComm, 0, sizeof( rsComm ) ); status = initRsCommWithStartupPack( &rsComm, NULL ); // =-=-=-=-=-=-=- // manufacture a network object for comms irods::network_object_ptr net_obj; irods::error ret = irods::network_factory( &rsComm, net_obj ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } if ( status < 0 ) { sendVersion( net_obj, status, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } /* Handle option to log sql commands */ tmpStr = getenv( SP_LOG_SQL ); if ( tmpStr != NULL ) { #ifdef SYSLOG int j = atoi( tmpStr ); rodsLogSqlReq( j ); #else rodsLogSqlReq( 1 ); #endif } /* Set the logging level */ tmpStr = getenv( SP_LOG_LEVEL ); if ( tmpStr != NULL ) { int i; i = atoi( tmpStr ); rodsLogLevel( i ); } else { rodsLogLevel( LOG_NOTICE ); /* default */ } #ifdef SYSLOG /* Open a connection to syslog */ openlog( "rodsAgent", LOG_ODELAY | LOG_PID, LOG_DAEMON ); #endif status = getRodsEnv( &rsComm.myEnv ); if ( status < 0 ) { rodsLog( LOG_ERROR, "agentMain :: getRodsEnv failed" ); sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } #if RODS_CAT if ( strstr( rsComm.myEnv.rodsDebug, "CAT" ) != NULL ) { chlDebug( rsComm.myEnv.rodsDebug ); } #endif status = initAgent( RULE_ENGINE_TRY_CACHE, &rsComm ); #ifdef SYS_TIMING printSysTiming( "irodsAgent", "initAgent", 0 ); #endif if ( status < 0 ) { rodsLog( LOG_ERROR, "agentMain :: initAgent failed: %d", status ); sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } /* move configConnectControl behind initAgent for now. need zoneName if * the user does not specify one in the input */ initConnectControl(); if ( rsComm.clientUser.userName[0] != '\0' ) { status = chkAllowedUser( rsComm.clientUser.userName, rsComm.clientUser.rodsZone ); if ( status < 0 ) { sendVersion( net_obj, status, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } } // =-=-=-=-=-=-=- // handle negotiations with the client regarding TLS if requested std::string neg_results; ret = irods::client_server_negotiation_for_server( net_obj, neg_results ); if ( !ret.ok() || neg_results == irods::CS_NEG_FAILURE ) { irods::log( PASS( ret ) ); // =-=-=-=-=-=-=- // send a 'we failed to negotiate' message here?? // or use the error stack rule engine thingie irods::log( PASS( ret ) ); sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( ret.code() ); } else { // =-=-=-=-=-=-=- // copy negotiation results to comm for action by network objects strncpy( rsComm.negotiation_results, neg_results.c_str(), MAX_NAME_LEN ); //rsComm.ssl_do_accept = 1; } /* send the server version and atatus as part of the protocol. Put * rsComm.reconnPort as the status */ ret = sendVersion( net_obj, status, rsComm.reconnPort, rsComm.reconnAddr, rsComm.cookie ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); sendVersion( net_obj, SYS_AGENT_INIT_ERR, 0, NULL, 0 ); unregister_handlers(); cleanupAndExit( status ); } #ifdef SYS_TIMING printSysTiming( "irodsAgent", "sendVersion", 0 ); #endif logAgentProc( &rsComm ); bool done = true; while ( !done ) { sleep( 1 ); } // =-=-=-=-=-=-=- // call initialization for network plugin as negotiated irods::network_object_ptr new_net_obj; ret = irods::network_factory( &rsComm, new_net_obj ); if ( !ret.ok() ) { return ret.code(); } ret = sockAgentStart( new_net_obj ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); return ret.code(); } new_net_obj->to_server( &rsComm ); status = agentMain( &rsComm ); // =-=-=-=-=-=-=- // call initialization for network plugin as negotiated ret = sockAgentStop( new_net_obj ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); return ret.code(); } new_net_obj->to_server( &rsComm ); unregister_handlers(); cleanupAndExit( status ); return ( status ); } int agentMain( rsComm_t *rsComm ) { irods::error result = SUCCESS(); int status = 0; // =-=-=-=-=-=-=- // compiler backwards compatibility hack // see header file for more details irods::dynamic_cast_hack(); bool auth_done = false; while ( result.ok() && status >= 0 ) { if ( false && rsComm->gsiRequest == 1 ) { status = igsiServersideAuth( rsComm ) ; rsComm->gsiRequest = 0; } if ( false && rsComm->gsiRequest == 2 ) { status = ikrbServersideAuth( rsComm ) ; rsComm->gsiRequest = 0; } // According to jason in the case of install a special boot user is used and auth agent request is never called and that is // okay. To handle that we set default to the native auth scheme here. if ( rsComm->auth_scheme == NULL ) { rsComm->auth_scheme = strdup( "native" ); } if ( !auth_done ) { if ( true ) { std::stringstream msg; msg << "qqq - Beginning"; DEBUGMSG( msg.str() ); } // construct an auth object based on the scheme specified in the comm irods::auth_object_ptr auth_obj; irods::error ret = irods::auth_factory( rsComm->auth_scheme, &rsComm->rError, auth_obj ); if ( true ) { std::stringstream msg; msg << "qqq - Ending."; DEBUGMSG( msg.str() ); } if ( ( result = ASSERT_PASS( ret, "Failed to factory an auth object for scheme: \"%s\".", rsComm->auth_scheme ) ).ok() ) { irods::plugin_ptr ptr; ret = auth_obj->resolve( irods::AUTH_INTERFACE, ptr ); if ( ( result = ASSERT_PASS( ret, "Failed to resolve the auth plugin for scheme: \"%s\".", rsComm->auth_scheme ) ).ok() ) { irods::auth_ptr auth_plugin = boost::dynamic_pointer_cast< irods::auth >( ptr ); // Call agent start char* foo = ""; ret = auth_plugin->call <rsComm_t*, const char* > ( irods::AUTH_CLIENT_START, auth_obj, rsComm, foo ); result = ASSERT_PASS( ret, "Failed during auth plugin agent start for scheme: \"%s\".", rsComm->auth_scheme ); auth_done = true; } } } if ( result.ok() ) { if ( rsComm->ssl_do_accept ) { status = sslAccept( rsComm ); rsComm->ssl_do_accept = 0; } if ( rsComm->ssl_do_shutdown ) { status = sslShutdown( rsComm ); rsComm->ssl_do_shutdown = 0; } status = readAndProcClientMsg( rsComm, READ_HEADER_TIMEOUT ); if ( status < 0 ) { if ( status == DISCONN_STATUS ) { status = 0; break; } } } } if ( !result.ok() ) { irods::log( result ); status = result.code(); return status; } // =-=-=-=-=-=-=- // determine if we even need to connect, break the // infinite reconnect loop. if ( !resc_mgr.need_maintenance_operations() ) { return status; } // =-=-=-=-=-=-=- // find the icat host rodsServerHost_t *rodsServerHost = 0; status = getRcatHost( MASTER_RCAT, 0, &rodsServerHost ); if ( status < 0 ) { irods::log( ERROR( status, "getRcatHost failed." ) ); return status; } // =-=-=-=-=-=-=- // connect to the icat host status = svrToSvrConnect( rsComm, rodsServerHost ); if ( status < 0 ) { irods::log( ERROR( status, "svrToSvrConnect failed." ) ); return status; } // =-=-=-=-=-=-=- // call post disconnect maintenance operations before exit status = resc_mgr.call_maintenance_operations( rodsServerHost->conn ); return ( status ); } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MumbleVoipModule.h" #include "MemoryLeakCheck.h" #include "RexLogicModule.h" #include "ModuleManager.h" #include "Avatar/Avatar.h" #include "EC_OgrePlaceable.h" #include "SceneManager.h" #include "ConsoleCommandServiceInterface.h" #include "EventManager.h" #include "LinkPlugin.h" #include "ServerObserver.h" #include "ConnectionManager.h" namespace MumbleVoip { std::string MumbleVoipModule::module_name_ = "MumbleVoipModule"; MumbleVoipModule::MumbleVoipModule() : ModuleInterfaceImpl(module_name_), link_plugin_(0), time_from_last_update_ms_(0), server_observer_(0), connection_manager_(0), use_camera_position_(false), mumble_client_started_(false) { } MumbleVoipModule::~MumbleVoipModule() { if (mumble_client_started_ && connection_manager_) { connection_manager_->KillMumbleClient(); } if (link_plugin_) SAFE_DELETE(link_plugin_); if (server_observer_) SAFE_DELETE(server_observer_); if (connection_manager_) SAFE_DELETE(connection_manager_); } void MumbleVoipModule::Load() { connection_manager_ = new ConnectionManager(framework_); link_plugin_ = new LinkPlugin(); server_observer_ = new ServerObserver(framework_); connect(server_observer_, SIGNAL(MumbleServerInfoReceived(ServerInfo)), this, SLOT(OnMumbleServerInfoReceived(ServerInfo)) ); } void MumbleVoipModule::Unload() { SAFE_DELETE(link_plugin_); SAFE_DELETE(server_observer_); } void MumbleVoipModule::Initialize() { InitializeConsoleCommands(); } void MumbleVoipModule::PostInitialize() { } void MumbleVoipModule::Uninitialize() { } void MumbleVoipModule::Update(f64 frametime) { if (link_plugin_ && link_plugin_->IsRunning()) UpdateLinkPlugin(frametime); if (connection_manager_) connection_manager_->Update(frametime); } bool MumbleVoipModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface* data) { if (server_observer_) server_observer_->HandleEvent(category_id, event_id, data); return false; } void MumbleVoipModule::UpdateLinkPlugin(f64 frametime) { if (!link_plugin_) return; time_from_last_update_ms_ += 1000*frametime; if (time_from_last_update_ms_ < UPDATE_TIME_MS_) return; time_from_last_update_ms_ = 0; RexLogic::RexLogicModule *rex_logic_module = dynamic_cast<RexLogic::RexLogicModule *>(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_WorldLogic).lock().get()); if (!rex_logic_module) return; RexLogic::AvatarPtr avatar = rex_logic_module->GetAvatarHandler(); if (avatar) { Scene::EntityPtr entity = avatar->GetUserAvatar(); if (!entity) return; const Foundation::ComponentInterfacePtr &placeable_component = entity->GetComponent("EC_OgrePlaceable"); if (placeable_component) { Vector3df top_vector = Vector3df::UNIT_Z; OgreRenderer::EC_OgrePlaceable *ogre_placeable = checked_static_cast<OgreRenderer::EC_OgrePlaceable *>(placeable_component.get()); Quaternion q = ogre_placeable->GetOrientation(); Vector3df position_vector = ogre_placeable->GetPosition(); Vector3df front_vector = q*Vector3df::UNIT_Z; link_plugin_->SetAvatarPosition(position_vector, front_vector, top_vector); if (!use_camera_position_) link_plugin_->SetCameraPosition(position_vector, front_vector, top_vector); } Scene::EntityPtr camera = rex_logic_module->GetCameraEntity().lock(); if (camera) { const Foundation::ComponentInterfacePtr &placeable_component = camera->GetComponent("EC_OgrePlaceable"); if (placeable_component) { Vector3df top_vector = Vector3df::UNIT_Z; OgreRenderer::EC_OgrePlaceable *ogre_placeable = checked_static_cast<OgreRenderer::EC_OgrePlaceable *>(placeable_component.get()); Quaternion q = ogre_placeable->GetOrientation(); Vector3df position_vector = ogre_placeable->GetPosition(); Vector3df front_vector = q*Vector3df::UNIT_X; if (use_camera_position_) link_plugin_->SetCameraPosition(position_vector, front_vector, top_vector); } } link_plugin_->SendData(); } } void MumbleVoipModule::InitializeConsoleCommands() { boost::shared_ptr<Console::CommandService> console_service = framework_->GetService<Console::CommandService>(Foundation::Service::ST_ConsoleCommand).lock(); if (console_service) { console_service->RegisterCommand(Console::CreateCommand("mumble link", "Start Mumble link plugin: 'mumble link(user_id, context_id)'", Console::Bind(this, &MumbleVoipModule::OnConsoleMumbleLink))); console_service->RegisterCommand(Console::CreateCommand("mumble unlink", "Stop Mumble link plugin: 'mumble unlink'", Console::Bind(this, &MumbleVoipModule::OnConsoleMumbleUnlink))); console_service->RegisterCommand(Console::CreateCommand("mumble start", "Start Mumble client application: 'mumble start(server_url)'", Console::Bind(this, &MumbleVoipModule::OnConsoleMumbleStart))); } } Console::CommandResult MumbleVoipModule::OnConsoleMumbleLink(const StringVector &params) { if (params.size() != 2) { return Console::ResultFailure("Wrong number of arguments: usage 'mumble link(id, context)'"); } QString id = params[0].c_str(); QString context = params[1].c_str(); link_plugin_->SetUserIdentity(id); link_plugin_->SetContextId(context); link_plugin_->SetApplicationName("Naali viewer"); link_plugin_->SetApplicationDescription("Naali viewer by realXtend project"); link_plugin_->Start(); if (!link_plugin_->IsRunning()) { QString error_message = "Link plugin connection cannot be established. "; error_message.append(link_plugin_->GetReason()); return Console::ResultFailure(error_message.toStdString()); } QString message = QString("Mumbe link plugin started: id=%1 context=%2").arg(id).arg(context); return Console::ResultSuccess(message.toStdString()); } Console::CommandResult MumbleVoipModule::OnConsoleMumbleUnlink(const StringVector &params) { if (params.size() != 0) { return Console::ResultFailure("Wrong number of arguments: usage 'mumble unlink'"); } if (!link_plugin_->IsRunning()) { return Console::ResultFailure("Mumbe link plugin was not running."); } link_plugin_->Stop(); return Console::ResultSuccess("Mumbe link plugin stopped."); } Console::CommandResult MumbleVoipModule::OnConsoleMumbleStart(const StringVector &params) { if (params.size() != 1) { return Console::ResultFailure("Wrong number of arguments: usage 'mumble start(server_url)'"); } QString server_url = params[0].c_str(); try { ConnectionManager::StartMumbleClient(server_url); return Console::ResultSuccess("Mumbe client started."); } catch(std::exception &e) { QString error_message = QString("Cannot start Mumble client: %1").arg(QString(e.what())); return Console::ResultFailure(error_message.toStdString()); } } void MumbleVoipModule::OnMumbleServerInfoReceived(ServerInfo info) { QUrl murmur_url(QString("mumble://%1/%2").arg(info.server).arg(info.channel)); // setScheme method does not add '//' between scheme and host. murmur_url.setUserName(info.user_name); murmur_url.setPassword(info.password); murmur_url.setQueryItems(QList<QPair<QString,QString> >() << QPair<QString,QString>("version", info.version)); try { connection_manager_->OpenConnection(info); LogInfo("Mumble connection established."); connection_manager_->SendAudio(true); LogDebug("Start sending audio."); //LogInfo("Starting mumble client."); //ConnectionManager::StartMumbleClient(murmur_url.toString()); //// it takes some time for a mumble client to setup shared memory for link plugins //// so we have to wait some time before we can start our link plugin. //user_id_for_link_plugin_ = info.avatar_id; //context_id_for_link_plugin_ = info.context_id; //QTimer::singleShot(2000, this, SLOT(StartLinkPlugin())); //mumble_client_started_ = true; } catch(std::exception &e) { QString messge = QString("Cannot start Mumble client: %1").arg(e.what()); LogError(messge.toStdString()); return; } } void MumbleVoipModule::StartLinkPlugin() { link_plugin_->SetUserIdentity(user_id_for_link_plugin_); link_plugin_->SetContextId(context_id_for_link_plugin_); link_plugin_->SetApplicationName("Naali viewer"); link_plugin_->SetApplicationDescription("Naali viewer by realXtend project"); link_plugin_->Start(); if (link_plugin_->IsRunning()) { QString message = QString("Mumbe link plugin started: id '%1' context '%2'").arg(user_id_for_link_plugin_).arg(context_id_for_link_plugin_); LogInfo(message.toStdString()); } else { QString error_message = QString("Link plugin connection cannot be established. %1 ").arg(link_plugin_->GetReason()); LogError(error_message.toStdString()); } } } // end of namespace: MumbleVoip extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler); void SetProfiler(Foundation::Profiler *profiler) { Foundation::ProfilerSection::SetProfiler(profiler); } using namespace MumbleVoip; POCO_BEGIN_MANIFEST(Foundation::ModuleInterface) POCO_EXPORT_CLASS(MumbleVoipModule) POCO_END_MANIFEST <commit_msg>Refactoring<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MumbleVoipModule.h" #include "MemoryLeakCheck.h" #include "RexLogicModule.h" #include "ModuleManager.h" #include "Avatar/Avatar.h" #include "EC_OgrePlaceable.h" #include "SceneManager.h" #include "ConsoleCommandServiceInterface.h" #include "EventManager.h" #include "LinkPlugin.h" #include "ServerObserver.h" #include "ConnectionManager.h" namespace MumbleVoip { std::string MumbleVoipModule::module_name_ = "MumbleVoipModule"; MumbleVoipModule::MumbleVoipModule() : ModuleInterfaceImpl(module_name_), link_plugin_(0), time_from_last_update_ms_(0), server_observer_(0), connection_manager_(0), use_camera_position_(false), mumble_client_started_(false) { } MumbleVoipModule::~MumbleVoipModule() { if (mumble_client_started_ && connection_manager_) { connection_manager_->KillMumbleClient(); } if (link_plugin_) SAFE_DELETE(link_plugin_); if (server_observer_) SAFE_DELETE(server_observer_); if (connection_manager_) SAFE_DELETE(connection_manager_); } void MumbleVoipModule::Load() { connection_manager_ = new ConnectionManager(framework_); link_plugin_ = new LinkPlugin(); server_observer_ = new ServerObserver(framework_); connect(server_observer_, SIGNAL(MumbleServerInfoReceived(ServerInfo)), this, SLOT(OnMumbleServerInfoReceived(ServerInfo)) ); } void MumbleVoipModule::Unload() { SAFE_DELETE(link_plugin_); SAFE_DELETE(server_observer_); } void MumbleVoipModule::Initialize() { InitializeConsoleCommands(); } void MumbleVoipModule::PostInitialize() { } void MumbleVoipModule::Uninitialize() { } void MumbleVoipModule::Update(f64 frametime) { if (link_plugin_ && link_plugin_->IsRunning()) UpdateLinkPlugin(frametime); if (connection_manager_) connection_manager_->Update(frametime); } bool MumbleVoipModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface* data) { if (server_observer_) server_observer_->HandleEvent(category_id, event_id, data); return false; } void MumbleVoipModule::UpdateLinkPlugin(f64 frametime) { if (!link_plugin_) return; time_from_last_update_ms_ += 1000*frametime; if (time_from_last_update_ms_ < UPDATE_TIME_MS_) return; time_from_last_update_ms_ = 0; RexLogic::RexLogicModule *rex_logic_module = dynamic_cast<RexLogic::RexLogicModule *>(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_WorldLogic).lock().get()); if (!rex_logic_module) return; RexLogic::AvatarPtr avatar = rex_logic_module->GetAvatarHandler(); if (avatar) { Scene::EntityPtr entity = avatar->GetUserAvatar(); if (!entity) return; const Foundation::ComponentInterfacePtr &placeable_component = entity->GetComponent("EC_OgrePlaceable"); if (placeable_component) { Vector3df top_vector = Vector3df::UNIT_Z; OgreRenderer::EC_OgrePlaceable *ogre_placeable = checked_static_cast<OgreRenderer::EC_OgrePlaceable *>(placeable_component.get()); Quaternion q = ogre_placeable->GetOrientation(); Vector3df position_vector = ogre_placeable->GetPosition(); Vector3df front_vector = q*Vector3df::UNIT_Z; link_plugin_->SetAvatarPosition(position_vector, front_vector, top_vector); if (!use_camera_position_) link_plugin_->SetCameraPosition(position_vector, front_vector, top_vector); } Scene::EntityPtr camera = rex_logic_module->GetCameraEntity().lock(); if (camera) { const Foundation::ComponentInterfacePtr &placeable_component = camera->GetComponent("EC_OgrePlaceable"); if (placeable_component) { Vector3df top_vector = Vector3df::UNIT_Z; OgreRenderer::EC_OgrePlaceable *ogre_placeable = checked_static_cast<OgreRenderer::EC_OgrePlaceable *>(placeable_component.get()); Quaternion q = ogre_placeable->GetOrientation(); Vector3df position_vector = ogre_placeable->GetPosition(); Vector3df front_vector = q*Vector3df::UNIT_X; if (use_camera_position_) link_plugin_->SetCameraPosition(position_vector, front_vector, top_vector); } } link_plugin_->SendData(); } } void MumbleVoipModule::InitializeConsoleCommands() { boost::shared_ptr<Console::CommandService> console_service = framework_->GetService<Console::CommandService>(Foundation::Service::ST_ConsoleCommand).lock(); if (console_service) { console_service->RegisterCommand(Console::CreateCommand("mumble link", "Start Mumble link plugin: 'mumble link(user_id, context_id)'", Console::Bind(this, &MumbleVoipModule::OnConsoleMumbleLink))); console_service->RegisterCommand(Console::CreateCommand("mumble unlink", "Stop Mumble link plugin: 'mumble unlink'", Console::Bind(this, &MumbleVoipModule::OnConsoleMumbleUnlink))); console_service->RegisterCommand(Console::CreateCommand("mumble start", "Start Mumble client application: 'mumble start(server_url)'", Console::Bind(this, &MumbleVoipModule::OnConsoleMumbleStart))); } } Console::CommandResult MumbleVoipModule::OnConsoleMumbleLink(const StringVector &params) { if (params.size() != 2) { return Console::ResultFailure("Wrong number of arguments: usage 'mumble link(id, context)'"); } QString id = params[0].c_str(); QString context = params[1].c_str(); link_plugin_->SetUserIdentity(id); link_plugin_->SetContextId(context); link_plugin_->SetApplicationName("Naali viewer"); link_plugin_->SetApplicationDescription("Naali viewer by realXtend project"); link_plugin_->Start(); if (!link_plugin_->IsRunning()) { QString error_message = "Link plugin connection cannot be established. "; error_message.append(link_plugin_->GetReason()); return Console::ResultFailure(error_message.toStdString()); } QString message = QString("Mumbe link plugin started: id=%1 context=%2").arg(id).arg(context); return Console::ResultSuccess(message.toStdString()); } Console::CommandResult MumbleVoipModule::OnConsoleMumbleUnlink(const StringVector &params) { if (params.size() != 0) { return Console::ResultFailure("Wrong number of arguments: usage 'mumble unlink'"); } if (!link_plugin_->IsRunning()) { return Console::ResultFailure("Mumbe link plugin was not running."); } link_plugin_->Stop(); return Console::ResultSuccess("Mumbe link plugin stopped."); } Console::CommandResult MumbleVoipModule::OnConsoleMumbleStart(const StringVector &params) { if (params.size() != 1) { return Console::ResultFailure("Wrong number of arguments: usage 'mumble start(server_url)'"); } QString server_url = params[0].c_str(); try { ConnectionManager::StartMumbleClient(server_url); return Console::ResultSuccess("Mumbe client started."); } catch(std::exception &e) { QString error_message = QString("Cannot start Mumble client: %1").arg(QString(e.what())); return Console::ResultFailure(error_message.toStdString()); } } void MumbleVoipModule::OnMumbleServerInfoReceived(ServerInfo info) { QUrl murmur_url(QString("mumble://%1/%2").arg(info.server).arg(info.channel)); // setScheme method does not add '//' between scheme and host. murmur_url.setUserName(info.user_name); murmur_url.setPassword(info.password); murmur_url.setQueryItems(QList<QPair<QString,QString> >() << QPair<QString,QString>("version", info.version)); try { connection_manager_->OpenConnection(info); LogInfo("Mumble connection established."); connection_manager_->SendAudio(true); LogDebug("Start sending audio."); //LogInfo("Starting mumble client."); //ConnectionManager::StartMumbleClient(murmur_url.toString()); //// it takes some time for a mumble client to setup shared memory for link plugins //// so we have to wait some time before we can start our link plugin. //user_id_for_link_plugin_ = info.avatar_id; //context_id_for_link_plugin_ = info.context_id; //QTimer::singleShot(2000, this, SLOT(StartLinkPlugin())); //mumble_client_started_ = true; } catch(std::exception &e) { QString messge = QString("Cannot start Mumble client: %1").arg(e.what()); LogError(messge.toStdString()); return; } } void MumbleVoipModule::StartLinkPlugin() { link_plugin_->SetUserIdentity(user_id_for_link_plugin_); link_plugin_->SetContextId(context_id_for_link_plugin_); link_plugin_->SetApplicationName("Naali viewer"); link_plugin_->SetApplicationDescription("Naali viewer by realXtend project"); link_plugin_->Start(); if (link_plugin_->IsRunning()) { QString message = QString("Mumbe link plugin started: id '%1' context '%2'").arg(user_id_for_link_plugin_).arg(context_id_for_link_plugin_); LogInfo(message.toStdString()); } else { QString error_message = QString("Link plugin connection cannot be established. %1 ").arg(link_plugin_->GetReason()); LogError(error_message.toStdString()); } } } // end of namespace: MumbleVoip extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler); void SetProfiler(Foundation::Profiler *profiler) { Foundation::ProfilerSection::SetProfiler(profiler); } using namespace MumbleVoip; POCO_BEGIN_MANIFEST(Foundation::ModuleInterface) POCO_EXPORT_CLASS(MumbleVoipModule) POCO_END_MANIFEST <|endoftext|>
<commit_before>/** * @file llwearabletype.cpp * @brief LLWearableType class implementation * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llwearabletype.h" #include "llinventoryfunctions.h" #include "lltrans.h" struct WearableEntry : public LLDictionaryEntry { WearableEntry(const std::string &name, const std::string& default_new_name, LLAssetType::EType assetType, LLInventoryIcon::EIconName iconName, BOOL disable_camera_switch = FALSE, BOOL allow_multiwear = TRUE) : LLDictionaryEntry(name), mAssetType(assetType), mDefaultNewName(default_new_name), mLabel(LLTrans::getString(name)), mIconName(iconName), mDisableCameraSwitch(disable_camera_switch), mAllowMultiwear(allow_multiwear) { } const LLAssetType::EType mAssetType; const std::string mLabel; const std::string mDefaultNewName; //keep mLabel for backward compatibility LLInventoryIcon::EIconName mIconName; BOOL mDisableCameraSwitch; BOOL mAllowMultiwear; }; class LLWearableDictionary : public LLSingleton<LLWearableDictionary>, public LLDictionary<LLWearableType::EType, WearableEntry> { public: LLWearableDictionary(); // [RLVa:KB] - Checked: 2010-03-03 (RLVa-1.2.0a) | Added: RLVa-1.2.0a protected: // The default implementation asserts on 'notFound()' and returns -1 which isn't a valid EWearableType virtual LLWearableType::EType notFound() const { return LLWearableType::WT_INVALID; } // [/RLVa:KB] }; LLWearableDictionary::LLWearableDictionary() { addEntry(LLWearableType::WT_SHAPE, new WearableEntry("shape", "New Shape", LLAssetType::AT_BODYPART, LLInventoryIcon::ICONNAME_BODYPART_SHAPE, FALSE, FALSE)); addEntry(LLWearableType::WT_SKIN, new WearableEntry("skin", "New Skin", LLAssetType::AT_BODYPART, LLInventoryIcon::ICONNAME_BODYPART_SKIN, FALSE, FALSE)); addEntry(LLWearableType::WT_HAIR, new WearableEntry("hair", "New Hair", LLAssetType::AT_BODYPART, LLInventoryIcon::ICONNAME_BODYPART_HAIR, FALSE, FALSE)); addEntry(LLWearableType::WT_EYES, new WearableEntry("eyes", "New Eyes", LLAssetType::AT_BODYPART, LLInventoryIcon::ICONNAME_BODYPART_EYES, FALSE, FALSE)); addEntry(LLWearableType::WT_SHIRT, new WearableEntry("shirt", "New Shirt", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_SHIRT, FALSE, TRUE)); addEntry(LLWearableType::WT_PANTS, new WearableEntry("pants", "New Pants", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_PANTS, FALSE, TRUE)); addEntry(LLWearableType::WT_SHOES, new WearableEntry("shoes", "New Shoes", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_SHOES, FALSE, TRUE)); addEntry(LLWearableType::WT_SOCKS, new WearableEntry("socks", "New Socks", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_SOCKS, FALSE, TRUE)); addEntry(LLWearableType::WT_JACKET, new WearableEntry("jacket", "New Jacket", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_JACKET, FALSE, TRUE)); addEntry(LLWearableType::WT_GLOVES, new WearableEntry("gloves", "New Gloves", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_GLOVES, FALSE, TRUE)); addEntry(LLWearableType::WT_UNDERSHIRT, new WearableEntry("undershirt", "New Undershirt", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_UNDERSHIRT, FALSE, TRUE)); addEntry(LLWearableType::WT_UNDERPANTS, new WearableEntry("underpants", "New Underpants", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_UNDERPANTS, FALSE, TRUE)); addEntry(LLWearableType::WT_SKIRT, new WearableEntry("skirt", "New Skirt", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_SKIRT, FALSE, TRUE)); addEntry(LLWearableType::WT_ALPHA, new WearableEntry("alpha", "New Alpha", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_ALPHA, FALSE, TRUE)); addEntry(LLWearableType::WT_TATTOO, new WearableEntry("tattoo", "New Tattoo", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_TATTOO, FALSE, TRUE)); addEntry(LLWearableType::WT_PHYSICS, new WearableEntry("physics", "New Physics", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_PHYSICS, TRUE, FALSE)); addEntry(LLWearableType::WT_INVALID, new WearableEntry("invalid", "Invalid Wearable", LLAssetType::AT_NONE, LLInventoryIcon::ICONNAME_NONE, FALSE, FALSE)); addEntry(LLWearableType::WT_NONE, new WearableEntry("none", "Invalid Wearable", LLAssetType::AT_NONE, LLInventoryIcon::ICONNAME_NONE, FALSE, FALSE)); } // static LLWearableType::EType LLWearableType::typeNameToType(const std::string& type_name) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const LLWearableType::EType wearable = dict->lookup(type_name); return wearable; } // static const std::string& LLWearableType::getTypeName(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getTypeName(WT_INVALID); return entry->mName; } //static const std::string& LLWearableType::getTypeDefaultNewName(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getTypeDefaultNewName(WT_INVALID); return entry->mDefaultNewName; } // static const std::string& LLWearableType::getTypeLabel(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getTypeLabel(WT_INVALID); return entry->mLabel; } // static LLAssetType::EType LLWearableType::getAssetType(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getAssetType(WT_INVALID); return entry->mAssetType; } // static LLInventoryIcon::EIconName LLWearableType::getIconName(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getIconName(WT_INVALID); return entry->mIconName; } // static BOOL LLWearableType::getDisableCameraSwitch(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); return entry->mDisableCameraSwitch; } // static BOOL LLWearableType::getAllowMultiwear(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); return entry->mAllowMultiwear; } <commit_msg>SH-1380 FIXED User can wear several physics objects<commit_after>/** * @file llwearabletype.cpp * @brief LLWearableType class implementation * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llwearabletype.h" #include "llinventoryfunctions.h" #include "lltrans.h" struct WearableEntry : public LLDictionaryEntry { WearableEntry(const std::string &name, const std::string& default_new_name, LLAssetType::EType assetType, LLInventoryIcon::EIconName iconName, BOOL disable_camera_switch = FALSE, BOOL allow_multiwear = TRUE) : LLDictionaryEntry(name), mAssetType(assetType), mDefaultNewName(default_new_name), mLabel(LLTrans::getString(name)), mIconName(iconName), mDisableCameraSwitch(disable_camera_switch), mAllowMultiwear(allow_multiwear) { } const LLAssetType::EType mAssetType; const std::string mLabel; const std::string mDefaultNewName; //keep mLabel for backward compatibility LLInventoryIcon::EIconName mIconName; BOOL mDisableCameraSwitch; BOOL mAllowMultiwear; }; class LLWearableDictionary : public LLSingleton<LLWearableDictionary>, public LLDictionary<LLWearableType::EType, WearableEntry> { public: LLWearableDictionary(); // [RLVa:KB] - Checked: 2010-03-03 (RLVa-1.2.0a) | Added: RLVa-1.2.0a protected: // The default implementation asserts on 'notFound()' and returns -1 which isn't a valid EWearableType virtual LLWearableType::EType notFound() const { return LLWearableType::WT_INVALID; } // [/RLVa:KB] }; LLWearableDictionary::LLWearableDictionary() { addEntry(LLWearableType::WT_SHAPE, new WearableEntry("shape", "New Shape", LLAssetType::AT_BODYPART, LLInventoryIcon::ICONNAME_BODYPART_SHAPE, FALSE, FALSE)); addEntry(LLWearableType::WT_SKIN, new WearableEntry("skin", "New Skin", LLAssetType::AT_BODYPART, LLInventoryIcon::ICONNAME_BODYPART_SKIN, FALSE, FALSE)); addEntry(LLWearableType::WT_HAIR, new WearableEntry("hair", "New Hair", LLAssetType::AT_BODYPART, LLInventoryIcon::ICONNAME_BODYPART_HAIR, FALSE, FALSE)); addEntry(LLWearableType::WT_EYES, new WearableEntry("eyes", "New Eyes", LLAssetType::AT_BODYPART, LLInventoryIcon::ICONNAME_BODYPART_EYES, FALSE, FALSE)); addEntry(LLWearableType::WT_SHIRT, new WearableEntry("shirt", "New Shirt", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_SHIRT, FALSE, TRUE)); addEntry(LLWearableType::WT_PANTS, new WearableEntry("pants", "New Pants", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_PANTS, FALSE, TRUE)); addEntry(LLWearableType::WT_SHOES, new WearableEntry("shoes", "New Shoes", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_SHOES, FALSE, TRUE)); addEntry(LLWearableType::WT_SOCKS, new WearableEntry("socks", "New Socks", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_SOCKS, FALSE, TRUE)); addEntry(LLWearableType::WT_JACKET, new WearableEntry("jacket", "New Jacket", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_JACKET, FALSE, TRUE)); addEntry(LLWearableType::WT_GLOVES, new WearableEntry("gloves", "New Gloves", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_GLOVES, FALSE, TRUE)); addEntry(LLWearableType::WT_UNDERSHIRT, new WearableEntry("undershirt", "New Undershirt", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_UNDERSHIRT, FALSE, TRUE)); addEntry(LLWearableType::WT_UNDERPANTS, new WearableEntry("underpants", "New Underpants", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_UNDERPANTS, FALSE, TRUE)); addEntry(LLWearableType::WT_SKIRT, new WearableEntry("skirt", "New Skirt", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_SKIRT, FALSE, TRUE)); addEntry(LLWearableType::WT_ALPHA, new WearableEntry("alpha", "New Alpha", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_ALPHA, FALSE, TRUE)); addEntry(LLWearableType::WT_TATTOO, new WearableEntry("tattoo", "New Tattoo", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_TATTOO, FALSE, TRUE)); addEntry(LLWearableType::WT_PHYSICS, new WearableEntry("physics", "New Physics", LLAssetType::AT_CLOTHING, LLInventoryIcon::ICONNAME_CLOTHING_PHYSICS, TRUE, TRUE)); addEntry(LLWearableType::WT_INVALID, new WearableEntry("invalid", "Invalid Wearable", LLAssetType::AT_NONE, LLInventoryIcon::ICONNAME_NONE, FALSE, FALSE)); addEntry(LLWearableType::WT_NONE, new WearableEntry("none", "Invalid Wearable", LLAssetType::AT_NONE, LLInventoryIcon::ICONNAME_NONE, FALSE, FALSE)); } // static LLWearableType::EType LLWearableType::typeNameToType(const std::string& type_name) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const LLWearableType::EType wearable = dict->lookup(type_name); return wearable; } // static const std::string& LLWearableType::getTypeName(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getTypeName(WT_INVALID); return entry->mName; } //static const std::string& LLWearableType::getTypeDefaultNewName(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getTypeDefaultNewName(WT_INVALID); return entry->mDefaultNewName; } // static const std::string& LLWearableType::getTypeLabel(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getTypeLabel(WT_INVALID); return entry->mLabel; } // static LLAssetType::EType LLWearableType::getAssetType(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getAssetType(WT_INVALID); return entry->mAssetType; } // static LLInventoryIcon::EIconName LLWearableType::getIconName(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); if (!entry) return getIconName(WT_INVALID); return entry->mIconName; } // static BOOL LLWearableType::getDisableCameraSwitch(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); return entry->mDisableCameraSwitch; } // static BOOL LLWearableType::getAllowMultiwear(LLWearableType::EType type) { const LLWearableDictionary *dict = LLWearableDictionary::getInstance(); const WearableEntry *entry = dict->lookup(type); return entry->mAllowMultiwear; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/sigtools.h" #include "kernel/rtlil.h" #include "kernel/log.h" static int next_bit_mode; static uint32_t next_bit_state; static RTLIL::State next_bit() { if (next_bit_mode == 0) return RTLIL::State::S0; if (next_bit_mode == 1) return RTLIL::State::S1; // xorshift32 next_bit_state ^= next_bit_state << 13; next_bit_state ^= next_bit_state >> 17; next_bit_state ^= next_bit_state << 5; log_assert(next_bit_state != 0); return ((next_bit_state >> (next_bit_state & 15)) & 1) ? RTLIL::State::S0 : RTLIL::State::S1; } struct SetundefWorker { void operator()(RTLIL::SigSpec &sig) { sig.expand(); for (auto &c : sig.chunks) if (c.wire == NULL && c.data.bits.at(0) > RTLIL::State::S1) c.data.bits.at(0) = next_bit(); sig.optimize(); } }; struct SetundefPass : public Pass { SetundefPass() : Pass("setundef", "replace undef values with defined constants") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" setundef [options] [selection]\n"); log("\n"); log("This command replaced undef (x) constants with defined (0/1) constants.\n"); log("\n"); log(" -undriven\n"); log(" also set undriven nets to constant values\n"); log("\n"); log(" -zero\n"); log(" replace with bits cleared (0)\n"); log("\n"); log(" -one\n"); log(" replace with bits set (1)\n"); log("\n"); log(" -random <seed>\n"); log(" replace with random bits using the specified integer als seed\n"); log(" value for the random number generator.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { bool got_value = false; bool undriven_mode = false; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-undriven") { undriven_mode = true; continue; } if (args[argidx] == "-zero") { got_value = true; next_bit_mode = 0; continue; } if (args[argidx] == "-one") { got_value = true; next_bit_mode = 1; continue; } if (args[argidx] == "-random" && !got_value && argidx+1 < args.size()) { got_value = true; next_bit_mode = 2; next_bit_state = atoi(args[++argidx].c_str()) + 1; for (int i = 0; i < 10; i++) next_bit(); continue; } break; } extra_args(args, argidx, design); if (!got_value) log_cmd_error("One of the options -zero, -one, or -random <seed> must be specified.\n"); for (auto &mod_it : design->modules) { RTLIL::Module *module = mod_it.second; if (!design->selected(module)) continue; if (undriven_mode) { if (!module->processes.empty()) log_error("The 'setundef' command can't operate in -undriven mode on modules with processes. Run 'proc' first.\n"); SigMap sigmap(module); SigPool undriven_signals; for (auto &it : module->wires) if (!it.second->port_input) undriven_signals.add(sigmap(it.second)); CellTypes ct(design); for (auto &it : module->cells) for (auto &conn : it.second->connections) if (!ct.cell_known(it.second->type) || ct.cell_output(it.second->type, conn.first)) undriven_signals.del(sigmap(conn.second)); RTLIL::SigSpec sig = undriven_signals.export_all(); for (auto &c : sig.chunks) { RTLIL::SigSpec bits; for (int i = 0; i < c.width; i++) bits.append(next_bit()); bits.optimize(); module->connections.push_back(RTLIL::SigSig(c, bits)); } } module->rewrite_sigspecs(SetundefWorker()); } } } SetundefPass; <commit_msg>Improved setundef random number generator<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/sigtools.h" #include "kernel/rtlil.h" #include "kernel/log.h" static int next_bit_mode; static uint32_t next_bit_state; static RTLIL::State next_bit() { if (next_bit_mode == 0) return RTLIL::State::S0; if (next_bit_mode == 1) return RTLIL::State::S1; // xorshift32 next_bit_state ^= next_bit_state << 13; next_bit_state ^= next_bit_state >> 17; next_bit_state ^= next_bit_state << 5; log_assert(next_bit_state != 0); return ((next_bit_state >> (next_bit_state & 15)) & 16) ? RTLIL::State::S0 : RTLIL::State::S1; } struct SetundefWorker { void operator()(RTLIL::SigSpec &sig) { sig.expand(); for (auto &c : sig.chunks) if (c.wire == NULL && c.data.bits.at(0) > RTLIL::State::S1) c.data.bits.at(0) = next_bit(); sig.optimize(); } }; struct SetundefPass : public Pass { SetundefPass() : Pass("setundef", "replace undef values with defined constants") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" setundef [options] [selection]\n"); log("\n"); log("This command replaced undef (x) constants with defined (0/1) constants.\n"); log("\n"); log(" -undriven\n"); log(" also set undriven nets to constant values\n"); log("\n"); log(" -zero\n"); log(" replace with bits cleared (0)\n"); log("\n"); log(" -one\n"); log(" replace with bits set (1)\n"); log("\n"); log(" -random <seed>\n"); log(" replace with random bits using the specified integer als seed\n"); log(" value for the random number generator.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { bool got_value = false; bool undriven_mode = false; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-undriven") { undriven_mode = true; continue; } if (args[argidx] == "-zero") { got_value = true; next_bit_mode = 0; continue; } if (args[argidx] == "-one") { got_value = true; next_bit_mode = 1; continue; } if (args[argidx] == "-random" && !got_value && argidx+1 < args.size()) { got_value = true; next_bit_mode = 2; next_bit_state = atoi(args[++argidx].c_str()) + 1; for (int i = 0; i < 10; i++) next_bit(); continue; } break; } extra_args(args, argidx, design); if (!got_value) log_cmd_error("One of the options -zero, -one, or -random <seed> must be specified.\n"); for (auto &mod_it : design->modules) { RTLIL::Module *module = mod_it.second; if (!design->selected(module)) continue; if (undriven_mode) { if (!module->processes.empty()) log_error("The 'setundef' command can't operate in -undriven mode on modules with processes. Run 'proc' first.\n"); SigMap sigmap(module); SigPool undriven_signals; for (auto &it : module->wires) if (!it.second->port_input) undriven_signals.add(sigmap(it.second)); CellTypes ct(design); for (auto &it : module->cells) for (auto &conn : it.second->connections) if (!ct.cell_known(it.second->type) || ct.cell_output(it.second->type, conn.first)) undriven_signals.del(sigmap(conn.second)); RTLIL::SigSpec sig = undriven_signals.export_all(); for (auto &c : sig.chunks) { RTLIL::SigSpec bits; for (int i = 0; i < c.width; i++) bits.append(next_bit()); bits.optimize(); module->connections.push_back(RTLIL::SigSig(c, bits)); } } module->rewrite_sigspecs(SetundefWorker()); } } } SetundefPass; <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "opt_status.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/log.h" #include <stdlib.h> #include <stdio.h> static SigMap assign_map; static SigSet<RTLIL::Cell*> mux_drivers; static bool handle_dff(RTLIL::Module *mod, RTLIL::Cell *dff) { RTLIL::SigSpec sig_d, sig_q, sig_c, sig_r; RTLIL::Const val_cp, val_rp, val_rv; if (dff->type == "$_DFF_N_" || dff->type == "$_DFF_P_") { sig_d = dff->connections["\\D"]; sig_q = dff->connections["\\Q"]; sig_c = dff->connections["\\C"]; val_cp = RTLIL::Const(dff->type == "$_DFF_P_", 1); } else if (dff->type.substr(0,6) == "$_DFF_" && dff->type.substr(9) == "_" && (dff->type[6] == 'N' || dff->type[6] == 'P') && (dff->type[7] == 'N' || dff->type[7] == 'P') && (dff->type[8] == '0' || dff->type[8] == '1')) { sig_d = dff->connections["\\D"]; sig_q = dff->connections["\\Q"]; sig_c = dff->connections["\\C"]; sig_r = dff->connections["\\R"]; val_cp = RTLIL::Const(dff->type[6] == 'P', 1); val_rp = RTLIL::Const(dff->type[7] == 'P', 1); val_rv = RTLIL::Const(dff->type[8] == '1', 1); } else if (dff->type == "$dff") { sig_d = dff->connections["\\D"]; sig_q = dff->connections["\\Q"]; sig_c = dff->connections["\\CLK"]; val_cp = RTLIL::Const(dff->parameters["\\CLK_POLARITY"].as_bool(), 1); } else if (dff->type == "$adff") { sig_d = dff->connections["\\D"]; sig_q = dff->connections["\\Q"]; sig_c = dff->connections["\\CLK"]; sig_r = dff->connections["\\ARST"]; val_cp = RTLIL::Const(dff->parameters["\\CLK_POLARITY"].as_bool(), 1); val_rp = RTLIL::Const(dff->parameters["\\ARST_POLARITY"].as_bool(), 1); val_rv = dff->parameters["\\ARST_VALUE"]; } else log_abort(); assign_map.apply(sig_d); assign_map.apply(sig_q); assign_map.apply(sig_c); assign_map.apply(sig_r); if (dff->type == "$dff" && mux_drivers.has(sig_d)) { std::set<RTLIL::Cell*> muxes; mux_drivers.find(sig_d, muxes); for (auto mux : muxes) { RTLIL::SigSpec sig_a = assign_map(mux->connections.at("\\A")); RTLIL::SigSpec sig_b = assign_map(mux->connections.at("\\B")); if (sig_a == sig_q && sig_b.is_fully_const()) { RTLIL::SigSig conn(sig_q, sig_b); mod->connections.push_back(conn); goto delete_dff; } if (sig_b == sig_q && sig_a.is_fully_const()) { RTLIL::SigSig conn(sig_q, sig_a); mod->connections.push_back(conn); goto delete_dff; } } } if (sig_d.is_fully_const() && sig_r.width == 0) { RTLIL::SigSig conn(sig_q, sig_d); mod->connections.push_back(conn); goto delete_dff; } if (sig_d == sig_q) { if (sig_r.width > 0) { RTLIL::SigSig conn(sig_q, val_rv); mod->connections.push_back(conn); } goto delete_dff; } return false; delete_dff: log("Removing %s (%s) from module %s.\n", dff->name.c_str(), dff->type.c_str(), mod->name.c_str()); OPT_DID_SOMETHING = true; mod->cells.erase(dff->name); delete dff; return true; } struct OptRmdffPass : public Pass { OptRmdffPass() : Pass("opt_rmdff", "remove DFFs with constant inputs") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" opt_rmdff [selection]\n"); log("\n"); log("This pass identifies flip-flops with constant inputs and replaces them with\n"); log("a constant driver.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { int total_count = 0; log_header("Executing OPT_RMDFF pass (remove dff with constant values).\n"); extra_args(args, 1, design); for (auto &mod_it : design->modules) { if (!design->selected(mod_it.second)) continue; assign_map.set(mod_it.second); mux_drivers.clear(); std::vector<std::string> dff_list; for (auto &it : mod_it.second->cells) { if (it.second->type == "$mux" || it.second->type == "$pmux") { if (it.second->connections.at("\\A").width == it.second->connections.at("\\B").width) mux_drivers.insert(assign_map(it.second->connections.at("\\Y")), it.second); continue; } if (!design->selected(mod_it.second, it.second)) continue; if (it.second->type == "$_DFF_N_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_P_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_NN0_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_NN1_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_NP0_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_NP1_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_PN0_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_PN1_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_PP0_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_PP1_") dff_list.push_back(it.first); if (it.second->type == "$dff") dff_list.push_back(it.first); if (it.second->type == "$adff") dff_list.push_back(it.first); } for (auto &id : dff_list) { if (mod_it.second->cells.count(id) > 0 && handle_dff(mod_it.second, mod_it.second->cells[id])) total_count++; } } assign_map.clear(); mux_drivers.clear(); log("Replaced %d DFF cells.\n", total_count); } } OptRmdffPass; <commit_msg>Added support for $adff with undef data inputs to opt_rmdff<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "opt_status.h" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/log.h" #include <stdlib.h> #include <stdio.h> static SigMap assign_map; static SigSet<RTLIL::Cell*> mux_drivers; static bool handle_dff(RTLIL::Module *mod, RTLIL::Cell *dff) { RTLIL::SigSpec sig_d, sig_q, sig_c, sig_r; RTLIL::Const val_cp, val_rp, val_rv; if (dff->type == "$_DFF_N_" || dff->type == "$_DFF_P_") { sig_d = dff->connections["\\D"]; sig_q = dff->connections["\\Q"]; sig_c = dff->connections["\\C"]; val_cp = RTLIL::Const(dff->type == "$_DFF_P_", 1); } else if (dff->type.substr(0,6) == "$_DFF_" && dff->type.substr(9) == "_" && (dff->type[6] == 'N' || dff->type[6] == 'P') && (dff->type[7] == 'N' || dff->type[7] == 'P') && (dff->type[8] == '0' || dff->type[8] == '1')) { sig_d = dff->connections["\\D"]; sig_q = dff->connections["\\Q"]; sig_c = dff->connections["\\C"]; sig_r = dff->connections["\\R"]; val_cp = RTLIL::Const(dff->type[6] == 'P', 1); val_rp = RTLIL::Const(dff->type[7] == 'P', 1); val_rv = RTLIL::Const(dff->type[8] == '1', 1); } else if (dff->type == "$dff") { sig_d = dff->connections["\\D"]; sig_q = dff->connections["\\Q"]; sig_c = dff->connections["\\CLK"]; val_cp = RTLIL::Const(dff->parameters["\\CLK_POLARITY"].as_bool(), 1); } else if (dff->type == "$adff") { sig_d = dff->connections["\\D"]; sig_q = dff->connections["\\Q"]; sig_c = dff->connections["\\CLK"]; sig_r = dff->connections["\\ARST"]; val_cp = RTLIL::Const(dff->parameters["\\CLK_POLARITY"].as_bool(), 1); val_rp = RTLIL::Const(dff->parameters["\\ARST_POLARITY"].as_bool(), 1); val_rv = dff->parameters["\\ARST_VALUE"]; } else log_abort(); assign_map.apply(sig_d); assign_map.apply(sig_q); assign_map.apply(sig_c); assign_map.apply(sig_r); if (dff->type == "$dff" && mux_drivers.has(sig_d)) { std::set<RTLIL::Cell*> muxes; mux_drivers.find(sig_d, muxes); for (auto mux : muxes) { RTLIL::SigSpec sig_a = assign_map(mux->connections.at("\\A")); RTLIL::SigSpec sig_b = assign_map(mux->connections.at("\\B")); if (sig_a == sig_q && sig_b.is_fully_const()) { RTLIL::SigSig conn(sig_q, sig_b); mod->connections.push_back(conn); goto delete_dff; } if (sig_b == sig_q && sig_a.is_fully_const()) { RTLIL::SigSig conn(sig_q, sig_a); mod->connections.push_back(conn); goto delete_dff; } } } if (sig_d.is_fully_undef() && sig_d.width == int(val_rv.bits.size())) { RTLIL::SigSig conn(sig_q, val_rv); mod->connections.push_back(conn); goto delete_dff; } if (sig_d.is_fully_const() && sig_r.width == 0) { RTLIL::SigSig conn(sig_q, sig_d); mod->connections.push_back(conn); goto delete_dff; } if (sig_d == sig_q) { if (sig_r.width > 0) { RTLIL::SigSig conn(sig_q, val_rv); mod->connections.push_back(conn); } goto delete_dff; } return false; delete_dff: log("Removing %s (%s) from module %s.\n", dff->name.c_str(), dff->type.c_str(), mod->name.c_str()); OPT_DID_SOMETHING = true; mod->cells.erase(dff->name); delete dff; return true; } struct OptRmdffPass : public Pass { OptRmdffPass() : Pass("opt_rmdff", "remove DFFs with constant inputs") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" opt_rmdff [selection]\n"); log("\n"); log("This pass identifies flip-flops with constant inputs and replaces them with\n"); log("a constant driver.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { int total_count = 0; log_header("Executing OPT_RMDFF pass (remove dff with constant values).\n"); extra_args(args, 1, design); for (auto &mod_it : design->modules) { if (!design->selected(mod_it.second)) continue; assign_map.set(mod_it.second); mux_drivers.clear(); std::vector<std::string> dff_list; for (auto &it : mod_it.second->cells) { if (it.second->type == "$mux" || it.second->type == "$pmux") { if (it.second->connections.at("\\A").width == it.second->connections.at("\\B").width) mux_drivers.insert(assign_map(it.second->connections.at("\\Y")), it.second); continue; } if (!design->selected(mod_it.second, it.second)) continue; if (it.second->type == "$_DFF_N_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_P_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_NN0_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_NN1_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_NP0_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_NP1_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_PN0_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_PN1_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_PP0_") dff_list.push_back(it.first); if (it.second->type == "$_DFF_PP1_") dff_list.push_back(it.first); if (it.second->type == "$dff") dff_list.push_back(it.first); if (it.second->type == "$adff") dff_list.push_back(it.first); } for (auto &id : dff_list) { if (mod_it.second->cells.count(id) > 0 && handle_dff(mod_it.second, mod_it.second->cells[id])) total_count++; } } assign_map.clear(); mux_drivers.clear(); log("Replaced %d DFF cells.\n", total_count); } } OptRmdffPass; <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" #include "kernel/celltypes.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct opts_t { bool initeq = false; bool anyeq = false; bool fwd = false; bool bwd = false; bool nop = false; }; struct FmcombineWorker { const opts_t &opts; Design *design; Module *original = nullptr; Module *module = nullptr; IdString orig_type, combined_type; FmcombineWorker(Design *design, IdString orig_type, const opts_t &opts) : opts(opts), design(design), original(design->module(orig_type)), orig_type(orig_type), combined_type(stringf("$fmcombine%s", orig_type.c_str())) { } SigSpec import_sig(SigSpec sig, const string &suffix) { SigSpec newsig; for (auto chunk : sig.chunks()) { if (chunk.wire != nullptr) chunk.wire = module->wire(chunk.wire->name.str() + suffix); newsig.append(chunk); } return newsig; } Cell *import_prim_cell(Cell *cell, const string &suffix) { Cell *c = module->addCell(cell->name.str() + suffix, cell->type); c->parameters = cell->parameters; c->attributes = cell->attributes; for (auto &conn : cell->connections()) c->setPort(conn.first, import_sig(conn.second, suffix)); return c; } void import_hier_cell(Cell *cell) { if (!cell->parameters.empty()) log_cmd_error("Cell %s.%s has unresolved instance parameters.\n", log_id(original), log_id(cell)); FmcombineWorker sub_worker(design, cell->type, opts); sub_worker.generate(); Cell *c = module->addCell(cell->name.str() + "_combined", sub_worker.combined_type); // c->parameters = cell->parameters; c->attributes = cell->attributes; for (auto &conn : cell->connections()) { c->setPort(conn.first.str() + "_gold", import_sig(conn.second, "_gold")); c->setPort(conn.first.str() + "_gate", import_sig(conn.second, "_gate")); } } void generate() { if (design->module(combined_type)) { // log("Combined module %s already exists.\n", log_id(combined_type)); return; } log("Generating combined module %s from module %s.\n", log_id(combined_type), log_id(orig_type)); module = design->addModule(combined_type); for (auto wire : original->wires()) { module->addWire(wire->name.str() + "_gold", wire); module->addWire(wire->name.str() + "_gate", wire); } module->fixup_ports(); for (auto cell : original->cells()) { if (design->module(cell->type) == nullptr) { if (opts.anyeq && cell->type.in(ID($anyseq), ID($anyconst))) { Cell *gold = import_prim_cell(cell, "_gold"); for (auto &conn : cell->connections()) module->connect(import_sig(conn.second, "_gate"), gold->getPort(conn.first)); } else { Cell *gold = import_prim_cell(cell, "_gold"); Cell *gate = import_prim_cell(cell, "_gate"); if (opts.initeq) { if (RTLIL::builtin_ff_cell_types().count(cell->type)) { SigSpec gold_q = gold->getPort(ID::Q); SigSpec gate_q = gate->getPort(ID::Q); SigSpec en = module->Initstate(NEW_ID); SigSpec eq = module->Eq(NEW_ID, gold_q, gate_q); module->addAssume(NEW_ID, eq, en); } } } } else { import_hier_cell(cell); } } for (auto &conn : original->connections()) { module->connect(import_sig(conn.first, "_gold"), import_sig(conn.second, "_gold")); module->connect(import_sig(conn.first, "_gate"), import_sig(conn.second, "_gate")); } if (opts.nop) return; CellTypes ct; ct.setup_internals_eval(); ct.setup_stdcells_eval(); SigMap sigmap(module); dict<SigBit, SigBit> data_bit_to_eq_net; dict<Cell*, SigSpec> cell_to_eq_nets; dict<SigSpec, SigSpec> reduce_db; dict<SigSpec, SigSpec> invert_db; for (auto cell : original->cells()) { if (!ct.cell_known(cell->type)) continue; for (auto &conn : cell->connections()) { if (!cell->output(conn.first)) continue; SigSpec A = import_sig(conn.second, "_gold"); SigSpec B = import_sig(conn.second, "_gate"); SigBit EQ = module->Eq(NEW_ID, A, B); for (auto bit : sigmap({A, B})) data_bit_to_eq_net[bit] = EQ; cell_to_eq_nets[cell].append(EQ); } } for (auto cell : original->cells()) { if (!ct.cell_known(cell->type)) continue; bool skip_cell = !cell_to_eq_nets.count(cell); pool<SigBit> src_eq_bits; for (auto &conn : cell->connections()) { if (skip_cell) break; if (cell->output(conn.first)) continue; SigSpec A = import_sig(conn.second, "_gold"); SigSpec B = import_sig(conn.second, "_gate"); for (auto bit : sigmap({A, B})) { if (data_bit_to_eq_net.count(bit)) src_eq_bits.insert(data_bit_to_eq_net.at(bit)); else skip_cell = true; } } if (!skip_cell) { SigSpec antecedent = SigSpec(src_eq_bits); antecedent.sort_and_unify(); if (GetSize(antecedent) > 1) { if (reduce_db.count(antecedent) == 0) reduce_db[antecedent] = module->ReduceAnd(NEW_ID, antecedent); antecedent = reduce_db.at(antecedent); } SigSpec consequent = cell_to_eq_nets.at(cell); consequent.sort_and_unify(); if (GetSize(consequent) > 1) { if (reduce_db.count(consequent) == 0) reduce_db[consequent] = module->ReduceAnd(NEW_ID, consequent); consequent = reduce_db.at(consequent); } if (opts.fwd) module->addAssume(NEW_ID, consequent, antecedent); if (opts.bwd) { if (invert_db.count(antecedent) == 0) invert_db[antecedent] = module->Not(NEW_ID, antecedent); if (invert_db.count(consequent) == 0) invert_db[consequent] = module->Not(NEW_ID, consequent); module->addAssume(NEW_ID, invert_db.at(antecedent), invert_db.at(consequent)); } } } } }; struct FmcombinePass : public Pass { FmcombinePass() : Pass("fmcombine", "combine two instances of a cell into one") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" fmcombine [options] module_name gold_cell gate_cell\n"); // log(" fmcombine [options] @gold_cell @gate_cell\n"); log("\n"); log("This pass takes two cells, which are instances of the same module, and replaces\n"); log("them with one instance of a special 'combined' module, that effectively\n"); log("contains two copies of the original module, plus some formal properties.\n"); log("\n"); log("This is useful for formal test benches that check what differences in behavior\n"); log("a slight difference in input causes in a module.\n"); log("\n"); log(" -initeq\n"); log(" Insert assumptions that initially all FFs in both circuits have the\n"); log(" same initial values.\n"); log("\n"); log(" -anyeq\n"); log(" Do not duplicate $anyseq/$anyconst cells.\n"); log("\n"); log(" -fwd\n"); log(" Insert forward hint assumptions into the combined module.\n"); log("\n"); log(" -bwd\n"); log(" Insert backward hint assumptions into the combined module.\n"); log(" (Backward hints are logically equivalend to fordward hits, but\n"); log(" some solvers are faster with bwd hints, or even both -bwd and -fwd.)\n"); log("\n"); log(" -nop\n"); log(" Don't insert hint assumptions into the combined module.\n"); log(" (This should not provide any speedup over the original design, but\n"); log(" strangely sometimes it does.)\n"); log("\n"); log("If none of -fwd, -bwd, and -nop is given, then -fwd is used as default.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { opts_t opts; Module *module = nullptr; Cell *gold_cell = nullptr; Cell *gate_cell = nullptr; log_header(design, "Executing FMCOMBINE pass.\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-o" && argidx+1 < args.size()) { // filename = args[++argidx]; // continue; // } if (args[argidx] == "-initeq") { opts.initeq = true; continue; } if (args[argidx] == "-anyeq") { opts.anyeq = true; continue; } if (args[argidx] == "-fwd") { opts.fwd = true; continue; } if (args[argidx] == "-bwd") { opts.bwd = true; continue; } if (args[argidx] == "-nop") { opts.nop = true; continue; } break; } if (argidx+2 == args.size()) { string gold_name = args[argidx++]; string gate_name = args[argidx++]; log_cmd_error("fmcombine @gold_cell @gate_cell call style is not implemented yet."); } else if (argidx+3 == args.size()) { IdString module_name = RTLIL::escape_id(args[argidx++]); IdString gold_name = RTLIL::escape_id(args[argidx++]); IdString gate_name = RTLIL::escape_id(args[argidx++]); module = design->module(module_name); if (module == nullptr) log_cmd_error("Module %s not found.\n", log_id(module_name)); gold_cell = module->cell(gold_name); if (gold_cell == nullptr) log_cmd_error("Gold cell %s not found in module %s.\n", log_id(gold_name), log_id(module)); gate_cell = module->cell(gate_name); if (gate_cell == nullptr) log_cmd_error("Gate cell %s not found in module %s.\n", log_id(gate_name), log_id(module)); } else { log_cmd_error("Invalid number of arguments.\n"); } // extra_args(args, argidx, design); if (opts.nop && (opts.fwd || opts.bwd)) log_cmd_error("Option -nop can not be combined with -fwd and/or -bwd.\n"); if (!opts.nop && !opts.fwd && !opts.bwd) opts.fwd = true; if (gold_cell->type != gate_cell->type) log_cmd_error("Types of gold and gate cells do not match.\n"); if (!gold_cell->parameters.empty()) log_cmd_error("Gold cell has unresolved instance parameters.\n"); if (!gate_cell->parameters.empty()) log_cmd_error("Gate cell has unresolved instance parameters.\n"); FmcombineWorker worker(design, gold_cell->type, opts); worker.generate(); IdString combined_cell_name = module->uniquify(stringf("\\%s_%s", log_id(gold_cell), log_id(gate_cell))); Cell *cell = module->addCell(combined_cell_name, worker.combined_type); cell->attributes = gold_cell->attributes; cell->add_strpool_attribute(ID::src, gate_cell->get_strpool_attribute(ID::src)); log("Combining cells %s and %s in module %s into new cell %s.\n", log_id(gold_cell), log_id(gate_cell), log_id(module), log_id(cell)); for (auto &conn : gold_cell->connections()) cell->setPort(conn.first.str() + "_gold", conn.second); module->remove(gold_cell); for (auto &conn : gate_cell->connections()) cell->setPort(conn.first.str() + "_gate", conn.second); module->remove(gate_cell); } } FmcombinePass; PRIVATE_NAMESPACE_END <commit_msg>fmcombine: Add _gold/_gate suffix to memids<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" #include "kernel/celltypes.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct opts_t { bool initeq = false; bool anyeq = false; bool fwd = false; bool bwd = false; bool nop = false; }; struct FmcombineWorker { const opts_t &opts; Design *design; Module *original = nullptr; Module *module = nullptr; IdString orig_type, combined_type; FmcombineWorker(Design *design, IdString orig_type, const opts_t &opts) : opts(opts), design(design), original(design->module(orig_type)), orig_type(orig_type), combined_type(stringf("$fmcombine%s", orig_type.c_str())) { } SigSpec import_sig(SigSpec sig, const string &suffix) { SigSpec newsig; for (auto chunk : sig.chunks()) { if (chunk.wire != nullptr) chunk.wire = module->wire(chunk.wire->name.str() + suffix); newsig.append(chunk); } return newsig; } Cell *import_prim_cell(Cell *cell, const string &suffix) { Cell *c = module->addCell(cell->name.str() + suffix, cell->type); c->parameters = cell->parameters; c->attributes = cell->attributes; if (cell->is_mem_cell()) c->parameters[ID::MEMID] = cell->parameters[ID::MEMID].decode_string() + suffix; for (auto &conn : cell->connections()) c->setPort(conn.first, import_sig(conn.second, suffix)); return c; } void import_hier_cell(Cell *cell) { if (!cell->parameters.empty()) log_cmd_error("Cell %s.%s has unresolved instance parameters.\n", log_id(original), log_id(cell)); FmcombineWorker sub_worker(design, cell->type, opts); sub_worker.generate(); Cell *c = module->addCell(cell->name.str() + "_combined", sub_worker.combined_type); // c->parameters = cell->parameters; c->attributes = cell->attributes; for (auto &conn : cell->connections()) { c->setPort(conn.first.str() + "_gold", import_sig(conn.second, "_gold")); c->setPort(conn.first.str() + "_gate", import_sig(conn.second, "_gate")); } } void generate() { if (design->module(combined_type)) { // log("Combined module %s already exists.\n", log_id(combined_type)); return; } log("Generating combined module %s from module %s.\n", log_id(combined_type), log_id(orig_type)); module = design->addModule(combined_type); for (auto wire : original->wires()) { module->addWire(wire->name.str() + "_gold", wire); module->addWire(wire->name.str() + "_gate", wire); } module->fixup_ports(); for (auto cell : original->cells()) { if (design->module(cell->type) == nullptr) { if (opts.anyeq && cell->type.in(ID($anyseq), ID($anyconst))) { Cell *gold = import_prim_cell(cell, "_gold"); for (auto &conn : cell->connections()) module->connect(import_sig(conn.second, "_gate"), gold->getPort(conn.first)); } else { Cell *gold = import_prim_cell(cell, "_gold"); Cell *gate = import_prim_cell(cell, "_gate"); if (opts.initeq) { if (RTLIL::builtin_ff_cell_types().count(cell->type)) { SigSpec gold_q = gold->getPort(ID::Q); SigSpec gate_q = gate->getPort(ID::Q); SigSpec en = module->Initstate(NEW_ID); SigSpec eq = module->Eq(NEW_ID, gold_q, gate_q); module->addAssume(NEW_ID, eq, en); } } } } else { import_hier_cell(cell); } } for (auto &conn : original->connections()) { module->connect(import_sig(conn.first, "_gold"), import_sig(conn.second, "_gold")); module->connect(import_sig(conn.first, "_gate"), import_sig(conn.second, "_gate")); } if (opts.nop) return; CellTypes ct; ct.setup_internals_eval(); ct.setup_stdcells_eval(); SigMap sigmap(module); dict<SigBit, SigBit> data_bit_to_eq_net; dict<Cell*, SigSpec> cell_to_eq_nets; dict<SigSpec, SigSpec> reduce_db; dict<SigSpec, SigSpec> invert_db; for (auto cell : original->cells()) { if (!ct.cell_known(cell->type)) continue; for (auto &conn : cell->connections()) { if (!cell->output(conn.first)) continue; SigSpec A = import_sig(conn.second, "_gold"); SigSpec B = import_sig(conn.second, "_gate"); SigBit EQ = module->Eq(NEW_ID, A, B); for (auto bit : sigmap({A, B})) data_bit_to_eq_net[bit] = EQ; cell_to_eq_nets[cell].append(EQ); } } for (auto cell : original->cells()) { if (!ct.cell_known(cell->type)) continue; bool skip_cell = !cell_to_eq_nets.count(cell); pool<SigBit> src_eq_bits; for (auto &conn : cell->connections()) { if (skip_cell) break; if (cell->output(conn.first)) continue; SigSpec A = import_sig(conn.second, "_gold"); SigSpec B = import_sig(conn.second, "_gate"); for (auto bit : sigmap({A, B})) { if (data_bit_to_eq_net.count(bit)) src_eq_bits.insert(data_bit_to_eq_net.at(bit)); else skip_cell = true; } } if (!skip_cell) { SigSpec antecedent = SigSpec(src_eq_bits); antecedent.sort_and_unify(); if (GetSize(antecedent) > 1) { if (reduce_db.count(antecedent) == 0) reduce_db[antecedent] = module->ReduceAnd(NEW_ID, antecedent); antecedent = reduce_db.at(antecedent); } SigSpec consequent = cell_to_eq_nets.at(cell); consequent.sort_and_unify(); if (GetSize(consequent) > 1) { if (reduce_db.count(consequent) == 0) reduce_db[consequent] = module->ReduceAnd(NEW_ID, consequent); consequent = reduce_db.at(consequent); } if (opts.fwd) module->addAssume(NEW_ID, consequent, antecedent); if (opts.bwd) { if (invert_db.count(antecedent) == 0) invert_db[antecedent] = module->Not(NEW_ID, antecedent); if (invert_db.count(consequent) == 0) invert_db[consequent] = module->Not(NEW_ID, consequent); module->addAssume(NEW_ID, invert_db.at(antecedent), invert_db.at(consequent)); } } } } }; struct FmcombinePass : public Pass { FmcombinePass() : Pass("fmcombine", "combine two instances of a cell into one") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" fmcombine [options] module_name gold_cell gate_cell\n"); // log(" fmcombine [options] @gold_cell @gate_cell\n"); log("\n"); log("This pass takes two cells, which are instances of the same module, and replaces\n"); log("them with one instance of a special 'combined' module, that effectively\n"); log("contains two copies of the original module, plus some formal properties.\n"); log("\n"); log("This is useful for formal test benches that check what differences in behavior\n"); log("a slight difference in input causes in a module.\n"); log("\n"); log(" -initeq\n"); log(" Insert assumptions that initially all FFs in both circuits have the\n"); log(" same initial values.\n"); log("\n"); log(" -anyeq\n"); log(" Do not duplicate $anyseq/$anyconst cells.\n"); log("\n"); log(" -fwd\n"); log(" Insert forward hint assumptions into the combined module.\n"); log("\n"); log(" -bwd\n"); log(" Insert backward hint assumptions into the combined module.\n"); log(" (Backward hints are logically equivalend to fordward hits, but\n"); log(" some solvers are faster with bwd hints, or even both -bwd and -fwd.)\n"); log("\n"); log(" -nop\n"); log(" Don't insert hint assumptions into the combined module.\n"); log(" (This should not provide any speedup over the original design, but\n"); log(" strangely sometimes it does.)\n"); log("\n"); log("If none of -fwd, -bwd, and -nop is given, then -fwd is used as default.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { opts_t opts; Module *module = nullptr; Cell *gold_cell = nullptr; Cell *gate_cell = nullptr; log_header(design, "Executing FMCOMBINE pass.\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-o" && argidx+1 < args.size()) { // filename = args[++argidx]; // continue; // } if (args[argidx] == "-initeq") { opts.initeq = true; continue; } if (args[argidx] == "-anyeq") { opts.anyeq = true; continue; } if (args[argidx] == "-fwd") { opts.fwd = true; continue; } if (args[argidx] == "-bwd") { opts.bwd = true; continue; } if (args[argidx] == "-nop") { opts.nop = true; continue; } break; } if (argidx+2 == args.size()) { string gold_name = args[argidx++]; string gate_name = args[argidx++]; log_cmd_error("fmcombine @gold_cell @gate_cell call style is not implemented yet."); } else if (argidx+3 == args.size()) { IdString module_name = RTLIL::escape_id(args[argidx++]); IdString gold_name = RTLIL::escape_id(args[argidx++]); IdString gate_name = RTLIL::escape_id(args[argidx++]); module = design->module(module_name); if (module == nullptr) log_cmd_error("Module %s not found.\n", log_id(module_name)); gold_cell = module->cell(gold_name); if (gold_cell == nullptr) log_cmd_error("Gold cell %s not found in module %s.\n", log_id(gold_name), log_id(module)); gate_cell = module->cell(gate_name); if (gate_cell == nullptr) log_cmd_error("Gate cell %s not found in module %s.\n", log_id(gate_name), log_id(module)); } else { log_cmd_error("Invalid number of arguments.\n"); } // extra_args(args, argidx, design); if (opts.nop && (opts.fwd || opts.bwd)) log_cmd_error("Option -nop can not be combined with -fwd and/or -bwd.\n"); if (!opts.nop && !opts.fwd && !opts.bwd) opts.fwd = true; if (gold_cell->type != gate_cell->type) log_cmd_error("Types of gold and gate cells do not match.\n"); if (!gold_cell->parameters.empty()) log_cmd_error("Gold cell has unresolved instance parameters.\n"); if (!gate_cell->parameters.empty()) log_cmd_error("Gate cell has unresolved instance parameters.\n"); FmcombineWorker worker(design, gold_cell->type, opts); worker.generate(); IdString combined_cell_name = module->uniquify(stringf("\\%s_%s", log_id(gold_cell), log_id(gate_cell))); Cell *cell = module->addCell(combined_cell_name, worker.combined_type); cell->attributes = gold_cell->attributes; cell->add_strpool_attribute(ID::src, gate_cell->get_strpool_attribute(ID::src)); log("Combining cells %s and %s in module %s into new cell %s.\n", log_id(gold_cell), log_id(gate_cell), log_id(module), log_id(cell)); for (auto &conn : gold_cell->connections()) cell->setPort(conn.first.str() + "_gold", conn.second); module->remove(gold_cell); for (auto &conn : gate_cell->connections()) cell->setPort(conn.first.str() + "_gate", conn.second); module->remove(gate_cell); } } FmcombinePass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct ZinitPass : public Pass { ZinitPass() : Pass("zinit", "add inverters so all FF are zero-initialized") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" zinit [options] [selection]\n"); log("\n"); log("Add inverters as needed to make all FFs zero-initialized.\n"); log("\n"); log(" -all\n"); log(" also add zero initialization to uninitialized FFs\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { bool all_mode = false; log_header(design, "Executing ZINIT pass (make all FFs zero-initialized).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-all") { all_mode = true; continue; } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) { SigMap sigmap(module); dict<SigBit, State> initbits; pool<SigBit> donebits; for (auto wire : module->selected_wires()) { if (wire->attributes.count(ID::init) == 0) continue; SigSpec wirebits = sigmap(wire); Const initval = wire->attributes.at(ID::init); wire->attributes.erase(ID::init); for (int i = 0; i < GetSize(wirebits) && i < GetSize(initval); i++) { SigBit bit = wirebits[i]; State val = initval[i]; if (val != State::S0 && val != State::S1 && bit.wire != nullptr) continue; if (initbits.count(bit)) { if (initbits.at(bit) != val) log_error("Conflicting init values for signal %s (%s = %s != %s).\n", log_signal(bit), log_signal(SigBit(wire, i)), log_signal(val), log_signal(initbits.at(bit))); continue; } initbits[bit] = val; } } pool<IdString> dff_types = { ID($ff), ID($dff), ID($dffe), ID($dffsr), ID($adff), ID($_FF_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($_DFFSR_NNN_), ID($_DFFSR_NNP_), ID($_DFFSR_NPN_), ID($_DFFSR_NPP_), ID($_DFFSR_PNN_), ID($_DFFSR_PNP_), ID($_DFFSR_PPN_), ID($_DFFSR_PPP_), ID($_DFF_N_), ID($_DFF_NN0_), ID($_DFF_NN1_), ID($_DFF_NP0_), ID($_DFF_NP1_), ID($_DFF_P_), ID($_DFF_PN0_), ID($_DFF_PN1_), ID($_DFF_PP0_), ID($_DFF_PP1_) }; for (auto cell : module->selected_cells()) { if (!dff_types.count(cell->type)) continue; SigSpec sig_d = sigmap(cell->getPort(ID::D)); SigSpec sig_q = sigmap(cell->getPort(ID::Q)); if (GetSize(sig_d) < 1 || GetSize(sig_q) < 1) continue; Const initval; for (int i = 0; i < GetSize(sig_q); i++) { if (initbits.count(sig_q[i])) { initval.bits.push_back(initbits.at(sig_q[i])); donebits.insert(sig_q[i]); } else initval.bits.push_back(all_mode ? State::S0 : State::Sx); } Wire *initwire = module->addWire(NEW_ID, GetSize(initval)); initwire->attributes[ID::init] = initval; for (int i = 0; i < GetSize(initwire); i++) if (initval.bits.at(i) == State::S1) { sig_d[i] = module->NotGate(NEW_ID, sig_d[i]); module->addNotGate(NEW_ID, SigSpec(initwire, i), sig_q[i]); initwire->attributes[ID::init].bits.at(i) = State::S0; } else { module->connect(sig_q[i], SigSpec(initwire, i)); } log("FF init value for cell %s (%s): %s = %s\n", log_id(cell), log_id(cell->type), log_signal(sig_q), log_signal(initval)); cell->setPort(ID::D, sig_d); cell->setPort(ID::Q, initwire); } for (auto &it : initbits) if (donebits.count(it.first) == 0) log_error("Failed to handle init bit %s = %s.\n", log_signal(it.first), log_signal(it.second)); } } } ZinitPass; PRIVATE_NAMESPACE_END <commit_msg>Supress error for unhandled \init if whole module selected<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct ZinitPass : public Pass { ZinitPass() : Pass("zinit", "add inverters so all FF are zero-initialized") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" zinit [options] [selection]\n"); log("\n"); log("Add inverters as needed to make all FFs zero-initialized.\n"); log("\n"); log(" -all\n"); log(" also add zero initialization to uninitialized FFs\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { bool all_mode = false; log_header(design, "Executing ZINIT pass (make all FFs zero-initialized).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-all") { all_mode = true; continue; } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) { SigMap sigmap(module); dict<SigBit, State> initbits; pool<SigBit> donebits; for (auto wire : module->selected_wires()) { if (wire->attributes.count(ID::init) == 0) continue; SigSpec wirebits = sigmap(wire); Const initval = wire->attributes.at(ID::init); wire->attributes.erase(ID::init); for (int i = 0; i < GetSize(wirebits) && i < GetSize(initval); i++) { SigBit bit = wirebits[i]; State val = initval[i]; if (val != State::S0 && val != State::S1 && bit.wire != nullptr) continue; if (initbits.count(bit)) { if (initbits.at(bit) != val) log_error("Conflicting init values for signal %s (%s = %s != %s).\n", log_signal(bit), log_signal(SigBit(wire, i)), log_signal(val), log_signal(initbits.at(bit))); continue; } initbits[bit] = val; } } pool<IdString> dff_types = { ID($ff), ID($dff), ID($dffe), ID($dffsr), ID($adff), ID($_FF_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($_DFFSR_NNN_), ID($_DFFSR_NNP_), ID($_DFFSR_NPN_), ID($_DFFSR_NPP_), ID($_DFFSR_PNN_), ID($_DFFSR_PNP_), ID($_DFFSR_PPN_), ID($_DFFSR_PPP_), ID($_DFF_N_), ID($_DFF_NN0_), ID($_DFF_NN1_), ID($_DFF_NP0_), ID($_DFF_NP1_), ID($_DFF_P_), ID($_DFF_PN0_), ID($_DFF_PN1_), ID($_DFF_PP0_), ID($_DFF_PP1_) }; for (auto cell : module->selected_cells()) { if (!dff_types.count(cell->type)) continue; SigSpec sig_d = sigmap(cell->getPort(ID::D)); SigSpec sig_q = sigmap(cell->getPort(ID::Q)); if (GetSize(sig_d) < 1 || GetSize(sig_q) < 1) continue; Const initval; for (int i = 0; i < GetSize(sig_q); i++) { if (initbits.count(sig_q[i])) { initval.bits.push_back(initbits.at(sig_q[i])); donebits.insert(sig_q[i]); } else initval.bits.push_back(all_mode ? State::S0 : State::Sx); } Wire *initwire = module->addWire(NEW_ID, GetSize(initval)); initwire->attributes[ID::init] = initval; for (int i = 0; i < GetSize(initwire); i++) if (initval.bits.at(i) == State::S1) { sig_d[i] = module->NotGate(NEW_ID, sig_d[i]); module->addNotGate(NEW_ID, SigSpec(initwire, i), sig_q[i]); initwire->attributes[ID::init].bits.at(i) = State::S0; } else { module->connect(sig_q[i], SigSpec(initwire, i)); } log("FF init value for cell %s (%s): %s = %s\n", log_id(cell), log_id(cell->type), log_signal(sig_q), log_signal(initval)); cell->setPort(ID::D, sig_d); cell->setPort(ID::Q, initwire); } if (!design->selected_whole_module(module)) for (auto &it : initbits) if (donebits.count(it.first) == 0) log_error("Failed to handle init bit %s = %s.\n", log_signal(it.first), log_signal(it.second)); } } } ZinitPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/** * \file route.hxx * Provides a class to manage a list of waypoints (i.e. a route). */ // Written by Curtis Olson, started October 2000. // // Copyright (C) 2000 Curtis L. Olson - curt@hfrl.umn.edu // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // $Id$ #ifndef _ROUTE_HXX #define _ROUTE_HXX #ifndef __cplusplus # error This library requires C++ #endif #include <simgear/compiler.h> #include STL_STRING #include <vector> SG_USING_STD(string); SG_USING_STD(vector); #include <simgear/route/waypoint.hxx> /** * A class to manage a list of waypoints (i.e. a route). */ class SGRoute { private: typedef vector < SGWayPoint > route_list; route_list route; int current_wp; void update_distance(int index); public: /** Constructor */ SGRoute(); /** Destructor */ ~SGRoute(); /** Clear the entire route */ inline void clear() { route.clear(); current_wp = 0; } /** * Add waypoint (default), or insert waypoint at position n. * @param wp a waypoint */ void add_waypoint( const SGWayPoint &wp, int n = -1 ); /** * Get the number of waypoints (i.e. route length ) * @return route length */ inline int size() const { return route.size(); } /** * Get the front waypoint. * @return the first waypoint. */ inline SGWayPoint get_first() const { if ( route.size() ) { return route[0]; } else { return SGWayPoint( 0.0, 0.0, 0.0, SGWayPoint::WGS84, "invalid" ); } } /** * Get the current waypoint * @return the current waypoint */ inline SGWayPoint get_current() const { if ( current_wp < (int)route.size() ) { return route[current_wp]; } else { return SGWayPoint( 0.0, 0.0, 0.0, SGWayPoint::WGS84, "invalid" ); } } /** * Set the current waypoint * @param number of waypoint to make current. */ inline void set_current( int n ) { if ( n >= 0 && n < (int)route.size() ) { current_wp = n; } } /** Increment the current waypoint pointer. */ inline void increment_current() { if ( current_wp < (int)route.size() - 1 ) { ++current_wp; } } /** * Get the nth waypoint * @param n waypoint number * @return the nth waypoint */ inline SGWayPoint get_waypoint( const int n ) const { if ( n < (int)route.size() ) { return route[n]; } else { return SGWayPoint( 0.0, 0.0, 0.0, SGWayPoint::WGS84, "invalid" ); } } /** Delete the front waypoint */ inline void delete_first() { delete_waypoint(0); } /** Delete waypoint waypoint with index n (last one if n < 0) */ void delete_waypoint( int n = 0 ); /** * Calculate perpendicular distance from the current route segment * This routine assumes all points are laying on a flat plane and * ignores the altitude (or Z) dimension. For most accurate * results, use with CARTESIAN way points. */ double distance_off_route( double x, double y ) const; }; #endif // _ROUTE_HXX <commit_msg>Modified Files: simgear/route/route.hxx: Remove unused include.<commit_after>/** * \file route.hxx * Provides a class to manage a list of waypoints (i.e. a route). */ // Written by Curtis Olson, started October 2000. // // Copyright (C) 2000 Curtis L. Olson - curt@hfrl.umn.edu // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // $Id$ #ifndef _ROUTE_HXX #define _ROUTE_HXX #ifndef __cplusplus # error This library requires C++ #endif #include <simgear/compiler.h> #include <vector> SG_USING_STD(vector); #include <simgear/route/waypoint.hxx> /** * A class to manage a list of waypoints (i.e. a route). */ class SGRoute { private: typedef vector < SGWayPoint > route_list; route_list route; int current_wp; void update_distance(int index); public: /** Constructor */ SGRoute(); /** Destructor */ ~SGRoute(); /** Clear the entire route */ inline void clear() { route.clear(); current_wp = 0; } /** * Add waypoint (default), or insert waypoint at position n. * @param wp a waypoint */ void add_waypoint( const SGWayPoint &wp, int n = -1 ); /** * Get the number of waypoints (i.e. route length ) * @return route length */ inline int size() const { return route.size(); } /** * Get the front waypoint. * @return the first waypoint. */ inline SGWayPoint get_first() const { if ( route.size() ) { return route[0]; } else { return SGWayPoint( 0.0, 0.0, 0.0, SGWayPoint::WGS84, "invalid" ); } } /** * Get the current waypoint * @return the current waypoint */ inline SGWayPoint get_current() const { if ( current_wp < (int)route.size() ) { return route[current_wp]; } else { return SGWayPoint( 0.0, 0.0, 0.0, SGWayPoint::WGS84, "invalid" ); } } /** * Set the current waypoint * @param number of waypoint to make current. */ inline void set_current( int n ) { if ( n >= 0 && n < (int)route.size() ) { current_wp = n; } } /** Increment the current waypoint pointer. */ inline void increment_current() { if ( current_wp < (int)route.size() - 1 ) { ++current_wp; } } /** * Get the nth waypoint * @param n waypoint number * @return the nth waypoint */ inline SGWayPoint get_waypoint( const int n ) const { if ( n < (int)route.size() ) { return route[n]; } else { return SGWayPoint( 0.0, 0.0, 0.0, SGWayPoint::WGS84, "invalid" ); } } /** Delete the front waypoint */ inline void delete_first() { delete_waypoint(0); } /** Delete waypoint waypoint with index n (last one if n < 0) */ void delete_waypoint( int n = 0 ); /** * Calculate perpendicular distance from the current route segment * This routine assumes all points are laying on a flat plane and * ignores the altitude (or Z) dimension. For most accurate * results, use with CARTESIAN way points. */ double distance_off_route( double x, double y ) const; }; #endif // _ROUTE_HXX <|endoftext|>
<commit_before>/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #include <system_error> #ifndef _WIN32 #include <dirent.h> #endif #ifdef __APPLE__ #include <sys/attr.h> #include <sys/utsname.h> #include <sys/vnode.h> #endif #include "FileDescriptor.h" using namespace watchman; using watchman::FileDescriptor; using watchman::OpenFileHandleOptions; #ifdef HAVE_GETATTRLISTBULK // The ordering of these fields is defined by the ordering of the // corresponding ATTR_XXX flags that are listed after each item. // Those flags appear in a specific order in the getattrlist() // man page. We use FSOPT_PACK_INVAL_ATTRS to ensure that the // kernel won't omit a field that it didn't return to us. typedef struct { uint32_t len; attribute_set_t returned; // ATTR_CMN_RETURNED_ATTRS uint32_t err; // ATTR_CMN_ERROR /* The attribute data length will not be greater than NAME_MAX + 1 * characters, which is NAME_MAX * 3 + 1 bytes (as one UTF-8-encoded * character may take up to three bytes */ attrreference_t name; // ATTR_CMN_NAME dev_t dev; // ATTR_CMN_DEVID fsobj_type_t objtype; // ATTR_CMN_OBJTYPE struct timespec mtime; // ATTR_CMN_MODTIME struct timespec ctime; // ATTR_CMN_CHGTIME struct timespec atime; // ATTR_CMN_ACCTIME uid_t uid; // ATTR_CMN_OWNERID gid_t gid; // ATTR_CMN_GRPID uint32_t mode; // ATTR_CMN_ACCESSMASK, Only the permission bits of st_mode // are valid; other bits should be ignored, // e.g., by masking with ~S_IFMT. uint64_t ino; // ATTR_CMN_FILEID uint32_t link; // ATTR_FILE_LINKCOUNT or ATTR_DIR_LINKCOUNT off_t file_size; // ATTR_FILE_TOTALSIZE } __attribute__((packed)) bulk_attr_item; #endif #ifndef _WIN32 class DirHandle : public watchman_dir_handle { #ifdef HAVE_GETATTRLISTBULK std::string dirName_; FileDescriptor fd_; struct attrlist attrlist_; int retcount_{0}; char buf_[64 * (sizeof(bulk_attr_item) + NAME_MAX * 3 + 1)]; char* cursor_{nullptr}; #endif DIR* d_{nullptr}; struct watchman_dir_ent ent_; public: explicit DirHandle(const char* path, bool strict); ~DirHandle() override; const watchman_dir_ent* readDir() override; int getFd() const override; }; #endif #ifndef _WIN32 /* Opens a directory making sure it's not a symlink */ static DIR* opendir_nofollow(const char* path) { auto fd = openFileHandle(path, OpenFileHandleOptions::strictOpenDir()); #if !defined(HAVE_FDOPENDIR) || defined(__APPLE__) /* fdopendir doesn't work on earlier versions OS X, and we don't * use this function since 10.10, as we prefer to use getattrlistbulk * in that case */ return opendir(path); #else // errno should be set appropriately if this is not a directory auto d = fdopendir(fd.fd()); if (d) { fd.release(); } return d; #endif } #endif #ifdef HAVE_GETATTRLISTBULK // I've seen bulkstat report incorrect sizes on kernel version 14.5.0. // (That's OSX 10.10.5). // Let's avoid it for major kernel versions < 15. // Using statics here to avoid querying the uname on every opendir. // There is opportunity for a data race the first time through, but the // worst case side effect is wasted compute early on. static bool use_bulkstat_by_default(void) { static bool probed = false; static bool safe = false; if (!probed) { struct utsname name; if (uname(&name) == 0) { int maj = 0, min = 0, patch = 0; sscanf(name.release, "%d.%d.%d", &maj, &min, &patch); if (maj >= 15) { safe = true; } } probed = true; } return safe; } #endif #ifndef _WIN32 std::unique_ptr<watchman_dir_handle> w_dir_open(const char* path, bool strict) { return std::make_unique<DirHandle>(path, strict); } #ifdef HAVE_GETATTRLISTBULK static std::string flagsToLabel( const std::unordered_map<uint32_t, const char*>& labels, uint32_t flags) { std::string str; for (const auto& it : labels) { if (it.first == 0) { // Sometimes a define evaluates to zero; it's not useful so skip it continue; } if ((flags & it.first) == it.first) { if (!str.empty()) { str.append(" "); } str.append(it.second); flags &= ~it.first; } } if (flags == 0) { return str; } return to<std::string>(str, " unknown:", flags); } static const std::unordered_map<uint32_t, const char*> commonLabels = { {ATTR_CMN_RETURNED_ATTRS, "ATTR_CMN_RETURNED_ATTRS"}, {ATTR_CMN_ERROR, "ATTR_CMN_ERROR"}, {ATTR_CMN_NAME, "ATTR_CMN_NAME"}, {ATTR_CMN_DEVID, "ATTR_CMN_DEVID"}, {ATTR_CMN_OBJTYPE, "ATTR_CMN_OBJTYPE"}, {ATTR_CMN_MODTIME, "ATTR_CMN_MODTIME"}, {ATTR_CMN_CHGTIME, "ATTR_CMN_CHGTIME"}, {ATTR_CMN_ACCTIME, "ATTR_CMN_ACCTIME"}, {ATTR_CMN_OWNERID, "ATTR_CMN_OWNERID"}, {ATTR_CMN_GRPID, "ATTR_CMN_GRPID"}, {ATTR_CMN_ACCESSMASK, "ATTR_CMN_ACCESSMASK"}, {ATTR_CMN_FILEID, "ATTR_CMN_FILEID"}, }; #endif DirHandle::DirHandle(const char* path, bool strict) #ifdef HAVE_GETATTRLISTBULK : dirName_(path) #endif { #ifdef HAVE_GETATTRLISTBULK dirName_ = path; if (cfg_get_bool("_use_bulkstat", use_bulkstat_by_default())) { auto opts = strict ? OpenFileHandleOptions::strictOpenDir() : OpenFileHandleOptions::openDir(); fd_ = openFileHandle(path, opts); auto info = fd_.getInfo(); if (!info.isDir()) { throw std::system_error(ENOTDIR, std::generic_category(), path); } attrlist_ = attrlist(); attrlist_.bitmapcount = ATTR_BIT_MAP_COUNT; // These field flags are listed here in the same order that they // are listed in the getattrlist() manpage, which is also the // same order that they will be emitted into the buffer, which // is thus the order that they must appear in bulk_attr_item. attrlist_.commonattr = ATTR_CMN_RETURNED_ATTRS | ATTR_CMN_ERROR | ATTR_CMN_NAME | ATTR_CMN_DEVID | ATTR_CMN_OBJTYPE | ATTR_CMN_MODTIME | ATTR_CMN_CHGTIME | ATTR_CMN_ACCTIME | ATTR_CMN_OWNERID | ATTR_CMN_GRPID | ATTR_CMN_ACCESSMASK | ATTR_CMN_FILEID; attrlist_.dirattr = ATTR_DIR_LINKCOUNT; attrlist_.fileattr = ATTR_FILE_TOTALSIZE | ATTR_FILE_LINKCOUNT; return; } #endif d_ = strict ? opendir_nofollow(path) : opendir(path); if (!d_) { throw std::system_error( errno, std::generic_category(), std::string(strict ? "opendir_nofollow: " : "opendir: ") + path); } } const watchman_dir_ent* DirHandle::readDir() { #ifdef HAVE_GETATTRLISTBULK if (fd_) { bulk_attr_item* item; if (!cursor_) { // Read the next batch of results int retcount; errno = 0; retcount = getattrlistbulk( fd_.fd(), &attrlist_, buf_, sizeof(buf_), // FSOPT_PACK_INVAL_ATTRS informs the kernel that we want to // include attrs in our buffer even if it doesn't return them // to us; we want this because we took pains to craft our // bulk_attr_item struct to avoid pointer math. FSOPT_PACK_INVAL_ATTRS); if (retcount == -1) { throw std::system_error( errno, std::generic_category(), "getattrlistbulk"); } if (retcount == 0) { // End of the stream return nullptr; } retcount_ = retcount; cursor_ = buf_; } // Decode the next item item = (bulk_attr_item*)cursor_; cursor_ += item->len; if (--retcount_ == 0) { cursor_ = nullptr; } w_string_piece name{}; if (item->returned.commonattr & ATTR_CMN_NAME) { ent_.d_name = ((char*)&item->name) + item->name.attr_dataoffset; name = w_string_piece(ent_.d_name); } if ((item->returned.commonattr & ATTR_CMN_ERROR) && item->err != 0) { log(ERR, "getattrlistbulk: error while reading dir: ", dirName_, "/", name, ": ", item->err, " ", strerror(item->err), "\n"); // No name means we've got nothing useful to go on if (name.empty()) { throw std::system_error( item->err, std::generic_category(), "getattrlistbulk"); } // Getting the name means that we can at least enumerate the dir // contents. ent_.has_stat = false; return &ent_; } if (name.empty()) { throw std::system_error( EIO, std::generic_category(), to<std::string>( "getattrlistbulk didn't return a name for a directory entry under ", dirName_, "!?")); } if (item->returned.commonattr != attrlist_.commonattr) { log(ERR, "getattrlistbulk didn't return all useful stat data for ", dirName_, "/", name, " returned=", flagsToLabel(commonLabels, item->returned.commonattr), "\n"); // We can still yield the name, so we don't need to throw an exception // in this case. ent_.has_stat = false; return &ent_; } ent_.stat = watchman::FileInformation(); ent_.stat.dev = item->dev; memcpy(&ent_.stat.mtime, &item->mtime, sizeof(item->mtime)); memcpy(&ent_.stat.ctime, &item->ctime, sizeof(item->ctime)); memcpy(&ent_.stat.atime, &item->atime, sizeof(item->atime)); ent_.stat.uid = item->uid; ent_.stat.gid = item->gid; ent_.stat.mode = item->mode & ~S_IFMT; ent_.stat.ino = item->ino; switch (item->objtype) { case VREG: ent_.stat.mode |= S_IFREG; ent_.stat.size = item->file_size; ent_.stat.nlink = item->link; break; case VDIR: ent_.stat.mode |= S_IFDIR; ent_.stat.nlink = item->link; break; case VLNK: ent_.stat.mode |= S_IFLNK; ent_.stat.size = item->file_size; break; case VBLK: ent_.stat.mode |= S_IFBLK; break; case VCHR: ent_.stat.mode |= S_IFCHR; break; case VFIFO: ent_.stat.mode |= S_IFIFO; break; case VSOCK: ent_.stat.mode |= S_IFSOCK; break; } ent_.has_stat = true; return &ent_; } #endif if (!d_) { return nullptr; } errno = 0; auto dent = readdir(d_); if (!dent) { if (errno) { throw std::system_error(errno, std::generic_category(), "readdir"); } return nullptr; } ent_.d_name = dent->d_name; ent_.has_stat = false; return &ent_; } DirHandle::~DirHandle() { if (d_) { closedir(d_); } } int DirHandle::getFd() const { #ifdef HAVE_GETATTRLISTBULK if (cfg_get_bool("_use_bulkstat", use_bulkstat_by_default())) { return fd_.fd(); } #endif return dirfd(d_); } #endif /* vim:ts=2:sw=2:et: */ <commit_msg>watchman: tighten up some edge cases in getattrlistbulk<commit_after>/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "watchman.h" #include <system_error> #ifndef _WIN32 #include <dirent.h> #endif #ifdef __APPLE__ #include <sys/attr.h> #include <sys/utsname.h> #include <sys/vnode.h> #endif #include "FileDescriptor.h" using namespace watchman; using watchman::FileDescriptor; using watchman::OpenFileHandleOptions; #ifdef HAVE_GETATTRLISTBULK // The ordering of these fields is defined by the ordering of the // corresponding ATTR_XXX flags that are listed after each item. // Those flags appear in a specific order in the getattrlist() // man page. We use FSOPT_PACK_INVAL_ATTRS to ensure that the // kernel won't omit a field that it didn't return to us. typedef struct { uint32_t len; attribute_set_t returned; // ATTR_CMN_RETURNED_ATTRS uint32_t err; // ATTR_CMN_ERROR /* The attribute data length will not be greater than NAME_MAX + 1 * characters, which is NAME_MAX * 3 + 1 bytes (as one UTF-8-encoded * character may take up to three bytes */ attrreference_t name; // ATTR_CMN_NAME dev_t dev; // ATTR_CMN_DEVID fsobj_type_t objtype; // ATTR_CMN_OBJTYPE struct timespec mtime; // ATTR_CMN_MODTIME struct timespec ctime; // ATTR_CMN_CHGTIME struct timespec atime; // ATTR_CMN_ACCTIME uid_t uid; // ATTR_CMN_OWNERID gid_t gid; // ATTR_CMN_GRPID uint32_t mode; // ATTR_CMN_ACCESSMASK, Only the permission bits of st_mode // are valid; other bits should be ignored, // e.g., by masking with ~S_IFMT. uint64_t ino; // ATTR_CMN_FILEID uint32_t link; // ATTR_FILE_LINKCOUNT or ATTR_DIR_LINKCOUNT off_t file_size; // ATTR_FILE_TOTALSIZE } __attribute__((packed)) bulk_attr_item; #endif #ifndef _WIN32 class DirHandle : public watchman_dir_handle { #ifdef HAVE_GETATTRLISTBULK std::string dirName_; FileDescriptor fd_; struct attrlist attrlist_; int retcount_{0}; char buf_[64 * (sizeof(bulk_attr_item) + NAME_MAX * 3 + 1)]; char* cursor_{nullptr}; #endif DIR* d_{nullptr}; struct watchman_dir_ent ent_; public: explicit DirHandle(const char* path, bool strict); ~DirHandle() override; const watchman_dir_ent* readDir() override; int getFd() const override; }; #endif #ifndef _WIN32 /* Opens a directory making sure it's not a symlink */ static DIR* opendir_nofollow(const char* path) { auto fd = openFileHandle(path, OpenFileHandleOptions::strictOpenDir()); #if !defined(HAVE_FDOPENDIR) || defined(__APPLE__) /* fdopendir doesn't work on earlier versions OS X, and we don't * use this function since 10.10, as we prefer to use getattrlistbulk * in that case */ return opendir(path); #else // errno should be set appropriately if this is not a directory auto d = fdopendir(fd.fd()); if (d) { fd.release(); } return d; #endif } #endif #ifdef HAVE_GETATTRLISTBULK // I've seen bulkstat report incorrect sizes on kernel version 14.5.0. // (That's OSX 10.10.5). // Let's avoid it for major kernel versions < 15. // Using statics here to avoid querying the uname on every opendir. // There is opportunity for a data race the first time through, but the // worst case side effect is wasted compute early on. static bool use_bulkstat_by_default(void) { static bool probed = false; static bool safe = false; if (!probed) { struct utsname name; if (uname(&name) == 0) { int maj = 0, min = 0, patch = 0; sscanf(name.release, "%d.%d.%d", &maj, &min, &patch); if (maj >= 15) { safe = true; } } probed = true; } return safe; } #endif #ifndef _WIN32 std::unique_ptr<watchman_dir_handle> w_dir_open(const char* path, bool strict) { return std::make_unique<DirHandle>(path, strict); } #ifdef HAVE_GETATTRLISTBULK static std::string flagsToLabel( const std::unordered_map<uint32_t, const char*>& labels, uint32_t flags) { std::string str; for (const auto& it : labels) { if (it.first == 0) { // Sometimes a define evaluates to zero; it's not useful so skip it continue; } if ((flags & it.first) == it.first) { if (!str.empty()) { str.append(" "); } str.append(it.second); flags &= ~it.first; } } if (flags == 0) { return str; } return to<std::string>(str, " unknown:", flags); } static const std::unordered_map<uint32_t, const char*> commonLabels = { {ATTR_CMN_RETURNED_ATTRS, "ATTR_CMN_RETURNED_ATTRS"}, {ATTR_CMN_ERROR, "ATTR_CMN_ERROR"}, {ATTR_CMN_NAME, "ATTR_CMN_NAME"}, {ATTR_CMN_DEVID, "ATTR_CMN_DEVID"}, {ATTR_CMN_OBJTYPE, "ATTR_CMN_OBJTYPE"}, {ATTR_CMN_MODTIME, "ATTR_CMN_MODTIME"}, {ATTR_CMN_CHGTIME, "ATTR_CMN_CHGTIME"}, {ATTR_CMN_ACCTIME, "ATTR_CMN_ACCTIME"}, {ATTR_CMN_OWNERID, "ATTR_CMN_OWNERID"}, {ATTR_CMN_GRPID, "ATTR_CMN_GRPID"}, {ATTR_CMN_ACCESSMASK, "ATTR_CMN_ACCESSMASK"}, {ATTR_CMN_FILEID, "ATTR_CMN_FILEID"}, }; #endif DirHandle::DirHandle(const char* path, bool strict) #ifdef HAVE_GETATTRLISTBULK : dirName_(path) #endif { #ifdef HAVE_GETATTRLISTBULK dirName_ = path; if (cfg_get_bool("_use_bulkstat", use_bulkstat_by_default())) { auto opts = strict ? OpenFileHandleOptions::strictOpenDir() : OpenFileHandleOptions::openDir(); fd_ = openFileHandle(path, opts); auto info = fd_.getInfo(); if (!info.isDir()) { throw std::system_error(ENOTDIR, std::generic_category(), path); } attrlist_ = attrlist{}; attrlist_.bitmapcount = ATTR_BIT_MAP_COUNT; // These field flags are listed here in the same order that they // are listed in the getattrlist() manpage, which is also the // same order that they will be emitted into the buffer, which // is thus the order that they must appear in bulk_attr_item. attrlist_.commonattr = ATTR_CMN_RETURNED_ATTRS | ATTR_CMN_ERROR | ATTR_CMN_NAME | ATTR_CMN_DEVID | ATTR_CMN_OBJTYPE | ATTR_CMN_MODTIME | ATTR_CMN_CHGTIME | ATTR_CMN_ACCTIME | ATTR_CMN_OWNERID | ATTR_CMN_GRPID | ATTR_CMN_ACCESSMASK | ATTR_CMN_FILEID; attrlist_.dirattr = ATTR_DIR_LINKCOUNT; attrlist_.fileattr = ATTR_FILE_TOTALSIZE | ATTR_FILE_LINKCOUNT; return; } #endif d_ = strict ? opendir_nofollow(path) : opendir(path); if (!d_) { throw std::system_error( errno, std::generic_category(), std::string(strict ? "opendir_nofollow: " : "opendir: ") + path); } } const watchman_dir_ent* DirHandle::readDir() { #ifdef HAVE_GETATTRLISTBULK if (fd_) { bulk_attr_item* item; if (!cursor_) { // Read the next batch of results int retcount; memset(buf_, 0, sizeof(buf_)); errno = 0; retcount = getattrlistbulk( fd_.fd(), &attrlist_, buf_, sizeof(buf_), // FSOPT_PACK_INVAL_ATTRS informs the kernel that we want to // include attrs in our buffer even if it doesn't return them // to us; we want this because we took pains to craft our // bulk_attr_item struct to avoid pointer math. FSOPT_PACK_INVAL_ATTRS); if (retcount == -1) { throw std::system_error( errno, std::generic_category(), "getattrlistbulk"); } if (retcount == 0) { // End of the stream return nullptr; } retcount_ = retcount; cursor_ = buf_; } // Decode the next item item = (bulk_attr_item*)cursor_; cursor_ += item->len; if (cursor_ > buf_ + sizeof(buf_)) { // This shouldn't happen in practice: the man page indicates that ERANGE // is returned from getattrlistbulk() if the buffer isn't large enough // for a single entry. throw std::system_error( ENOSPC, std::generic_category(), "getattrlistbulk: attributes overflow size of buf storage"); } if (--retcount_ == 0) { // No more entries from the last chunk cursor_ = nullptr; } w_string_piece name{}; if (item->returned.commonattr & ATTR_CMN_NAME) { ent_.d_name = ((char*)&item->name) + item->name.attr_dataoffset; // Check that the data is within bounds. // This shouldn't happen in practice: as per the above comment, // we expect to have encountered an ERANGE before we get here. // Note that even though the data reference records the length, // that length is the padded length of the value; the true // name value is a NUL terminated string within that space. if (ent_.d_name + item->name.attr_length > buf_ + sizeof(buf_)) { throw std::system_error( ENOSPC, std::generic_category(), "getattrlistbulk: name overflows size of buf storage"); } name = w_string_piece(ent_.d_name); } if ((item->returned.commonattr & ATTR_CMN_ERROR) && item->err != 0) { log(ERR, "getattrlistbulk: error while reading dir: ", dirName_, "/", name, ": ", item->err, " ", strerror(item->err), "\n"); // No name means we've got nothing useful to go on if (name.empty()) { throw std::system_error( item->err, std::generic_category(), "getattrlistbulk"); } // Getting the name means that we can at least enumerate the dir // contents. ent_.has_stat = false; return &ent_; } if (name.empty()) { throw std::system_error( EIO, std::generic_category(), to<std::string>( "getattrlistbulk didn't return a name for a directory entry under ", dirName_, "!?")); } if ((item->returned.commonattr & attrlist_.commonattr) != attrlist_.commonattr) { log(ERR, "getattrlistbulk didn't return all useful stat data for ", dirName_, "/", name, " returned=", flagsToLabel(commonLabels, item->returned.commonattr), "\n"); // We can still yield the name, so we don't need to throw an exception // in this case. ent_.has_stat = false; return &ent_; } ent_.stat = watchman::FileInformation(); ent_.stat.dev = item->dev; memcpy(&ent_.stat.mtime, &item->mtime, sizeof(item->mtime)); memcpy(&ent_.stat.ctime, &item->ctime, sizeof(item->ctime)); memcpy(&ent_.stat.atime, &item->atime, sizeof(item->atime)); ent_.stat.uid = item->uid; ent_.stat.gid = item->gid; ent_.stat.mode = item->mode & ~S_IFMT; ent_.stat.ino = item->ino; switch (item->objtype) { case VREG: ent_.stat.mode |= S_IFREG; ent_.stat.size = item->file_size; ent_.stat.nlink = item->link; break; case VDIR: ent_.stat.mode |= S_IFDIR; ent_.stat.nlink = item->link; break; case VLNK: ent_.stat.mode |= S_IFLNK; ent_.stat.size = item->file_size; break; case VBLK: ent_.stat.mode |= S_IFBLK; break; case VCHR: ent_.stat.mode |= S_IFCHR; break; case VFIFO: ent_.stat.mode |= S_IFIFO; break; case VSOCK: ent_.stat.mode |= S_IFSOCK; break; } ent_.has_stat = true; return &ent_; } #endif if (!d_) { return nullptr; } errno = 0; auto dent = readdir(d_); if (!dent) { if (errno) { throw std::system_error(errno, std::generic_category(), "readdir"); } return nullptr; } ent_.d_name = dent->d_name; ent_.has_stat = false; return &ent_; } DirHandle::~DirHandle() { if (d_) { closedir(d_); } } int DirHandle::getFd() const { #ifdef HAVE_GETATTRLISTBULK if (cfg_get_bool("_use_bulkstat", use_bulkstat_by_default())) { return fd_.fd(); } #endif return dirfd(d_); } #endif /* vim:ts=2:sw=2:et: */ <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "CodeGenerationVisitor.h" #include "expressions/ReferenceExpression.h" #include "expressions/MetaCallExpression.h" #include "ModelBase/src/nodes/NameText.h" #include "declarations/MetaDefinition.h" #include "expressions/BooleanLiteral.h" namespace OOModel { CodeGenerationVisitor::CodeGenerationVisitor(QMap<QString, Model::Node *> args) : args_{args} {} void CodeGenerationVisitor::init() { addType<ReferenceExpression>(visitReferenceExpression); addType<Model::NameText>(visitNameText); addType<MetaCallExpression>(visitMetaCallExpression); } void CodeGenerationVisitor::visitReferenceExpression(CodeGenerationVisitor* v, OOModel::ReferenceExpression* n) { auto input = n->name(); if (!input.contains("##")) { if (auto argument = v->args_[input]) { if (auto argumentReference = DCast<ReferenceExpression>(argument)) { // case: there exists a replacement and it is another ReferenceExpression // -> copy name (replacing it would cause child nodes of n to disappear) n->setName(argumentReference->name()); } else { // case: there exists a replacement and it is not a ReferenceExpression // -> replace node auto cloned = argument->clone(); n->parent()->replaceChild(n, cloned); // visit the cloned tree and return to avoid visiting the children of n v->visitChildren(cloned); return; } } } else { // case: n's name is a concatenated identifier (a##b) // -> build identifier QStringList parts = input.split("##"); bool modified = false; for (auto i = 0; i < parts.size(); i++) if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]])) { parts[i] = argument->name(); modified = true; } if (modified) n->setName(parts.join("")); } v->visitChildren(n); } void CodeGenerationVisitor::visitNameText(CodeGenerationVisitor* v, Model::NameText* n) { auto input = n->get(); if (!input.contains("##")) { if (auto argument = DCast<ReferenceExpression>(v->args_[input])) { // case: n's name is an existing argument of type ReferenceExpression // -> copy name as new text n->set(argument->name()); } } else { // case: n's text is a concatenated text (a##b) // -> build text QStringList parts = input.split("##"); bool modified = false; for (auto i = 0; i < parts.size(); i++) if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]])) { parts[i] = argument->name(); modified = true; } if (modified) n->set(parts.join("")); } v->visitChildren(n); } void CodeGenerationVisitor::visitMetaCallExpression(CodeGenerationVisitor* v, MetaCallExpression* n) { /* * process arguments before generating. * this ensures proper argument propagation. */ v->visitChildren(n); if (!n->metaDefinition()) { // case: unresolved meta definition // -> check if it is a predefined meta function if (auto metaDef = DCast<ReferenceExpression>(n->callee())) v->handlePredefinedFunction(metaDef->name(), n); } else { // case: resolved meta definition // -> generate recursively n->generatedTree(); } } void CodeGenerationVisitor::handlePredefinedFunction(QString function, MetaCallExpression* n) { /* * only handle predefined functions if they are nested in another meta call. * this helps preventing unintentional modification of parents which are not generated nodes. */ if (!n->firstAncestorOfType<MetaCallExpression>()) return; if (function == "SET_OVERRIDE_FLAG") { if (n->arguments()->size() != 1) { qDebug() << function << "#arguments != 1"; return; } if (auto argument = DCast<ReferenceExpression>(n->arguments()->first())) if (auto flag = DCast<BooleanLiteral>(args_[argument->name()])) if (auto p = n->firstAncestorOfType<Declaration>()) p->modifiers()->set(Modifier::Override, flag->value()); } } } <commit_msg>add stringification support<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "CodeGenerationVisitor.h" #include "expressions/ReferenceExpression.h" #include "expressions/MetaCallExpression.h" #include "ModelBase/src/nodes/NameText.h" #include "declarations/MetaDefinition.h" #include "expressions/BooleanLiteral.h" namespace OOModel { CodeGenerationVisitor::CodeGenerationVisitor(QMap<QString, Model::Node *> args) : args_{args} {} void CodeGenerationVisitor::init() { addType<ReferenceExpression>(visitReferenceExpression); addType<Model::NameText>(visitNameText); addType<MetaCallExpression>(visitMetaCallExpression); } void CodeGenerationVisitor::visitReferenceExpression(CodeGenerationVisitor* v, OOModel::ReferenceExpression* n) { auto input = n->name(); if (!input.contains("##")) { if (input.startsWith("#")) { if (auto argument = v->args_[input.right(input.length() - 1)]) if (auto argumentReference = DCast<ReferenceExpression>(argument)) n->parent()->replaceChild(n, new OOModel::StringLiteral(argumentReference->name())); } else if (auto argument = v->args_[input]) { if (auto argumentReference = DCast<ReferenceExpression>(argument)) { // case: there exists a replacement and it is another ReferenceExpression // -> copy name (replacing it would cause child nodes of n to disappear) n->setName(argumentReference->name()); } else { // case: there exists a replacement and it is not a ReferenceExpression // -> replace node auto cloned = argument->clone(); n->parent()->replaceChild(n, cloned); // visit the cloned tree and return to avoid visiting the children of n v->visitChildren(cloned); return; } } } else { // case: n's name is a concatenated identifier (a##b) // -> build identifier QStringList parts = input.split("##"); bool modified = false; for (auto i = 0; i < parts.size(); i++) if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]])) { parts[i] = argument->name(); modified = true; } if (modified) n->setName(parts.join("")); } v->visitChildren(n); } void CodeGenerationVisitor::visitNameText(CodeGenerationVisitor* v, Model::NameText* n) { auto input = n->get(); if (!input.contains("##")) { if (auto argument = DCast<ReferenceExpression>(v->args_[input])) { // case: n's name is an existing argument of type ReferenceExpression // -> copy name as new text n->set(argument->name()); } } else { // case: n's text is a concatenated text (a##b) // -> build text QStringList parts = input.split("##"); bool modified = false; for (auto i = 0; i < parts.size(); i++) if (auto argument = DCast<ReferenceExpression>(v->args_[parts[i]])) { parts[i] = argument->name(); modified = true; } if (modified) n->set(parts.join("")); } v->visitChildren(n); } void CodeGenerationVisitor::visitMetaCallExpression(CodeGenerationVisitor* v, MetaCallExpression* n) { /* * process arguments before generating. * this ensures proper argument propagation. */ v->visitChildren(n); if (!n->metaDefinition()) { // case: unresolved meta definition // -> check if it is a predefined meta function if (auto metaDef = DCast<ReferenceExpression>(n->callee())) v->handlePredefinedFunction(metaDef->name(), n); } else { // case: resolved meta definition // -> generate recursively n->generatedTree(); } } void CodeGenerationVisitor::handlePredefinedFunction(QString function, MetaCallExpression* n) { /* * only handle predefined functions if they are nested in another meta call. * this helps preventing unintentional modification of parents which are not generated nodes. */ if (!n->firstAncestorOfType<MetaCallExpression>()) return; if (function == "SET_OVERRIDE_FLAG") { if (n->arguments()->size() != 1) { qDebug() << function << "#arguments != 1"; return; } if (auto argument = DCast<ReferenceExpression>(n->arguments()->first())) if (auto flag = DCast<BooleanLiteral>(args_[argument->name()])) if (auto p = n->firstAncestorOfType<Declaration>()) p->modifiers()->set(Modifier::Override, flag->value()); } } } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreStreamSerialiser.h" #include "OgreException.h" #include "OgreStringConverter.h" #include "OgreLogManager.h" #include "OgreVector2.h" #include "OgreVector3.h" #include "OgreVector4.h" #include "OgreMatrix3.h" #include "OgreMatrix4.h" #include "OgreQuaternion.h" namespace Ogre { //--------------------------------------------------------------------- uint32 StreamSerialiser::HEADER_ID = 0x0001; uint32 StreamSerialiser::REVERSE_HEADER_ID = 0x1000; uint32 StreamSerialiser::CHUNK_HEADER_SIZE = sizeof(uint32) + // id sizeof(uint16) + // version sizeof(uint32) + // length sizeof(uint32); // checksum //--------------------------------------------------------------------- StreamSerialiser::StreamSerialiser(const DataStreamPtr& stream, Endian endianMode, bool autoHeader) : mStream(stream) , mEndian(endianMode) , mFlipEndian(false) , mReadWriteHeader(autoHeader) { if (mEndian != ENDIAN_AUTO) { #if OGRE_ENDIAN == OGRE_ENDIAN_BIG if (mEndian == ENDIAN_LITTLE) mFlipEndian = true; #else if (mEndian == ENDIAN_BIG) mFlipEndian = true; #endif } checkStream(); } //--------------------------------------------------------------------- StreamSerialiser::~StreamSerialiser() { // really this should be empty if read/write was complete, but be tidy if (!mChunkStack.empty()) { LogManager::getSingleton().stream() << "Warning: stream " << mStream->getName() << " was not fully read / written; " << mChunkStack.size() << " chunks remain unterminated."; } for (ChunkStack::iterator i = mChunkStack.begin(); i != mChunkStack.end(); ++i) delete *i; mChunkStack.clear(); } //--------------------------------------------------------------------- uint32 StreamSerialiser::makeIdentifier(const String& code) { assert(code.length() <= 4 && "Characters after the 4th are being ignored"); uint32 ret = 0; size_t c = std::min((size_t)4, code.length()); for (size_t i = 0; i < c; ++i) { ret += (code.at(i) << (i * 8)); } return ret; } //--------------------------------------------------------------------- uint32 StreamSerialiser::getCurrentChunkID() const { if (mChunkStack.empty()) return 0; else return mChunkStack.back()->id; } //--------------------------------------------------------------------- const StreamSerialiser::Chunk* StreamSerialiser::readChunkBegin() { // Have we figured out the endian mode yet? if (mReadWriteHeader) readHeader(); if (mEndian == ENDIAN_AUTO) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Endian mode has not been determined, did you disable header without setting?", "StreamSerialiser::readChunkBegin"); Chunk* chunk = readChunkImpl(); mChunkStack.push_back(chunk); return chunk; } //--------------------------------------------------------------------- void StreamSerialiser::readChunkEnd(uint32 id) { Chunk* c = popChunk(id); checkStream(); // skip to the end of the chunk if we were not there already // this lets us quite reading a chunk anywhere and have the read marker // automatically skip to the next one if (mStream->tell() < (c->offset + c->length)) mStream->seek(c->offset + c->length); OGRE_DELETE c; } //--------------------------------------------------------------------- void StreamSerialiser::readHeader() { uint32 headerid; size_t actually_read = mStream->read(&headerid, sizeof(uint32)); // skip back mStream->skip(0 - (long)actually_read); // validate that this is a header chunk if (headerid == REVERSE_HEADER_ID) { mFlipEndian = true; } else if (headerid == HEADER_ID) { mFlipEndian = false; } else { // no good OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Cannot determine endian mode because header is missing", "StreamSerialiser::readHeader"); } determineEndianness(); mReadWriteHeader = false; const Chunk* c = readChunkBegin(); // endian should be flipped now assert(c->id == HEADER_ID); readChunkEnd(HEADER_ID); } //--------------------------------------------------------------------- void StreamSerialiser::determineEndianness() { #if OGRE_ENDIAN == OGRE_ENDIAN_BIG if (mFlipEndian) mEndian = ENDIAN_LITTLE; else mEndian = ENDIAN_BIG; #else if (mFlipEndian) mEndian = ENDIAN_BIG; else mEndian = ENDIAN_LITTLE; #endif } //--------------------------------------------------------------------- const StreamSerialiser::Chunk* StreamSerialiser::getCurrentChunk() const { if (mChunkStack.empty()) return 0; else return mChunkStack.back(); } //--------------------------------------------------------------------- bool StreamSerialiser::eof() const { checkStream(); return mStream->eof(); } //--------------------------------------------------------------------- void StreamSerialiser::checkStream(bool failOnEof, bool validateReadable, bool validateWriteable) const { if (mStream.isNull()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, stream is null", "StreamSerialiser::checkStream"); if (failOnEof && mStream->eof()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, end of file on stream", "StreamSerialiser::checkStream"); if (validateReadable && !mStream->isReadable()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, file is not readable", "StreamSerialiser::checkStream"); if (validateWriteable && !mStream->isWriteable()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, file is not writeable", "StreamSerialiser::checkStream"); } //--------------------------------------------------------------------- void StreamSerialiser::writeHeader() { if (mEndian == ENDIAN_AUTO) determineEndianness(); // Header chunk has zero data size writeChunkImpl(HEADER_ID, 1); writeChunkEnd(HEADER_ID); mReadWriteHeader = false; } //--------------------------------------------------------------------- void StreamSerialiser::writeChunkBegin(uint32 id, uint16 version /* = 1 */) { checkStream(false, false, true); if (mReadWriteHeader) writeHeader(); if (mEndian == ENDIAN_AUTO) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Endian mode has not been determined, did you disable header without setting?", "StreamSerialiser::writeChunkBegin"); writeChunkImpl(id, version); } //--------------------------------------------------------------------- void StreamSerialiser::writeChunkEnd(uint32 id) { checkStream(false, false, true); Chunk* c = popChunk(id); // update the sizes size_t currPos = mStream->tell(); c->length = static_cast<uint32>(currPos - c->offset - CHUNK_HEADER_SIZE); // seek to 'length' position in stream for this chunk // skip id (32) and version (16) mStream->seek(c->offset + sizeof(uint32) + sizeof(uint16)); write(&c->length); // write updated checksum uint32 checksum = calculateChecksum(c); write(&checksum); // seek back to previous position mStream->seek(currPos); OGRE_DELETE c; } //--------------------------------------------------------------------- StreamSerialiser::Chunk* StreamSerialiser::readChunkImpl() { Chunk *chunk = OGRE_NEW Chunk(); chunk->offset = static_cast<uint32>(mStream->tell()); read(&chunk->id); read(&chunk->version); read(&chunk->length); uint32 checksum; read(&checksum); if (checksum != calculateChecksum(chunk)) { // no good, this is an invalid chunk uint32 off = chunk->offset; OGRE_DELETE chunk; OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Corrupt chunk detected in stream " + mStream->getName() + " at byte " + StringConverter::toString(off), "StreamSerialiser::readChunkImpl"); } else { return chunk; } } //--------------------------------------------------------------------- void StreamSerialiser::writeChunkImpl(uint32 id, uint16 version) { Chunk* c = OGRE_NEW Chunk(); c->id = id; c->version = version; c->offset = mStream->tell(); c->length = 0; mChunkStack.push_back(c); write(&c->id); write(&c->version); write(&c->length); // write length again, this is just a placeholder for the checksum (to come later) write(&c->length); } //--------------------------------------------------------------------- void StreamSerialiser::writeData(const void* buf, size_t size, size_t count) { checkStream(false, false, true); size_t totSize = size * count; if (mFlipEndian) { void* pToWrite = OGRE_MALLOC(totSize, MEMCATEGORY_GENERAL); memcpy(pToWrite, buf, totSize); flipEndian(pToWrite, size, count); mStream->write(pToWrite, totSize); OGRE_FREE(pToWrite, MEMCATEGORY_GENERAL); } else { mStream->write(buf, totSize); } } //--------------------------------------------------------------------- void StreamSerialiser::write(const Vector2* vec) { write(vec->ptr(), 2); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Vector3* vec) { write(vec->ptr(), 3); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Vector4* vec) { write(vec->ptr(), 4); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Quaternion* q) { write(q->ptr(), 4); } //--------------------------------------------------------------------- void StreamSerialiser::write(const String* string) { mStream->write(string->c_str(), string->size()); // write terminator (newline) char eol = '\n'; mStream->write(&eol, 1); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Matrix3* m) { write((*m)[0], 9); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Matrix4* m) { write((*m)[0], 12); } //--------------------------------------------------------------------- void StreamSerialiser::readData(void* buf, size_t size, size_t count) { checkStream(true, true, false); size_t totSize = size * count; mStream->read(buf, totSize); if (mFlipEndian) flipEndian(buf, size, count); } //--------------------------------------------------------------------- void StreamSerialiser::read(Vector2* vec) { read(vec->ptr(), 2); } //--------------------------------------------------------------------- void StreamSerialiser::read(Vector3* vec) { read(vec->ptr(), 3); } //--------------------------------------------------------------------- void StreamSerialiser::read(Vector4* vec) { read(vec->ptr(), 4); } //--------------------------------------------------------------------- void StreamSerialiser::read(Quaternion* q) { read(q->ptr(), 4); } //--------------------------------------------------------------------- void StreamSerialiser::read(Matrix3* m) { read((*m)[0], 9); } //--------------------------------------------------------------------- void StreamSerialiser::read(Matrix4* m) { read((*m)[0], 12); } //--------------------------------------------------------------------- void StreamSerialiser::read(String* string) { String readStr = mStream->getLine(false); string->swap(readStr); } //--------------------------------------------------------------------- void StreamSerialiser::flipEndian(void * pBase, size_t size, size_t count) { for (size_t c = 0; c < count; ++c) { void *pData = (void *)((long)pBase + (c * size)); char swapByte; for(size_t byteIndex = 0; byteIndex < size/2; byteIndex++) { swapByte = *(char *)((long)pData + byteIndex); *(char *)((long)pData + byteIndex) = *(char *)((long)pData + size - byteIndex - 1); *(char *)((long)pData + size - byteIndex - 1) = swapByte; } } } //--------------------------------------------------------------------- void StreamSerialiser::flipEndian(void * pData, size_t size) { flipEndian(pData, size, 1); } //--------------------------------------------------------------------- uint32 StreamSerialiser::calculateChecksum(Chunk* c) { return FastHash((const char*)c, sizeof(uint32) * 2 + sizeof(uint16)); } //--------------------------------------------------------------------- StreamSerialiser::Chunk* StreamSerialiser::popChunk(uint id) { if (mChunkStack.empty()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "No active chunk!", "StreamSerialiser::popChunk"); const Chunk* chunk = mChunkStack.back(); if (chunk->id != id) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Incorrect chunk id!", "StreamSerialiser::popChunk"); Chunk* c = mChunkStack.back(); mChunkStack.pop_back(); return c; } } <commit_msg>(bugfix) Added OgreCommon.h to OgreStreamSerialiser.cpp (would not compile on Linux due to FastHash not being known)<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreCommon.h" #include "OgreStreamSerialiser.h" #include "OgreException.h" #include "OgreStringConverter.h" #include "OgreLogManager.h" #include "OgreVector2.h" #include "OgreVector3.h" #include "OgreVector4.h" #include "OgreMatrix3.h" #include "OgreMatrix4.h" #include "OgreQuaternion.h" namespace Ogre { //--------------------------------------------------------------------- uint32 StreamSerialiser::HEADER_ID = 0x0001; uint32 StreamSerialiser::REVERSE_HEADER_ID = 0x1000; uint32 StreamSerialiser::CHUNK_HEADER_SIZE = sizeof(uint32) + // id sizeof(uint16) + // version sizeof(uint32) + // length sizeof(uint32); // checksum //--------------------------------------------------------------------- StreamSerialiser::StreamSerialiser(const DataStreamPtr& stream, Endian endianMode, bool autoHeader) : mStream(stream) , mEndian(endianMode) , mFlipEndian(false) , mReadWriteHeader(autoHeader) { if (mEndian != ENDIAN_AUTO) { #if OGRE_ENDIAN == OGRE_ENDIAN_BIG if (mEndian == ENDIAN_LITTLE) mFlipEndian = true; #else if (mEndian == ENDIAN_BIG) mFlipEndian = true; #endif } checkStream(); } //--------------------------------------------------------------------- StreamSerialiser::~StreamSerialiser() { // really this should be empty if read/write was complete, but be tidy if (!mChunkStack.empty()) { LogManager::getSingleton().stream() << "Warning: stream " << mStream->getName() << " was not fully read / written; " << mChunkStack.size() << " chunks remain unterminated."; } for (ChunkStack::iterator i = mChunkStack.begin(); i != mChunkStack.end(); ++i) delete *i; mChunkStack.clear(); } //--------------------------------------------------------------------- uint32 StreamSerialiser::makeIdentifier(const String& code) { assert(code.length() <= 4 && "Characters after the 4th are being ignored"); uint32 ret = 0; size_t c = std::min((size_t)4, code.length()); for (size_t i = 0; i < c; ++i) { ret += (code.at(i) << (i * 8)); } return ret; } //--------------------------------------------------------------------- uint32 StreamSerialiser::getCurrentChunkID() const { if (mChunkStack.empty()) return 0; else return mChunkStack.back()->id; } //--------------------------------------------------------------------- const StreamSerialiser::Chunk* StreamSerialiser::readChunkBegin() { // Have we figured out the endian mode yet? if (mReadWriteHeader) readHeader(); if (mEndian == ENDIAN_AUTO) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Endian mode has not been determined, did you disable header without setting?", "StreamSerialiser::readChunkBegin"); Chunk* chunk = readChunkImpl(); mChunkStack.push_back(chunk); return chunk; } //--------------------------------------------------------------------- void StreamSerialiser::readChunkEnd(uint32 id) { Chunk* c = popChunk(id); checkStream(); // skip to the end of the chunk if we were not there already // this lets us quite reading a chunk anywhere and have the read marker // automatically skip to the next one if (mStream->tell() < (c->offset + c->length)) mStream->seek(c->offset + c->length); OGRE_DELETE c; } //--------------------------------------------------------------------- void StreamSerialiser::readHeader() { uint32 headerid; size_t actually_read = mStream->read(&headerid, sizeof(uint32)); // skip back mStream->skip(0 - (long)actually_read); // validate that this is a header chunk if (headerid == REVERSE_HEADER_ID) { mFlipEndian = true; } else if (headerid == HEADER_ID) { mFlipEndian = false; } else { // no good OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Cannot determine endian mode because header is missing", "StreamSerialiser::readHeader"); } determineEndianness(); mReadWriteHeader = false; const Chunk* c = readChunkBegin(); // endian should be flipped now assert(c->id == HEADER_ID); readChunkEnd(HEADER_ID); } //--------------------------------------------------------------------- void StreamSerialiser::determineEndianness() { #if OGRE_ENDIAN == OGRE_ENDIAN_BIG if (mFlipEndian) mEndian = ENDIAN_LITTLE; else mEndian = ENDIAN_BIG; #else if (mFlipEndian) mEndian = ENDIAN_BIG; else mEndian = ENDIAN_LITTLE; #endif } //--------------------------------------------------------------------- const StreamSerialiser::Chunk* StreamSerialiser::getCurrentChunk() const { if (mChunkStack.empty()) return 0; else return mChunkStack.back(); } //--------------------------------------------------------------------- bool StreamSerialiser::eof() const { checkStream(); return mStream->eof(); } //--------------------------------------------------------------------- void StreamSerialiser::checkStream(bool failOnEof, bool validateReadable, bool validateWriteable) const { if (mStream.isNull()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, stream is null", "StreamSerialiser::checkStream"); if (failOnEof && mStream->eof()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, end of file on stream", "StreamSerialiser::checkStream"); if (validateReadable && !mStream->isReadable()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, file is not readable", "StreamSerialiser::checkStream"); if (validateWriteable && !mStream->isWriteable()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, file is not writeable", "StreamSerialiser::checkStream"); } //--------------------------------------------------------------------- void StreamSerialiser::writeHeader() { if (mEndian == ENDIAN_AUTO) determineEndianness(); // Header chunk has zero data size writeChunkImpl(HEADER_ID, 1); writeChunkEnd(HEADER_ID); mReadWriteHeader = false; } //--------------------------------------------------------------------- void StreamSerialiser::writeChunkBegin(uint32 id, uint16 version /* = 1 */) { checkStream(false, false, true); if (mReadWriteHeader) writeHeader(); if (mEndian == ENDIAN_AUTO) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Endian mode has not been determined, did you disable header without setting?", "StreamSerialiser::writeChunkBegin"); writeChunkImpl(id, version); } //--------------------------------------------------------------------- void StreamSerialiser::writeChunkEnd(uint32 id) { checkStream(false, false, true); Chunk* c = popChunk(id); // update the sizes size_t currPos = mStream->tell(); c->length = static_cast<uint32>(currPos - c->offset - CHUNK_HEADER_SIZE); // seek to 'length' position in stream for this chunk // skip id (32) and version (16) mStream->seek(c->offset + sizeof(uint32) + sizeof(uint16)); write(&c->length); // write updated checksum uint32 checksum = calculateChecksum(c); write(&checksum); // seek back to previous position mStream->seek(currPos); OGRE_DELETE c; } //--------------------------------------------------------------------- StreamSerialiser::Chunk* StreamSerialiser::readChunkImpl() { Chunk *chunk = OGRE_NEW Chunk(); chunk->offset = static_cast<uint32>(mStream->tell()); read(&chunk->id); read(&chunk->version); read(&chunk->length); uint32 checksum; read(&checksum); if (checksum != calculateChecksum(chunk)) { // no good, this is an invalid chunk uint32 off = chunk->offset; OGRE_DELETE chunk; OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Corrupt chunk detected in stream " + mStream->getName() + " at byte " + StringConverter::toString(off), "StreamSerialiser::readChunkImpl"); } else { return chunk; } } //--------------------------------------------------------------------- void StreamSerialiser::writeChunkImpl(uint32 id, uint16 version) { Chunk* c = OGRE_NEW Chunk(); c->id = id; c->version = version; c->offset = mStream->tell(); c->length = 0; mChunkStack.push_back(c); write(&c->id); write(&c->version); write(&c->length); // write length again, this is just a placeholder for the checksum (to come later) write(&c->length); } //--------------------------------------------------------------------- void StreamSerialiser::writeData(const void* buf, size_t size, size_t count) { checkStream(false, false, true); size_t totSize = size * count; if (mFlipEndian) { void* pToWrite = OGRE_MALLOC(totSize, MEMCATEGORY_GENERAL); memcpy(pToWrite, buf, totSize); flipEndian(pToWrite, size, count); mStream->write(pToWrite, totSize); OGRE_FREE(pToWrite, MEMCATEGORY_GENERAL); } else { mStream->write(buf, totSize); } } //--------------------------------------------------------------------- void StreamSerialiser::write(const Vector2* vec) { write(vec->ptr(), 2); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Vector3* vec) { write(vec->ptr(), 3); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Vector4* vec) { write(vec->ptr(), 4); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Quaternion* q) { write(q->ptr(), 4); } //--------------------------------------------------------------------- void StreamSerialiser::write(const String* string) { mStream->write(string->c_str(), string->size()); // write terminator (newline) char eol = '\n'; mStream->write(&eol, 1); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Matrix3* m) { write((*m)[0], 9); } //--------------------------------------------------------------------- void StreamSerialiser::write(const Matrix4* m) { write((*m)[0], 12); } //--------------------------------------------------------------------- void StreamSerialiser::readData(void* buf, size_t size, size_t count) { checkStream(true, true, false); size_t totSize = size * count; mStream->read(buf, totSize); if (mFlipEndian) flipEndian(buf, size, count); } //--------------------------------------------------------------------- void StreamSerialiser::read(Vector2* vec) { read(vec->ptr(), 2); } //--------------------------------------------------------------------- void StreamSerialiser::read(Vector3* vec) { read(vec->ptr(), 3); } //--------------------------------------------------------------------- void StreamSerialiser::read(Vector4* vec) { read(vec->ptr(), 4); } //--------------------------------------------------------------------- void StreamSerialiser::read(Quaternion* q) { read(q->ptr(), 4); } //--------------------------------------------------------------------- void StreamSerialiser::read(Matrix3* m) { read((*m)[0], 9); } //--------------------------------------------------------------------- void StreamSerialiser::read(Matrix4* m) { read((*m)[0], 12); } //--------------------------------------------------------------------- void StreamSerialiser::read(String* string) { String readStr = mStream->getLine(false); string->swap(readStr); } //--------------------------------------------------------------------- void StreamSerialiser::flipEndian(void * pBase, size_t size, size_t count) { for (size_t c = 0; c < count; ++c) { void *pData = (void *)((long)pBase + (c * size)); char swapByte; for(size_t byteIndex = 0; byteIndex < size/2; byteIndex++) { swapByte = *(char *)((long)pData + byteIndex); *(char *)((long)pData + byteIndex) = *(char *)((long)pData + size - byteIndex - 1); *(char *)((long)pData + size - byteIndex - 1) = swapByte; } } } //--------------------------------------------------------------------- void StreamSerialiser::flipEndian(void * pData, size_t size) { flipEndian(pData, size, 1); } //--------------------------------------------------------------------- uint32 StreamSerialiser::calculateChecksum(Chunk* c) { return FastHash((const char*)c, sizeof(uint32) * 2 + sizeof(uint16)); } //--------------------------------------------------------------------- StreamSerialiser::Chunk* StreamSerialiser::popChunk(uint id) { if (mChunkStack.empty()) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "No active chunk!", "StreamSerialiser::popChunk"); const Chunk* chunk = mChunkStack.back(); if (chunk->id != id) OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Incorrect chunk id!", "StreamSerialiser::popChunk"); Chunk* c = mChunkStack.back(); mChunkStack.pop_back(); return c; } } <|endoftext|>
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include <windows.h> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/scoped_ptr.h" #include "ipc/attachment_broker_privileged_win.h" #include "ipc/attachment_broker_unprivileged_win.h" #include "ipc/handle_attachment_win.h" #include "ipc/handle_win.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_message.h" #include "ipc/ipc_test_base.h" namespace { const char kDataBuffer[] = "This is some test data to write to the file."; // Returns the contents of the file represented by |h| as a std::string. std::string ReadFromFile(HANDLE h) { SetFilePointer(h, 0, nullptr, FILE_BEGIN); char buffer[100]; DWORD bytes_read; BOOL success = ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)), &bytes_read, nullptr); return success ? std::string(buffer, bytes_read) : std::string(); } HANDLE GetHandleFromBrokeredAttachment( const scoped_refptr<IPC::BrokerableAttachment>& attachment) { if (attachment->GetType() != IPC::BrokerableAttachment::TYPE_BROKERABLE_ATTACHMENT) return nullptr; if (attachment->GetBrokerableType() != IPC::BrokerableAttachment::WIN_HANDLE) return nullptr; IPC::internal::HandleAttachmentWin* received_handle_attachment = static_cast<IPC::internal::HandleAttachmentWin*>(attachment.get()); return received_handle_attachment->get_handle(); } // Returns true if |attachment| is a file HANDLE whose contents is // |kDataBuffer|. bool CheckContentsOfBrokeredAttachment( const scoped_refptr<IPC::BrokerableAttachment>& attachment) { HANDLE h = GetHandleFromBrokeredAttachment(attachment); if (h == nullptr) return false; std::string contents = ReadFromFile(h); return contents == std::string(kDataBuffer); } enum TestResult { RESULT_UNKNOWN, RESULT_SUCCESS, RESULT_FAILURE, }; // Once the test is finished, send a control message to the parent process with // the result. The message may require the runloop to be run before its // dispatched. void SendControlMessage(IPC::Sender* sender, bool success) { IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL); TestResult result = success ? RESULT_SUCCESS : RESULT_FAILURE; message->WriteInt(result); sender->Send(message); } class MockObserver : public IPC::AttachmentBroker::Observer { public: void ReceivedBrokerableAttachmentWithId( const IPC::BrokerableAttachment::AttachmentId& id) override { id_ = id; } IPC::BrokerableAttachment::AttachmentId* get_id() { return &id_; } private: IPC::BrokerableAttachment::AttachmentId id_; }; // Forwards all messages to |listener_|. Quits the message loop after a // message is received, or the channel has an error. class ProxyListener : public IPC::Listener { public: ProxyListener() : reason_(MESSAGE_RECEIVED) {} ~ProxyListener() override {} // The reason for exiting the message loop. enum Reason { MESSAGE_RECEIVED, CHANNEL_ERROR }; bool OnMessageReceived(const IPC::Message& message) override { bool result = listener_->OnMessageReceived(message); reason_ = MESSAGE_RECEIVED; base::MessageLoop::current()->Quit(); return result; } void OnChannelError() override { reason_ = CHANNEL_ERROR; base::MessageLoop::current()->Quit(); } void set_listener(IPC::Listener* listener) { listener_ = listener; } Reason get_reason() { return reason_; } private: IPC::Listener* listener_; Reason reason_; }; // Waits for a result to be sent over the channel. Quits the message loop // after a message is received, or the channel has an error. class ResultListener : public IPC::Listener { public: ResultListener() : result_(RESULT_UNKNOWN) {} ~ResultListener() override {} bool OnMessageReceived(const IPC::Message& message) override { base::PickleIterator iter(message); int result; EXPECT_TRUE(iter.ReadInt(&result)); result_ = static_cast<TestResult>(result); return true; } TestResult get_result() { return result_; } private: TestResult result_; }; // The parent process acts as an unprivileged process. The forked process acts // as the privileged process. class IPCAttachmentBrokerPrivilegedWinTest : public IPCTestBase { public: IPCAttachmentBrokerPrivilegedWinTest() : message_index_(0) {} ~IPCAttachmentBrokerPrivilegedWinTest() override {} void SetUp() override { IPCTestBase::SetUp(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(), &temp_path_)); } void TearDown() override { IPCTestBase::TearDown(); } // Takes ownership of |broker|. Has no effect if called after CommonSetUp(). void set_broker(IPC::AttachmentBrokerUnprivilegedWin* broker) { broker_.reset(broker); } void CommonSetUp() { if (!broker_.get()) set_broker(new IPC::AttachmentBrokerUnprivilegedWin); broker_->AddObserver(&observer_); set_attachment_broker(broker_.get()); CreateChannel(&proxy_listener_); broker_->DesignateBrokerCommunicationChannel(channel()); ASSERT_TRUE(ConnectChannel()); ASSERT_TRUE(StartClient()); } void CommonTearDown() { // Close the channel so the client's OnChannelError() gets fired. channel()->Close(); EXPECT_TRUE(WaitForClientShutdown()); DestroyChannel(); broker_.reset(); } HANDLE CreateTempFile() { EXPECT_NE(-1, WriteFile(temp_path_, kDataBuffer, static_cast<int>(strlen(kDataBuffer)))); HANDLE h = CreateFile(temp_path_.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); EXPECT_NE(h, INVALID_HANDLE_VALUE); return h; } void SendMessageWithAttachment(HANDLE h) { IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL); message->WriteInt(message_index_++); scoped_refptr<IPC::internal::HandleAttachmentWin> attachment( new IPC::internal::HandleAttachmentWin(h, IPC::HandleWin::DUPLICATE)); ASSERT_TRUE(message->WriteAttachment(attachment)); sender()->Send(message); } ProxyListener* get_proxy_listener() { return &proxy_listener_; } IPC::AttachmentBrokerUnprivilegedWin* get_broker() { return broker_.get(); } MockObserver* get_observer() { return &observer_; } private: base::ScopedTempDir temp_dir_; base::FilePath temp_path_; int message_index_; ProxyListener proxy_listener_; scoped_ptr<IPC::AttachmentBrokerUnprivilegedWin> broker_; MockObserver observer_; }; // A broker which always sets the current process as the destination process // for attachments. class MockBroker : public IPC::AttachmentBrokerUnprivilegedWin { public: MockBroker() {} ~MockBroker() override {} bool SendAttachmentToProcess(const IPC::BrokerableAttachment* attachment, base::ProcessId destination_process) override { return IPC::AttachmentBrokerUnprivilegedWin::SendAttachmentToProcess( attachment, base::Process::Current().Pid()); } }; // An unprivileged process makes a file HANDLE, and writes a string to it. The // file HANDLE is sent to the privileged process using the attachment broker. // The privileged process dups the HANDLE into its own HANDLE table. This test // checks that the file has the same contents in the privileged process. TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandle) { Init("SendHandle"); CommonSetUp(); ResultListener result_listener; get_proxy_listener()->set_listener(&result_listener); HANDLE h = CreateTempFile(); SendMessageWithAttachment(h); base::MessageLoop::current()->Run(); // Check the result. ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED, get_proxy_listener()->get_reason()); ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS); CommonTearDown(); } // Similar to SendHandle, except the file HANDLE attached to the message has // neither read nor write permissions. TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandleWithoutPermissions) { Init("SendHandleWithoutPermissions"); CommonSetUp(); ResultListener result_listener; get_proxy_listener()->set_listener(&result_listener); HANDLE h = CreateTempFile(); HANDLE h2; BOOL result = ::DuplicateHandle(GetCurrentProcess(), h, GetCurrentProcess(), &h2, 0, FALSE, DUPLICATE_CLOSE_SOURCE); ASSERT_TRUE(result); SendMessageWithAttachment(h2); base::MessageLoop::current()->Run(); // Check the result. ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED, get_proxy_listener()->get_reason()); ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS); CommonTearDown(); } // Similar to SendHandle, except the attachment's destination process is this // process. This is an unrealistic scenario, but simulates an unprivileged // process sending an attachment to another unprivileged process. TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandleToSelf) { Init("SendHandleToSelf"); set_broker(new MockBroker); CommonSetUp(); // Technically, the channel is an endpoint, but we need the proxy listener to // receive the messages so that it can quit the message loop. channel()->SetAttachmentBrokerEndpoint(false); get_proxy_listener()->set_listener(get_broker()); HANDLE h = CreateTempFile(); SendMessageWithAttachment(h); base::MessageLoop::current()->Run(); // Get the received attachment. IPC::BrokerableAttachment::AttachmentId* id = get_observer()->get_id(); scoped_refptr<IPC::BrokerableAttachment> received_attachment; get_broker()->GetAttachmentWithId(*id, &received_attachment); ASSERT_NE(received_attachment.get(), nullptr); // Check that it's a new entry in the HANDLE table. HANDLE h2 = GetHandleFromBrokeredAttachment(received_attachment); EXPECT_NE(h2, h); EXPECT_NE(h2, nullptr); // But it still points to the same file. std::string contents = ReadFromFile(h); EXPECT_EQ(contents, std::string(kDataBuffer)); CommonTearDown(); } // Similar to SendHandle, except this test uses the HandleWin class. TEST_F(IPCAttachmentBrokerPrivilegedWinTest, SendHandleWin) { Init("SendHandleWin"); CommonSetUp(); ResultListener result_listener; get_proxy_listener()->set_listener(&result_listener); HANDLE h = CreateTempFile(); IPC::HandleWin handle_win(h, IPC::HandleWin::FILE_READ_WRITE); IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL); message->WriteInt(0); IPC::ParamTraits<IPC::HandleWin>::Write(message, handle_win); sender()->Send(message); base::MessageLoop::current()->Run(); // Check the result. ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED, get_proxy_listener()->get_reason()); ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS); CommonTearDown(); } using OnMessageReceivedCallback = void (*)(MockObserver* observer, IPC::AttachmentBrokerPrivilegedWin* broker, IPC::Sender* sender); int CommonPrivilegedProcessMain(OnMessageReceivedCallback callback, const char* channel_name) { base::MessageLoopForIO main_message_loop; ProxyListener listener; // Set up IPC channel. IPC::AttachmentBrokerPrivilegedWin broker; listener.set_listener(&broker); scoped_ptr<IPC::Channel> channel(IPC::Channel::CreateClient( IPCTestBase::GetChannelName(channel_name), &listener, &broker)); broker.RegisterCommunicationChannel(channel.get()); CHECK(channel->Connect()); MockObserver observer; broker.AddObserver(&observer); while (true) { base::MessageLoop::current()->Run(); ProxyListener::Reason reason = listener.get_reason(); if (reason == ProxyListener::CHANNEL_ERROR) break; callback(&observer, &broker, channel.get()); } return 0; } void SendHandleCallback(MockObserver* observer, IPC::AttachmentBrokerPrivilegedWin* broker, IPC::Sender* sender) { IPC::BrokerableAttachment::AttachmentId* id = observer->get_id(); scoped_refptr<IPC::BrokerableAttachment> received_attachment; broker->GetAttachmentWithId(*id, &received_attachment); // Check that it's the expected handle. bool success = CheckContentsOfBrokeredAttachment(received_attachment); SendControlMessage(sender, success); } MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandle) { return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandle"); } void SendHandleWithoutPermissionsCallback( MockObserver* observer, IPC::AttachmentBrokerPrivilegedWin* broker, IPC::Sender* sender) { IPC::BrokerableAttachment::AttachmentId* id = observer->get_id(); scoped_refptr<IPC::BrokerableAttachment> received_attachment; broker->GetAttachmentWithId(*id, &received_attachment); // Check that it's the expected handle. HANDLE h = GetHandleFromBrokeredAttachment(received_attachment); if (h != nullptr) { SetFilePointer(h, 0, nullptr, FILE_BEGIN); char buffer[100]; DWORD bytes_read; BOOL success = ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)), &bytes_read, nullptr); if (!success && GetLastError() == ERROR_ACCESS_DENIED) { SendControlMessage(sender, true); return; } } SendControlMessage(sender, false); } MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWithoutPermissions) { return CommonPrivilegedProcessMain(&SendHandleWithoutPermissionsCallback, "SendHandleWithoutPermissions"); } void SendHandleToSelfCallback(MockObserver* observer, IPC::AttachmentBrokerPrivilegedWin* broker, IPC::Sender* sender) { // Do nothing special. The default behavior already runs the // AttachmentBrokerPrivilegedWin. } MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleToSelf) { return CommonPrivilegedProcessMain(&SendHandleToSelfCallback, "SendHandleToSelf"); } MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWin) { return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandleWin"); } } // namespace <commit_msg>ipc: Temporarily disable attachment broker end-to-end tests.<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include <windows.h> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/scoped_ptr.h" #include "ipc/attachment_broker_privileged_win.h" #include "ipc/attachment_broker_unprivileged_win.h" #include "ipc/handle_attachment_win.h" #include "ipc/handle_win.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_message.h" #include "ipc/ipc_test_base.h" namespace { const char kDataBuffer[] = "This is some test data to write to the file."; // Returns the contents of the file represented by |h| as a std::string. std::string ReadFromFile(HANDLE h) { SetFilePointer(h, 0, nullptr, FILE_BEGIN); char buffer[100]; DWORD bytes_read; BOOL success = ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)), &bytes_read, nullptr); return success ? std::string(buffer, bytes_read) : std::string(); } HANDLE GetHandleFromBrokeredAttachment( const scoped_refptr<IPC::BrokerableAttachment>& attachment) { if (attachment->GetType() != IPC::BrokerableAttachment::TYPE_BROKERABLE_ATTACHMENT) return nullptr; if (attachment->GetBrokerableType() != IPC::BrokerableAttachment::WIN_HANDLE) return nullptr; IPC::internal::HandleAttachmentWin* received_handle_attachment = static_cast<IPC::internal::HandleAttachmentWin*>(attachment.get()); return received_handle_attachment->get_handle(); } // Returns true if |attachment| is a file HANDLE whose contents is // |kDataBuffer|. bool CheckContentsOfBrokeredAttachment( const scoped_refptr<IPC::BrokerableAttachment>& attachment) { HANDLE h = GetHandleFromBrokeredAttachment(attachment); if (h == nullptr) return false; std::string contents = ReadFromFile(h); return contents == std::string(kDataBuffer); } enum TestResult { RESULT_UNKNOWN, RESULT_SUCCESS, RESULT_FAILURE, }; // Once the test is finished, send a control message to the parent process with // the result. The message may require the runloop to be run before its // dispatched. void SendControlMessage(IPC::Sender* sender, bool success) { IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL); TestResult result = success ? RESULT_SUCCESS : RESULT_FAILURE; message->WriteInt(result); sender->Send(message); } class MockObserver : public IPC::AttachmentBroker::Observer { public: void ReceivedBrokerableAttachmentWithId( const IPC::BrokerableAttachment::AttachmentId& id) override { id_ = id; } IPC::BrokerableAttachment::AttachmentId* get_id() { return &id_; } private: IPC::BrokerableAttachment::AttachmentId id_; }; // Forwards all messages to |listener_|. Quits the message loop after a // message is received, or the channel has an error. class ProxyListener : public IPC::Listener { public: ProxyListener() : reason_(MESSAGE_RECEIVED) {} ~ProxyListener() override {} // The reason for exiting the message loop. enum Reason { MESSAGE_RECEIVED, CHANNEL_ERROR }; bool OnMessageReceived(const IPC::Message& message) override { bool result = listener_->OnMessageReceived(message); reason_ = MESSAGE_RECEIVED; base::MessageLoop::current()->Quit(); return result; } void OnChannelError() override { reason_ = CHANNEL_ERROR; base::MessageLoop::current()->Quit(); } void set_listener(IPC::Listener* listener) { listener_ = listener; } Reason get_reason() { return reason_; } private: IPC::Listener* listener_; Reason reason_; }; // Waits for a result to be sent over the channel. Quits the message loop // after a message is received, or the channel has an error. class ResultListener : public IPC::Listener { public: ResultListener() : result_(RESULT_UNKNOWN) {} ~ResultListener() override {} bool OnMessageReceived(const IPC::Message& message) override { base::PickleIterator iter(message); int result; EXPECT_TRUE(iter.ReadInt(&result)); result_ = static_cast<TestResult>(result); return true; } TestResult get_result() { return result_; } private: TestResult result_; }; // The parent process acts as an unprivileged process. The forked process acts // as the privileged process. class IPCAttachmentBrokerPrivilegedWinTest : public IPCTestBase { public: IPCAttachmentBrokerPrivilegedWinTest() : message_index_(0) {} ~IPCAttachmentBrokerPrivilegedWinTest() override {} void SetUp() override { IPCTestBase::SetUp(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(), &temp_path_)); } void TearDown() override { IPCTestBase::TearDown(); } // Takes ownership of |broker|. Has no effect if called after CommonSetUp(). void set_broker(IPC::AttachmentBrokerUnprivilegedWin* broker) { broker_.reset(broker); } void CommonSetUp() { if (!broker_.get()) set_broker(new IPC::AttachmentBrokerUnprivilegedWin); broker_->AddObserver(&observer_); set_attachment_broker(broker_.get()); CreateChannel(&proxy_listener_); broker_->DesignateBrokerCommunicationChannel(channel()); ASSERT_TRUE(ConnectChannel()); ASSERT_TRUE(StartClient()); } void CommonTearDown() { // Close the channel so the client's OnChannelError() gets fired. channel()->Close(); EXPECT_TRUE(WaitForClientShutdown()); DestroyChannel(); broker_.reset(); } HANDLE CreateTempFile() { EXPECT_NE(-1, WriteFile(temp_path_, kDataBuffer, static_cast<int>(strlen(kDataBuffer)))); HANDLE h = CreateFile(temp_path_.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); EXPECT_NE(h, INVALID_HANDLE_VALUE); return h; } void SendMessageWithAttachment(HANDLE h) { IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL); message->WriteInt(message_index_++); scoped_refptr<IPC::internal::HandleAttachmentWin> attachment( new IPC::internal::HandleAttachmentWin(h, IPC::HandleWin::DUPLICATE)); ASSERT_TRUE(message->WriteAttachment(attachment)); sender()->Send(message); } ProxyListener* get_proxy_listener() { return &proxy_listener_; } IPC::AttachmentBrokerUnprivilegedWin* get_broker() { return broker_.get(); } MockObserver* get_observer() { return &observer_; } private: base::ScopedTempDir temp_dir_; base::FilePath temp_path_; int message_index_; ProxyListener proxy_listener_; scoped_ptr<IPC::AttachmentBrokerUnprivilegedWin> broker_; MockObserver observer_; }; // A broker which always sets the current process as the destination process // for attachments. class MockBroker : public IPC::AttachmentBrokerUnprivilegedWin { public: MockBroker() {} ~MockBroker() override {} bool SendAttachmentToProcess(const IPC::BrokerableAttachment* attachment, base::ProcessId destination_process) override { return IPC::AttachmentBrokerUnprivilegedWin::SendAttachmentToProcess( attachment, base::Process::Current().Pid()); } }; // An unprivileged process makes a file HANDLE, and writes a string to it. The // file HANDLE is sent to the privileged process using the attachment broker. // The privileged process dups the HANDLE into its own HANDLE table. This test // checks that the file has the same contents in the privileged process. TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandle) { Init("SendHandle"); CommonSetUp(); ResultListener result_listener; get_proxy_listener()->set_listener(&result_listener); HANDLE h = CreateTempFile(); SendMessageWithAttachment(h); base::MessageLoop::current()->Run(); // Check the result. ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED, get_proxy_listener()->get_reason()); ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS); CommonTearDown(); } // Similar to SendHandle, except the file HANDLE attached to the message has // neither read nor write permissions. TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandleWithoutPermissions) { Init("SendHandleWithoutPermissions"); CommonSetUp(); ResultListener result_listener; get_proxy_listener()->set_listener(&result_listener); HANDLE h = CreateTempFile(); HANDLE h2; BOOL result = ::DuplicateHandle(GetCurrentProcess(), h, GetCurrentProcess(), &h2, 0, FALSE, DUPLICATE_CLOSE_SOURCE); ASSERT_TRUE(result); SendMessageWithAttachment(h2); base::MessageLoop::current()->Run(); // Check the result. ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED, get_proxy_listener()->get_reason()); ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS); CommonTearDown(); } // Similar to SendHandle, except the attachment's destination process is this // process. This is an unrealistic scenario, but simulates an unprivileged // process sending an attachment to another unprivileged process. TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandleToSelf) { Init("SendHandleToSelf"); set_broker(new MockBroker); CommonSetUp(); // Technically, the channel is an endpoint, but we need the proxy listener to // receive the messages so that it can quit the message loop. channel()->SetAttachmentBrokerEndpoint(false); get_proxy_listener()->set_listener(get_broker()); HANDLE h = CreateTempFile(); SendMessageWithAttachment(h); base::MessageLoop::current()->Run(); // Get the received attachment. IPC::BrokerableAttachment::AttachmentId* id = get_observer()->get_id(); scoped_refptr<IPC::BrokerableAttachment> received_attachment; get_broker()->GetAttachmentWithId(*id, &received_attachment); ASSERT_NE(received_attachment.get(), nullptr); // Check that it's a new entry in the HANDLE table. HANDLE h2 = GetHandleFromBrokeredAttachment(received_attachment); EXPECT_NE(h2, h); EXPECT_NE(h2, nullptr); // But it still points to the same file. std::string contents = ReadFromFile(h); EXPECT_EQ(contents, std::string(kDataBuffer)); CommonTearDown(); } // Similar to SendHandle, except this test uses the HandleWin class. TEST_F(IPCAttachmentBrokerPrivilegedWinTest, DISABLED_SendHandleWin) { Init("SendHandleWin"); CommonSetUp(); ResultListener result_listener; get_proxy_listener()->set_listener(&result_listener); HANDLE h = CreateTempFile(); IPC::HandleWin handle_win(h, IPC::HandleWin::FILE_READ_WRITE); IPC::Message* message = new IPC::Message(0, 2, IPC::Message::PRIORITY_NORMAL); message->WriteInt(0); IPC::ParamTraits<IPC::HandleWin>::Write(message, handle_win); sender()->Send(message); base::MessageLoop::current()->Run(); // Check the result. ASSERT_EQ(ProxyListener::MESSAGE_RECEIVED, get_proxy_listener()->get_reason()); ASSERT_EQ(result_listener.get_result(), RESULT_SUCCESS); CommonTearDown(); } using OnMessageReceivedCallback = void (*)(MockObserver* observer, IPC::AttachmentBrokerPrivilegedWin* broker, IPC::Sender* sender); int CommonPrivilegedProcessMain(OnMessageReceivedCallback callback, const char* channel_name) { base::MessageLoopForIO main_message_loop; ProxyListener listener; // Set up IPC channel. IPC::AttachmentBrokerPrivilegedWin broker; listener.set_listener(&broker); scoped_ptr<IPC::Channel> channel(IPC::Channel::CreateClient( IPCTestBase::GetChannelName(channel_name), &listener, &broker)); broker.RegisterCommunicationChannel(channel.get()); CHECK(channel->Connect()); MockObserver observer; broker.AddObserver(&observer); while (true) { base::MessageLoop::current()->Run(); ProxyListener::Reason reason = listener.get_reason(); if (reason == ProxyListener::CHANNEL_ERROR) break; callback(&observer, &broker, channel.get()); } return 0; } void SendHandleCallback(MockObserver* observer, IPC::AttachmentBrokerPrivilegedWin* broker, IPC::Sender* sender) { IPC::BrokerableAttachment::AttachmentId* id = observer->get_id(); scoped_refptr<IPC::BrokerableAttachment> received_attachment; broker->GetAttachmentWithId(*id, &received_attachment); // Check that it's the expected handle. bool success = CheckContentsOfBrokeredAttachment(received_attachment); SendControlMessage(sender, success); } MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandle) { return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandle"); } void SendHandleWithoutPermissionsCallback( MockObserver* observer, IPC::AttachmentBrokerPrivilegedWin* broker, IPC::Sender* sender) { IPC::BrokerableAttachment::AttachmentId* id = observer->get_id(); scoped_refptr<IPC::BrokerableAttachment> received_attachment; broker->GetAttachmentWithId(*id, &received_attachment); // Check that it's the expected handle. HANDLE h = GetHandleFromBrokeredAttachment(received_attachment); if (h != nullptr) { SetFilePointer(h, 0, nullptr, FILE_BEGIN); char buffer[100]; DWORD bytes_read; BOOL success = ::ReadFile(h, buffer, static_cast<DWORD>(strlen(kDataBuffer)), &bytes_read, nullptr); if (!success && GetLastError() == ERROR_ACCESS_DENIED) { SendControlMessage(sender, true); return; } } SendControlMessage(sender, false); } MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWithoutPermissions) { return CommonPrivilegedProcessMain(&SendHandleWithoutPermissionsCallback, "SendHandleWithoutPermissions"); } void SendHandleToSelfCallback(MockObserver* observer, IPC::AttachmentBrokerPrivilegedWin* broker, IPC::Sender* sender) { // Do nothing special. The default behavior already runs the // AttachmentBrokerPrivilegedWin. } MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleToSelf) { return CommonPrivilegedProcessMain(&SendHandleToSelfCallback, "SendHandleToSelf"); } MULTIPROCESS_IPC_TEST_CLIENT_MAIN(SendHandleWin) { return CommonPrivilegedProcessMain(&SendHandleCallback, "SendHandleWin"); } } // namespace <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <slib/core.h> #include <slib/ui.h> #include "sapp.h" using namespace slib; int main(int argc, const char * argv[]) { System::setDebugFlags(); CList<String> args; for (int i = 0; i < argc; i++) { String arg = argv[i]; arg = arg.trim(); if (arg == "-NSDocumentRevisionsDebugMode") { i++; } else { args.add_NoLock(arg); } } String command; if (args.getCount() < 2) { while (1) { Println("Input the command or file path"); command = Console::readLine().trim(); if (command.isNotNull()) { break; } } } else { command = args[1]; } if (command == "gen") { String path; if (args.getCount() < 3) { path = System::getCurrentDirectory(); } else { path = args[2]; } if (File::isDirectory(path)) { path += "/sapp.xml"; if (!(File::isFile(path))) { Println("sapp.xml is not found in %s", path); return -1; } } else { if (!(File::isFile(path))) { Println("sapp file is not found in %s", path); return -1; } } Ref<SAppDocument> doc = new SAppDocument; if (!(doc->open(path))) { return -1; } if (!(doc->openResources())) { return -1; } if (!(doc->generateCpp())) { return -1; } } else { String path = command; if (File::isFile(path + ".xml")) { path += ".xml"; } else if (File::isFile(path + ".uiml")) { path += ".uiml"; } else if (!(File::isFile(path))) { Println("File is not found in %s", path); return -1; } path = File::getRealPath(path); if (!(File::isFile(path))) { Println("File is not found in %s", path); return -1; } String pathDir = File::getParentDirectoryPath(path); if (File::getFileName(pathDir) == "ui") { String pathApp = File::getParentDirectoryPath(pathDir); if (!(File::isFile(pathApp + "/sapp.xml"))) { Println("sapp.xml is not found in %s", pathApp); return -1; } Ref<SAppDocument> doc = new SAppDocument; if (!(doc->open(pathApp + "/sapp.xml"))) { return -1; } if (!(doc->openUiResource(path))) { return -1; } String layoutName = File::getFileNameOnly(path); SAppSimulateLayoutParam param; String pathConfig = pathApp + "/.sapp.conf"; Json config = Json::parseJsonFromTextFile(pathConfig); param.windowSize.x = config["simulator_window_width"].getInt32(param.windowSize.x); param.windowSize.y = config["simulator_window_height"].getInt32(param.windowSize.y); param.onCloseWindow = [pathConfig](Window* window, UIEvent* ev) { Json config = Json::parseJsonFromTextFile(pathConfig); if (config.isNull()) { config = Json::createMap(); } UISize size = window->getClientSize(); config.putItem("simulator_window_width", size.x); config.putItem("simulator_window_height", size.y); File::writeAllTextUTF8(pathConfig, config.toJsonString()); UI::quitApp(); }; doc->simulateLayoutInWindow(layoutName, param); UI::runApp(); } else { Println("Not supported file: %s", path); return -1; } } return 0; } <commit_msg>tool/sapp: improved parsing input parameter<commit_after>/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <slib/core.h> #include <slib/ui.h> #include "sapp.h" using namespace slib; int main(int argc, const char * argv[]) { System::setDebugFlags(); List<String> args; for (int i = 0; i < argc; i++) { String arg = argv[i]; arg = arg.trim(); if (arg == "-NSDocumentRevisionsDebugMode") { i++; } else { args.add_NoLock(arg); } } String command; if (args.getCount() < 2) { while (1) { Println("Input the command or file path"); String input = Console::readLine().trim(); args = input.split(" "); if (args.isNotEmpty()) { command = args[0]; } args.insert_NoLock(0, sl_null); if (command.isNotEmpty()) { break; } } } else { command = args[1]; } if (command == "gen") { String path; if (args.getCount() < 3) { path = System::getCurrentDirectory(); } else { path = args[2]; } if (File::isDirectory(path)) { path += "/sapp.xml"; if (!(File::isFile(path))) { Println("sapp.xml is not found in %s", path); return -1; } } else { if (!(File::isFile(path))) { Println("sapp file is not found in %s", path); return -1; } } Ref<SAppDocument> doc = new SAppDocument; if (!(doc->open(path))) { return -1; } if (!(doc->openResources())) { return -1; } if (!(doc->generateCpp())) { return -1; } } else { String path = command; if (File::isFile(path + ".xml")) { path += ".xml"; } else if (File::isFile(path + ".uiml")) { path += ".uiml"; } else if (!(File::isFile(path))) { Println("File is not found in %s", path); return -1; } path = File::getRealPath(path); if (!(File::isFile(path))) { Println("File is not found in %s", path); return -1; } String pathDir = File::getParentDirectoryPath(path); if (File::getFileName(pathDir) == "ui") { String pathApp = File::getParentDirectoryPath(pathDir); if (!(File::isFile(pathApp + "/sapp.xml"))) { Println("sapp.xml is not found in %s", pathApp); return -1; } Ref<SAppDocument> doc = new SAppDocument; if (!(doc->open(pathApp + "/sapp.xml"))) { return -1; } if (!(doc->openUiResource(path))) { return -1; } String layoutName = File::getFileNameOnly(path); SAppSimulateLayoutParam param; String pathConfig = pathApp + "/.sapp.conf"; Json config = Json::parseJsonFromTextFile(pathConfig); param.windowSize.x = config["simulator_window_width"].getInt32(param.windowSize.x); param.windowSize.y = config["simulator_window_height"].getInt32(param.windowSize.y); param.onCloseWindow = [pathConfig](Window* window, UIEvent* ev) { Json config = Json::parseJsonFromTextFile(pathConfig); if (config.isNull()) { config = Json::createMap(); } UISize size = window->getClientSize(); config.putItem("simulator_window_width", size.x); config.putItem("simulator_window_height", size.y); File::writeAllTextUTF8(pathConfig, config.toJsonString()); UI::quitApp(); }; doc->simulateLayoutInWindow(layoutName, param); UI::runApp(); } else { Println("Not supported file: %s", path); return -1; } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef ALIGN_HH_ #define ALIGN_HH_ #include <cstdint> #include <cstdlib> template <typename T> inline T align_up(T v, T align) { return (v + align - 1) & ~(align - 1); } template <typename T> inline T* align_up(T* v, size_t align) { static_assert(sizeof(T) == 1, "align byte pointers only"); return reinterpret_cast<T*>(align_up(reinterpret_cast<uintptr_t>(v), align)); } template <typename T> inline T align_down(T v, T align) { return v & ~(align - 1); } template <typename T> inline T* align_down(T* v, size_t align) { static_assert(sizeof(T) == 1, "align byte pointers only"); return reinterpret_cast<T*>(align_down(reinterpret_cast<uintptr_t>(v), align)); } #endif /* ALIGN_HH_ */ <commit_msg>Make align methods constexpr for usage in statics/constexprs<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef ALIGN_HH_ #define ALIGN_HH_ #include <cstdint> #include <cstdlib> template <typename T> inline constexpr T align_up(T v, T align) { return (v + align - 1) & ~(align - 1); } template <typename T> inline constexpr T* align_up(T* v, size_t align) { static_assert(sizeof(T) == 1, "align byte pointers only"); return reinterpret_cast<T*>(align_up(reinterpret_cast<uintptr_t>(v), align)); } template <typename T> inline constexpr T align_down(T v, T align) { return v & ~(align - 1); } template <typename T> inline constexpr T* align_down(T* v, size_t align) { static_assert(sizeof(T) == 1, "align byte pointers only"); return reinterpret_cast<T*>(align_down(reinterpret_cast<uintptr_t>(v), align)); } #endif /* ALIGN_HH_ */ <|endoftext|>
<commit_before>// See LICENSE file for copyright and license details. #include <cstdlib> #include <cassert> #include <ctime> #include <stdexcept> #include "core/core.hpp" #include "core/jsonHelpers.hpp" Core::Core() : mConfig(parseConfig("confCore.json")), mCurrentPlayer(nullptr), mSelectedUnit(nullptr), mPathfinder(*this), mMap(JsonValueToV2i(mConfig["mapSize"])), mEventManager(*this), mInitialUnitsPerPlayerCount(mConfig["initialUnitsPerPlayerCount"].asInt()), mPlayersCount(mConfig["playersCount"].asInt()) { srand(std::time(nullptr)); initUnitTypes(); cleanFow(); initPlayers(); initObstacles(); initUnits(); calculateFow(); } Core::~Core() { for (auto* unitPointer : mUnits) { delete unitPointer; } for (auto* unitPointer : mDeadUnits) { delete unitPointer; } for (auto* playerPointer : mPlayers) { delete playerPointer; } } const std::list<Player*>& Core::players() { return mPlayers; } const Player& Core::currentPlayer() const { return *mCurrentPlayer; } Player& Core::currentPlayer() { return *mCurrentPlayer; } Unit& Core::selectedUnit() { return *mSelectedUnit; } bool Core::isAnyUnitSelected() { return mSelectedUnit != NULL; } std::list<Unit*>& Core::units() { return mUnits; } std::list<Unit*>& Core::deadUnits() { return mDeadUnits; } Pathfinder& Core::pathfinder() { return mPathfinder; } const Map& Core::map() const { return mMap; } Map& Core::map() { return mMap; } EventManager& Core::eventManager() { return mEventManager; } void Core::setSelectedUnit(Unit& unit) { mSelectedUnit = &unit; } void Core::deselectedAnyUnits() { mSelectedUnit = nullptr; } void Core::setCurrentPlayer(Player* player) { mCurrentPlayer = player; } void Core::createLocalHuman(int id) { auto p = new Player; mPlayers.push_back(p); p->id = id; p->lastSeenEventID = HAVE_NOT_SEEN_ANY_EVENTS; } void Core::initLocalPlayers(std::vector<int> unitIDs) { for (int id : unitIDs) { createLocalHuman(id); } mCurrentPlayer = mPlayers.back(); } void Core::refreshUnits(int playerID) { for (auto u : units()) { if (u->playerID() == playerID) { u->setActionPoints(getUnitType(u->typeID()).actionPoints); } } } bool Core::isLosClear(const V2i& from, const V2i& to) { Los los(from, to); for (V2i p = los.getNext(); !los.isFinished(); p = los.getNext()) { #if 1 // TODO: temp hack. fix los, remove this. if (!map().isInboard(p)) { return false; } #endif if (isUnitAt(p) || map().tile(p).obstacle) { return false; } } return true; } void Core::cleanFow() { map().forEachTile([](Tile& tile) { tile.fow = 0; }); } void Core::calculateFow() { assert(mCurrentPlayer); cleanFow(); map().forEachPos([this](const V2i& p) { for (auto u : mUnits) { int maxDist = getUnitType(u->typeID()).rangeOfVision; bool isPlayerOk = (u->playerID() == mCurrentPlayer->id); bool isDistanceOk = (p.distance(u->position()) < maxDist); bool isLosOk = isLosClear(p, u->position()); if (isPlayerOk && isDistanceOk && isLosOk) { map().tile(p).fow++; } } }); } Unit& Core::unitAt(const V2i& pos) { for (auto u : mUnits) { if (u->position() == pos) { return *u; } } throw std::logic_error("No unit at pos!"); } bool Core::isUnitAt(const V2i& pos) { #if 0 return (map().tile(pos).unit != NULL); #else for (auto u : mUnits) { if (u->position() == pos) { return true; } } return false; #endif } Unit& Core::id2unit(int id) { for (auto u : mUnits) { if (u->id() == id) { return *u; } } throw std::logic_error("No unit with this ID!"); } int Core::getNewUnitID() { if (!mUnits.empty()) { auto lastUnit = mUnits.back(); return lastUnit->id() + 1; } else { return 0; } } void Core::addUnit(const V2i& p, int playerID) { assert(map().isInboard(p)); assert(playerID >= 0 && playerID < 16); int typeID = rnd(0, static_cast<int>(UnitTypeID::COUNT) - 1); auto u = new Unit(getNewUnitID(), playerID, typeID); u->setPosition(p); u->setDirection(Dir(rnd(0, 6 - 1))); u->setActionPoints(getUnitType(u->typeID()).actionPoints); mUnits.push_back(u); calculateFow(); } void Core::initUnits() { for (auto player : players()) { for (int i = 0; i < mInitialUnitsPerPlayerCount; i++) { V2i p(rnd(0, map().size().x() - 1), rnd(0, map().size().y() - 1)); if (!map().tile(p).obstacle && !isUnitAt(p)) { addUnit(p, player->id); } else { i--; } } } } void Core::initObstacles() { map().forEachTile([](Tile& tile) { tile.obstacle = ((rand() % 100) > 85); }); } void Core::initPlayers() { std::vector<int> playerIDs; for (int i = 0; i < mPlayersCount; i++) { playerIDs.push_back(i); } initLocalPlayers(playerIDs); } <commit_msg>Core::initObstacles(): rand -> rnd<commit_after>// See LICENSE file for copyright and license details. #include <cstdlib> #include <cassert> #include <ctime> #include <stdexcept> #include "core/core.hpp" #include "core/jsonHelpers.hpp" Core::Core() : mConfig(parseConfig("confCore.json")), mCurrentPlayer(nullptr), mSelectedUnit(nullptr), mPathfinder(*this), mMap(JsonValueToV2i(mConfig["mapSize"])), mEventManager(*this), mInitialUnitsPerPlayerCount(mConfig["initialUnitsPerPlayerCount"].asInt()), mPlayersCount(mConfig["playersCount"].asInt()) { srand(std::time(nullptr)); initUnitTypes(); cleanFow(); initPlayers(); initObstacles(); initUnits(); calculateFow(); } Core::~Core() { for (auto* unitPointer : mUnits) { delete unitPointer; } for (auto* unitPointer : mDeadUnits) { delete unitPointer; } for (auto* playerPointer : mPlayers) { delete playerPointer; } } const std::list<Player*>& Core::players() { return mPlayers; } const Player& Core::currentPlayer() const { return *mCurrentPlayer; } Player& Core::currentPlayer() { return *mCurrentPlayer; } Unit& Core::selectedUnit() { return *mSelectedUnit; } bool Core::isAnyUnitSelected() { return mSelectedUnit != NULL; } std::list<Unit*>& Core::units() { return mUnits; } std::list<Unit*>& Core::deadUnits() { return mDeadUnits; } Pathfinder& Core::pathfinder() { return mPathfinder; } const Map& Core::map() const { return mMap; } Map& Core::map() { return mMap; } EventManager& Core::eventManager() { return mEventManager; } void Core::setSelectedUnit(Unit& unit) { mSelectedUnit = &unit; } void Core::deselectedAnyUnits() { mSelectedUnit = nullptr; } void Core::setCurrentPlayer(Player* player) { mCurrentPlayer = player; } void Core::createLocalHuman(int id) { auto p = new Player; mPlayers.push_back(p); p->id = id; p->lastSeenEventID = HAVE_NOT_SEEN_ANY_EVENTS; } void Core::initLocalPlayers(std::vector<int> unitIDs) { for (int id : unitIDs) { createLocalHuman(id); } mCurrentPlayer = mPlayers.back(); } void Core::refreshUnits(int playerID) { for (auto u : units()) { if (u->playerID() == playerID) { u->setActionPoints(getUnitType(u->typeID()).actionPoints); } } } bool Core::isLosClear(const V2i& from, const V2i& to) { Los los(from, to); for (V2i p = los.getNext(); !los.isFinished(); p = los.getNext()) { #if 1 // TODO: temp hack. fix los, remove this. if (!map().isInboard(p)) { return false; } #endif if (isUnitAt(p) || map().tile(p).obstacle) { return false; } } return true; } void Core::cleanFow() { map().forEachTile([](Tile& tile) { tile.fow = 0; }); } void Core::calculateFow() { assert(mCurrentPlayer); cleanFow(); map().forEachPos([this](const V2i& p) { for (auto u : mUnits) { int maxDist = getUnitType(u->typeID()).rangeOfVision; bool isPlayerOk = (u->playerID() == mCurrentPlayer->id); bool isDistanceOk = (p.distance(u->position()) < maxDist); bool isLosOk = isLosClear(p, u->position()); if (isPlayerOk && isDistanceOk && isLosOk) { map().tile(p).fow++; } } }); } Unit& Core::unitAt(const V2i& pos) { for (auto u : mUnits) { if (u->position() == pos) { return *u; } } throw std::logic_error("No unit at pos!"); } bool Core::isUnitAt(const V2i& pos) { #if 0 return (map().tile(pos).unit != NULL); #else for (auto u : mUnits) { if (u->position() == pos) { return true; } } return false; #endif } Unit& Core::id2unit(int id) { for (auto u : mUnits) { if (u->id() == id) { return *u; } } throw std::logic_error("No unit with this ID!"); } int Core::getNewUnitID() { if (!mUnits.empty()) { auto lastUnit = mUnits.back(); return lastUnit->id() + 1; } else { return 0; } } void Core::addUnit(const V2i& p, int playerID) { assert(map().isInboard(p)); assert(playerID >= 0 && playerID < 16); int typeID = rnd(0, static_cast<int>(UnitTypeID::COUNT) - 1); auto u = new Unit(getNewUnitID(), playerID, typeID); u->setPosition(p); u->setDirection(Dir(rnd(0, 6 - 1))); u->setActionPoints(getUnitType(u->typeID()).actionPoints); mUnits.push_back(u); calculateFow(); } void Core::initUnits() { for (auto player : players()) { for (int i = 0; i < mInitialUnitsPerPlayerCount; i++) { V2i p(rnd(0, map().size().x() - 1), rnd(0, map().size().y() - 1)); if (!map().tile(p).obstacle && !isUnitAt(p)) { addUnit(p, player->id); } else { i--; } } } } void Core::initObstacles() { map().forEachTile([](Tile& tile) { tile.obstacle = (rnd(0, 100) > 85); }); } void Core::initPlayers() { std::vector<int> playerIDs; for (int i = 0; i < mPlayersCount; i++) { playerIDs.push_back(i); } initLocalPlayers(playerIDs); } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef FILE_DESC_HH_ #define FILE_DESC_HH_ #include "sstring.hh" #include <sys/types.h> #include <unistd.h> #include <assert.h> #include <utility> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/eventfd.h> #include <sys/timerfd.h> #include <sys/signalfd.h> #include <sys/socket.h> #include <sys/epoll.h> #include <sys/mman.h> #include <signal.h> #include <system_error> #include <boost/optional.hpp> #include <pthread.h> #include <memory> #include "net/api.hh" inline void throw_system_error_on(bool condition); template <typename T> inline void throw_kernel_error(T r); class file_desc { int _fd; public: file_desc() = delete; file_desc(const file_desc&) = delete; file_desc(file_desc&& x) : _fd(x._fd) { x._fd = -1; } ~file_desc() { if (_fd != -1) { ::close(_fd); } } void operator=(const file_desc&) = delete; file_desc& operator=(file_desc&& x) { if (this != &x) { std::swap(_fd, x._fd); if (x._fd != -1) { x.close(); } } return *this; } void close() { assert(_fd != -1); auto r = ::close(_fd); throw_system_error_on(r == -1); _fd = -1; } int get() const { return _fd; } static file_desc open(sstring name, int flags, mode_t mode = 0) { int fd = ::open(name.c_str(), flags, mode); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc socket(int family, int type, int protocol = 0) { int fd = ::socket(family, type, protocol); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc eventfd(unsigned initval, int flags) { int fd = ::eventfd(initval, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc epoll_create(int flags = 0) { int fd = ::epoll_create1(flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc timerfd_create(int clockid, int flags) { int fd = ::timerfd_create(clockid, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc signalfd(const sigset_t& mask, int flags) { int fd = ::signalfd(-1, &mask, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc temporary(sstring directory); file_desc dup() const { int fd = ::dup(get()); throw_system_error_on(fd == -1); return file_desc(fd); } file_desc accept(sockaddr& sa, socklen_t& sl, int flags = 0) { auto ret = ::accept4(_fd, &sa, &sl, flags); throw_system_error_on(ret == -1); return file_desc(ret); } int ioctl(int request) { return ioctl(request, 0); } int ioctl(int request, int value) { int r = ::ioctl(_fd, request, value); throw_system_error_on(r == -1); return r; } int ioctl(int request, unsigned int value) { int r = ::ioctl(_fd, request, value); throw_system_error_on(r == -1); return r; } template <class X> int ioctl(int request, X& data) { int r = ::ioctl(_fd, request, &data); throw_system_error_on(r == -1); return r; } template <class X> int ioctl(int request, X&& data) { int r = ::ioctl(_fd, request, &data); throw_system_error_on(r == -1); return r; } template <class X> int setsockopt(int level, int optname, X&& data) { int r = ::setsockopt(_fd, level, optname, &data, sizeof(data)); throw_system_error_on(r == -1); return r; } int setsockopt(int level, int optname, const char* data) { int r = ::setsockopt(_fd, level, optname, data, strlen(data) + 1); throw_system_error_on(r == -1); return r; } boost::optional<size_t> read(void* buffer, size_t len) { auto r = ::read(_fd, buffer, len); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<ssize_t> recv(void* buffer, size_t len, int flags) { auto r = ::recv(_fd, buffer, len, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { r }; } boost::optional<size_t> recvmsg(msghdr* mh, int flags) { auto r = ::recvmsg(_fd, mh, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> send(const void* buffer, size_t len, int flags) { auto r = ::send(_fd, buffer, len, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> sendto(socket_address& addr, const void* buf, size_t len, int flags) { auto r = ::sendto(_fd, buf, len, flags, &addr.u.sa, sizeof(addr.u.sas)); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> sendmsg(const msghdr* msg, int flags) { auto r = ::sendmsg(_fd, msg, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } void bind(sockaddr& sa, socklen_t sl) { auto r = ::bind(_fd, &sa, sl); throw_system_error_on(r == -1); } socket_address get_address() { socket_address addr; auto len = (socklen_t) sizeof(addr.u.sas); auto r = ::getsockname(_fd, &addr.u.sa, &len); throw_system_error_on(r == -1); return addr; } void listen(int backlog) { auto fd = ::listen(_fd, backlog); throw_system_error_on(fd == -1); } boost::optional<size_t> write(const void* buf, size_t len) { auto r = ::write(_fd, buf, len); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> writev(const iovec *iov, int iovcnt) { auto r = ::writev(_fd, iov, iovcnt); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } void timerfd_settime(int flags, const itimerspec& its) { auto r = ::timerfd_settime(_fd, flags, &its, NULL); throw_system_error_on(r == -1); } void *map(size_t size, unsigned flags, bool shared, size_t offset) { void *x = mmap(NULL, size, flags, shared ? MAP_SHARED : MAP_PRIVATE, _fd, offset); throw_system_error_on(x == nullptr); return x; } void *map_shared_rw(size_t size, size_t offset) { return map(size, PROT_READ | PROT_WRITE, true, offset); } void *map_shared_ro(size_t size, size_t offset) { return map(size, PROT_READ, true, offset); } void *map_private_rw(size_t size, size_t offset) { return map(size, PROT_READ | PROT_WRITE, false, offset); } void *map_private_ro(size_t size, size_t offset) { return map(size, PROT_READ, false, offset); } private: file_desc(int fd) : _fd(fd) {} }; struct mmap_deleter { size_t _size; void operator()(void* ptr) const; }; using mmap_area = std::unique_ptr<char[], mmap_deleter>; mmap_area mmap_anonymous(void* addr, size_t length, int prot, int flags); class posix_thread { public: class attr; private: // must allocate, since this class is moveable std::unique_ptr<std::function<void ()>> _func; pthread_t _pthread; bool _valid = true; mmap_area _stack; private: static void* start_routine(void* arg); public: posix_thread(std::function<void ()> func); posix_thread(attr a, std::function<void ()> func); posix_thread(posix_thread&& x); ~posix_thread(); void join(); public: class attr { public: struct stack_size { size_t size = 0; }; attr() = default; template <typename... A> attr(A... a) { set(std::forward<A>(a)...); } void set() {} template <typename A, typename... Rest> void set(A a, Rest... rest) { set(std::forward<A>(a)); set(std::forward<Rest>(rest)...); } void set(stack_size ss) { _stack_size = ss; } private: stack_size _stack_size; friend class posix_thread; }; }; inline void throw_system_error_on(bool condition) { if (condition) { throw std::system_error(errno, std::system_category()); } } template <typename T> inline void throw_kernel_error(T r) { static_assert(std::is_signed<T>::value, "kernel error variables must be signed"); if (r < 0) { throw std::system_error(-r, std::system_category()); } } inline sigset_t make_sigset_mask(int signo) { sigset_t set; sigemptyset(&set); sigaddset(&set, signo); return set; } void pin_this_thread(unsigned cpu_id); #endif /* FILE_DESC_HH_ */ <commit_msg>posix: add support for ftruncate()<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef FILE_DESC_HH_ #define FILE_DESC_HH_ #include "sstring.hh" #include <sys/types.h> #include <unistd.h> #include <assert.h> #include <utility> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/eventfd.h> #include <sys/timerfd.h> #include <sys/signalfd.h> #include <sys/socket.h> #include <sys/epoll.h> #include <sys/mman.h> #include <signal.h> #include <system_error> #include <boost/optional.hpp> #include <pthread.h> #include <memory> #include "net/api.hh" inline void throw_system_error_on(bool condition); template <typename T> inline void throw_kernel_error(T r); class file_desc { int _fd; public: file_desc() = delete; file_desc(const file_desc&) = delete; file_desc(file_desc&& x) : _fd(x._fd) { x._fd = -1; } ~file_desc() { if (_fd != -1) { ::close(_fd); } } void operator=(const file_desc&) = delete; file_desc& operator=(file_desc&& x) { if (this != &x) { std::swap(_fd, x._fd); if (x._fd != -1) { x.close(); } } return *this; } void close() { assert(_fd != -1); auto r = ::close(_fd); throw_system_error_on(r == -1); _fd = -1; } int get() const { return _fd; } static file_desc open(sstring name, int flags, mode_t mode = 0) { int fd = ::open(name.c_str(), flags, mode); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc socket(int family, int type, int protocol = 0) { int fd = ::socket(family, type, protocol); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc eventfd(unsigned initval, int flags) { int fd = ::eventfd(initval, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc epoll_create(int flags = 0) { int fd = ::epoll_create1(flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc timerfd_create(int clockid, int flags) { int fd = ::timerfd_create(clockid, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc signalfd(const sigset_t& mask, int flags) { int fd = ::signalfd(-1, &mask, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc temporary(sstring directory); file_desc dup() const { int fd = ::dup(get()); throw_system_error_on(fd == -1); return file_desc(fd); } file_desc accept(sockaddr& sa, socklen_t& sl, int flags = 0) { auto ret = ::accept4(_fd, &sa, &sl, flags); throw_system_error_on(ret == -1); return file_desc(ret); } void truncate(size_t size) { auto ret = ::ftruncate(_fd, size); throw_system_error_on(ret); } int ioctl(int request) { return ioctl(request, 0); } int ioctl(int request, int value) { int r = ::ioctl(_fd, request, value); throw_system_error_on(r == -1); return r; } int ioctl(int request, unsigned int value) { int r = ::ioctl(_fd, request, value); throw_system_error_on(r == -1); return r; } template <class X> int ioctl(int request, X& data) { int r = ::ioctl(_fd, request, &data); throw_system_error_on(r == -1); return r; } template <class X> int ioctl(int request, X&& data) { int r = ::ioctl(_fd, request, &data); throw_system_error_on(r == -1); return r; } template <class X> int setsockopt(int level, int optname, X&& data) { int r = ::setsockopt(_fd, level, optname, &data, sizeof(data)); throw_system_error_on(r == -1); return r; } int setsockopt(int level, int optname, const char* data) { int r = ::setsockopt(_fd, level, optname, data, strlen(data) + 1); throw_system_error_on(r == -1); return r; } boost::optional<size_t> read(void* buffer, size_t len) { auto r = ::read(_fd, buffer, len); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<ssize_t> recv(void* buffer, size_t len, int flags) { auto r = ::recv(_fd, buffer, len, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { r }; } boost::optional<size_t> recvmsg(msghdr* mh, int flags) { auto r = ::recvmsg(_fd, mh, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> send(const void* buffer, size_t len, int flags) { auto r = ::send(_fd, buffer, len, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> sendto(socket_address& addr, const void* buf, size_t len, int flags) { auto r = ::sendto(_fd, buf, len, flags, &addr.u.sa, sizeof(addr.u.sas)); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> sendmsg(const msghdr* msg, int flags) { auto r = ::sendmsg(_fd, msg, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } void bind(sockaddr& sa, socklen_t sl) { auto r = ::bind(_fd, &sa, sl); throw_system_error_on(r == -1); } socket_address get_address() { socket_address addr; auto len = (socklen_t) sizeof(addr.u.sas); auto r = ::getsockname(_fd, &addr.u.sa, &len); throw_system_error_on(r == -1); return addr; } void listen(int backlog) { auto fd = ::listen(_fd, backlog); throw_system_error_on(fd == -1); } boost::optional<size_t> write(const void* buf, size_t len) { auto r = ::write(_fd, buf, len); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> writev(const iovec *iov, int iovcnt) { auto r = ::writev(_fd, iov, iovcnt); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } void timerfd_settime(int flags, const itimerspec& its) { auto r = ::timerfd_settime(_fd, flags, &its, NULL); throw_system_error_on(r == -1); } void *map(size_t size, unsigned flags, bool shared, size_t offset) { void *x = mmap(NULL, size, flags, shared ? MAP_SHARED : MAP_PRIVATE, _fd, offset); throw_system_error_on(x == nullptr); return x; } void *map_shared_rw(size_t size, size_t offset) { return map(size, PROT_READ | PROT_WRITE, true, offset); } void *map_shared_ro(size_t size, size_t offset) { return map(size, PROT_READ, true, offset); } void *map_private_rw(size_t size, size_t offset) { return map(size, PROT_READ | PROT_WRITE, false, offset); } void *map_private_ro(size_t size, size_t offset) { return map(size, PROT_READ, false, offset); } private: file_desc(int fd) : _fd(fd) {} }; struct mmap_deleter { size_t _size; void operator()(void* ptr) const; }; using mmap_area = std::unique_ptr<char[], mmap_deleter>; mmap_area mmap_anonymous(void* addr, size_t length, int prot, int flags); class posix_thread { public: class attr; private: // must allocate, since this class is moveable std::unique_ptr<std::function<void ()>> _func; pthread_t _pthread; bool _valid = true; mmap_area _stack; private: static void* start_routine(void* arg); public: posix_thread(std::function<void ()> func); posix_thread(attr a, std::function<void ()> func); posix_thread(posix_thread&& x); ~posix_thread(); void join(); public: class attr { public: struct stack_size { size_t size = 0; }; attr() = default; template <typename... A> attr(A... a) { set(std::forward<A>(a)...); } void set() {} template <typename A, typename... Rest> void set(A a, Rest... rest) { set(std::forward<A>(a)); set(std::forward<Rest>(rest)...); } void set(stack_size ss) { _stack_size = ss; } private: stack_size _stack_size; friend class posix_thread; }; }; inline void throw_system_error_on(bool condition) { if (condition) { throw std::system_error(errno, std::system_category()); } } template <typename T> inline void throw_kernel_error(T r) { static_assert(std::is_signed<T>::value, "kernel error variables must be signed"); if (r < 0) { throw std::system_error(-r, std::system_category()); } } inline sigset_t make_sigset_mask(int signo) { sigset_t set; sigemptyset(&set); sigaddset(&set, signo); return set; } void pin_this_thread(unsigned cpu_id); #endif /* FILE_DESC_HH_ */ <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <diffpp/diffpp.hpp> ////////////////////////////////////////////////////////////////////////////////////////// /// all tests shall be contained in functions with the following signature: typedef bool(*test_function)(); /// a test returns true on success, and false on failure ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// /// test the difference between the strings "abcabba" and "cbabac". Expected result is 5. bool test_difference_strings( void ); ////////////////////////////////////////////////////////////////////////////////////////// /// after definition, all test functions will be added to this array, for automated execution test_function tests[] = { &test_difference_strings, }; bool test_difference_strings( void ) { const std::string abcabba("abcabba"); const std::string cbabac("cbabac"); int result = diffpp::difference<std::string::const_iterator, std::string::const_iterator> ( abcabba.begin(), cbabac.begin(), static_cast<int>(abcabba.size()), static_cast<int>(cbabac.size()), std::equal_to<char>() ); if ( result != 5 ) return false; result = diffpp::difference_bwd(abcabba.begin(), cbabac.begin(), abcabba.size(), cbabac.size(), std::equal_to<char>() ); if ( result != 5 ) return false; result = diffpp::difference(std::string::iterator(), cbabac.begin(), 0, static_cast<int>(cbabac.size()), std::equal_to<char>() ); return result == cbabac.size(); } template < typename container_t, typename range_a, typename range_b > inline std::string print_diff_merge( const container_t &sln, const range_a &leftstr, const range_b &rightstr ) { std::string merged; for ( auto iter(sln.begin()); iter != sln.end(); ++iter ) { diffpp::point start = iter->get_start(); diffpp::edit::command_t comm = iter->get_command(); int dir = iter->get_direction(); int matches = iter->get_matches(); diffpp::point end = iter->get_end(); int idxA = ~dir ? start.x : end.x; int idxB = ~dir ? start.y : end.y; if ( ~dir ) { if ( comm == diffpp::edit::DELETE && idxA >= 0 ) { std::cout << leftstr[idxA] << " -> "<< leftstr[idxA]<< std::endl; merged.push_back(leftstr[idxA]); ++idxA; } else { if ( idxB >= 0 ) { std::cout << " " << rightstr[idxB] << " <- " << rightstr[idxB] << std::endl; merged.push_back(rightstr[idxB]); } ++idxB; } } int step(0); for ( ; step < matches; ++step ) { char a = ' '; if ( idxA+step >= 0 && idxA+step < leftstr.size() ) { std::cout << leftstr[idxA+step]<< " -> "; a = leftstr[idxA+step]; } else { std::cout << " "; a = rightstr[idxB+step]; } merged.push_back(a); std::cout << a; if ( idxB+step >= 0 && idxB+step < rightstr.size() ) { std::cout << " <- " << rightstr[idxB+step]<<std::endl; } else { std::cout << std::endl; } } if ( !(~dir) ) { if ( comm == diffpp::edit::DELETE && idxA+step < static_cast<int>(leftstr.size()) ) { std::cout<< leftstr[idxA+step] << " -> " << leftstr[idxA+step]<< std::endl; merged.push_back(leftstr[idxA+step]); } else if( idxB+step < static_cast<int>(rightstr.size()) ) { std::cout<< " " << rightstr[idxB+step] << " <- " << rightstr[idxB+step] << std::endl; merged.push_back(rightstr[idxB+step]); } } } std::cout << "merge of:" << std::endl << "\t\"" << leftstr << "\"" << std::endl << "with:" << std::endl << "\t" << "\"" << rightstr << "\"" << std::endl << "results:" << std::endl << "\t\t\"" << merged << "\"" << std::endl; return merged; } int main() { const unsigned test_count = sizeof(tests) / sizeof(test_function); unsigned test_idx = 0; unsigned passed_tests = 0; test_function test = tests[0]; if ( test_count > 0 ) do { bool test_result = (*test)(); std::cout<< "test " << test_idx << " of " << test_count << " " << ( test_result ? std::string("[passed]") : std::string("[failed]") ) << std::endl; passed_tests += test_result; ++test_idx; } while ( test_idx < test_count ); std::cout << "Test done. Failed " << test_count - passed_tests << " out of " << test_count << std::endl; return ( test_count - passed_tests ) != 0; } <commit_msg>add more tests for difference<commit_after>#include <iostream> #include <string> #include <vector> #include <diffpp/diffpp.hpp> ////////////////////////////////////////////////////////////////////////////////////////// /// all tests shall be contained in functions with the following signature: typedef bool(*test_function)(); /// a test returns true on success, and false on failure ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// /// test the difference between the strings "abcabba" and "cbabac". Expected result is 5. bool test_difference_strings( void ); ////////////////////////////////////////////////////////////////////////////////////////// /// after definition, all test functions will be added to this array, for automated execution test_function tests[] = { &test_difference_strings, }; bool test_difference_strings( void ) { const std::string abcabba("abcabba"); const std::string cbabac("cbabac"); /**/ int result = diffpp::difference( abcabba.begin(), cbabac.begin(), int(abcabba.size()), int(cbabac.size()), std::equal_to<char>() ); if ( result != 5 ) return false; result = diffpp::difference_bwd(abcabba.begin(), cbabac.begin(), abcabba.size(), cbabac.size(), std::equal_to<char>() ); if ( result != 5 ) return false; /* sizeB=0 */ result = diffpp::difference(std::string::iterator(), cbabac.begin(), 0, int(cbabac.size()), std::equal_to<char>() ); if ( result != cbabac.size() ) return false; result = diffpp::difference_bwd(std::string::iterator(), cbabac.begin(), 0, int(cbabac.size()), std::equal_to<char>() ); if ( result != cbabac.size() ) return false; /* sizeA=0 */ result = diffpp::difference(abcabba.begin(), std::string::iterator(), int(abcabba.size()), 0, std::equal_to<char>() ); if ( result != abcabba.size() ) return false; result = diffpp::difference_bwd(abcabba.begin(), std::string::iterator(), int(abcabba.size()), 0, std::equal_to<char>() ); if ( result != abcabba.size() ) return false; /* A == B */ result = diffpp::difference( abcabba.begin(), abcabba.begin(), int(abcabba.size()), int(abcabba.size()), std::equal_to<char>() ); if ( result != 0 ) return false; result = diffpp::difference_bwd(abcabba.begin(), abcabba.begin(), abcabba.size(), abcabba.size(), std::equal_to<char>() ); if ( result != 0 ) return false; /* N+M = 0 */ result = diffpp::difference( std::string::iterator(), std::string::iterator(), 0, 0, std::equal_to<char>() ); if ( result != 0 ) return false; result = diffpp::difference_bwd(std::string::iterator(), std::string::iterator(), 0, 0, std::equal_to<char>() ); if ( result != 0 ) return false; return true; } template < typename container_t, typename range_a, typename range_b > inline std::string print_diff_merge( const container_t &sln, const range_a &leftstr, const range_b &rightstr ) { std::string merged; for ( auto iter(sln.begin()); iter != sln.end(); ++iter ) { diffpp::point start = iter->get_start(); diffpp::edit::command_t comm = iter->get_command(); int dir = iter->get_direction(); int matches = iter->get_matches(); diffpp::point end = iter->get_end(); int idxA = ~dir ? start.x : end.x; int idxB = ~dir ? start.y : end.y; if ( ~dir ) { if ( comm == diffpp::edit::DELETE && idxA >= 0 ) { std::cout << leftstr[idxA] << " -> "<< leftstr[idxA]<< std::endl; merged.push_back(leftstr[idxA]); ++idxA; } else { if ( idxB >= 0 ) { std::cout << " " << rightstr[idxB] << " <- " << rightstr[idxB] << std::endl; merged.push_back(rightstr[idxB]); } ++idxB; } } int step(0); for ( ; step < matches; ++step ) { char a = ' '; if ( idxA+step >= 0 && idxA+step < leftstr.size() ) { std::cout << leftstr[idxA+step]<< " -> "; a = leftstr[idxA+step]; } else { std::cout << " "; a = rightstr[idxB+step]; } merged.push_back(a); std::cout << a; if ( idxB+step >= 0 && idxB+step < rightstr.size() ) { std::cout << " <- " << rightstr[idxB+step]<<std::endl; } else { std::cout << std::endl; } } if ( !(~dir) ) { if ( comm == diffpp::edit::DELETE && idxA+step < static_cast<int>(leftstr.size()) ) { std::cout<< leftstr[idxA+step] << " -> " << leftstr[idxA+step]<< std::endl; merged.push_back(leftstr[idxA+step]); } else if( idxB+step < static_cast<int>(rightstr.size()) ) { std::cout<< " " << rightstr[idxB+step] << " <- " << rightstr[idxB+step] << std::endl; merged.push_back(rightstr[idxB+step]); } } } std::cout << "merge of:" << std::endl << "\t\"" << leftstr << "\"" << std::endl << "with:" << std::endl << "\t" << "\"" << rightstr << "\"" << std::endl << "results:" << std::endl << "\t\t\"" << merged << "\"" << std::endl; return merged; } int main() { const unsigned test_count = sizeof(tests) / sizeof(test_function); unsigned test_idx = 0; unsigned passed_tests = 0; test_function test = tests[0]; if ( test_count > 0 ) do { bool test_result = (*test)(); std::cout<< "test " << test_idx << " of " << test_count << " " << ( test_result ? std::string("[passed]") : std::string("[failed]") ) << std::endl; passed_tests += test_result; ++test_idx; } while ( test_idx < test_count ); std::cout << "Test done. Failed " << test_count - passed_tests << " out of " << test_count << std::endl; return ( test_count - passed_tests ) != 0; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "bzfsAPI.h" #include <Python.h> #include "PyBZFlag.h" Python::BZFlag *module_bzflag; BZ_GET_PLUGIN_VERSION BZF_PLUGIN_CALL int bz_Load (const char *commandLine) { Py_SetProgramName ("BZFlag"); Py_Initialize (); module_bzflag = new Python::BZFlag (); } BZF_PLUGIN_CALL int bz_Unload (void) { Py_Finalize (); } <commit_msg>well, maybe this is correct. who knows. time to go get clean.<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "bzfsAPI.h" #include "OSFile.h" #include <Python.h> #include "PyBZFlag.h" static char *ReadFile (const char *filename); static Python::BZFlag *module_bzflag; static PyObject *global_dict; BZ_GET_PLUGIN_VERSION BZF_PLUGIN_CALL int bz_Load (const char *commandLine) { Py_SetProgramName ("BZFlag"); Py_Initialize (); module_bzflag = new Python::BZFlag (); char *buffer = ReadFile (commandLine); PyCodeObject *code = (PyCodeObject *) Py_CompileString (buffer, commandLine, Py_file_input); global_dict = PyDict_New (); PyDict_SetItemString (global_dict, "__builtins__", PyEval_GetBuiltins ()); PyDict_SetItemString (global_dict, "__name__", PyString_FromString ("__main__")); PyEval_EvalCode (code, global_dict, global_dict); } BZF_PLUGIN_CALL int bz_Unload (void) { PyDict_Clear (global_dict); Py_DECREF (global_dict); Py_Finalize (); } static char * ReadFile (const char *filename) { OSFile osf; osf.open (filename, "r"); char *buffer = new char[osf.size ()]; osf.read (buffer, osf.size ()); osf.close (); return buffer; } <|endoftext|>
<commit_before>// Subscribes to Point Cloud Data, updates the occupancy grid, then publishes the data. #include <cv_bridge/cv_bridge.h> #include <igvc_msgs/map.h> #include <math.h> #include <nav_msgs/Odometry.h> #include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <ros/publisher.h> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <stdlib.h> #include <Eigen/Core> #include <igvc_utils/NodeUtils.hpp> #include <igvc_utils/RobotState.hpp> #include <opencv2/core/eigen.hpp> #include <opencv2/opencv.hpp> #include <tf/transform_datatypes.h> #include <tf_conversions/tf_eigen.h> #include "octomapper.h" #include <visualization_msgs/Marker.h> #include <signal.h> cv_bridge::CvImage img_bridge; ros::Publisher map_pub; // Publishes map ros::Publisher debug_pub; // Debug version of above ros::Publisher debug_pcl_pub; // Publishes map as individual PCL points ros::Publisher ground_pub; // Publishes map as individual PCL points ros::Publisher nonground_pub; // Publishes map as individual PCL points ros::Publisher sensor_pub; // Publishes map as individual PCL points std::unique_ptr<cv::Mat> published_map; // matrix will be publishing std::map<std::string, tf::StampedTransform> transforms; std::unique_ptr<tf::TransformListener> tf_listener; double resolution; double transform_max_wait_time; int start_x; // start x location int start_y; // start y location int length_y; int width_x; bool debug; double radius; RobotState state; RobotState state2; std::unique_ptr<Octomapper> octomapper; pc_map_pair pc_map_pair; /** * Updates <code>RobotState state</code> with the latest tf transform using the timestamp of the message passed in * @param msg <code>pcl::PointCloud</code> message with the timestamp used for looking up the tf transform */ void getOdomTransform(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg) { tf::StampedTransform transform; tf::StampedTransform transform2; ros::Time messageTimeStamp; pcl_conversions::fromPCL(msg->header.stamp, messageTimeStamp); if (tf_listener->waitForTransform("/odom", "/base_link", messageTimeStamp, ros::Duration(transform_max_wait_time))) { tf_listener->lookupTransform("/odom", "/base_link", messageTimeStamp, transform); state.setState(transform); tf_listener->lookupTransform("/odom", "/lidar", messageTimeStamp, transform2); state2.setState(transform2); } else { ROS_ERROR("Failed to get transform from /base_link to /odom in time, using newest transforms"); tf_listener->lookupTransform("/odom", "/base_link", ros::Time(0), transform); state.setState(transform); tf_listener->lookupTransform("/odom", "/lidar", ros::Time(0), transform2); state2.setState(transform2); } } // Populates igvc_msgs::map message with information from sensor_msgs::Image and the timestamp from pcl_stamp /** * Populates <code>igvc_msgs::map message</code> with information from <code>sensor_msgs::Image</code> and the * timestamp from <code>pcl_stamp</code> * @param message message to be filled out * @param image image containing map data to be put into <code>message</code> * @param pcl_stamp time stamp from the pcl to be used for <code>message</code> */ void setMsgValues(igvc_msgs::map &message, sensor_msgs::Image &image, uint64_t pcl_stamp) { pcl_conversions::fromPCL(pcl_stamp, image.header.stamp); pcl_conversions::fromPCL(pcl_stamp, message.header.stamp); message.header.frame_id = "/odom"; message.image = image; message.length = length_y / resolution; message.width = width_x / resolution; message.resolution = resolution; message.orientation = state.yaw(); message.x = std::round(state.x() / resolution) + start_x/resolution; message.y = std::round(state.y() / resolution) + start_y/resolution; message.x_initial = start_x / resolution; message.y_initial = start_y / resolution; } /** * Checks if transform from base_footprint to msg.header.frame_id exists * @param msg * @param topic */ bool checkExistsStaticTransform(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic) { if (transforms.find(topic) == transforms.end()) { // Wait for transform between frame_id (ex. /scan/pointcloud) and base_footprint. ros::Time messageTimeStamp; pcl_conversions::fromPCL(msg->header.stamp, messageTimeStamp); ROS_INFO_STREAM("Getting transform for " << topic << " from " << msg->header.frame_id << " to /base_footprint \n"); if (tf_listener->waitForTransform("/base_footprint", msg->header.frame_id, messageTimeStamp, ros::Duration(3.0))) { tf::StampedTransform transform; tf_listener->lookupTransform("/base_footprint", msg->header.frame_id, messageTimeStamp, transform); transforms.insert(std::pair<std::string, tf::StampedTransform>(topic, transform)); ROS_INFO_STREAM("Found transform!"); } else { ROS_ERROR_STREAM("Failed to find transform using empty transform"); return false; } } return true; } /** * Publishes the given map at the given stamp * @param map map to be published * @param stamp pcl stamp of the timestamp to be used */ void publish(const cv::Mat &map, uint64_t stamp) { igvc_msgs::map message; // >> message to be sent sensor_msgs::Image image; // >> image in the message img_bridge = cv_bridge::CvImage(message.header, sensor_msgs::image_encodings::MONO8, map); img_bridge.toImageMsg(image); // from cv_bridge to sensor_msgs::Image setMsgValues(message, image, stamp); map_pub.publish(message); if (debug) { debug_pub.publish(image); // ROS_INFO_STREAM("\nThe robot is located at " << state); pcl::PointCloud<pcl::PointXYZRGB>::Ptr fromOcuGrid = boost::make_shared<pcl::PointCloud<pcl::PointXYZRGB>>(); for (int i = 0; i < width_x/resolution; i++) { for (int j = 0; j < length_y/resolution; j++) { pcl::PointXYZRGB p; uchar prob = map.at<uchar>(i, j); if (prob > 127) { p = pcl::PointXYZRGB(); p.x = (i * resolution) - (width_x / 2); p.y = (j * resolution) - (length_y / 2); p.r = 0; p.g = static_cast<uint8_t>((prob - 127) * 2); p.b = 0; fromOcuGrid->points.push_back(p); // ROS_INFO_STREAM("(" << i << ", " << j << ") -> (" << p.x << ", " << p.y << ")"); } else if (prob < 127) { p = pcl::PointXYZRGB(); p.x = (i * resolution) - (width_x / 2); p.y = (j * resolution) - (length_y / 2); p.r = 0; p.g = 0; p.b = static_cast<uint8_t>((127 - prob) * 2); fromOcuGrid->points.push_back(p); // ROS_INFO_STREAM("(" << i << ", " << j << ") -> (" << p.x << ", " << p.y << ")"); } else if (prob == 127) { } // Set x y coordinates as the center of the grid cell. } } fromOcuGrid->header.frame_id = "/odom"; fromOcuGrid->header.stamp = stamp; // ROS_INFO_STREAM("Size: " << fromOcuGrid->points.size() << " / " << (width_x * length_y)); debug_pcl_pub.publish(fromOcuGrid); } } /** * Callback for pointcloud. Filters the lidar scan, then inserts it into the octree. * @param pc lidar scan */ void pc_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &pc) { // Pass through filter to only keep ones closest to us pcl::PointCloud<pcl::PointXYZ>::Ptr small(new pcl::PointCloud<pcl::PointXYZ>); float dist; for (int point_i = 0; point_i < pc->size(); ++point_i) { dist = pc->at(point_i).x * pc->at(point_i).x + pc->at(point_i).y * pc->at(point_i).y + pc->at(point_i).z * pc->at(point_i).z; if (dist <= radius*radius*radius) { small->push_back(pc->at(point_i)); } } // ROS_INFO("Got Pointcloud"); // make transformed clouds pcl::PointCloud<pcl::PointXYZ>::Ptr transformed = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>()); // Check if static transform already exists for this topic. if (!checkExistsStaticTransform(pc, "/scan/pointcloud")) { ROS_ERROR("Sleeping 2 seconds then trying again..."); ros::Duration(2).sleep(); return; } // Lookup transform form Ros Localization for position getOdomTransform(pc); // Apply transformation from lidar to base_link aka robot pose pcl_ros::transformPointCloud(*small, *transformed, transforms.at("/scan/pointcloud")); pcl_ros::transformPointCloud(*transformed, *transformed, state.transform); visualization_msgs::Marker points; points.header.frame_id = "/odom"; points.header.stamp = ros::Time::now(); points.pose.position.x = state2.transform.getOrigin().getX(); points.pose.position.y = state2.transform.getOrigin().getY(); points.pose.position.z = state2.transform.getOrigin().getZ(); points.action = visualization_msgs::Marker::ADD; points.id = 0; points.type = visualization_msgs::Marker::CUBE; points.scale.x = 0.05; points.scale.y = 0.05; points.scale.z = 0.05; points.color.g = 1.0f; points.color.a = 1.0; sensor_pub.publish(points); octomapper->insert_scan(state2.transform.getOrigin(), pc_map_pair, *transformed); // ROS_INFO("Publishing"); // Publish map // ROS_INFO_STREAM("octomap tree size1: " << pc_map_pair.octree->getNumLeafNodes()); octomapper->get_updated_map(pc_map_pair); // ROS_INFO_STREAM("octomap tree size2: " << pc_map_pair.octree->getNumLeafNodes()); publish(*(pc_map_pair.map), pc->header.stamp); } /** * Cleanup method to release resouces held * @param sig */ void node_cleanup(int sig) { published_map.reset(); published_map.reset(); octomapper.reset(); tf_listener.reset(); ros::shutdown(); } int main(int argc, char **argv) { ros::init(argc, argv, "mapper"); ros::NodeHandle nh; ros::NodeHandle pNh("~"); std::string topics; signal(SIGINT, node_cleanup); std::list<ros::Subscriber> subs; tf_listener = std::unique_ptr<tf::TransformListener>(new tf::TransformListener()); octomapper = std::unique_ptr<Octomapper>(new Octomapper(pNh)); octomapper->create_octree(pc_map_pair); // assumes all params inputted in meters igvc::getParam(pNh, "octree/resolution", resolution); igvc::getParam(pNh, "map/length", length_y); igvc::getParam(pNh, "map/width", width_x); igvc::getParam(pNh, "map/start_x", start_x); igvc::getParam(pNh, "map/start_y", start_y); igvc::getParam(pNh, "debug", debug); igvc::getParam(pNh, "sensor_model/max_range", radius); // convert from meters to grid ros::Subscriber pcl_sub = nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>("/scan/pointcloud", 1, &pc_callback); published_map = std::unique_ptr<cv::Mat>(new cv::Mat(length_y, width_x, CV_8UC1)); map_pub = nh.advertise<igvc_msgs::map>("/map", 1); if (debug) { debug_pub = nh.advertise<sensor_msgs::Image>("/map_debug", 1); debug_pcl_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/map_debug_pcl", 1); ground_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ>>("/ground_pcl", 1); nonground_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ>>("/nonground_pcl", 1); sensor_pub = nh.advertise<visualization_msgs::Marker>("/sensor_pos", 1); } ros::spin(); } <commit_msg>Changed ros_error to ros_debug<commit_after>// Subscribes to Point Cloud Data, updates the occupancy grid, then publishes the data. #include <cv_bridge/cv_bridge.h> #include <igvc_msgs/map.h> #include <math.h> #include <nav_msgs/Odometry.h> #include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <ros/publisher.h> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <stdlib.h> #include <Eigen/Core> #include <igvc_utils/NodeUtils.hpp> #include <igvc_utils/RobotState.hpp> #include <opencv2/core/eigen.hpp> #include <opencv2/opencv.hpp> #include <tf/transform_datatypes.h> #include <tf_conversions/tf_eigen.h> #include "octomapper.h" #include <visualization_msgs/Marker.h> #include <signal.h> cv_bridge::CvImage img_bridge; ros::Publisher map_pub; // Publishes map ros::Publisher debug_pub; // Debug version of above ros::Publisher debug_pcl_pub; // Publishes map as individual PCL points ros::Publisher ground_pub; // Publishes map as individual PCL points ros::Publisher nonground_pub; // Publishes map as individual PCL points ros::Publisher sensor_pub; // Publishes map as individual PCL points std::unique_ptr<cv::Mat> published_map; // matrix will be publishing std::map<std::string, tf::StampedTransform> transforms; std::unique_ptr<tf::TransformListener> tf_listener; double resolution; double transform_max_wait_time; int start_x; // start x location int start_y; // start y location int length_y; int width_x; bool debug; double radius; RobotState state; RobotState state2; std::unique_ptr<Octomapper> octomapper; pc_map_pair pc_map_pair; /** * Updates <code>RobotState state</code> with the latest tf transform using the timestamp of the message passed in * @param msg <code>pcl::PointCloud</code> message with the timestamp used for looking up the tf transform */ void getOdomTransform(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg) { tf::StampedTransform transform; tf::StampedTransform transform2; ros::Time messageTimeStamp; pcl_conversions::fromPCL(msg->header.stamp, messageTimeStamp); if (tf_listener->waitForTransform("/odom", "/base_link", messageTimeStamp, ros::Duration(transform_max_wait_time))) { tf_listener->lookupTransform("/odom", "/base_link", messageTimeStamp, transform); state.setState(transform); tf_listener->lookupTransform("/odom", "/lidar", messageTimeStamp, transform2); state2.setState(transform2); } else { ROS_DEBUG("Failed to get transform from /base_link to /odom in time, using newest transforms"); tf_listener->lookupTransform("/odom", "/base_link", ros::Time(0), transform); state.setState(transform); tf_listener->lookupTransform("/odom", "/lidar", ros::Time(0), transform2); state2.setState(transform2); } } // Populates igvc_msgs::map message with information from sensor_msgs::Image and the timestamp from pcl_stamp /** * Populates <code>igvc_msgs::map message</code> with information from <code>sensor_msgs::Image</code> and the * timestamp from <code>pcl_stamp</code> * @param message message to be filled out * @param image image containing map data to be put into <code>message</code> * @param pcl_stamp time stamp from the pcl to be used for <code>message</code> */ void setMsgValues(igvc_msgs::map &message, sensor_msgs::Image &image, uint64_t pcl_stamp) { pcl_conversions::fromPCL(pcl_stamp, image.header.stamp); pcl_conversions::fromPCL(pcl_stamp, message.header.stamp); message.header.frame_id = "/odom"; message.image = image; message.length = length_y / resolution; message.width = width_x / resolution; message.resolution = resolution; message.orientation = state.yaw(); message.x = std::round(state.x() / resolution) + start_x/resolution; message.y = std::round(state.y() / resolution) + start_y/resolution; message.x_initial = start_x / resolution; message.y_initial = start_y / resolution; } /** * Checks if transform from base_footprint to msg.header.frame_id exists * @param msg * @param topic */ bool checkExistsStaticTransform(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic) { if (transforms.find(topic) == transforms.end()) { // Wait for transform between frame_id (ex. /scan/pointcloud) and base_footprint. ros::Time messageTimeStamp; pcl_conversions::fromPCL(msg->header.stamp, messageTimeStamp); ROS_INFO_STREAM("Getting transform for " << topic << " from " << msg->header.frame_id << " to /base_footprint \n"); if (tf_listener->waitForTransform("/base_footprint", msg->header.frame_id, messageTimeStamp, ros::Duration(3.0))) { tf::StampedTransform transform; tf_listener->lookupTransform("/base_footprint", msg->header.frame_id, messageTimeStamp, transform); transforms.insert(std::pair<std::string, tf::StampedTransform>(topic, transform)); ROS_INFO_STREAM("Found transform!"); } else { ROS_ERROR_STREAM("Failed to find transform using empty transform"); return false; } } return true; } /** * Publishes the given map at the given stamp * @param map map to be published * @param stamp pcl stamp of the timestamp to be used */ void publish(const cv::Mat &map, uint64_t stamp) { igvc_msgs::map message; // >> message to be sent sensor_msgs::Image image; // >> image in the message img_bridge = cv_bridge::CvImage(message.header, sensor_msgs::image_encodings::MONO8, map); img_bridge.toImageMsg(image); // from cv_bridge to sensor_msgs::Image setMsgValues(message, image, stamp); map_pub.publish(message); if (debug) { debug_pub.publish(image); // ROS_INFO_STREAM("\nThe robot is located at " << state); pcl::PointCloud<pcl::PointXYZRGB>::Ptr fromOcuGrid = boost::make_shared<pcl::PointCloud<pcl::PointXYZRGB>>(); for (int i = 0; i < width_x/resolution; i++) { for (int j = 0; j < length_y/resolution; j++) { pcl::PointXYZRGB p; uchar prob = map.at<uchar>(i, j); if (prob > 127) { p = pcl::PointXYZRGB(); p.x = (i * resolution) - (width_x / 2); p.y = (j * resolution) - (length_y / 2); p.r = 0; p.g = static_cast<uint8_t>((prob - 127) * 2); p.b = 0; fromOcuGrid->points.push_back(p); // ROS_INFO_STREAM("(" << i << ", " << j << ") -> (" << p.x << ", " << p.y << ")"); } else if (prob < 127) { p = pcl::PointXYZRGB(); p.x = (i * resolution) - (width_x / 2); p.y = (j * resolution) - (length_y / 2); p.r = 0; p.g = 0; p.b = static_cast<uint8_t>((127 - prob) * 2); fromOcuGrid->points.push_back(p); // ROS_INFO_STREAM("(" << i << ", " << j << ") -> (" << p.x << ", " << p.y << ")"); } else if (prob == 127) { } // Set x y coordinates as the center of the grid cell. } } fromOcuGrid->header.frame_id = "/odom"; fromOcuGrid->header.stamp = stamp; // ROS_INFO_STREAM("Size: " << fromOcuGrid->points.size() << " / " << (width_x * length_y)); debug_pcl_pub.publish(fromOcuGrid); } } /** * Callback for pointcloud. Filters the lidar scan, then inserts it into the octree. * @param pc lidar scan */ void pc_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &pc) { // Pass through filter to only keep ones closest to us pcl::PointCloud<pcl::PointXYZ>::Ptr small(new pcl::PointCloud<pcl::PointXYZ>); float dist; for (int point_i = 0; point_i < pc->size(); ++point_i) { dist = pc->at(point_i).x * pc->at(point_i).x + pc->at(point_i).y * pc->at(point_i).y + pc->at(point_i).z * pc->at(point_i).z; if (dist <= radius*radius*radius) { small->push_back(pc->at(point_i)); } } // ROS_INFO("Got Pointcloud"); // make transformed clouds pcl::PointCloud<pcl::PointXYZ>::Ptr transformed = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>()); // Check if static transform already exists for this topic. if (!checkExistsStaticTransform(pc, "/scan/pointcloud")) { ROS_ERROR("Sleeping 2 seconds then trying again..."); ros::Duration(2).sleep(); return; } // Lookup transform form Ros Localization for position getOdomTransform(pc); // Apply transformation from lidar to base_link aka robot pose pcl_ros::transformPointCloud(*small, *transformed, transforms.at("/scan/pointcloud")); pcl_ros::transformPointCloud(*transformed, *transformed, state.transform); visualization_msgs::Marker points; points.header.frame_id = "/odom"; points.header.stamp = ros::Time::now(); points.pose.position.x = state2.transform.getOrigin().getX(); points.pose.position.y = state2.transform.getOrigin().getY(); points.pose.position.z = state2.transform.getOrigin().getZ(); points.action = visualization_msgs::Marker::ADD; points.id = 0; points.type = visualization_msgs::Marker::CUBE; points.scale.x = 0.05; points.scale.y = 0.05; points.scale.z = 0.05; points.color.g = 1.0f; points.color.a = 1.0; sensor_pub.publish(points); octomapper->insert_scan(state2.transform.getOrigin(), pc_map_pair, *transformed); // ROS_INFO("Publishing"); // Publish map // ROS_INFO_STREAM("octomap tree size1: " << pc_map_pair.octree->getNumLeafNodes()); octomapper->get_updated_map(pc_map_pair); // ROS_INFO_STREAM("octomap tree size2: " << pc_map_pair.octree->getNumLeafNodes()); publish(*(pc_map_pair.map), pc->header.stamp); } /** * Cleanup method to release resouces held * @param sig */ void node_cleanup(int sig) { published_map.reset(); published_map.reset(); octomapper.reset(); tf_listener.reset(); ros::shutdown(); } int main(int argc, char **argv) { ros::init(argc, argv, "mapper"); ros::NodeHandle nh; ros::NodeHandle pNh("~"); std::string topics; signal(SIGINT, node_cleanup); std::list<ros::Subscriber> subs; tf_listener = std::unique_ptr<tf::TransformListener>(new tf::TransformListener()); octomapper = std::unique_ptr<Octomapper>(new Octomapper(pNh)); octomapper->create_octree(pc_map_pair); // assumes all params inputted in meters igvc::getParam(pNh, "octree/resolution", resolution); igvc::getParam(pNh, "map/length", length_y); igvc::getParam(pNh, "map/width", width_x); igvc::getParam(pNh, "map/start_x", start_x); igvc::getParam(pNh, "map/start_y", start_y); igvc::getParam(pNh, "debug", debug); igvc::getParam(pNh, "sensor_model/max_range", radius); // convert from meters to grid ros::Subscriber pcl_sub = nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>("/scan/pointcloud", 1, &pc_callback); published_map = std::unique_ptr<cv::Mat>(new cv::Mat(length_y, width_x, CV_8UC1)); map_pub = nh.advertise<igvc_msgs::map>("/map", 1); if (debug) { debug_pub = nh.advertise<sensor_msgs::Image>("/map_debug", 1); debug_pcl_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/map_debug_pcl", 1); ground_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ>>("/ground_pcl", 1); nonground_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ>>("/nonground_pcl", 1); sensor_pub = nh.advertise<visualization_msgs::Marker>("/sensor_pos", 1); } ros::spin(); } <|endoftext|>
<commit_before>/*! * \file tessellated_path.hpp * \brief file tessellated_path.hpp * * Copyright 2016 by Intel. * * Contact: kevin.rogovin@intel.com * * This Source Code Form is subject to the * terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with * this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #pragma once #include <fastuidraw/util/fastuidraw_memory.hpp> #include <fastuidraw/util/vecN.hpp> #include <fastuidraw/util/c_array.hpp> #include <fastuidraw/util/reference_counted.hpp> namespace fastuidraw { ///@cond class Path; class StrokedPath; class FilledPath; ///@endcond /*!\addtogroup Paths @{ */ /*! \brief A TessellatedPath represents the tessellation of a Path. */ class TessellatedPath: public reference_counted<TessellatedPath>::non_concurrent { public: /*! \brief A TessellationParams stores how finely to tessellate the curves of a path. */ class TessellationParams { public: /*! Ctor, initializes values. */ TessellationParams(void): m_curvature_tessellation(true), m_threshhold(float(M_PI)/30.0f), m_max_segments(32) {} /*! Non-equal comparison operator. \param rhs value to which to compare against */ bool operator!=(const TessellationParams &rhs) const { return m_curvature_tessellation != rhs.m_curvature_tessellation || m_threshhold != rhs.m_threshhold || m_max_segments != rhs.m_max_segments; } /*! Provided as a conveniance. Equivalent to \code m_curvature_tessellation = true; m_threshhold = p; \endcode \param p value to which to assign to \ref m_threshhold */ TessellationParams& curvature_tessellate(float p) { m_curvature_tessellation = true; m_threshhold = p; return *this; } /*! Provided as a conveniance. Equivalent to \code m_curvature_tessellation = true; m_threshhold = 2.0f * static_cast<float>(M_PI) / static_cast<float>(N); \endcode \param N number of points for goal to tessellate a circle to. */ TessellationParams& curvature_tessellate_num_points_in_circle(unsigned int N) { m_curvature_tessellation = true; m_threshhold = 2.0f * static_cast<float>(M_PI) / static_cast<float>(N); return *this; } /*! Provided as a conveniance. Equivalent to \code m_curvature_tessellation = false; m_threshhold = p; \endcode \param p value to which to assign to \ref m_threshhold */ TessellationParams& curve_distance_tessellate(float p) { m_curvature_tessellation = false; m_threshhold = p; return *this; } /*! Set the value of \ref m_max_segments. \param v value to which to assign to \ref m_max_segments */ TessellationParams& max_segments(unsigned int v) { m_max_segments = v; return *this; } /*! Specifies the meaning of \ref m_threshhold. */ bool m_curvature_tessellation; /*! Meaning depends on \ref m_curvature_tessellation. - If m_curvature_tessellation is true, then represents the goal of how much curvature is to be between successive points of a tessellated edge. This value is crudely estimated via Simpson's rule. A value of PI / N for a circle represents tessellating the circle into N points. - If m_curvature_tessellation is false, then represents the goal of the maximum allowed distance between the line segment between from successive points of a tessellated edge and the sub-curve of the starting curve between those two points. */ float m_threshhold; /*! Maximum number of segments to tessellate each PathContour::interpolator_base from each PathContour of a Path. */ unsigned int m_max_segments; }; /*! \brief Represents point of a tessellated path. */ class point { public: /*! The position of the point. */ vec2 m_p; /*! The derivative of the curve at the point. */ vec2 m_p_t; /*! Gives the distance of the point from the start of the -edge- on which the point resides. */ float m_distance_from_edge_start; /*! Gives the distance of the point from the start of the -contour- on which the point resides. */ float m_distance_from_contour_start; /*! Gives the length of the edge on which the point lies. This value is the same for all points along a fixed edge. */ float m_edge_length; /*! Gives the length of the contour open on which the point lies. This value is the same for all points along a fixed contour. */ float m_open_contour_length; /*! Gives the length of the contour closed on which the point lies. This value is the same for all points along a fixed contour. */ float m_closed_contour_length; }; /*! Ctor. Construct a TessellatedPath from a Path \param input source path to tessellate \param P parameters on how to tessellate the source Path */ TessellatedPath(const Path &input, TessellationParams P); ~TessellatedPath(); /*! Returns the tessellation parameters used to construct this TessellatedPath. */ const TessellationParams& tessellation_parameters(void) const; /*! Returns the tessellation threshold achieved for distance between curve and sub-edges. */ float effective_curve_distance_threshhold(void) const; /*! Returns the tessellation threshold achieved for the (approximated) curvature between successive points of the tessellation. */ float effective_curvature_threshhold(void) const; /*! Returns the maximum number of segments any edge needed */ unsigned int max_segments(void) const; /*! Returns all the point data */ const_c_array<point> point_data(void) const; /*! Returns the number of contours */ unsigned int number_contours(void) const; /*! Returns the range into point_data() for the named contour. The contour data is a sequence of lines. Points that are shared between edges are replicated (because the derivatives are different). */ range_type<unsigned int> contour_range(unsigned int contour) const; /*! Returns the range into point_data() for the named contour lacking the closing edge. The contour data is a sequence of lines. Points that are shared between edges are replicated (because the derivatives are different). */ range_type<unsigned int> unclosed_contour_range(unsigned int contour) const; /*! Returns the point data of the named contour. The contour data is a sequence of lines. */ const_c_array<point> contour_point_data(unsigned int contour) const; /*! Returns the point data of the named contour lacking the point data of the closing edge. The contour data is a sequence of lines. */ const_c_array<point> unclosed_contour_point_data(unsigned int contour) const; /*! Returns the number of edges for the named contour */ unsigned int number_edges(unsigned int contour) const; /*! Returns the range into point_data(void) for the named edge of the named contour. The returned range does include the end point of the edge. */ range_type<unsigned int> edge_range(unsigned int contour, unsigned int edge) const; /*! Returns the point data of the named edge of the named contour. */ const_c_array<point> edge_point_data(unsigned int contour, unsigned int edge) const; /*! Returns the minimum point of the bounding box of the tessellation. */ vec2 bounding_box_min(void) const; /*! Returns the maximum point of the bounding box of the tessellation. */ vec2 bounding_box_max(void) const; /*! Returns the dimensions of the bounding box of the tessellated path. */ vec2 bounding_box_size(void) const; /*! Returns this TessellatedPath stroked. The StrokedPath object is constructed lazily. */ const reference_counted_ptr<const StrokedPath>& stroked(void) const; /*! Returns this TessellatedPath filled. The FilledPath object is constructed lazily. */ const reference_counted_ptr<const FilledPath>& filled(void) const; private: void *m_d; }; /*! @} */ } <commit_msg>fastuidraw/tessellated_path: doxytag improvements<commit_after>/*! * \file tessellated_path.hpp * \brief file tessellated_path.hpp * * Copyright 2016 by Intel. * * Contact: kevin.rogovin@intel.com * * This Source Code Form is subject to the * terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with * this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #pragma once #include <fastuidraw/util/fastuidraw_memory.hpp> #include <fastuidraw/util/vecN.hpp> #include <fastuidraw/util/c_array.hpp> #include <fastuidraw/util/reference_counted.hpp> namespace fastuidraw { ///@cond class Path; class StrokedPath; class FilledPath; ///@endcond /*!\addtogroup Paths @{ */ /*! \brief A TessellatedPath represents the tessellation of a Path. A single contour of a TessellatedPath is constructed from a single \ref PathContour of the source \ref Path. Each edge of a contour of a TessellatedPath is contructed from a single \ref PathContour::interpolator_base of the source \ref PathContour. The ordering of the contours of a TessellatedPath is the same ordering as the source \ref PathContour objects of the source \ref Path. Also, the ordering of edges within a contour is the same ordering as the \ref PathContour::interpolator_base objects of the source \ref PathContour. In particular, for each contour of a TessellatedPath, the closing edge is the last edge. */ class TessellatedPath: public reference_counted<TessellatedPath>::non_concurrent { public: /*! \brief A TessellationParams stores how finely to tessellate the curves of a path. */ class TessellationParams { public: /*! Ctor, initializes values. */ TessellationParams(void): m_curvature_tessellation(true), m_threshhold(float(M_PI)/30.0f), m_max_segments(32) {} /*! Non-equal comparison operator. \param rhs value to which to compare against */ bool operator!=(const TessellationParams &rhs) const { return m_curvature_tessellation != rhs.m_curvature_tessellation || m_threshhold != rhs.m_threshhold || m_max_segments != rhs.m_max_segments; } /*! Provided as a conveniance. Equivalent to \code m_curvature_tessellation = true; m_threshhold = p; \endcode \param p value to which to assign to \ref m_threshhold */ TessellationParams& curvature_tessellate(float p) { m_curvature_tessellation = true; m_threshhold = p; return *this; } /*! Provided as a conveniance. Equivalent to \code m_curvature_tessellation = true; m_threshhold = 2.0f * static_cast<float>(M_PI) / static_cast<float>(N); \endcode \param N number of points for goal to tessellate a circle to. */ TessellationParams& curvature_tessellate_num_points_in_circle(unsigned int N) { m_curvature_tessellation = true; m_threshhold = 2.0f * static_cast<float>(M_PI) / static_cast<float>(N); return *this; } /*! Provided as a conveniance. Equivalent to \code m_curvature_tessellation = false; m_threshhold = p; \endcode \param p value to which to assign to \ref m_threshhold */ TessellationParams& curve_distance_tessellate(float p) { m_curvature_tessellation = false; m_threshhold = p; return *this; } /*! Set the value of \ref m_max_segments. \param v value to which to assign to \ref m_max_segments */ TessellationParams& max_segments(unsigned int v) { m_max_segments = v; return *this; } /*! Specifies the meaning of \ref m_threshhold. */ bool m_curvature_tessellation; /*! Meaning depends on \ref m_curvature_tessellation. - If m_curvature_tessellation is true, then represents the goal of how much curvature is to be between successive points of a tessellated edge. This value is crudely estimated via Simpson's rule. A value of PI / N for a circle represents tessellating the circle into N points. - If m_curvature_tessellation is false, then represents the goal of the maximum allowed distance between the line segment between from successive points of a tessellated edge and the sub-curve of the starting curve between those two points. */ float m_threshhold; /*! Maximum number of segments to tessellate each PathContour::interpolator_base from each PathContour of a Path. */ unsigned int m_max_segments; }; /*! \brief Represents point of a tessellated path. */ class point { public: /*! The position of the point. */ vec2 m_p; /*! The derivative of the curve at the point. */ vec2 m_p_t; /*! Gives the distance of the point from the start of the edge (i.e PathContour::interpolator_base) on which the point resides. */ float m_distance_from_edge_start; /*! Gives the distance of the point from the start of the -contour- on which the point resides. */ float m_distance_from_contour_start; /*! Gives the length of the edge (i.e. PathContour::interpolator_base) on which the point lies. This value is the same for all points along a fixed edge. */ float m_edge_length; /*! Gives the length of the contour open on which the point lies. This value is the same for all points along a fixed contour. */ float m_open_contour_length; /*! Gives the length of the contour closed on which the point lies. This value is the same for all points along a fixed contour. */ float m_closed_contour_length; }; /*! Ctor. Construct a TessellatedPath from a Path \param input source path to tessellate \param P parameters on how to tessellate the source Path */ TessellatedPath(const Path &input, TessellationParams P); ~TessellatedPath(); /*! Returns the tessellation parameters used to construct this TessellatedPath. */ const TessellationParams& tessellation_parameters(void) const; /*! Returns the tessellation threshold achieved for distance between curve and sub-edges. */ float effective_curve_distance_threshhold(void) const; /*! Returns the tessellation threshold achieved for the (approximated) curvature between successive points of the tessellation. */ float effective_curvature_threshhold(void) const; /*! Returns the maximum number of segments any edge needed */ unsigned int max_segments(void) const; /*! Returns all the point data */ const_c_array<point> point_data(void) const; /*! Returns the number of contours */ unsigned int number_contours(void) const; /*! Returns the range into point_data() for the named contour. The contour data is a sequence of points specifing a line strip. Points that are shared between edges (an edge corresponds to a PathContour::interpolator_base) are replicated (because the derivatives are different). \param contour which path contour to query, must have that 0 <= contour < number_contours() */ range_type<unsigned int> contour_range(unsigned int contour) const; /*! Returns the range into point_data() for the named contour lacking the closing edge. The contour data is a sequence of points specifing a line strip. Points that are shared between edges (an edge corresponds to a PathContour::interpolator_base) are replicated (because the derivatives are different). \param contour which path contour to query, must have that 0 <= contour < number_contours() */ range_type<unsigned int> unclosed_contour_range(unsigned int contour) const; /*! Returns the point data of the named contour including the closing edge. The contour data is a sequence of points specifing a line strip. Points that are shared between edges (an edge corresponds to a PathContour::interpolator_base) are replicated (because the derivatives are different). Provided as a conveniance, equivalent to \code point_data().sub_array(contour_range(contour)) \endcode \param contour which path contour to query, must have that 0 <= contour < number_contours() */ const_c_array<point> contour_point_data(unsigned int contour) const; /*! Returns the point data of the named contour lacking the point data of the closing edge. The contour data is a sequence of points specifing a line strip. Points that are shared between edges (an edge corresponds to a PathContour::interpolator_base) are replicated (because the derivatives are different). Provided as a conveniance, equivalent to \code point_data().sub_array(unclosed_contour_range(contour)) \endcode \param contour which path contour to query, must have that 0 <= contour < number_contours() */ const_c_array<point> unclosed_contour_point_data(unsigned int contour) const; /*! Returns the number of edges for the named contour \param contour which path contour to query, must have that 0 <= contour < number_contours() */ unsigned int number_edges(unsigned int contour) const; /*! Returns the range into point_data(void) for the named edge of the named contour. The returned range does include the end point of the edge. The edge corresponds to the PathContour::interpolator_base Path::contour(contour)->interpolator(edge). \param contour which path contour to query, must have that 0 <= contour < number_contours() \param edge which edge of the contour to query, must have that 0 <= edge < number_edges(contour) */ range_type<unsigned int> edge_range(unsigned int contour, unsigned int edge) const; /*! Returns the point data of the named edge of the named contour, provided as a conveniance, equivalent to \code point_data().sub_array(edge_range(contour, edge)) \endcode \param contour which path contour to query, must have that 0 <= contour < number_contours() \param edge which edge of the contour to query, must have that 0 <= edge < number_edges(contour) */ const_c_array<point> edge_point_data(unsigned int contour, unsigned int edge) const; /*! Returns the minimum point of the bounding box of the tessellation. */ vec2 bounding_box_min(void) const; /*! Returns the maximum point of the bounding box of the tessellation. */ vec2 bounding_box_max(void) const; /*! Returns the dimensions of the bounding box of the tessellated path. */ vec2 bounding_box_size(void) const; /*! Returns this TessellatedPath stroked. The StrokedPath object is constructed lazily. */ const reference_counted_ptr<const StrokedPath>& stroked(void) const; /*! Returns this TessellatedPath filled. The FilledPath object is constructed lazily. */ const reference_counted_ptr<const FilledPath>& filled(void) const; private: void *m_d; }; /*! @} */ } <|endoftext|>
<commit_before>#pragma once #ifndef BINARYDATA_HPP #define BINARYDATA_HPP #include <memory> class BINARY_DATA { unsigned char* m_data; size_t m_size; public: BINARY_DATA() : m_data(nullptr), m_size(0) {} BINARY_DATA(const unsigned int size) { m_size = size; m_data = (new unsigned char[size]); } BINARY_DATA(void* data, const size_t size) { setData(data,size); } BINARY_DATA(const BINARY_DATA& binary_data) { m_size = binary_data.m_size; m_data = binary_data.m_data; } ~BINARY_DATA(){} void setData(void* data, const size_t size) { m_data = reinterpret_cast<unsigned char*>(data); m_size = size; } size_t size() const { return m_size; } void* ptr() const { return reinterpret_cast<void*>(m_data); } void clear() { delete[m_size] m_data; m_size = 0; } }; #endif<commit_msg>Binary data deallocation fix<commit_after>#pragma once #ifndef BINARYDATA_HPP #define BINARYDATA_HPP #include <memory> class BINARY_DATA { unsigned char* m_data; size_t m_size; public: BINARY_DATA() : m_data(nullptr), m_size(0) {} BINARY_DATA(const unsigned int size) { m_size = size; m_data = (new unsigned char[size]); } BINARY_DATA(void* data, const size_t size) { setData(data,size); } BINARY_DATA(const BINARY_DATA& binary_data) { m_size = binary_data.m_size; m_data = binary_data.m_data; } ~BINARY_DATA(){} void setData(void* data, const size_t size) { m_data = reinterpret_cast<unsigned char*>(data); m_size = size; } size_t size() const { return m_size; } void* ptr() const { return reinterpret_cast<void*>(m_data); } void clear() { delete[] m_data; m_size = 0; } }; #endif<|endoftext|>
<commit_before>/* * Copyright 2015 Aldebaran * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef ALROS_BRIDGE_HPP #define ALROS_BRIDGE_HPP #include <vector> #include <queue> /* * BOOST */ #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/scoped_ptr.hpp> /* * ALDEB */ #include <qi/session.hpp> /* * PUBLIC INTERFACE */ #include <alrosbridge/publisher/publisher.hpp> namespace alros { /** * @brief Interface for ALRosBridge which is registered as a naoqi2 Module, * once the external roscore ip is set, this class will advertise and publish ros messages */ class Bridge { public: /** * @brief Constructor for ALRosBridge * @param session[in] session pointer for naoqi2 service registration */ Bridge( qi::SessionPtr& session ); /** * @brief Destructor for ALRosBridge, * destroys all ros nodehandle and shutsdown all publisher */ ~Bridge(); /** * @brief registers a publisher * @param publisher to register * @see Publisher * @note it will be called by value to expose that internally there will be a copy, * eventually this should be replaced by move semantics C++11 */ void registerPublisher( publisher::Publisher pub ); /** * @brief poll function to check if publishing is enabled * @return bool indicating if publishing is enabled/disabled */ bool isAlive() const; /** * @brief qicli call function to get current master uri * @return string indicating http master uri */ std::string getMasterURI() const; /** * @brief qicli call function to set current master uri * @param string in form of http://<ip>:11311 */ void setMasterURI( const std::string& uri ); /** * @brief qicli call function to start/enable publishing all registered publisher */ void start(); /** * @brief qicli call function to stop/disable publishing all registered publisher */ void stop(); private: qi::SessionPtr sessionPtr_; bool publish_enabled_; const size_t freq_; boost::thread publisherThread_; //ros::Rate r_; void registerDefaultPublisher(); void initPublisher(); void rosLoop(); boost::scoped_ptr<ros::NodeHandle> nhPtr_; boost::mutex mutex_reinit_; std::vector< publisher::Publisher > all_publisher_; /** Pub Publisher to execute at a specific time */ struct ScheduledPublish { ScheduledPublish(const ros::Time& schedule, alros::publisher::Publisher* pub) : schedule_(schedule), pub_(pub) { } bool operator < (const ScheduledPublish& sp_in) const { return schedule_ > sp_in.schedule_; } /** Time at which the publisher will be called */ ros::Time schedule_; /** Time at which the publisher will be called */ alros::publisher::Publisher* pub_; }; /** Priority queue to process the publishers according to their frequency */ std::priority_queue<ScheduledPublish> pub_queue_; }; } // alros #endif <commit_msg>const pointer implementation<commit_after>/* * Copyright 2015 Aldebaran * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef ALROS_BRIDGE_HPP #define ALROS_BRIDGE_HPP #include <vector> #include <queue> /* * BOOST */ #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/scoped_ptr.hpp> /* * ALDEB */ #include <qi/session.hpp> /* * PUBLIC INTERFACE */ #include <alrosbridge/publisher/publisher.hpp> namespace alros { /** * @brief Interface for ALRosBridge which is registered as a naoqi2 Module, * once the external roscore ip is set, this class will advertise and publish ros messages */ class Bridge { public: /** * @brief Constructor for ALRosBridge * @param session[in] session pointer for naoqi2 service registration */ Bridge( qi::SessionPtr& session ); /** * @brief Destructor for ALRosBridge, * destroys all ros nodehandle and shutsdown all publisher */ ~Bridge(); /** * @brief registers a publisher * @param publisher to register * @see Publisher * @note it will be called by value to expose that internally there will be a copy, * eventually this should be replaced by move semantics C++11 */ void registerPublisher( publisher::Publisher pub ); /** * @brief poll function to check if publishing is enabled * @return bool indicating if publishing is enabled/disabled */ bool isAlive() const; /** * @brief qicli call function to get current master uri * @return string indicating http master uri */ std::string getMasterURI() const; /** * @brief qicli call function to set current master uri * @param string in form of http://<ip>:11311 */ void setMasterURI( const std::string& uri ); /** * @brief qicli call function to start/enable publishing all registered publisher */ void start(); /** * @brief qicli call function to stop/disable publishing all registered publisher */ void stop(); private: qi::SessionPtr sessionPtr_; bool publish_enabled_; const size_t freq_; boost::thread publisherThread_; //ros::Rate r_; void registerDefaultPublisher(); void initPublisher(); void rosLoop(); boost::scoped_ptr<ros::NodeHandle> nhPtr_; boost::mutex mutex_reinit_; std::vector< publisher::Publisher > all_publisher_; /** Pub Publisher to execute at a specific time */ struct ScheduledPublish { ScheduledPublish(const ros::Time& schedule, alros::publisher::Publisher* pub) : schedule_(schedule), pub_(pub) { } ScheduledPublish& operator= ( const ScheduledPublish& rhs ) { schedule_ = rhs.schedule_; alros::publisher::Publisher*& ptr= const_cast< alros::publisher::Publisher*& >(this->pub_); ptr = rhs.pub_; //alros::publisher::Publisher** ptr= const_cast< alros::publisher::Publisher** >(&(this->pub_)); //*ptr = rhs.pub_; return *this; } bool operator < (const ScheduledPublish& sp_in) const { return schedule_ > sp_in.schedule_; } /** Time at which the publisher will be called */ ros::Time schedule_; /** Time at which the publisher will be called */ alros::publisher::Publisher* const pub_; ScheduledPublish(const ScheduledPublish& rhs):schedule_(rhs.schedule_), pub_(rhs.pub_) {} }; /** Priority queue to process the publishers according to their frequency */ std::priority_queue<ScheduledPublish> pub_queue_; }; } // alros #endif <|endoftext|>
<commit_before>// Copyright (c) 2020, Open Source Robotics Foundation, Inc. // All rights reserved. // // Software License Agreement (BSD License 2.0) // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the Willow Garage nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef CONTROL_TOOLBOX__PID_ROS_HPP_ #define CONTROL_TOOLBOX__PID_ROS_HPP_ #include <memory> #include <string> #include "control_msgs/msg/pid_state.hpp" #include "rclcpp/clock.hpp" #include "rclcpp/duration.hpp" #include "rclcpp/node.hpp" #include "realtime_tools/realtime_buffer.h" #include "realtime_tools/realtime_publisher.h" #include "control_toolbox/pid.hpp" #include "control_toolbox/visibility_control.hpp" namespace control_toolbox { class CONTROL_TOOLBOX_PUBLIC PidROS { public: /*! * \brief Constructor of PidROS class. * * The node is passed to this class to handler the ROS parameters, this class allows * to add a prefix to the pid parameters * * \param node ROS node * \param topic_prefix prefix to add to the pid parameters. */ template<class NodeT> explicit PidROS(std::shared_ptr<NodeT> node_ptr, std::string topic_prefix = std::string("")) : PidROS( node_ptr->get_node_base_interface(), node_ptr->get_node_logging_interface(), node_ptr->get_node_parameters_interface(), node_ptr->get_node_topics_interface(), topic_prefix) { } PidROS( rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base, rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging, rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_params, rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr topics_interface, std::string topic_prefix = std::string("")) : node_base_(node_base), node_logging_(node_logging), node_params_(node_params), topics_interface_(topics_interface) { initialize(topic_prefix); } /*! * \brief Initialize the PID controller and set the parameters * \param p The proportional gain. * \param i The integral gain. * \param d The derivative gain. * \param i_max The max integral windup. * \param i_min The min integral windup. * \param antiwindup antiwindup. */ void initPid(double p, double i, double d, double i_max, double i_min, bool antiwindup); /*! * \brief Initialize the PID controller based on already set parameters * \return True is all parameters are set (p, i, d, i_min and i_max), False otherwise */ bool initPid(); /*! * \brief Reset the state of this PID controller */ void reset(); /*! * \brief Set the PID error and compute the PID command with nonuniform time * step size. The derivative error is computed from the change in the error * and the timestep \c dt. * * \param error Error since last call (error = target - state) * \param dt Change in time since last call in seconds * * \returns PID command */ double computeCommand(double error, rclcpp::Duration dt); /*! * \brief Get PID gains for the controller. * \return gains A struct of the PID gain values */ Pid::Gains getGains(); /*! * \brief Set PID gains for the controller. * \param p The proportional gain. * \param i The integral gain. * \param d The derivative gain. * \param i_max The max integral windup. * \param i_min The min integral windup. * \param antiwindup antiwindup. */ void setGains(double p, double i, double d, double i_max, double i_min, bool antiwindup = false); /*! * \brief Set PID gains for the controller. * \param gains A struct of the PID gain values */ void setGains(const Pid::Gains & gains); /*! * \brief Set current command for this PID controller * \param cmd command to set */ void setCurrentCmd(double cmd); /*! * \brief Return current command for this PID controller * \return current cmd */ double getCurrentCmd(); /*! * \brief Return PID state publisher * \return shared_ptr to the PID state publisher */ std::shared_ptr<rclcpp::Publisher<control_msgs::msg::PidState>> getPidStatePublisher(); /*! * \brief Return PID error terms for the controller. * \param pe[out] The proportional error. * \param ie[out] The integral error. * \param de[out] The derivative error. */ void getCurrentPIDErrors(double & pe, double & ie, double & de); /*! * \brief Print to console the current parameters */ void printValues(); private: void setParameterEventCallback(); void publishPIDState(double cmd, double error, rclcpp::Duration dt); void declareParam(const std::string & param_name, rclcpp::ParameterValue param_value); bool getDoubleParam(const std::string & param_name, double & value); bool getBooleanParam(const std::string & param_name, bool & value); void initialize(std::string topic_prefix); rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr parameter_callback_; rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_; rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_; rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_params_; rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr topics_interface_; std::shared_ptr<realtime_tools::RealtimePublisher<control_msgs::msg::PidState>> rt_state_pub_; std::shared_ptr<rclcpp::Publisher<control_msgs::msg::PidState>> state_pub_; Pid pid_; std::string topic_prefix_; }; } // namespace control_toolbox #endif // CONTROL_TOOLBOX__PID_ROS_HPP_ <commit_msg>Add getParametersCallbackHandle function<commit_after>// Copyright (c) 2020, Open Source Robotics Foundation, Inc. // All rights reserved. // // Software License Agreement (BSD License 2.0) // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the Willow Garage nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef CONTROL_TOOLBOX__PID_ROS_HPP_ #define CONTROL_TOOLBOX__PID_ROS_HPP_ #include <memory> #include <string> #include "control_msgs/msg/pid_state.hpp" #include "rclcpp/clock.hpp" #include "rclcpp/duration.hpp" #include "rclcpp/node.hpp" #include "realtime_tools/realtime_buffer.h" #include "realtime_tools/realtime_publisher.h" #include "control_toolbox/pid.hpp" #include "control_toolbox/visibility_control.hpp" namespace control_toolbox { class CONTROL_TOOLBOX_PUBLIC PidROS { public: /*! * \brief Constructor of PidROS class. * * The node is passed to this class to handler the ROS parameters, this class allows * to add a prefix to the pid parameters * * \param node ROS node * \param topic_prefix prefix to add to the pid parameters. */ template<class NodeT> explicit PidROS(std::shared_ptr<NodeT> node_ptr, std::string topic_prefix = std::string("")) : PidROS( node_ptr->get_node_base_interface(), node_ptr->get_node_logging_interface(), node_ptr->get_node_parameters_interface(), node_ptr->get_node_topics_interface(), topic_prefix) { } PidROS( rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base, rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging, rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_params, rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr topics_interface, std::string topic_prefix = std::string("")) : node_base_(node_base), node_logging_(node_logging), node_params_(node_params), topics_interface_(topics_interface) { initialize(topic_prefix); } /*! * \brief Initialize the PID controller and set the parameters * \param p The proportional gain. * \param i The integral gain. * \param d The derivative gain. * \param i_max The max integral windup. * \param i_min The min integral windup. * \param antiwindup antiwindup. */ void initPid(double p, double i, double d, double i_max, double i_min, bool antiwindup); /*! * \brief Initialize the PID controller based on already set parameters * \return True is all parameters are set (p, i, d, i_min and i_max), False otherwise */ bool initPid(); /*! * \brief Reset the state of this PID controller */ void reset(); /*! * \brief Set the PID error and compute the PID command with nonuniform time * step size. The derivative error is computed from the change in the error * and the timestep \c dt. * * \param error Error since last call (error = target - state) * \param dt Change in time since last call in seconds * * \returns PID command */ double computeCommand(double error, rclcpp::Duration dt); /*! * \brief Get PID gains for the controller. * \return gains A struct of the PID gain values */ Pid::Gains getGains(); /*! * \brief Set PID gains for the controller. * \param p The proportional gain. * \param i The integral gain. * \param d The derivative gain. * \param i_max The max integral windup. * \param i_min The min integral windup. * \param antiwindup antiwindup. */ void setGains(double p, double i, double d, double i_max, double i_min, bool antiwindup = false); /*! * \brief Set PID gains for the controller. * \param gains A struct of the PID gain values */ void setGains(const Pid::Gains & gains); /*! * \brief Set current command for this PID controller * \param cmd command to set */ void setCurrentCmd(double cmd); /*! * \brief Return current command for this PID controller * \return current cmd */ double getCurrentCmd(); /*! * \brief Return PID state publisher * \return shared_ptr to the PID state publisher */ std::shared_ptr<rclcpp::Publisher<control_msgs::msg::PidState>> getPidStatePublisher(); /*! * \brief Return PID error terms for the controller. * \param pe[out] The proportional error. * \param ie[out] The integral error. * \param de[out] The derivative error. */ void getCurrentPIDErrors(double & pe, double & ie, double & de); /*! * \brief Print to console the current parameters */ void printValues(); /*! * \brief Return PID parameters callback handle * \return shared_ptr to the PID parameters callback handle */ inline rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr getParametersCallbackHandle() { return parameter_callback_; } private: void setParameterEventCallback(); void publishPIDState(double cmd, double error, rclcpp::Duration dt); void declareParam(const std::string & param_name, rclcpp::ParameterValue param_value); bool getDoubleParam(const std::string & param_name, double & value); bool getBooleanParam(const std::string & param_name, bool & value); void initialize(std::string topic_prefix); rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr parameter_callback_; rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_; rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_; rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_params_; rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr topics_interface_; std::shared_ptr<realtime_tools::RealtimePublisher<control_msgs::msg::PidState>> rt_state_pub_; std::shared_ptr<rclcpp::Publisher<control_msgs::msg::PidState>> state_pub_; Pid pid_; std::string topic_prefix_; }; } // namespace control_toolbox #endif // CONTROL_TOOLBOX__PID_ROS_HPP_ <|endoftext|>
<commit_before>#pragma once /** @file @brief pseudrandom generator @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #ifndef CYBOZU_DONT_USE_EXCEPTION #include <cybozu/exception.hpp> #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <wincrypt.h> #ifdef _MSC_VER #pragma comment (lib, "advapi32.lib") #endif #include <cybozu/critical_section.hpp> #else #include <sys/types.h> #include <fcntl.h> #endif namespace cybozu { class RandomGenerator { RandomGenerator(const RandomGenerator&); void operator=(const RandomGenerator&); public: #ifdef _WIN32 RandomGenerator() : prov_(0) , pos_(bufSize) { DWORD flagTbl[] = { 0, CRYPT_NEWKEYSET, CRYPT_MACHINE_KEYSET }; for (int i = 0; i < 3; i++) { if (CryptAcquireContext(&prov_, NULL, NULL, PROV_RSA_FULL, flagTbl[i]) != 0) return; } #ifdef CYBOZU_DONT_USE_EXCEPTION prov_ = 0; #else throw cybozu::Exception("randomgenerator"); #endif } bool read_inner(void *buf, size_t byteSize) { if (prov_ == 0) return false; return CryptGenRandom(prov_, static_cast<DWORD>(byteSize), static_cast<BYTE*>(buf)) != 0; } ~RandomGenerator() { if (prov_) { CryptReleaseContext(prov_, 0); } } /* fill buf[0..bufNum-1] with random data @note bufNum is not byte size */ template<class T> void read(bool *pb, T *buf, size_t bufNum) { cybozu::AutoLockCs al(cs_); const size_t byteSize = sizeof(T) * bufNum; if (byteSize > bufSize) { if (!read_inner(buf, byteSize)) { *pb = false; return; } } else { if (pos_ + byteSize > bufSize) { read_inner(buf_, bufSize); pos_ = 0; } memcpy(buf, buf_ + pos_, byteSize); pos_ += byteSize; } *pb = true; } private: HCRYPTPROV prov_; static const size_t bufSize = 1024; char buf_[bufSize]; size_t pos_; cybozu::CriticalSection cs_; #else RandomGenerator() : fp_(::fopen("/dev/urandom", "rb")) { #ifndef CYBOZU_DONT_USE_EXCEPTION if (!fp_) throw cybozu::Exception("randomgenerator"); #endif } ~RandomGenerator() { if (fp_) ::fclose(fp_); } /* fill buf[0..bufNum-1] with random data @note bufNum is not byte size */ template<class T> void read(bool *pb, T *buf, size_t bufNum) { if (fp_ == 0) { *pb = false; return; } const size_t byteSize = sizeof(T) * bufNum; *pb = ::fread(buf, 1, (int)byteSize, fp_) == byteSize; } private: FILE *fp_; #endif #ifndef CYBOZU_DONT_USE_EXCEPTION public: template<class T> void read(T *buf, size_t bufNum) { bool b; read(&b, buf, bufNum); if (!b) throw cybozu::Exception("RandomGenerator:read") << bufNum; } uint32_t get32() { uint32_t ret; read(&ret, 1); return ret; } uint64_t get64() { uint64_t ret; read(&ret, 1); return ret; } uint32_t operator()() { return get32(); } #endif }; template<class T, class RG> void shuffle(T* v, size_t n, RG& rg) { if (n <= 1) return; for (size_t i = 0; i < n - 1; i++) { size_t r = i + size_t(rg.get64() % (n - i)); using namespace std; swap(v[i], v[r]); } } template<class V, class RG> void shuffle(V& v, RG& rg) { shuffle(v.data(), v.size(), rg); } } // cybozu <commit_msg>use CRYPT_VERIFYCONTEXT for RandomGenerator<commit_after>#pragma once /** @file @brief pseudrandom generator @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #ifndef CYBOZU_DONT_USE_EXCEPTION #include <cybozu/exception.hpp> #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <wincrypt.h> #ifdef _MSC_VER #pragma comment (lib, "advapi32.lib") #endif #else #include <sys/types.h> #include <fcntl.h> #endif namespace cybozu { class RandomGenerator { RandomGenerator(const RandomGenerator&); void operator=(const RandomGenerator&); public: #ifdef _WIN32 RandomGenerator() : prov_(0) { DWORD flagTbl[] = { CRYPT_VERIFYCONTEXT | CRYPT_SILENT, CRYPT_MACHINE_KEYSET }; for (int i = 0; i < CYBOZU_NUM_OF_ARRAY(flagTbl); i++) { if (CryptAcquireContext(&prov_, NULL, NULL, PROV_RSA_FULL, flagTbl[i]) != 0) return; } #ifdef CYBOZU_DONT_USE_EXCEPTION prov_ = 0; #else throw cybozu::Exception("randomgenerator"); #endif } bool read_inner(void *buf, size_t byteSize) { if (prov_ == 0) return false; return CryptGenRandom(prov_, static_cast<DWORD>(byteSize), static_cast<BYTE*>(buf)) != 0; } ~RandomGenerator() { if (prov_) { CryptReleaseContext(prov_, 0); } } /* fill buf[0..bufNum-1] with random data @note bufNum is not byte size */ template<class T> void read(bool *pb, T *buf, size_t bufNum) { const size_t byteSize = sizeof(T) * bufNum; *pb = read_inner(buf, byteSize); } private: HCRYPTPROV prov_; #else RandomGenerator() : fp_(::fopen("/dev/urandom", "rb")) { #ifndef CYBOZU_DONT_USE_EXCEPTION if (!fp_) throw cybozu::Exception("randomgenerator"); #endif } ~RandomGenerator() { if (fp_) ::fclose(fp_); } /* fill buf[0..bufNum-1] with random data @note bufNum is not byte size */ template<class T> void read(bool *pb, T *buf, size_t bufNum) { if (fp_ == 0) { *pb = false; return; } const size_t byteSize = sizeof(T) * bufNum; *pb = ::fread(buf, 1, (int)byteSize, fp_) == byteSize; } private: FILE *fp_; #endif #ifndef CYBOZU_DONT_USE_EXCEPTION public: template<class T> void read(T *buf, size_t bufNum) { bool b; read(&b, buf, bufNum); if (!b) throw cybozu::Exception("RandomGenerator:read") << bufNum; } uint32_t get32() { uint32_t ret; read(&ret, 1); return ret; } uint64_t get64() { uint64_t ret; read(&ret, 1); return ret; } uint32_t operator()() { return get32(); } #endif }; template<class T, class RG> void shuffle(T* v, size_t n, RG& rg) { if (n <= 1) return; for (size_t i = 0; i < n - 1; i++) { size_t r = i + size_t(rg.get64() % (n - i)); using namespace std; swap(v[i], v[r]); } } template<class V, class RG> void shuffle(V& v, RG& rg) { shuffle(v.data(), v.size(), rg); } } // cybozu <|endoftext|>
<commit_before>/** * \file * \brief DynamicThread class header * * \author Copyright (C) 2015-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ #define INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ #include "distortos/internal/scheduler/DynamicThreadBase.hpp" #include "distortos/assert.h" namespace distortos { /// \addtogroup threads /// \{ /** * \brief DynamicThread class is a type-erased interface for thread that has dynamic storage for bound function, stack * and internal DynamicSignalsReceiver object. */ #ifdef CONFIG_THREAD_DETACH_ENABLE class DynamicThread : public Thread { public: /** * \brief DynamicThread's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThread(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThread's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThread{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } /** * \brief DynamicThread's destructor */ ~DynamicThread() override; /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; /** * \brief Generates signal for thread. * * Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html * * Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be * unblocked. * * \param [in] signalNumber is the signal that will be generated, [0; 31] * * \return 0 on success, error code otherwise: * - EINVAL - \a signalNumber value is invalid; * - ENOTSUP - reception of signals is disabled for this thread; * - EINVAL - internal thread object was detached; * * \ingroup signals */ int generateSignal(uint8_t signalNumber) override; /** * \return effective priority of thread */ uint8_t getEffectivePriority() const override; /** * \brief Gets set of currently pending signals. * * Similar to sigpending() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigpending.html * * This function shall return the set of signals that are blocked from delivery and are pending on the thread. * * \return set of currently pending signals * * \ingroup signals */ SignalSet getPendingSignalSet() const override; /** * \return priority of thread */ uint8_t getPriority() const override; /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const override; /** * \return current state of thread */ ThreadState getState() const override; /** * \brief Waits for thread termination. * * Similar to std::thread::join() - http://en.cppreference.com/w/cpp/thread/thread/join * Similar to POSIX pthread_join() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html * * Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to * join() on the same target thread are undefined. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EDEADLK - deadlock condition was detected, * - EINVAL - this thread is not joinable, * - EINVAL - internal thread object was detached; * - ... * * \ingroup synchronization */ int join() override; /** * \brief Queues signal for thread. * * Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html * * Adds the signalNumber and signal value (sigval union) to queue of SignalInformation objects. If this thread is * currently waiting for this signal, it will be unblocked. * * \param [in] signalNumber is the signal that will be queued, [0; 31] * \param [in] value is the signal value * * \return 0 on success, error code otherwise: * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in * associated queue of SignalInformation objects; * - EINVAL - \a signalNumber value is invalid; * - ENOTSUP - reception or queuing of signals are disabled for this thread; * - EINVAL - internal thread object was detached; * * \ingroup signals */ int queueSignal(uint8_t signalNumber, sigval value) override; /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}) override; /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy) override; /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - EINVAL - thread is already started; * - EINVAL - internal thread object was detached; * - error codes returned by scheduler::Scheduler::add(); */ int start() override; DynamicThread(const DynamicThread&) = delete; DynamicThread(DynamicThread&&) = default; const DynamicThread& operator=(const DynamicThread&) = delete; DynamicThread& operator=(DynamicThread&&) = delete; private: /// internal thread object std::unique_ptr<internal::DynamicThreadBase> detachableThread_; }; #else // !def CONFIG_THREAD_DETACH_ENABLE class DynamicThread : public internal::DynamicThreadBase { public: using internal::DynamicThreadBase::DynamicThreadBase; }; #endif // !def CONFIG_THREAD_DETACH_ENABLE /** * \brief Helper factory function to make DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeDynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) { return {stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...}; } /** * \brief Helper factory function to make DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeDynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) { return {parameters, std::forward<Function>(function), std::forward<Args>(args)...}; } /** * \brief Helper factory function to make and start DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeAndStartDynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) { auto thread = makeDynamicThread(stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...); { const auto ret = thread.start(); assert(ret == 0 && "Could not start thread!"); } return thread; } /** * \brief Helper factory function to make and start DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeAndStartDynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) { auto thread = makeDynamicThread(parameters, std::forward<Function>(function), std::forward<Args>(args)...); { const auto ret = thread.start(); assert(ret == 0 && "Could not start thread!"); } return thread; } /// \} #ifdef CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThread::DynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : detachableThread_{new internal::DynamicThreadBase{stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, *this, std::forward<Function>(function), std::forward<Args>(args)...}} { } #endif // def CONFIG_THREAD_DETACH_ENABLE } // namespace distortos #endif // INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ <commit_msg>DynamicThread::generateSignal() may return ENOMEM<commit_after>/** * \file * \brief DynamicThread class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ #define INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ #include "distortos/internal/scheduler/DynamicThreadBase.hpp" #include "distortos/assert.h" namespace distortos { /// \addtogroup threads /// \{ /** * \brief DynamicThread class is a type-erased interface for thread that has dynamic storage for bound function, stack * and internal DynamicSignalsReceiver object. */ #ifdef CONFIG_THREAD_DETACH_ENABLE class DynamicThread : public Thread { public: /** * \brief DynamicThread's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThread(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThread's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThread{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } /** * \brief DynamicThread's destructor */ ~DynamicThread() override; /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; /** * \brief Generates signal for thread. * * Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html * * Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be * unblocked. * * \param [in] signalNumber is the signal that will be generated, [0; 31] * * \return 0 on success, error code otherwise: * - EINVAL - \a signalNumber value is invalid; * - ENOMEM - amount of free stack is too small to request delivery of signals; * - ENOTSUP - reception of signals is disabled for this thread; * - EINVAL - internal thread object was detached; * * \ingroup signals */ int generateSignal(uint8_t signalNumber) override; /** * \return effective priority of thread */ uint8_t getEffectivePriority() const override; /** * \brief Gets set of currently pending signals. * * Similar to sigpending() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigpending.html * * This function shall return the set of signals that are blocked from delivery and are pending on the thread. * * \return set of currently pending signals * * \ingroup signals */ SignalSet getPendingSignalSet() const override; /** * \return priority of thread */ uint8_t getPriority() const override; /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const override; /** * \return current state of thread */ ThreadState getState() const override; /** * \brief Waits for thread termination. * * Similar to std::thread::join() - http://en.cppreference.com/w/cpp/thread/thread/join * Similar to POSIX pthread_join() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html * * Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to * join() on the same target thread are undefined. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EDEADLK - deadlock condition was detected, * - EINVAL - this thread is not joinable, * - EINVAL - internal thread object was detached; * - ... * * \ingroup synchronization */ int join() override; /** * \brief Queues signal for thread. * * Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html * * Adds the signalNumber and signal value (sigval union) to queue of SignalInformation objects. If this thread is * currently waiting for this signal, it will be unblocked. * * \param [in] signalNumber is the signal that will be queued, [0; 31] * \param [in] value is the signal value * * \return 0 on success, error code otherwise: * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in * associated queue of SignalInformation objects; * - EINVAL - \a signalNumber value is invalid; * - ENOTSUP - reception or queuing of signals are disabled for this thread; * - EINVAL - internal thread object was detached; * * \ingroup signals */ int queueSignal(uint8_t signalNumber, sigval value) override; /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}) override; /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy) override; /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - EINVAL - thread is already started; * - EINVAL - internal thread object was detached; * - error codes returned by scheduler::Scheduler::add(); */ int start() override; DynamicThread(const DynamicThread&) = delete; DynamicThread(DynamicThread&&) = default; const DynamicThread& operator=(const DynamicThread&) = delete; DynamicThread& operator=(DynamicThread&&) = delete; private: /// internal thread object std::unique_ptr<internal::DynamicThreadBase> detachableThread_; }; #else // !def CONFIG_THREAD_DETACH_ENABLE class DynamicThread : public internal::DynamicThreadBase { public: using internal::DynamicThreadBase::DynamicThreadBase; }; #endif // !def CONFIG_THREAD_DETACH_ENABLE /** * \brief Helper factory function to make DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeDynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) { return {stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...}; } /** * \brief Helper factory function to make DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeDynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) { return {parameters, std::forward<Function>(function), std::forward<Args>(args)...}; } /** * \brief Helper factory function to make and start DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeAndStartDynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) { auto thread = makeDynamicThread(stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...); { const auto ret = thread.start(); assert(ret == 0 && "Could not start thread!"); } return thread; } /** * \brief Helper factory function to make and start DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeAndStartDynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) { auto thread = makeDynamicThread(parameters, std::forward<Function>(function), std::forward<Args>(args)...); { const auto ret = thread.start(); assert(ret == 0 && "Could not start thread!"); } return thread; } /// \} #ifdef CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThread::DynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : detachableThread_{new internal::DynamicThreadBase{stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, *this, std::forward<Function>(function), std::forward<Args>(args)...}} { } #endif // def CONFIG_THREAD_DETACH_ENABLE } // namespace distortos #endif // INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ <|endoftext|>
<commit_before>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "xeumeuleu_test_pch.h" #include <xeumeuleu/xml.hpp> namespace { template< typename T > std::string write( const T& value ) { xml::xostringstream xos; xos << xml::content( "element", value ); return xos.str(); } std::string format( const std::string& value ) { return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element>" + value + "</element>\n"; } } // ----------------------------------------------------------------------------- // Name: reading_empty_content_throws_proper_exception // Created: MCO 2007-09-09 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( reading_empty_content_throws_proper_exception ) { xml::xistringstream xis( "<element/>" ); std::string value; try { xis >> xml::content( "element", value ); } catch( std::exception& e ) { BOOST_CHECK_EQUAL( "string_input (line 1, column 11) : node 'element' does not have a content", e.what() ); return; } BOOST_FAIL( "should have thrown" ); } // ----------------------------------------------------------------------------- // Name: streaming_content_writes_text_content_as_it_is // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_writes_text_content_as_it_is ) { BOOST_CHECK_EQUAL( format( " this is the content " ), write< const char* >( " this is the content " ) ); } namespace { template< typename T > void check_numeric_limits() { { const T value = std::numeric_limits< T >::max(); std::stringstream stream; stream << value; BOOST_CHECK_EQUAL( format( stream.str() ), write< T >( value ) ); } { const T value = std::numeric_limits< T >::min(); std::stringstream stream; stream << value; BOOST_CHECK_EQUAL( format( stream.str() ), write< T >( value ) ); } } } // ----------------------------------------------------------------------------- // Name: streaming_content_writes_node_content // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_writes_node_content ) { check_numeric_limits< short >(); check_numeric_limits< int >(); check_numeric_limits< long >(); check_numeric_limits< long long >(); check_numeric_limits< float >(); check_numeric_limits< double >(); check_numeric_limits< long double >(); check_numeric_limits< unsigned short >(); check_numeric_limits< unsigned int >(); check_numeric_limits< unsigned long >(); check_numeric_limits< unsigned long long >(); } // ----------------------------------------------------------------------------- // Name: streaming_content_writes_node_special_value_content // Created: MCO 2007-09-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_writes_node_special_value_content ) { BOOST_CHECK_EQUAL( format( "INF" ), write< float >( std::numeric_limits< float >::infinity() ) ); BOOST_CHECK_EQUAL( format( "-INF" ), write< float >( - std::numeric_limits< float >::infinity() ) ); BOOST_CHECK_EQUAL( format( "NaN" ), write< float >( std::numeric_limits< float >::quiet_NaN() ) ); BOOST_CHECK_EQUAL( format( "NaN" ), write< float >( std::numeric_limits< float >::signaling_NaN() ) ); BOOST_CHECK_EQUAL( format( "INF" ), write< double >( std::numeric_limits< double >::infinity() ) ); BOOST_CHECK_EQUAL( format( "-INF" ), write< double >( - std::numeric_limits< double >::infinity() ) ); BOOST_CHECK_EQUAL( format( "NaN" ), write< double >( std::numeric_limits< double >::quiet_NaN() ) ); BOOST_CHECK_EQUAL( format( "NaN" ), write< double >( std::numeric_limits< double >::signaling_NaN() ) ); } // ----------------------------------------------------------------------------- // Name: streaming_stack_content_writes_node_content // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_stack_content_writes_node_content ) { BOOST_CHECK_EQUAL( format( "7" ), write< int >( 7 ) ); BOOST_CHECK_EQUAL( format( "17.23" ), write< double >( 17.23 ) ); BOOST_CHECK_EQUAL( format( "1.23" ), write< float >( 1.23f ) ); } namespace { template< typename T > T read( const std::string& value ) { T result; xml::xistringstream xis( "<element> " + value + " </element>"); xis >> xml::content( "element", result ); return result; } } // ----------------------------------------------------------------------------- // Name: streaming_content_reads_node_content // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_reads_node_content ) { BOOST_CHECK_EQUAL( " this is the value ", read< std::string >( "this is the value" ) ); BOOST_CHECK_EQUAL( 1.23f, read< float >( "1.23" ) ); BOOST_CHECK_EQUAL( 17.23f, read< float >( "17.23" ) ); BOOST_CHECK_EQUAL( 1e+99, read< double >( "1e+99" ) ); BOOST_CHECK_EQUAL( 17.23, read< double >( "17.23" ) ); BOOST_CHECK_EQUAL( 12, read< int >( "12" ) ); BOOST_CHECK_EQUAL( 32767, read< short >( "32767" ) ); BOOST_CHECK_EQUAL( true, read< bool >( "true" ) ); BOOST_CHECK_EQUAL( 5, read< long >( "5" ) ); BOOST_CHECK_EQUAL( -777, read< long long >( "-777" ) ); BOOST_CHECK_EQUAL( 4294967295u, read< unsigned int >( "4294967295" ) ); BOOST_CHECK_EQUAL( 65535u, read< unsigned short >( "65535" ) ); BOOST_CHECK_EQUAL( 4294967295u, read< unsigned long >( "4294967295" ) ); BOOST_CHECK_EQUAL( 4294967295u, read< unsigned long long >( "4294967295" ) ); BOOST_CHECK_EQUAL( std::numeric_limits< float >::infinity(), read< float >( "INF" ) ); BOOST_CHECK_EQUAL( - std::numeric_limits< float >::infinity(), read< float >( "-INF" ) ); { const float NaN = read< float >( "NaN" ); BOOST_CHECK( NaN != NaN ); } BOOST_CHECK_EQUAL( std::numeric_limits< double >::infinity(), read< double >( "INF" ) ); BOOST_CHECK_EQUAL( - std::numeric_limits< double >::infinity(), read< double >( "-INF" ) ); { const double NaN = read< double >( "NaN" ); BOOST_CHECK( NaN != NaN ); } } // ----------------------------------------------------------------------------- // Name: streaming_content_with_invalid_format_throws_an_exception // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_with_invalid_format_throws_an_exception ) { BOOST_CHECK_THROW( read< int >( "12.3" ), xml::exception ); BOOST_CHECK_THROW( read< short >( "300000" ), xml::exception ); BOOST_CHECK_THROW( read< unsigned int >( "12.3" ), xml::exception ); BOOST_CHECK_THROW( read< unsigned int >( "-42" ), xml::exception ); BOOST_CHECK_THROW( read< float >( "1e+99" ), xml::exception ); BOOST_CHECK_THROW( read< float >( "not a number" ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: read_content_directly_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_content_directly_is_valid ) { xml::xistringstream xis( "<element>the content value</element>" ); BOOST_CHECK_EQUAL( "the content value", xis.content< std::string >( "element" ) ); } // ----------------------------------------------------------------------------- // Name: read_content_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_content_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element>the content value</element>" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( "the content value", xis.content( "element", value ) ); } // ----------------------------------------------------------------------------- // Name: read_unexisting_content_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_unexisting_content_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element/>" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( value, xis.content( "element", value ) ); } // ----------------------------------------------------------------------------- // Name: read_content_in_namespace_is_valid // Created: MCO 2008-11-23 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_content_in_namespace_is_valid ) { xml::xistringstream xis( "<ns:element xmlns:ns='http://www.example.org'>the content value</ns:element>" ); const std::string expected = "the content value"; std::string actual; xis >> xml::content( "ns:element", actual ); BOOST_CHECK_EQUAL( expected, actual ); } namespace { class user_type {}; } namespace xml { xistream& operator>>( xistream& xis, user_type& ) { return xis; } } // ----------------------------------------------------------------------------- // Name: reading_content_can_be_specialized_for_user_types // Created: MCO 2009-05-30 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( reading_content_can_be_specialized_for_user_types ) { xml::xistringstream xis( "<root/>" ); user_type u; xis >> xml::content( "root", u ); } // ----------------------------------------------------------------------------- // Name: direct_reading_content_can_be_specialized_for_user_types // Created: MCO 2009-05-30 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( direct_reading_content_can_be_specialized_for_user_types ) { xml::xistringstream xis( "<root/>" ); xis.content< user_type >( "root" ); } <commit_msg>Added test to describe the behaviour of serialising several pieces of data in content<commit_after>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "xeumeuleu_test_pch.h" #include <xeumeuleu/xml.hpp> namespace { template< typename T > std::string write( const T& value ) { xml::xostringstream xos; xos << xml::content( "element", value ); return xos.str(); } std::string format( const std::string& value ) { return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element>" + value + "</element>\n"; } } // ----------------------------------------------------------------------------- // Name: reading_empty_content_throws_proper_exception // Created: MCO 2007-09-09 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( reading_empty_content_throws_proper_exception ) { xml::xistringstream xis( "<element/>" ); std::string value; try { xis >> xml::content( "element", value ); } catch( std::exception& e ) { BOOST_CHECK_EQUAL( "string_input (line 1, column 11) : node 'element' does not have a content", e.what() ); return; } BOOST_FAIL( "should have thrown" ); } // ----------------------------------------------------------------------------- // Name: streaming_content_writes_text_content_as_it_is // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_writes_text_content_as_it_is ) { BOOST_CHECK_EQUAL( format( " this is the content " ), write< const char* >( " this is the content " ) ); } // ----------------------------------------------------------------------------- // Name: streaming_content_in_two_parts_concatenates_content // Created: MCO 2009-11-26 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_in_two_parts_concatenates_content ) { xml::xostringstream xos; xos << xml::start( "element" ) << "the value " << 12; BOOST_CHECK_EQUAL( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element>the value 12</element>\n", xos.str() ); } namespace { template< typename T > void check_numeric_limits() { { const T value = std::numeric_limits< T >::max(); std::stringstream stream; stream << value; BOOST_CHECK_EQUAL( format( stream.str() ), write< T >( value ) ); } { const T value = std::numeric_limits< T >::min(); std::stringstream stream; stream << value; BOOST_CHECK_EQUAL( format( stream.str() ), write< T >( value ) ); } } } // ----------------------------------------------------------------------------- // Name: streaming_content_writes_node_content // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_writes_node_content ) { check_numeric_limits< short >(); check_numeric_limits< int >(); check_numeric_limits< long >(); check_numeric_limits< long long >(); check_numeric_limits< float >(); check_numeric_limits< double >(); check_numeric_limits< long double >(); check_numeric_limits< unsigned short >(); check_numeric_limits< unsigned int >(); check_numeric_limits< unsigned long >(); check_numeric_limits< unsigned long long >(); } // ----------------------------------------------------------------------------- // Name: streaming_content_writes_node_special_value_content // Created: MCO 2007-09-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_writes_node_special_value_content ) { BOOST_CHECK_EQUAL( format( "INF" ), write< float >( std::numeric_limits< float >::infinity() ) ); BOOST_CHECK_EQUAL( format( "-INF" ), write< float >( - std::numeric_limits< float >::infinity() ) ); BOOST_CHECK_EQUAL( format( "NaN" ), write< float >( std::numeric_limits< float >::quiet_NaN() ) ); BOOST_CHECK_EQUAL( format( "NaN" ), write< float >( std::numeric_limits< float >::signaling_NaN() ) ); BOOST_CHECK_EQUAL( format( "INF" ), write< double >( std::numeric_limits< double >::infinity() ) ); BOOST_CHECK_EQUAL( format( "-INF" ), write< double >( - std::numeric_limits< double >::infinity() ) ); BOOST_CHECK_EQUAL( format( "NaN" ), write< double >( std::numeric_limits< double >::quiet_NaN() ) ); BOOST_CHECK_EQUAL( format( "NaN" ), write< double >( std::numeric_limits< double >::signaling_NaN() ) ); } // ----------------------------------------------------------------------------- // Name: streaming_stack_content_writes_node_content // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_stack_content_writes_node_content ) { BOOST_CHECK_EQUAL( format( "7" ), write< int >( 7 ) ); BOOST_CHECK_EQUAL( format( "17.23" ), write< double >( 17.23 ) ); BOOST_CHECK_EQUAL( format( "1.23" ), write< float >( 1.23f ) ); } namespace { template< typename T > T read( const std::string& value ) { T result; xml::xistringstream xis( "<element> " + value + " </element>"); xis >> xml::content( "element", result ); return result; } } // ----------------------------------------------------------------------------- // Name: streaming_content_reads_node_content // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_reads_node_content ) { BOOST_CHECK_EQUAL( " this is the value ", read< std::string >( "this is the value" ) ); BOOST_CHECK_EQUAL( 1.23f, read< float >( "1.23" ) ); BOOST_CHECK_EQUAL( 17.23f, read< float >( "17.23" ) ); BOOST_CHECK_EQUAL( 1e+99, read< double >( "1e+99" ) ); BOOST_CHECK_EQUAL( 17.23, read< double >( "17.23" ) ); BOOST_CHECK_EQUAL( 12, read< int >( "12" ) ); BOOST_CHECK_EQUAL( 32767, read< short >( "32767" ) ); BOOST_CHECK_EQUAL( true, read< bool >( "true" ) ); BOOST_CHECK_EQUAL( 5, read< long >( "5" ) ); BOOST_CHECK_EQUAL( -777, read< long long >( "-777" ) ); BOOST_CHECK_EQUAL( 4294967295u, read< unsigned int >( "4294967295" ) ); BOOST_CHECK_EQUAL( 65535u, read< unsigned short >( "65535" ) ); BOOST_CHECK_EQUAL( 4294967295u, read< unsigned long >( "4294967295" ) ); BOOST_CHECK_EQUAL( 4294967295u, read< unsigned long long >( "4294967295" ) ); BOOST_CHECK_EQUAL( std::numeric_limits< float >::infinity(), read< float >( "INF" ) ); BOOST_CHECK_EQUAL( - std::numeric_limits< float >::infinity(), read< float >( "-INF" ) ); { const float NaN = read< float >( "NaN" ); BOOST_CHECK( NaN != NaN ); } BOOST_CHECK_EQUAL( std::numeric_limits< double >::infinity(), read< double >( "INF" ) ); BOOST_CHECK_EQUAL( - std::numeric_limits< double >::infinity(), read< double >( "-INF" ) ); { const double NaN = read< double >( "NaN" ); BOOST_CHECK( NaN != NaN ); } } // ----------------------------------------------------------------------------- // Name: streaming_content_with_invalid_format_throws_an_exception // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_content_with_invalid_format_throws_an_exception ) { BOOST_CHECK_THROW( read< int >( "12.3" ), xml::exception ); BOOST_CHECK_THROW( read< short >( "300000" ), xml::exception ); BOOST_CHECK_THROW( read< unsigned int >( "12.3" ), xml::exception ); BOOST_CHECK_THROW( read< unsigned int >( "-42" ), xml::exception ); BOOST_CHECK_THROW( read< float >( "1e+99" ), xml::exception ); BOOST_CHECK_THROW( read< float >( "not a number" ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: read_content_directly_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_content_directly_is_valid ) { xml::xistringstream xis( "<element>the content value</element>" ); BOOST_CHECK_EQUAL( "the content value", xis.content< std::string >( "element" ) ); } // ----------------------------------------------------------------------------- // Name: read_content_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_content_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element>the content value</element>" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( "the content value", xis.content( "element", value ) ); } // ----------------------------------------------------------------------------- // Name: read_unexisting_content_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_unexisting_content_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element/>" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( value, xis.content( "element", value ) ); } // ----------------------------------------------------------------------------- // Name: read_content_in_namespace_is_valid // Created: MCO 2008-11-23 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_content_in_namespace_is_valid ) { xml::xistringstream xis( "<ns:element xmlns:ns='http://www.example.org'>the content value</ns:element>" ); const std::string expected = "the content value"; std::string actual; xis >> xml::content( "ns:element", actual ); BOOST_CHECK_EQUAL( expected, actual ); } namespace { class user_type {}; } namespace xml { xistream& operator>>( xistream& xis, user_type& ) { return xis; } } // ----------------------------------------------------------------------------- // Name: reading_content_can_be_specialized_for_user_types // Created: MCO 2009-05-30 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( reading_content_can_be_specialized_for_user_types ) { xml::xistringstream xis( "<root/>" ); user_type u; xis >> xml::content( "root", u ); } // ----------------------------------------------------------------------------- // Name: direct_reading_content_can_be_specialized_for_user_types // Created: MCO 2009-05-30 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( direct_reading_content_can_be_specialized_for_user_types ) { xml::xistringstream xis( "<root/>" ); xis.content< user_type >( "root" ); } <|endoftext|>
<commit_before>/** * \file * \brief DynamicThread class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ #define INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ #include "distortos/internal/scheduler/DynamicThreadBase.hpp" #include "distortos/assert.h" namespace distortos { /// \addtogroup threads /// \{ /** * \brief DynamicThread class is a type-erased interface for thread that has dynamic storage for bound function, stack * and internal DynamicSignalsReceiver object. */ #ifdef CONFIG_THREAD_DETACH_ENABLE class DynamicThread : public Thread { public: /** * \brief DynamicThread's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThread(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThread's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThread{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } /** * \brief DynamicThread's destructor */ ~DynamicThread() override; /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; /** * \brief Generates signal for thread. * * Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html * * Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be * unblocked. * * \param [in] signalNumber is the signal that will be generated, [0; 31] * * \return 0 on success, error code otherwise: * - EINVAL - internal thread object was detached; * - EINVAL - \a signalNumber value is invalid; * - ENOMEM - amount of free stack is too small to request delivery of signals; * - ENOTSUP - reception of signals is disabled for this thread; * * \ingroup signals */ int generateSignal(uint8_t signalNumber) override; /** * \return effective priority of thread */ uint8_t getEffectivePriority() const override; /** * \brief Gets set of currently pending signals. * * Similar to sigpending() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigpending.html * * This function shall return the set of signals that are blocked from delivery and are pending on the thread. * * \return set of currently pending signals * * \ingroup signals */ SignalSet getPendingSignalSet() const override; /** * \return priority of thread */ uint8_t getPriority() const override; /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const override; /** * \return "high water mark" (max usage) of thread's stack, bytes */ size_t getStackHighWaterMark() const override; /** * \return size of thread's stack, bytes */ size_t getStackSize() const override; /** * \return current state of thread */ ThreadState getState() const override; /** * \brief Waits for thread termination. * * Similar to std::thread::join() - http://en.cppreference.com/w/cpp/thread/thread/join * Similar to POSIX pthread_join() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html * * Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to * join() on the same target thread are undefined. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EDEADLK - deadlock condition was detected, * - EINVAL - this thread is not joinable, * - EINVAL - internal thread object was detached; * - ... * * \ingroup synchronization */ int join() override; /** * \brief Queues signal for thread. * * Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html * * Adds the signalNumber and signal value (sigval union) to queue of SignalInformation objects. If this thread is * currently waiting for this signal, it will be unblocked. * * \param [in] signalNumber is the signal that will be queued, [0; 31] * \param [in] value is the signal value * * \return 0 on success, error code otherwise: * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in * associated queue of SignalInformation objects; * - EINVAL - internal thread object was detached; * - EINVAL - \a signalNumber value is invalid; * - ENOMEM - amount of free stack is too small to request delivery of signals; * - ENOTSUP - reception or queuing of signals are disabled for this thread; * * \ingroup signals */ int queueSignal(uint8_t signalNumber, sigval value) override; /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}) override; /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy) override; /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - EINVAL - thread is already started; * - EINVAL - internal thread object was detached; * - error codes returned by internal::Scheduler::add(); */ int start(); DynamicThread(const DynamicThread&) = delete; DynamicThread(DynamicThread&&) = default; const DynamicThread& operator=(const DynamicThread&) = delete; DynamicThread& operator=(DynamicThread&&) = delete; private: /// internal thread object std::unique_ptr<internal::DynamicThreadBase> detachableThread_; }; #else // !def CONFIG_THREAD_DETACH_ENABLE class DynamicThread : public internal::DynamicThreadBase { public: using internal::DynamicThreadBase::DynamicThreadBase; }; #endif // !def CONFIG_THREAD_DETACH_ENABLE /** * \brief Helper factory function to make DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeDynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) { return {stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...}; } /** * \brief Helper factory function to make DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeDynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) { return {parameters, std::forward<Function>(function), std::forward<Args>(args)...}; } /** * \brief Helper factory function to make and start DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeAndStartDynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) { auto thread = makeDynamicThread(stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...); { const auto ret = thread.start(); assert(ret == 0 && "Could not start thread!"); } return thread; } /** * \brief Helper factory function to make and start DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeAndStartDynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) { auto thread = makeDynamicThread(parameters, std::forward<Function>(function), std::forward<Args>(args)...); { const auto ret = thread.start(); assert(ret == 0 && "Could not start thread!"); } return thread; } /// \} #ifdef CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThread::DynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : detachableThread_{new internal::DynamicThreadBase{stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, *this, std::forward<Function>(function), std::forward<Args>(args)...}} { } #endif // def CONFIG_THREAD_DETACH_ENABLE } // namespace distortos #endif // INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ <commit_msg>Simplify comment for DynamicThread::start()<commit_after>/** * \file * \brief DynamicThread class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ #define INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ #include "distortos/internal/scheduler/DynamicThreadBase.hpp" #include "distortos/assert.h" namespace distortos { /// \addtogroup threads /// \{ /** * \brief DynamicThread class is a type-erased interface for thread that has dynamic storage for bound function, stack * and internal DynamicSignalsReceiver object. */ #ifdef CONFIG_THREAD_DETACH_ENABLE class DynamicThread : public Thread { public: /** * \brief DynamicThread's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThread(size_t stackSize, bool canReceiveSignals, size_t queuedSignals, size_t signalActions, uint8_t priority, SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args); /** * \brief DynamicThread's constructor * * \tparam Function is the function that will be executed in separate thread * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function */ template<typename Function, typename... Args> DynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) : DynamicThread{parameters.stackSize, parameters.canReceiveSignals, parameters.queuedSignals, parameters.signalActions, parameters.priority, parameters.schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...} { } /** * \brief DynamicThread's destructor */ ~DynamicThread() override; /** * \brief Detaches the thread. * * Similar to std::thread::detach() - http://en.cppreference.com/w/cpp/thread/thread/detach * Similar to POSIX pthread_detach() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_detach.html * * Detaches the executing thread from the Thread object, allowing execution to continue independently. All resources * allocated for the thread will be deallocated when the thread terminates. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EINVAL - this thread is already detached; */ int detach() override; /** * \brief Generates signal for thread. * * Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html * * Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be * unblocked. * * \param [in] signalNumber is the signal that will be generated, [0; 31] * * \return 0 on success, error code otherwise: * - EINVAL - internal thread object was detached; * - EINVAL - \a signalNumber value is invalid; * - ENOMEM - amount of free stack is too small to request delivery of signals; * - ENOTSUP - reception of signals is disabled for this thread; * * \ingroup signals */ int generateSignal(uint8_t signalNumber) override; /** * \return effective priority of thread */ uint8_t getEffectivePriority() const override; /** * \brief Gets set of currently pending signals. * * Similar to sigpending() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigpending.html * * This function shall return the set of signals that are blocked from delivery and are pending on the thread. * * \return set of currently pending signals * * \ingroup signals */ SignalSet getPendingSignalSet() const override; /** * \return priority of thread */ uint8_t getPriority() const override; /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const override; /** * \return "high water mark" (max usage) of thread's stack, bytes */ size_t getStackHighWaterMark() const override; /** * \return size of thread's stack, bytes */ size_t getStackSize() const override; /** * \return current state of thread */ ThreadState getState() const override; /** * \brief Waits for thread termination. * * Similar to std::thread::join() - http://en.cppreference.com/w/cpp/thread/thread/join * Similar to POSIX pthread_join() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html * * Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to * join() on the same target thread are undefined. * * \warning This function must not be called from interrupt context! * * \return 0 on success, error code otherwise: * - EDEADLK - deadlock condition was detected, * - EINVAL - this thread is not joinable, * - EINVAL - internal thread object was detached; * - ... * * \ingroup synchronization */ int join() override; /** * \brief Queues signal for thread. * * Similar to sigqueue() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigqueue.html * * Adds the signalNumber and signal value (sigval union) to queue of SignalInformation objects. If this thread is * currently waiting for this signal, it will be unblocked. * * \param [in] signalNumber is the signal that will be queued, [0; 31] * \param [in] value is the signal value * * \return 0 on success, error code otherwise: * - EAGAIN - no resources are available to queue the signal, maximal number of signals is already queued in * associated queue of SignalInformation objects; * - EINVAL - internal thread object was detached; * - EINVAL - \a signalNumber value is invalid; * - ENOMEM - amount of free stack is too small to request delivery of signals; * - ENOTSUP - reception or queuing of signals are disabled for this thread; * * \ingroup signals */ int queueSignal(uint8_t signalNumber, sigval value) override; /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}) override; /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy) override; /** * \brief Starts the thread. * * This operation can be performed on threads in "New" state only. * * \return 0 on success, error code otherwise: * - EINVAL - internal thread object was detached; * - error codes returned by internal::DynamicThreadBase::start(); */ int start(); DynamicThread(const DynamicThread&) = delete; DynamicThread(DynamicThread&&) = default; const DynamicThread& operator=(const DynamicThread&) = delete; DynamicThread& operator=(DynamicThread&&) = delete; private: /// internal thread object std::unique_ptr<internal::DynamicThreadBase> detachableThread_; }; #else // !def CONFIG_THREAD_DETACH_ENABLE class DynamicThread : public internal::DynamicThreadBase { public: using internal::DynamicThreadBase::DynamicThreadBase; }; #endif // !def CONFIG_THREAD_DETACH_ENABLE /** * \brief Helper factory function to make DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeDynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) { return {stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...}; } /** * \brief Helper factory function to make DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeDynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) { return {parameters, std::forward<Function>(function), std::forward<Args>(args)...}; } /** * \brief Helper factory function to make and start DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] stackSize is the size of stack, bytes * \param [in] canReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this * thread * \param [in] queuedSignals is the max number of queued signals for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable queuing of signals for this thread * \param [in] signalActions is the max number of different SignalAction objects for this thread, relevant only if * \a canReceiveSignals == true, 0 to disable catching of signals for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeAndStartDynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) { auto thread = makeDynamicThread(stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...); { const auto ret = thread.start(); assert(ret == 0 && "Could not start thread!"); } return thread; } /** * \brief Helper factory function to make and start DynamicThread object * * \tparam Function is the function that will be executed * \tparam Args are the arguments for \a Function * * \param [in] parameters is a DynamicThreadParameters struct with thread parameters * \param [in] function is a function that will be executed in separate thread * \param [in] args are arguments for \a function * * \return DynamicThread object */ template<typename Function, typename... Args> DynamicThread makeAndStartDynamicThread(const DynamicThreadParameters parameters, Function&& function, Args&&... args) { auto thread = makeDynamicThread(parameters, std::forward<Function>(function), std::forward<Args>(args)...); { const auto ret = thread.start(); assert(ret == 0 && "Could not start thread!"); } return thread; } /// \} #ifdef CONFIG_THREAD_DETACH_ENABLE template<typename Function, typename... Args> DynamicThread::DynamicThread(const size_t stackSize, const bool canReceiveSignals, const size_t queuedSignals, const size_t signalActions, const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) : detachableThread_{new internal::DynamicThreadBase{stackSize, canReceiveSignals, queuedSignals, signalActions, priority, schedulingPolicy, *this, std::forward<Function>(function), std::forward<Args>(args)...}} { } #endif // def CONFIG_THREAD_DETACH_ENABLE } // namespace distortos #endif // INCLUDE_DISTORTOS_DYNAMICTHREAD_HPP_ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file sgd_context.hpp * \brief Stochastic Gradient Descent (SGD) context Implementation. */ #pragma once #include "etl/etl.hpp" #include "dll/layer_traits.hpp" #include "dll/dbn_traits.hpp" namespace dll { /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto num_visible = layer_t::num_visible; static constexpr const auto num_hidden = layer_t::num_hidden; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, num_visible, num_hidden> w_grad; etl::fast_matrix<weight, num_hidden> b_grad; etl::fast_matrix<weight, num_visible, num_hidden> w_inc; etl::fast_matrix<weight, num_hidden> b_inc; etl::fast_matrix<weight, batch_size, num_visible> input; etl::fast_matrix<weight, batch_size, num_hidden> output; etl::fast_matrix<weight, batch_size, num_hidden> errors; sgd_context() : w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 2> w_grad; etl::dyn_matrix<weight, 1> b_grad; etl::dyn_matrix<weight, 2> w_inc; etl::dyn_matrix<weight, 1> b_inc; etl::dyn_matrix<weight, 2> input; etl::dyn_matrix<weight, 2> output; etl::dyn_matrix<weight, 2> errors; sgd_context(std::size_t num_visible, std::size_t num_hidden) : w_grad(num_visible, num_hidden), b_grad(num_hidden), w_inc(num_visible, num_hidden, 0.0), b_inc(num_hidden, 0.0), input(batch_size, num_visible, 0.0), output(batch_size, num_hidden, 0.0), errors(batch_size, num_hidden, 0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const std::size_t NV1 = layer_t::NV1; static constexpr const std::size_t NV2 = layer_t::NV2; static constexpr const std::size_t NH1 = layer_t::NH1; static constexpr const std::size_t NH2 = layer_t::NH2; static constexpr const std::size_t NW1 = layer_t::NW1; static constexpr const std::size_t NW2 = layer_t::NW2; static constexpr const std::size_t NC = layer_t::NC; static constexpr const std::size_t K = layer_t::K; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, K, NC, NW1, NW2> w_grad; etl::fast_matrix<weight, K> b_grad; etl::fast_matrix<weight, K, NC, NW1, NW2> w_inc; etl::fast_matrix<weight, K> b_inc; etl::fast_matrix<weight, batch_size, NC, NV1, NV2> input; etl::fast_matrix<weight, batch_size, K, NH1, NH2> output; etl::fast_matrix<weight, batch_size, K, NH1, NH2> errors; sgd_context() : w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> w_grad; etl::dyn_matrix<weight, 1> b_grad; etl::dyn_matrix<weight, 4> w_inc; etl::dyn_matrix<weight, 1> b_inc; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2) : w_grad(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_grad(k), w_inc(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_inc(k), input(batch_size, nc, nv1, nv2), output(batch_size, k, nh1, nh2), errors(batch_size, k, nh1, nh2) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const std::size_t I1 = layer_t::I1; static constexpr const std::size_t I2 = layer_t::I2; static constexpr const std::size_t I3 = layer_t::I3; static constexpr const std::size_t O1 = layer_t::O1; static constexpr const std::size_t O2 = layer_t::O2; static constexpr const std::size_t O3 = layer_t::O3; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, batch_size, I1, I2, I3> input; etl::fast_matrix<weight, batch_size, O1, O2, O3> output; etl::fast_matrix<weight, batch_size, O1, O2, O3> errors; }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t i1, size_t i2, size_t i3, size_t c1, size_t c2, size_t c3) : input(batch_size, i1, i2, i3), output(batch_size, i1 / c1, i2 / c2, i3 / c3), errors(batch_size, i1 / c1, i2 / c2, i3 / c3) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_unpooling_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const std::size_t I1 = layer_t::I1; static constexpr const std::size_t I2 = layer_t::I2; static constexpr const std::size_t I3 = layer_t::I3; static constexpr const std::size_t O1 = layer_t::O1; static constexpr const std::size_t O2 = layer_t::O2; static constexpr const std::size_t O3 = layer_t::O3; static constexpr const auto batch_size = DBN::batch_size; etl::fast_matrix<weight, batch_size, I1, I2, I3> input; etl::fast_matrix<weight, batch_size, O1, O2, O3> output; etl::fast_matrix<weight, batch_size, O1, O2, O3> errors; }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_unpooling_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr const auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t i1, size_t i2, size_t i3, size_t c1, size_t c2, size_t c3) : input(batch_size, i1, i2, i3), output(batch_size, i1 * c1, i2 * c2, i3 * c3), errors(batch_size, i1 * c1, i2 * c2, i3 * c3) {} }; template <typename DBN, typename Layer> struct transform_output_type { static constexpr const auto dimensions = dbn_traits<DBN>::is_convolutional() ? 4 : 2; using weight = typename DBN::weight; using type = etl::dyn_matrix<weight, dimensions>; }; template <typename DBN, typename Layer> using transform_output_type_t = typename transform_output_type<DBN, Layer>::type; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_transform_layer()>> { using layer_t = Layer; using weight = typename DBN::weight; using inputs_t = transform_output_type_t<DBN, Layer>; inputs_t input; inputs_t output; inputs_t errors; }; } //end of dll namespace <commit_msg>More cleanup<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file sgd_context.hpp * \brief Stochastic Gradient Descent (SGD) context Implementation. */ #pragma once #include "etl/etl.hpp" #include "dll/layer_traits.hpp" #include "dll/dbn_traits.hpp" namespace dll { /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr auto num_visible = layer_t::num_visible; static constexpr auto num_hidden = layer_t::num_hidden; static constexpr auto batch_size = DBN::batch_size; etl::fast_matrix<weight, num_visible, num_hidden> w_grad; etl::fast_matrix<weight, num_hidden> b_grad; etl::fast_matrix<weight, num_visible, num_hidden> w_inc; etl::fast_matrix<weight, num_hidden> b_inc; etl::fast_matrix<weight, batch_size, num_visible> input; etl::fast_matrix<weight, batch_size, num_hidden> output; etl::fast_matrix<weight, batch_size, num_hidden> errors; sgd_context() : w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 2> w_grad; etl::dyn_matrix<weight, 1> b_grad; etl::dyn_matrix<weight, 2> w_inc; etl::dyn_matrix<weight, 1> b_inc; etl::dyn_matrix<weight, 2> input; etl::dyn_matrix<weight, 2> output; etl::dyn_matrix<weight, 2> errors; sgd_context(size_t num_visible, size_t num_hidden) : w_grad(num_visible, num_hidden), b_grad(num_hidden), w_inc(num_visible, num_hidden, 0.0), b_inc(num_hidden, 0.0), input(batch_size, num_visible, 0.0), output(batch_size, num_hidden, 0.0), errors(batch_size, num_hidden, 0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr size_t NV1 = layer_t::NV1; static constexpr size_t NV2 = layer_t::NV2; static constexpr size_t NH1 = layer_t::NH1; static constexpr size_t NH2 = layer_t::NH2; static constexpr size_t NW1 = layer_t::NW1; static constexpr size_t NW2 = layer_t::NW2; static constexpr size_t NC = layer_t::NC; static constexpr size_t K = layer_t::K; static constexpr auto batch_size = DBN::batch_size; etl::fast_matrix<weight, K, NC, NW1, NW2> w_grad; etl::fast_matrix<weight, K> b_grad; etl::fast_matrix<weight, K, NC, NW1, NW2> w_inc; etl::fast_matrix<weight, K> b_inc; etl::fast_matrix<weight, batch_size, NC, NV1, NV2> input; etl::fast_matrix<weight, batch_size, K, NH1, NH2> output; etl::fast_matrix<weight, batch_size, K, NH1, NH2> errors; sgd_context() : w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> w_grad; etl::dyn_matrix<weight, 1> b_grad; etl::dyn_matrix<weight, 4> w_inc; etl::dyn_matrix<weight, 1> b_inc; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2) : w_grad(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_grad(k), w_inc(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_inc(k), input(batch_size, nc, nv1, nv2), output(batch_size, k, nh1, nh2), errors(batch_size, k, nh1, nh2) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr size_t I1 = layer_t::I1; static constexpr size_t I2 = layer_t::I2; static constexpr size_t I3 = layer_t::I3; static constexpr size_t O1 = layer_t::O1; static constexpr size_t O2 = layer_t::O2; static constexpr size_t O3 = layer_t::O3; static constexpr auto batch_size = DBN::batch_size; etl::fast_matrix<weight, batch_size, I1, I2, I3> input; etl::fast_matrix<weight, batch_size, O1, O2, O3> output; etl::fast_matrix<weight, batch_size, O1, O2, O3> errors; }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t i1, size_t i2, size_t i3, size_t c1, size_t c2, size_t c3) : input(batch_size, i1, i2, i3), output(batch_size, i1 / c1, i2 / c2, i3 / c3), errors(batch_size, i1 / c1, i2 / c2, i3 / c3) {} }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_unpooling_layer() && !layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr size_t I1 = layer_t::I1; static constexpr size_t I2 = layer_t::I2; static constexpr size_t I3 = layer_t::I3; static constexpr size_t O1 = layer_t::O1; static constexpr size_t O2 = layer_t::O2; static constexpr size_t O3 = layer_t::O3; static constexpr auto batch_size = DBN::batch_size; etl::fast_matrix<weight, batch_size, I1, I2, I3> input; etl::fast_matrix<weight, batch_size, O1, O2, O3> output; etl::fast_matrix<weight, batch_size, O1, O2, O3> errors; }; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_unpooling_layer() && layer_traits<Layer>::is_dynamic()>> { using layer_t = Layer; using weight = typename layer_t::weight; static constexpr auto batch_size = DBN::batch_size; etl::dyn_matrix<weight, 4> input; etl::dyn_matrix<weight, 4> output; etl::dyn_matrix<weight, 4> errors; sgd_context(size_t i1, size_t i2, size_t i3, size_t c1, size_t c2, size_t c3) : input(batch_size, i1, i2, i3), output(batch_size, i1 * c1, i2 * c2, i3 * c3), errors(batch_size, i1 * c1, i2 * c2, i3 * c3) {} }; template <typename DBN, typename Layer> struct transform_output_type { static constexpr auto dimensions = dbn_traits<DBN>::is_convolutional() ? 4 : 2; using weight = typename DBN::weight; using type = etl::dyn_matrix<weight, dimensions>; }; template <typename DBN, typename Layer> using transform_output_type_t = typename transform_output_type<DBN, Layer>::type; /*! * \copydoc sgd_context */ template <typename DBN, typename Layer> struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_transform_layer()>> { using layer_t = Layer; using weight = typename DBN::weight; using inputs_t = transform_output_type_t<DBN, Layer>; inputs_t input; inputs_t output; inputs_t errors; }; } //end of dll namespace <|endoftext|>
<commit_before>#ifndef ENGINE_RESPONSE_OBJECTS_HPP_ #define ENGINE_RESPONSE_OBJECTS_HPP_ #include "extractor/turn_instructions.hpp" #include "extractor/travel_mode.hpp" #include "engine/polyline_compressor.hpp" #include "util/coordinate.hpp" #include "util/json_container.hpp" #include <boost/optional.hpp> #include <string> #include <algorithm> #include <vector> namespace osrm { namespace engine { struct Hint; namespace guidance { class RouteLeg; class RouteStep; class StepManeuver; class Route; class LegGeometry; } namespace api { namespace json { namespace detail { std::string instructionToString(extractor::TurnInstruction instruction); util::json::Array coordinateToLonLat(const util::Coordinate coordinate); std::string modeToString(const extractor::TravelMode mode); } // namespace detail template <typename ForwardIter> util::json::String makePolyline(ForwardIter begin, ForwardIter end) { return {encodePolyline(begin, end)}; } template <typename ForwardIter> util::json::Object makeGeoJSONLineString(ForwardIter begin, ForwardIter end) { util::json::Object geojson; geojson.values["type"] = "LineString"; util::json::Array coordinates; std::transform(begin, end, std::back_inserter(coordinates.values), [](const util::Coordinate loc) { return detail::coordinateToLonLat(loc); }); geojson.values["coordinates"] = std::move(coordinates); return geojson; } util::json::Object makeStepManeuver(const guidance::StepManeuver &maneuver); util::json::Object makeRouteStep(guidance::RouteStep &&step, boost::optional<util::json::Value> geometry); util::json::Object makeRoute(const guidance::Route &route, util::json::Array &&legs, boost::optional<util::json::Value> geometry); util::json::Object makeWaypoint(const util::Coordinate location, std::string &&name, const Hint &hint); util::json::Object makeRouteLeg(guidance::RouteLeg &&leg, util::json::Array &&steps); util::json::Array makeRouteLegs(std::vector<guidance::RouteLeg> &&legs, std::vector<util::json::Value> step_geometries); } } } // namespace engine } // namespace osrm #endif // ENGINE_GUIDANCE_API_RESPONSE_GENERATOR_HPP_ <commit_msg>Unwrap function call from identity lambda<commit_after>#ifndef ENGINE_RESPONSE_OBJECTS_HPP_ #define ENGINE_RESPONSE_OBJECTS_HPP_ #include "extractor/turn_instructions.hpp" #include "extractor/travel_mode.hpp" #include "engine/polyline_compressor.hpp" #include "util/coordinate.hpp" #include "util/json_container.hpp" #include <boost/optional.hpp> #include <string> #include <algorithm> #include <vector> namespace osrm { namespace engine { struct Hint; namespace guidance { class RouteLeg; class RouteStep; class StepManeuver; class Route; class LegGeometry; } namespace api { namespace json { namespace detail { std::string instructionToString(extractor::TurnInstruction instruction); util::json::Array coordinateToLonLat(const util::Coordinate coordinate); std::string modeToString(const extractor::TravelMode mode); } // namespace detail template <typename ForwardIter> util::json::String makePolyline(ForwardIter begin, ForwardIter end) { return {encodePolyline(begin, end)}; } template <typename ForwardIter> util::json::Object makeGeoJSONLineString(ForwardIter begin, ForwardIter end) { util::json::Object geojson; geojson.values["type"] = "LineString"; util::json::Array coordinates; std::transform(begin, end, std::back_inserter(coordinates.values), &detail::coordinateToLonLat); geojson.values["coordinates"] = std::move(coordinates); return geojson; } util::json::Object makeStepManeuver(const guidance::StepManeuver &maneuver); util::json::Object makeRouteStep(guidance::RouteStep &&step, boost::optional<util::json::Value> geometry); util::json::Object makeRoute(const guidance::Route &route, util::json::Array &&legs, boost::optional<util::json::Value> geometry); util::json::Object makeWaypoint(const util::Coordinate location, std::string &&name, const Hint &hint); util::json::Object makeRouteLeg(guidance::RouteLeg &&leg, util::json::Array &&steps); util::json::Array makeRouteLegs(std::vector<guidance::RouteLeg> &&legs, std::vector<util::json::Value> step_geometries); } } } // namespace engine } // namespace osrm #endif // ENGINE_GUIDANCE_API_RESPONSE_GENERATOR_HPP_ <|endoftext|>
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2006 Artem Pavlenko * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP #include <vector> #include <iostream> #include "envelope.hpp" #include "datasource.hpp" #include "layer.hpp" #include "map.hpp" #include "attribute_collector.hpp" #include "property_index.hpp" #include "utils.hpp" namespace mapnik { template <typename Processor> class feature_style_processor { struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output,Feature const& f) : output_(output),f_(f) {} void operator () (polygon_symbolizer const& sym) const { output_.process(sym,f_); } void operator () (polygon_pattern_symbolizer const& sym) const { output_.process(sym,f_); } void operator () (line_symbolizer const& sym) const { output_.process(sym,f_); } void operator () (line_pattern_symbolizer const& sym) const { output_.process(sym,f_); } void operator () (point_symbolizer const& sym) const { output_.process(sym,f_); } void operator () (raster_symbolizer const& sym) const { output_.process(sym,f_); } Processor & output_; Feature const& f_; }; public: feature_style_processor(Map const& m) : m_(m) {} void apply() { timer clock; Processor & p = static_cast<Processor&>(*this); std::vector<Layer>::const_iterator itr = m_.layers().begin(); while (itr != m_.layers().end()) { if (itr->isVisible(m_.scale()))// && itr->envelope().intersects(extent)) { apply_to_layer(*itr,p); } ++itr; } clock.stop(); } private: void apply_to_layer(Layer const& lay,Processor & p) { datasource *ds=lay.datasource().get(); if (ds) { Envelope<double> const& bbox=m_.getCurrentExtent(); double scale = m_.scale(); std::vector<std::string> const& style_names = lay.styles(); std::vector<std::string>::const_iterator stylesIter = style_names.begin(); while (stylesIter != style_names.end()) { std::set<std::string> names; attribute_collector<Feature> collector(names); property_index<Feature> indexer(names); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; feature_type_style const& style=m_.find_style(*stylesIter++); const std::vector<rule_type>& rules=style.get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); query q(bbox,m_.getWidth(),m_.getHeight()); while (ruleIter!=rules.end()) { if (ruleIter->active(scale)) { active_rules=true; filter_ptr& filter=const_cast<filter_ptr&>(ruleIter->get_filter()); filter->accept(collector); filter->accept(indexer); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } ++ruleIter; } std::set<std::string>::const_iterator namesIter=names.begin(); // push all property names while (namesIter!=names.end()) { q.add_property_name(*namesIter); ++namesIter; } if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); while (itr!=if_rules.end()) { filter_ptr const& filter=(*itr)->get_filter(); if (filter->pass(*feature)) { do_else=false; const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { boost::apply_visitor(symbol_dispatch(p,*feature),*symIter++); } } ++itr; } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr=else_rules.begin(); while (itr != else_rules.end()) { const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { boost::apply_visitor(symbol_dispatch(p,*feature),*symIter++); } ++itr; } } } } } } } } Map const& m_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <commit_msg>Of course,we can use one templated member functions to handle all symbolizers.<commit_after>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2006 Artem Pavlenko * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP #include <vector> #include <iostream> #include "envelope.hpp" #include "datasource.hpp" #include "layer.hpp" #include "map.hpp" #include "attribute_collector.hpp" #include "property_index.hpp" #include "utils.hpp" namespace mapnik { template <typename Processor> class feature_style_processor { struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output,Feature const& f) : output_(output),f_(f) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_); } Processor & output_; Feature const& f_; }; public: feature_style_processor(Map const& m) : m_(m) {} void apply() { timer clock; Processor & p = static_cast<Processor&>(*this); std::vector<Layer>::const_iterator itr = m_.layers().begin(); while (itr != m_.layers().end()) { if (itr->isVisible(m_.scale()))// && itr->envelope().intersects(extent)) { apply_to_layer(*itr,p); } ++itr; } clock.stop(); } private: void apply_to_layer(Layer const& lay,Processor & p) { datasource *ds=lay.datasource().get(); if (ds) { Envelope<double> const& bbox=m_.getCurrentExtent(); double scale = m_.scale(); std::vector<std::string> const& style_names = lay.styles(); std::vector<std::string>::const_iterator stylesIter = style_names.begin(); while (stylesIter != style_names.end()) { std::set<std::string> names; attribute_collector<Feature> collector(names); property_index<Feature> indexer(names); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; feature_type_style const& style=m_.find_style(*stylesIter++); const std::vector<rule_type>& rules=style.get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); query q(bbox,m_.getWidth(),m_.getHeight()); while (ruleIter!=rules.end()) { if (ruleIter->active(scale)) { active_rules=true; filter_ptr& filter=const_cast<filter_ptr&>(ruleIter->get_filter()); filter->accept(collector); filter->accept(indexer); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } ++ruleIter; } std::set<std::string>::const_iterator namesIter=names.begin(); // push all property names while (namesIter!=names.end()) { q.add_property_name(*namesIter); ++namesIter; } if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); while (itr!=if_rules.end()) { filter_ptr const& filter=(*itr)->get_filter(); if (filter->pass(*feature)) { do_else=false; const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { boost::apply_visitor(symbol_dispatch(p,*feature),*symIter++); } } ++itr; } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr=else_rules.begin(); while (itr != else_rules.end()) { const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { boost::apply_visitor(symbol_dispatch(p,*feature),*symIter++); } ++itr; } } } } } } } } Map const& m_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson * * Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GCN_TEXTBOX_HPP #define GCN_TEXTBOX_HPP #include <ctime> #include <string> #include <vector> #include "guichan/keylistener.hpp" #include "guichan/mouselistener.hpp" #include "guichan/platform.hpp" #include "guichan/widget.hpp" namespace gcn { /** * A TextBox in which you can write and/or display a lines of text. * * NOTE: A plain TextBox is really uggly and looks much better inside a * ScrollArea. */ class GCN_CORE_DECLSPEC TextBox: public Widget, public MouseListener, public KeyListener { public: /** * Constructor. */ TextBox(); /** * Constructor. * * @param text the text of the TextBox. */ TextBox(const std::string& text); /** * Sets the text. * * @param text the text of the TextBox. */ void setText(const std::string& text); /** * Gets the text. * @return the text of the TextBox. */ std::string getText() const; /** * Gets the row of a text. * * @return the text of a certain row in the TextBox. */ const std::string& getTextRow(int row) const; /** * Sets the text of a certain row in a TextBox. * * @param row the row number. * @param text the text of a certain row in the TextBox. */ void setTextRow(int row, const std::string& text); /** * Gets the number of rows in the text. * * @return the number of rows in the text. */ unsigned int getNumberOfRows() const; /** * Gets the caret position in the text. * * @return the caret position in the text. */ unsigned int getCaretPosition() const; /** * Sets the position of the caret in the text. * * @param position the positon of the caret. */ void setCaretPosition(unsigned int position); /** * Gets the row the caret is in in the text. * * @return the row the caret is in in the text. */ unsigned int getCaretRow() const; /** * Sets the row the caret should be in in the text. * * @param row the row number. */ void setCaretRow(int row); /** * Gets the column the caret is in in the text. * * @return the column the caret is in in the text. */ unsigned int getCaretColumn() const; /** * Sets the column the caret should be in in the text. * * @param column the column number. */ void setCaretColumn(int column); /** * Sets the row and the column the caret should be in in the text. * * @param row the row number. * @param column the column number. */ void setCaretRowColumn(int row, int column); /** * Scrolls the text to the caret if the TextBox is in a ScrollArea. */ virtual void scrollToCaret(); /** * Checks if the TextBox is editable. * * @return true it the TextBox is editable. */ bool isEditable() const; /** * Sets if the TextBox should be editable or not. * * @param editable true if the TextBox should be editable. */ void setEditable(bool editable); /** * Adds a text row to the text. * * @param row a row. */ virtual void addRow(const std::string row); /** * Checks if the TextBox is opaque * * @return true if the TextBox is opaque */ bool isOpaque(); /** * Sets the TextBox to be opaque. * * @param opaque true if the TextBox should be opaque. */ void setOpaque(bool opaque); // Inherited from Widget virtual void draw(Graphics* graphics); virtual void drawBorder(Graphics* graphics); virtual void fontChanged(); // Inherited from KeyListener virtual void keyPressed(KeyEvent& keyEvent); // Inherited from MouseListener virtual void mousePressed(MouseEvent& mouseEvent); virtual void mouseDragged(MouseEvent& mouseEvent); protected: /** * Draws the caret. * * @param graphics a Graphics object to draw with. * @param x the x position. * @param y the y position. */ virtual void drawCaret(Graphics* graphics, int x, int y); /** * Adjusts the TextBox size to fit the font size. */ virtual void adjustSize(); std::vector<std::string> mTextRows; int mCaretColumn; int mCaretRow; bool mEditable; bool mOpaque; }; } #endif // end GCN_TEXTBOX_HPP <commit_msg>A spelling mistake has been fixed.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson * * Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ^ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GCN_TEXTBOX_HPP #define GCN_TEXTBOX_HPP #include <ctime> #include <string> #include <vector> #include "guichan/keylistener.hpp" #include "guichan/mouselistener.hpp" #include "guichan/platform.hpp" #include "guichan/widget.hpp" namespace gcn { /** * A TextBox in which you can write and/or display a lines of text. * * NOTE: A plain TextBox is really ugly and looks much better inside a * ScrollArea. */ class GCN_CORE_DECLSPEC TextBox: public Widget, public MouseListener, public KeyListener { public: /** * Constructor. */ TextBox(); /** * Constructor. * * @param text the text of the TextBox. */ TextBox(const std::string& text); /** * Sets the text. * * @param text the text of the TextBox. */ void setText(const std::string& text); /** * Gets the text. * @return the text of the TextBox. */ std::string getText() const; /** * Gets the row of a text. * * @return the text of a certain row in the TextBox. */ const std::string& getTextRow(int row) const; /** * Sets the text of a certain row in a TextBox. * * @param row the row number. * @param text the text of a certain row in the TextBox. */ void setTextRow(int row, const std::string& text); /** * Gets the number of rows in the text. * * @return the number of rows in the text. */ unsigned int getNumberOfRows() const; /** * Gets the caret position in the text. * * @return the caret position in the text. */ unsigned int getCaretPosition() const; /** * Sets the position of the caret in the text. * * @param position the positon of the caret. */ void setCaretPosition(unsigned int position); /** * Gets the row the caret is in in the text. * * @return the row the caret is in in the text. */ unsigned int getCaretRow() const; /** * Sets the row the caret should be in in the text. * * @param row the row number. */ void setCaretRow(int row); /** * Gets the column the caret is in in the text. * * @return the column the caret is in in the text. */ unsigned int getCaretColumn() const; /** * Sets the column the caret should be in in the text. * * @param column the column number. */ void setCaretColumn(int column); /** * Sets the row and the column the caret should be in in the text. * * @param row the row number. * @param column the column number. */ void setCaretRowColumn(int row, int column); /** * Scrolls the text to the caret if the TextBox is in a ScrollArea. */ virtual void scrollToCaret(); /** * Checks if the TextBox is editable. * * @return true it the TextBox is editable. */ bool isEditable() const; /** * Sets if the TextBox should be editable or not. * * @param editable true if the TextBox should be editable. */ void setEditable(bool editable); /** * Adds a text row to the text. * * @param row a row. */ virtual void addRow(const std::string row); /** * Checks if the TextBox is opaque * * @return true if the TextBox is opaque */ bool isOpaque(); /** * Sets the TextBox to be opaque. * * @param opaque true if the TextBox should be opaque. */ void setOpaque(bool opaque); // Inherited from Widget virtual void draw(Graphics* graphics); virtual void drawBorder(Graphics* graphics); virtual void fontChanged(); // Inherited from KeyListener virtual void keyPressed(KeyEvent& keyEvent); // Inherited from MouseListener virtual void mousePressed(MouseEvent& mouseEvent); virtual void mouseDragged(MouseEvent& mouseEvent); protected: /** * Draws the caret. * * @param graphics a Graphics object to draw with. * @param x the x position. * @param y the y position. */ virtual void drawCaret(Graphics* graphics, int x, int y); /** * Adjusts the TextBox size to fit the font size. */ virtual void adjustSize(); std::vector<std::string> mTextRows; int mCaretColumn; int mCaretRow; bool mEditable; bool mOpaque; }; } #endif // end GCN_TEXTBOX_HPP <|endoftext|>
<commit_before>#ifndef SOLAIRE_CORE_ARRAY_LIST_HPP #define SOLAIRE_CORE_ARRAY_LIST_HPP //Copyright 2016 Adam G. Smith // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http ://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. #include "allocator.hpp" namespace solaire { template<class T, class I, class ALLOCATOR, I DEFAULT_ALLOCATION> class array_list { public: typedef T type; typedef I index; typedef ALLOCATOR allocator; typedef T* iterator; typedef const T* const_iterator; private: ALLOCATOR mAllocator; T* mData; I mSize; I mCapacity; public: constexpr size_t size() const { return static_cast<size_t>(mSize); } constexpr size_t capacity() const { return static_cast<size_t>(mCapacity); } inline void clear() { mSize = 0; } inline T& operator[](const size_t aIndex) { return mData[aIndex]; } constexpr const T& operator[](const size_t aIndex) const { return mData[aIndex]; } inline T& back() { return mData[mSize - 1]; } constexpr const T& back() const { return mData[mSize - 1]; } inline T& front() { return mData[mSize - 1]; } constexpr const T& front() const { return mData[mSize - 1]; } inline void pop_back() { mSize = mSize == 0 : 0 : mSize - 1; } inline iterator begin() { return mData; } constexpr const_iterator begin() const { return mData; } inline iterator end() { return mData + mSize; } constexpr const_iterator end() const { return mData + mSize; } inline void reserve(size_t aSize) const { if(aSize > mCapacity) resize(aSize); } inline void pop_front() { erase(begin()); } //! \todo move constructor //! \todo copy / move assignment //! \todo insert constexpr array_list() : mData(nullptr), mSize(0), mCapacity(0) {} constexpr array_list(size_t aCapacity) : mData(nullptr), mSize(0), mCapacity(0) { resize(aCapacity); } template<class T2, class I2, class ALLOCATOR2, I DEFAULT_ALLOCATION2> array_list(const array_list<T2, I2, ALLOCATOR2, DEFAULT_ALLOCATION2>& aOther) : mData(nullptr), mSize(0), mCapacity(0) { const size_t s = aOther.size(); mData = static_cast<T*>(mAllocator.allocate(aCapacity * sizeof(T))); mSize = s; mCapacity = s; for(size_t i = 0; i < s; ++i) new(mData + i) T(aOther[i]); } ~array_list() { if(mData) { for(I i = 0; i < mCapacity; ++i) mData[i].~T(); mAllocator.deallocate(mData); mSize = 0; mCapacity = 0; mData = nullptr; } } inline T& push_back(const T& aValue) { if(mSize == mCapacity) resize(mCapacity == 0 ? DEFAULT_ALLOCATION : mCapacity * 2); return mData[mSize++] = aValue; } T& push_front(const T& aValue) { if(mSize == mCapacity) resize(mCapacity == 0 ? DEFAULT_ALLOCATION : mCapacity * 2); for(size_t i = 0; i < mSize; ++i) mData[mSize - i] = std::move(mData[mSize - (i + 1)]); ++mSize; return mData[0] = aValue; } iterator erase(const const_iterator aPosition) { const size_t offset = aPosition - mData; --mSize; for(size_t i = offset; i < mSize; ++i) mData[i] = std::move(mData[i + 1]); return mData + offset; } private: void resize(const I aCapacity) { T* const tmp = static_cast<T*>(mAllocator.allocate(aCapacity * sizeof(T))); for(I i = 0; i < mSize; ++i) new(tmp + i) T(std::move(mData[i])); for(I i = mSize; i < aCapacity; ++i) new(tmp + i) T(); for(I i = 0; i < mCapacity; ++i) mData[i].~T(); if(mData) mAllocator.deallocate(mData); mData = tmp; mCapacity = aCapacity; } }; template<class T, size_t SIZE, class I = size_t> using static_array_list = array_list<T, I, static_allocator<SIZE * sizeof(T)>, SIZE>; template<class T, class I = size_t, I DEFAULT_ALLOCATION = 16> using heap_array_list = array_list<T, I, heap_allocator, DEFAULT_ALLOCATION>; } #endif<commit_msg>array_list insert<commit_after>#ifndef SOLAIRE_CORE_ARRAY_LIST_HPP #define SOLAIRE_CORE_ARRAY_LIST_HPP //Copyright 2016 Adam G. Smith // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http ://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. #include "allocator.hpp" namespace solaire { template<class T, class I, class ALLOCATOR, I DEFAULT_ALLOCATION> class array_list { public: typedef T type; typedef I index; typedef ALLOCATOR allocator; typedef T* iterator; typedef const T* const_iterator; private: ALLOCATOR mAllocator; T* mData; I mSize; I mCapacity; public: constexpr size_t size() const { return static_cast<size_t>(mSize); } constexpr size_t capacity() const { return static_cast<size_t>(mCapacity); } inline void clear() { mSize = 0; } inline T& operator[](const size_t aIndex) { return mData[aIndex]; } constexpr const T& operator[](const size_t aIndex) const { return mData[aIndex]; } inline T& back() { return mData[mSize - 1]; } constexpr const T& back() const { return mData[mSize - 1]; } inline T& front() { return mData[mSize - 1]; } constexpr const T& front() const { return mData[mSize - 1]; } inline void pop_back() { mSize = mSize == 0 : 0 : mSize - 1; } inline iterator begin() { return mData; } constexpr const_iterator begin() const { return mData; } inline iterator end() { return mData + mSize; } constexpr const_iterator end() const { return mData + mSize; } inline void reserve(size_t aSize) const { if(aSize > mCapacity) resize(aSize); } inline void pop_front() { erase(begin()); } inline T& push_front(const T& aValue) { return *insert(begin(), aValue); } //! \todo move constructor //! \todo copy / move assignment constexpr array_list() : mData(nullptr), mSize(0), mCapacity(0) {} constexpr array_list(size_t aCapacity) : mData(nullptr), mSize(0), mCapacity(0) { resize(aCapacity); } template<class T2, class I2, class ALLOCATOR2, I DEFAULT_ALLOCATION2> array_list(const array_list<T2, I2, ALLOCATOR2, DEFAULT_ALLOCATION2>& aOther) : mData(nullptr), mSize(0), mCapacity(0) { const size_t s = aOther.size(); mData = static_cast<T*>(mAllocator.allocate(aCapacity * sizeof(T))); mSize = s; mCapacity = s; for(size_t i = 0; i < s; ++i) new(mData + i) T(aOther[i]); } ~array_list() { if(mData) { for(I i = 0; i < mCapacity; ++i) mData[i].~T(); mAllocator.deallocate(mData); mSize = 0; mCapacity = 0; mData = nullptr; } } inline T& push_back(const T& aValue) { if(mSize == mCapacity) resize(mCapacity == 0 ? DEFAULT_ALLOCATION : mCapacity * 2); return mData[mSize++] = aValue; } iterator erase(const const_iterator aPosition) { const size_t offset = aPosition - mData; --mSize; for(size_t i = offset; i < mSize; ++i) mData[i] = std::move(mData[i + 1]); return mData + offset; } iterator insert(const const_iterator aPosition, const T& aValue) { const size_t offset = aPosition - mData; if(mSize == mCapacity) resize(mCapacity == 0 ? DEFAULT_ALLOCATION : mCapacity * 2); for(size_t i = mSize; i > offset; --i) mData[i] = std::move(mData[i-1]); mData[offset] = aValue; ++mSize; return mData + offset; } private: void resize(const I aCapacity) { T* const tmp = static_cast<T*>(mAllocator.allocate(aCapacity * sizeof(T))); for(I i = 0; i < mSize; ++i) new(tmp + i) T(std::move(mData[i])); for(I i = mSize; i < aCapacity; ++i) new(tmp + i) T(); for(I i = 0; i < mCapacity; ++i) mData[i].~T(); if(mData) mAllocator.deallocate(mData); mData = tmp; mCapacity = aCapacity; } }; template<class T, size_t SIZE, class I = size_t> using static_array_list = array_list<T, I, static_allocator<SIZE * sizeof(T)>, SIZE>; template<class T, class I = size_t, I DEFAULT_ALLOCATION = 16> using heap_array_list = array_list<T, I, heap_allocator, DEFAULT_ALLOCATION>; } #endif<|endoftext|>
<commit_before>#include "DrawCallBatching.h" #include "dataset/Image.h" #include "render/ShaderMgr.h" #include "render/RenderContextStack.h" #include "render/ShaderContext.h" #include <dtex.h> #include <gl/glew.h> namespace d2d { DrawCallBatching* DrawCallBatching::m_instance = NULL; ////////////////////////////////////////////////////////////////////////// static int TEX_ID = 0; static void _program(int n) { switch (n) { case DTEX_PROGRAM_NULL: ShaderMgr::Instance()->null(); break; case DTEX_PROGRAM_NORMAL: ShaderMgr::Instance()->sprite(); break; default: assert(0); } } static void _blend(int mode) { assert(mode == 0); // ShaderMgr::Instance()->SetBlendMode(0); } static void _set_texture(int id) { TEX_ID = id; ShaderMgr::Instance()->SetTexture(id); } static int _get_texture() { return ShaderMgr::Instance()->GetTexID(); } static void _set_target(int id) { ShaderMgr::Instance()->SetFBO(id); } static int _get_target() { return ShaderMgr::Instance()->GetFboID(); } static Vector LAST_OFFSET; static float LAST_SCALE; static int LAST_WIDTH, LAST_HEIGHT; static void _draw_begin() { RenderContextStack* ctx_stack = RenderContextStack::Instance(); ctx_stack->GetModelView(LAST_OFFSET, LAST_SCALE); ctx_stack->GetProjection(LAST_WIDTH, LAST_HEIGHT); ctx_stack->SetModelView(Vector(0, 0), 1); ctx_stack->SetProjection(2, 2); // glViewport(0, 0, 2, 2); } static void _draw(const float vb[16]) { ShaderMgr* shader = ShaderMgr::Instance(); shader->Draw(vb, TEX_ID); } static void _draw_end() { ShaderMgr::Instance()->Flush(); RenderContextStack* ctx_stack = RenderContextStack::Instance(); ctx_stack->SetModelView(LAST_OFFSET, LAST_SCALE); ctx_stack->SetProjection(LAST_WIDTH, LAST_HEIGHT); // glViewport(0, 0, ORI_WIDTH, ORI_HEIGHT); } static void _draw_flush() { ShaderMgr::Instance()->Flush(); } #define IS_POT(x) ((x) > 0 && ((x) & ((x) -1)) == 0) static int _texture_create(int type, int width, int height, const void* data, int channel,unsigned int id) { assert(type == DTEX_TF_RGBA8); // todo if ((type == DTEX_TF_RGBA8) || (IS_POT(width) && IS_POT(height))) { glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } else { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } GLint _format = GL_RGBA; GLenum _type = GL_UNSIGNED_BYTE; bool is_compressed = false; unsigned int size = 0; uint8_t* uncompressed = NULL; switch (type) { case DTEX_TF_RGBA8: is_compressed = false; _format = GL_RGBA; _type = GL_UNSIGNED_BYTE; break; case DTEX_TF_RGBA4: is_compressed = false; _format = GL_RGBA; _type = GL_UNSIGNED_SHORT_4_4_4_4; break; case DTEX_TF_PVR2: #ifdef __APPLE__ is_compressed = true; _type = COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; size = width * height * 8 * _type / 16; #endif // __APPLE__ break; case DTEX_TF_PVR4: #ifdef __APPLE__ is_compressed = true; _type = COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; size = width * height * 8 * _type / 16; #else // is_compressed = false; // _format = GL_RGBA; // _type = GL_UNSIGNED_BYTE; // uncompressed = dtex_pvr_decode(data, width, height); #endif // __APPLE__ break; case DTEX_TF_ETC1: #ifdef __ANDROID__ is_compressed = true; _type = GL_ETC1_RGB8_OES; size = width * height * 4 / 8; #else is_compressed = false; _format = GL_RGBA; _type = GL_UNSIGNED_BYTE; #ifdef USED_IN_EDITOR // uncompressed = dtex_etc1_decode(data, width, height); #endif // USED_IN_EDITOR #endif // __ANDROID__ break; default: dtex_fault("dtex_gl_create_texture: unknown texture type."); } glActiveTexture(GL_TEXTURE0 + channel); if (id == 0) { glGenTextures(1, (GLuint*)&id); } glBindTexture(GL_TEXTURE_2D, id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (is_compressed) { glCompressedTexImage2D(GL_TEXTURE_2D, 0, _type, width, height, 0, size, data); } else { if (uncompressed) { glTexImage2D(GL_TEXTURE_2D, 0, _format, (GLsizei)width, (GLsizei)height, 0, _format, _type, uncompressed); free(uncompressed); } else { glTexImage2D(GL_TEXTURE_2D, 0, _format, (GLsizei)width, (GLsizei)height, 0, _format, _type, data); } } return id; } static void _texture_release(int id) { GLuint texid = (GLuint)id; glActiveTexture(GL_TEXTURE0); glDeleteTextures(1, &texid); } static void _texture_update(const void* pixels, int x, int y, int w, int h, unsigned int id) { int old_id = ShaderMgr::Instance()->GetTexID(); glBindTexture(GL_TEXTURE_2D, id); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glBindTexture(GL_TEXTURE_2D, old_id); } static int _texture_id(int id) { return id; } ////////////////////////////////////////////////////////////////////////// static const char* CFG = "{ \n" " \"open_c1\" : true, \n" " \"open_c2\" : true, \n" " \"open_c3\" : false, \n" " \"open_cg\" : true, \n" " \"open_cs\" : true, \n" " \"c1_tex_size\" : 1024, \n" " \"c2_tex_size\" : 4096 \n" "} \n" ; DrawCallBatching::DrawCallBatching() { dtex_shader_init(&_program, &_blend, &_set_texture, &_get_texture, &_set_target, &_get_target, &_draw_begin, &_draw, &_draw_end, &_draw_flush); dtex_gl_texture_init(&_texture_create, &_texture_release, &_texture_update, &_texture_id); dtexf_create(CFG); } DrawCallBatching::~DrawCallBatching() { } void DrawCallBatching::LoadBegin() { dtexf_c2_load_begin(); } int DrawCallBatching::Load(const Image* img) { const std::string& filepath = img->GetFilepath(); std::map<std::string, int>::iterator itr = m_path2id.find(filepath); if (itr != m_path2id.end()) { return itr->second; } int key = m_path2id.size(); m_path2id.insert(std::make_pair(filepath, key)); dtexf_c2_load_tex(img->GetTexID(), img->GetClippedWidth(), img->GetClippedHeight(), key); return key; } void DrawCallBatching::LoadEnd() { dtexf_c2_load_end(); } void DrawCallBatching::ReloadBegin() { dtexf_c2_reload_begin(); } void DrawCallBatching::Reload(const Image* img) { int key; std::map<std::string, int>::iterator itr = m_path2id.find(img->GetFilepath()); assert(itr != m_path2id.end()); key = itr->second; dtexf_c2_reload_tex(img->GetTexID(), img->GetOriginWidth(), img->GetOriginHeight(), key); } void DrawCallBatching::ReloadEnd() { dtexf_c2_reload_end(); } float* DrawCallBatching::Query(const Image* img, int* id) { int key; std::map<std::string, int>::iterator itr = m_path2id.find(img->GetFilepath()); if (itr != m_path2id.end()) { key = itr->second; } else { dtexf_c2_load_begin(); key = Load(img); dtexf_c2_load_end(); } return dtexf_c2_query_tex(key, id); } void DrawCallBatching::Clear() { dtexf_c2_clear(); } dtex_cg* DrawCallBatching::GetDtexCG() { return dtexf_get_cg(); } void DrawCallBatching::OnSize(int w, int h) { dtex_set_screen(w, h, 1); } void DrawCallBatching::DebugDraw() const { ShaderContext::Flush(); dtexf_debug_draw(); } DrawCallBatching* DrawCallBatching::Instance() { if (!m_instance) { m_instance = new DrawCallBatching(); } return m_instance; } }<commit_msg>[FIXED] fbo tex should not use dtex<commit_after>#include "DrawCallBatching.h" #include "dataset/Image.h" #include "render/ShaderMgr.h" #include "render/RenderContextStack.h" #include "render/ShaderContext.h" #include <dtex.h> #include <gl/glew.h> namespace d2d { DrawCallBatching* DrawCallBatching::m_instance = NULL; ////////////////////////////////////////////////////////////////////////// static int TEX_ID = 0; static void _program(int n) { switch (n) { case DTEX_PROGRAM_NULL: ShaderMgr::Instance()->null(); break; case DTEX_PROGRAM_NORMAL: ShaderMgr::Instance()->sprite(); break; default: assert(0); } } static void _blend(int mode) { assert(mode == 0); // ShaderMgr::Instance()->SetBlendMode(0); } static void _set_texture(int id) { TEX_ID = id; ShaderMgr::Instance()->SetTexture(id); } static int _get_texture() { return ShaderMgr::Instance()->GetTexID(); } static void _set_target(int id) { ShaderMgr::Instance()->SetFBO(id); } static int _get_target() { return ShaderMgr::Instance()->GetFboID(); } static Vector LAST_OFFSET; static float LAST_SCALE; static int LAST_WIDTH, LAST_HEIGHT; static void _draw_begin() { RenderContextStack* ctx_stack = RenderContextStack::Instance(); ctx_stack->GetModelView(LAST_OFFSET, LAST_SCALE); ctx_stack->GetProjection(LAST_WIDTH, LAST_HEIGHT); ctx_stack->SetModelView(Vector(0, 0), 1); ctx_stack->SetProjection(2, 2); // glViewport(0, 0, 2, 2); } static void _draw(const float vb[16]) { ShaderMgr* shader = ShaderMgr::Instance(); shader->Draw(vb, TEX_ID); } static void _draw_end() { ShaderMgr::Instance()->Flush(); RenderContextStack* ctx_stack = RenderContextStack::Instance(); ctx_stack->SetModelView(LAST_OFFSET, LAST_SCALE); ctx_stack->SetProjection(LAST_WIDTH, LAST_HEIGHT); // glViewport(0, 0, ORI_WIDTH, ORI_HEIGHT); } static void _draw_flush() { ShaderMgr::Instance()->Flush(); } #define IS_POT(x) ((x) > 0 && ((x) & ((x) -1)) == 0) static int _texture_create(int type, int width, int height, const void* data, int channel,unsigned int id) { assert(type == DTEX_TF_RGBA8); // todo if ((type == DTEX_TF_RGBA8) || (IS_POT(width) && IS_POT(height))) { glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } else { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } GLint _format = GL_RGBA; GLenum _type = GL_UNSIGNED_BYTE; bool is_compressed = false; unsigned int size = 0; uint8_t* uncompressed = NULL; switch (type) { case DTEX_TF_RGBA8: is_compressed = false; _format = GL_RGBA; _type = GL_UNSIGNED_BYTE; break; case DTEX_TF_RGBA4: is_compressed = false; _format = GL_RGBA; _type = GL_UNSIGNED_SHORT_4_4_4_4; break; case DTEX_TF_PVR2: #ifdef __APPLE__ is_compressed = true; _type = COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; size = width * height * 8 * _type / 16; #endif // __APPLE__ break; case DTEX_TF_PVR4: #ifdef __APPLE__ is_compressed = true; _type = COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; size = width * height * 8 * _type / 16; #else // is_compressed = false; // _format = GL_RGBA; // _type = GL_UNSIGNED_BYTE; // uncompressed = dtex_pvr_decode(data, width, height); #endif // __APPLE__ break; case DTEX_TF_ETC1: #ifdef __ANDROID__ is_compressed = true; _type = GL_ETC1_RGB8_OES; size = width * height * 4 / 8; #else is_compressed = false; _format = GL_RGBA; _type = GL_UNSIGNED_BYTE; #ifdef USED_IN_EDITOR // uncompressed = dtex_etc1_decode(data, width, height); #endif // USED_IN_EDITOR #endif // __ANDROID__ break; default: dtex_fault("dtex_gl_create_texture: unknown texture type."); } glActiveTexture(GL_TEXTURE0 + channel); if (id == 0) { glGenTextures(1, (GLuint*)&id); } glBindTexture(GL_TEXTURE_2D, id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (is_compressed) { glCompressedTexImage2D(GL_TEXTURE_2D, 0, _type, width, height, 0, size, data); } else { if (uncompressed) { glTexImage2D(GL_TEXTURE_2D, 0, _format, (GLsizei)width, (GLsizei)height, 0, _format, _type, uncompressed); free(uncompressed); } else { glTexImage2D(GL_TEXTURE_2D, 0, _format, (GLsizei)width, (GLsizei)height, 0, _format, _type, data); } } return id; } static void _texture_release(int id) { GLuint texid = (GLuint)id; glActiveTexture(GL_TEXTURE0); glDeleteTextures(1, &texid); } static void _texture_update(const void* pixels, int x, int y, int w, int h, unsigned int id) { int old_id = ShaderMgr::Instance()->GetTexID(); glBindTexture(GL_TEXTURE_2D, id); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glBindTexture(GL_TEXTURE_2D, old_id); } static int _texture_id(int id) { return id; } ////////////////////////////////////////////////////////////////////////// static const char* CFG = "{ \n" " \"open_c1\" : true, \n" " \"open_c2\" : true, \n" " \"open_c3\" : false, \n" " \"open_cg\" : true, \n" " \"open_cs\" : true, \n" " \"c1_tex_size\" : 1024, \n" " \"c2_tex_size\" : 4096 \n" "} \n" ; DrawCallBatching::DrawCallBatching() { dtex_shader_init(&_program, &_blend, &_set_texture, &_get_texture, &_set_target, &_get_target, &_draw_begin, &_draw, &_draw_end, &_draw_flush); dtex_gl_texture_init(&_texture_create, &_texture_release, &_texture_update, &_texture_id); dtexf_create(CFG); } DrawCallBatching::~DrawCallBatching() { } void DrawCallBatching::LoadBegin() { dtexf_c2_load_begin(); } int DrawCallBatching::Load(const Image* img) { const std::string& filepath = img->GetFilepath(); std::map<std::string, int>::iterator itr = m_path2id.find(filepath); if (itr != m_path2id.end()) { return itr->second; } int key = m_path2id.size(); m_path2id.insert(std::make_pair(filepath, key)); dtexf_c2_load_tex(img->GetTexID(), img->GetClippedWidth(), img->GetClippedHeight(), key); return key; } void DrawCallBatching::LoadEnd() { dtexf_c2_load_end(); } void DrawCallBatching::ReloadBegin() { dtexf_c2_reload_begin(); } void DrawCallBatching::Reload(const Image* img) { int key; std::map<std::string, int>::iterator itr = m_path2id.find(img->GetFilepath()); assert(itr != m_path2id.end()); key = itr->second; dtexf_c2_reload_tex(img->GetTexID(), img->GetOriginWidth(), img->GetOriginHeight(), key); } void DrawCallBatching::ReloadEnd() { dtexf_c2_reload_end(); } float* DrawCallBatching::Query(const Image* img, int* id) { std::string filepath = img->GetFilepath(); if (filepath.empty()) { return NULL; } int key; std::map<std::string, int>::iterator itr = m_path2id.find(filepath); if (itr != m_path2id.end()) { key = itr->second; } else { dtexf_c2_load_begin(); key = Load(img); dtexf_c2_load_end(); } return dtexf_c2_query_tex(key, id); } void DrawCallBatching::Clear() { dtexf_c2_clear(); } dtex_cg* DrawCallBatching::GetDtexCG() { return dtexf_get_cg(); } void DrawCallBatching::OnSize(int w, int h) { dtex_set_screen(w, h, 1); } void DrawCallBatching::DebugDraw() const { ShaderContext::Flush(); dtexf_debug_draw(); } DrawCallBatching* DrawCallBatching::Instance() { if (!m_instance) { m_instance = new DrawCallBatching(); } return m_instance; } }<|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <string> #include <tabulate/column.hpp> #include <tabulate/font_style.hpp> #include <tabulate/printer.hpp> #include <tabulate/row.hpp> #include <tabulate/termcolor.hpp> #include <vector> #ifdef max #undef max #endif #ifdef min #undef min #endif namespace tabulate { Format &Cell::format() { std::shared_ptr<Row> parent = parent_.lock(); if (!format_.has_value()) { // no cell format format_ = parent->format(); // Use parent row format } else { // Cell has formatting // Merge cell formatting with parent row formatting format_ = Format::merge(format_.value(), parent->format()); } return format_.value(); } bool Cell::is_multi_byte_character_support_enabled() { return format().multi_byte_characters_.value(); } class TableInternal : public std::enable_shared_from_this<TableInternal> { public: static std::shared_ptr<TableInternal> create() { auto result = std::shared_ptr<TableInternal>(new TableInternal()); result->format_.set_defaults(); return result; } void add_row(const std::vector<std::string> &cells) { auto row = std::make_shared<Row>(shared_from_this()); for (auto &c : cells) { auto cell = std::make_shared<Cell>(row); cell->set_text(c); row->add_cell(cell); } rows_.push_back(row); } Row &operator[](size_t index) { return *(rows_[index]); } const Row &operator[](size_t index) const { return *(rows_[index]); } Column column(size_t index) { Column column(shared_from_this()); for (size_t i = 0; i < rows_.size(); ++i) { auto row = rows_[i]; auto &cell = row->cell(index); column.add_cell(cell); } return column; } size_t size() const { return rows_.size(); } Format &format() { return format_; } void print(std::ostream &stream) { Printer::print_table(stream, *this); } size_t estimate_num_columns() const { size_t result{0}; if (size()) { auto first_row = operator[](size_t(0)); result = first_row.size(); } return result; } private: friend class Table; TableInternal() {} TableInternal &operator=(const TableInternal &); TableInternal(const TableInternal &); std::vector<std::shared_ptr<Row>> rows_; Format format_; }; Format &Row::format() { std::shared_ptr<TableInternal> parent = parent_.lock(); if (!format_.has_value()) { // no row format format_ = parent->format(); // Use parent table format } else { // Row has formatting rules // Merge with parent table format format_ = Format::merge(format_.value(), parent->format()); } return format_.value(); } std::pair<std::vector<size_t>, std::vector<size_t>> Printer::compute_cell_dimensions(TableInternal &table) { std::pair<std::vector<size_t>, std::vector<size_t>> result; size_t num_rows = table.size(); size_t num_columns = table.estimate_num_columns(); std::vector<size_t> row_heights, column_widths{}; for (size_t i = 0; i < num_columns; ++i) { Column column = table.column(i); size_t configured_width = column.get_configured_width(); size_t computed_width = column.get_computed_width(); if (configured_width != 0) column_widths.push_back(configured_width); else column_widths.push_back(computed_width); } for (size_t i = 0; i < num_rows; ++i) { Row row = table[i]; size_t configured_height = row.get_configured_height(); size_t computed_height = row.get_computed_height(column_widths); // NOTE: Unlike column width, row height is calculated as the max // b/w configured height and computed height // which means that .width() has higher precedence than .height() // when both are configured by the user // // TODO: Maybe this can be configured? // If such a configuration is exposed, i.e., prefer height over width // then the logic will be reversed, i.e., // column_widths.push_back(std::max(configured_width, computed_width)) // and // row_height = configured_height if != 0 else computed_height row_heights.push_back(std::max(configured_height, computed_height)); } result.first = row_heights; result.second = column_widths; return result; } void Printer::print_table(std::ostream &stream, TableInternal &table) { size_t num_rows = table.size(); size_t num_columns = table.estimate_num_columns(); auto dimensions = compute_cell_dimensions(table); auto row_heights = dimensions.first; auto column_widths = dimensions.second; // For each row, for (size_t i = 0; i < num_rows; ++i) { // Print top border bool border_top_printed{true}; for (size_t j = 0; j < num_columns; ++j) { border_top_printed &= print_cell_border_top(stream, table, {i, j}, {row_heights[i], column_widths[j]}, num_columns); } if (border_top_printed) stream << termcolor::reset << "\n"; // Print row contents with word wrapping for (size_t k = 0; k < row_heights[i]; ++k) { for (size_t j = 0; j < num_columns; ++j) { print_row_in_cell(stream, table, {i, j}, {row_heights[i], column_widths[j]}, num_columns, k); } if (k + 1 < row_heights[i]) stream << termcolor::reset << "\n"; } if (i + 1 == num_rows) { // Check if there is bottom border to print: auto bottom_border_needed{true}; for (size_t j = 0; j < num_columns; ++j) { auto cell = table[i][j]; auto format = cell.format(); auto column_width = column_widths[j]; auto corner = format.corner_bottom_left_.value(); auto border_bottom = format.border_bottom_.value(); if (corner == "" && border_bottom == "") { bottom_border_needed = false; break; } } if (bottom_border_needed) stream << termcolor::reset << "\n"; // Print bottom border for table for (size_t j = 0; j < num_columns; ++j) { print_cell_border_bottom(stream, table, {i, j}, {row_heights[i], column_widths[j]}, num_columns); } } if (i + 1 < num_rows) stream << termcolor::reset << "\n"; // Don't add newline after last row } } void Printer::print_row_in_cell(std::ostream &stream, TableInternal &table, const std::pair<size_t, size_t> &index, const std::pair<size_t, size_t> &dimension, size_t num_columns, size_t row_index) { auto row_height = dimension.first; auto column_width = dimension.second; auto cell = table[index.first][index.second]; auto locale = cell.locale(); auto is_multi_byte_character_support_enabled = cell.is_multi_byte_character_support_enabled(); std::locale::global(std::locale(locale)); auto format = cell.format(); auto text = cell.get_text(); auto word_wrapped_text = Format::word_wrap(text, column_width, locale, is_multi_byte_character_support_enabled); auto text_height = std::count(word_wrapped_text.begin(), word_wrapped_text.end(), '\n') + 1; auto padding_top = format.padding_top_.value(); auto padding_bottom = format.padding_bottom_.value(); if (format.show_border_left_.value()) { apply_element_style(stream, format.border_left_color_.value(), format.border_left_background_color_.value(), {}); stream << format.border_left_.value(); reset_element_style(stream); } apply_element_style(stream, format.font_color_.value(), format.font_background_color_.value(), {}); if (row_index < padding_top) { // Padding top stream << std::string(column_width, ' '); } else if (row_index >= padding_top && (row_index <= (padding_top + text_height))) { // // Row contents // Retrieve padding left and right // (column_width - padding_left - padding_right) is the amount of space // available for cell text - Use this to word wrap cell contents auto padding_left = format.padding_left_.value(); auto padding_right = format.padding_right_.value(); // Check if input text has embedded \n that are to be respected auto newlines_in_input = Format::split_lines(text, "\n", cell.locale(), cell.is_multi_byte_character_support_enabled()) .size() - 1; std::string word_wrapped_text; // If there are no embedded \n characters, then apply word wrap if (newlines_in_input == 0) { // Apply word wrapping to input text // Then display one word-wrapped line at a time within cell if (column_width > (padding_left + padding_right)) word_wrapped_text = Format::word_wrap(text, column_width - padding_left - padding_right, cell.locale(), cell.is_multi_byte_character_support_enabled()); else { // Configured column width cannot be lower than (padding_left + padding_right) // This is a bad configuration // E.g., the user is trying to force the column width to be 5 // when padding_left and padding_right are each configured to 3 // (padding_left + padding_right) = 6 > column_width } } else { word_wrapped_text = text; // repect the embedded '\n' characters } auto lines = Format::split_lines(word_wrapped_text, "\n", cell.locale(), cell.is_multi_byte_character_support_enabled()); if (row_index - padding_top < lines.size()) { auto line = lines[row_index - padding_top]; // Print left padding characters stream << std::string(padding_left, ' '); // Print word-wrapped line line = Format::trim(line); auto line_with_padding_size = get_sequence_length(line, cell.locale(), cell.is_multi_byte_character_support_enabled()) + padding_left + padding_right; switch (format.font_align_.value()) { case FontAlign::left: print_content_left_aligned(stream, line, format, line_with_padding_size, column_width); break; case FontAlign::center: print_content_center_aligned(stream, line, format, line_with_padding_size, column_width); break; case FontAlign::right: print_content_right_aligned(stream, line, format, line_with_padding_size, column_width); break; } // Print right padding characters stream << std::string(padding_right, ' '); } else stream << std::string(column_width, ' '); } else { // Padding bottom stream << std::string(column_width, ' '); } reset_element_style(stream); if (index.second + 1 == num_columns) { // Print right border after last column if (format.show_border_right_.value()) { apply_element_style(stream, format.border_right_color_.value(), format.border_right_background_color_.value(), {}); stream << format.border_right_.value(); reset_element_style(stream); } } } bool Printer::print_cell_border_top(std::ostream &stream, TableInternal &table, const std::pair<size_t, size_t> &index, const std::pair<size_t, size_t> &dimension, size_t num_columns) { auto cell = table[index.first][index.second]; auto locale = cell.locale(); std::locale::global(std::locale(locale)); auto format = cell.format(); auto column_width = dimension.second; auto corner = format.corner_top_left_.value(); auto corner_color = format.corner_top_left_color_.value(); auto corner_background_color = format.corner_top_left_background_color_.value(); auto border_top = format.border_top_.value(); if ((corner == "" && border_top == "") || !format.show_border_top_.value()) return false; apply_element_style(stream, corner_color, corner_background_color, {}); stream << corner; reset_element_style(stream); for (size_t i = 0; i < column_width; ++i) { apply_element_style(stream, format.border_top_color_.value(), format.border_top_background_color_.value(), {}); stream << border_top; reset_element_style(stream); } if (index.second + 1 == num_columns) { // Print corner after last column corner = format.corner_top_right_.value(); corner_color = format.corner_top_right_color_.value(); corner_background_color = format.corner_top_right_background_color_.value(); apply_element_style(stream, corner_color, corner_background_color, {}); stream << corner; reset_element_style(stream); } return true; } bool Printer::print_cell_border_bottom(std::ostream &stream, TableInternal &table, const std::pair<size_t, size_t> &index, const std::pair<size_t, size_t> &dimension, size_t num_columns) { auto cell = table[index.first][index.second]; auto locale = cell.locale(); std::locale::global(std::locale(locale)); auto format = cell.format(); auto column_width = dimension.second; auto corner = format.corner_bottom_left_.value(); auto corner_color = format.corner_bottom_left_color_.value(); auto corner_background_color = format.corner_bottom_left_background_color_.value(); auto border_bottom = format.border_bottom_.value(); if ((corner == "" && border_bottom == "") || !format.show_border_bottom_.value()) return false; apply_element_style(stream, corner_color, corner_background_color, {}); stream << corner; reset_element_style(stream); for (size_t i = 0; i < column_width; ++i) { apply_element_style(stream, format.border_bottom_color_.value(), format.border_bottom_background_color_.value(), {}); stream << border_bottom; reset_element_style(stream); } if (index.second + 1 == num_columns) { // Print corner after last column corner = format.corner_bottom_right_.value(); corner_color = format.corner_bottom_right_color_.value(); corner_background_color = format.corner_bottom_right_background_color_.value(); apply_element_style(stream, corner_color, corner_background_color, {}); stream << corner; reset_element_style(stream); } return true; } } // namespace tabulate<commit_msg>Cleanup<commit_after>#include <algorithm> #include <iostream> #include <string> #include <tabulate/column.hpp> #include <tabulate/font_style.hpp> #include <tabulate/printer.hpp> #include <tabulate/row.hpp> #include <tabulate/termcolor.hpp> #include <vector> #ifdef max #undef max #endif #ifdef min #undef min #endif namespace tabulate { class TableInternal : public std::enable_shared_from_this<TableInternal> { public: static std::shared_ptr<TableInternal> create() { auto result = std::shared_ptr<TableInternal>(new TableInternal()); result->format_.set_defaults(); return result; } void add_row(const std::vector<std::string> &cells) { auto row = std::make_shared<Row>(shared_from_this()); for (auto &c : cells) { auto cell = std::make_shared<Cell>(row); cell->set_text(c); row->add_cell(cell); } rows_.push_back(row); } Row &operator[](size_t index) { return *(rows_[index]); } const Row &operator[](size_t index) const { return *(rows_[index]); } Column column(size_t index) { Column column(shared_from_this()); for (size_t i = 0; i < rows_.size(); ++i) { auto row = rows_[i]; auto &cell = row->cell(index); column.add_cell(cell); } return column; } size_t size() const { return rows_.size(); } Format &format() { return format_; } void print(std::ostream &stream) { Printer::print_table(stream, *this); } size_t estimate_num_columns() const { size_t result{0}; if (size()) { auto first_row = operator[](size_t(0)); result = first_row.size(); } return result; } private: friend class Table; TableInternal() {} TableInternal &operator=(const TableInternal &); TableInternal(const TableInternal &); std::vector<std::shared_ptr<Row>> rows_; Format format_; }; Format &Cell::format() { std::shared_ptr<Row> parent = parent_.lock(); if (!format_.has_value()) { // no cell format format_ = parent->format(); // Use parent row format } else { // Cell has formatting // Merge cell formatting with parent row formatting format_ = Format::merge(format_.value(), parent->format()); } return format_.value(); } bool Cell::is_multi_byte_character_support_enabled() { return format().multi_byte_characters_.value(); } Format &Row::format() { std::shared_ptr<TableInternal> parent = parent_.lock(); if (!format_.has_value()) { // no row format format_ = parent->format(); // Use parent table format } else { // Row has formatting rules // Merge with parent table format format_ = Format::merge(format_.value(), parent->format()); } return format_.value(); } std::pair<std::vector<size_t>, std::vector<size_t>> Printer::compute_cell_dimensions(TableInternal &table) { std::pair<std::vector<size_t>, std::vector<size_t>> result; size_t num_rows = table.size(); size_t num_columns = table.estimate_num_columns(); std::vector<size_t> row_heights, column_widths{}; for (size_t i = 0; i < num_columns; ++i) { Column column = table.column(i); size_t configured_width = column.get_configured_width(); size_t computed_width = column.get_computed_width(); if (configured_width != 0) column_widths.push_back(configured_width); else column_widths.push_back(computed_width); } for (size_t i = 0; i < num_rows; ++i) { Row row = table[i]; size_t configured_height = row.get_configured_height(); size_t computed_height = row.get_computed_height(column_widths); // NOTE: Unlike column width, row height is calculated as the max // b/w configured height and computed height // which means that .width() has higher precedence than .height() // when both are configured by the user // // TODO: Maybe this can be configured? // If such a configuration is exposed, i.e., prefer height over width // then the logic will be reversed, i.e., // column_widths.push_back(std::max(configured_width, computed_width)) // and // row_height = configured_height if != 0 else computed_height row_heights.push_back(std::max(configured_height, computed_height)); } result.first = row_heights; result.second = column_widths; return result; } void Printer::print_table(std::ostream &stream, TableInternal &table) { size_t num_rows = table.size(); size_t num_columns = table.estimate_num_columns(); auto dimensions = compute_cell_dimensions(table); auto row_heights = dimensions.first; auto column_widths = dimensions.second; // For each row, for (size_t i = 0; i < num_rows; ++i) { // Print top border bool border_top_printed{true}; for (size_t j = 0; j < num_columns; ++j) { border_top_printed &= print_cell_border_top(stream, table, {i, j}, {row_heights[i], column_widths[j]}, num_columns); } if (border_top_printed) stream << termcolor::reset << "\n"; // Print row contents with word wrapping for (size_t k = 0; k < row_heights[i]; ++k) { for (size_t j = 0; j < num_columns; ++j) { print_row_in_cell(stream, table, {i, j}, {row_heights[i], column_widths[j]}, num_columns, k); } if (k + 1 < row_heights[i]) stream << termcolor::reset << "\n"; } if (i + 1 == num_rows) { // Check if there is bottom border to print: auto bottom_border_needed{true}; for (size_t j = 0; j < num_columns; ++j) { auto cell = table[i][j]; auto format = cell.format(); auto column_width = column_widths[j]; auto corner = format.corner_bottom_left_.value(); auto border_bottom = format.border_bottom_.value(); if (corner == "" && border_bottom == "") { bottom_border_needed = false; break; } } if (bottom_border_needed) stream << termcolor::reset << "\n"; // Print bottom border for table for (size_t j = 0; j < num_columns; ++j) { print_cell_border_bottom(stream, table, {i, j}, {row_heights[i], column_widths[j]}, num_columns); } } if (i + 1 < num_rows) stream << termcolor::reset << "\n"; // Don't add newline after last row } } void Printer::print_row_in_cell(std::ostream &stream, TableInternal &table, const std::pair<size_t, size_t> &index, const std::pair<size_t, size_t> &dimension, size_t num_columns, size_t row_index) { auto row_height = dimension.first; auto column_width = dimension.second; auto cell = table[index.first][index.second]; auto locale = cell.locale(); auto is_multi_byte_character_support_enabled = cell.is_multi_byte_character_support_enabled(); std::locale::global(std::locale(locale)); auto format = cell.format(); auto text = cell.get_text(); auto word_wrapped_text = Format::word_wrap(text, column_width, locale, is_multi_byte_character_support_enabled); auto text_height = std::count(word_wrapped_text.begin(), word_wrapped_text.end(), '\n') + 1; auto padding_top = format.padding_top_.value(); auto padding_bottom = format.padding_bottom_.value(); if (format.show_border_left_.value()) { apply_element_style(stream, format.border_left_color_.value(), format.border_left_background_color_.value(), {}); stream << format.border_left_.value(); reset_element_style(stream); } apply_element_style(stream, format.font_color_.value(), format.font_background_color_.value(), {}); if (row_index < padding_top) { // Padding top stream << std::string(column_width, ' '); } else if (row_index >= padding_top && (row_index <= (padding_top + text_height))) { // // Row contents // Retrieve padding left and right // (column_width - padding_left - padding_right) is the amount of space // available for cell text - Use this to word wrap cell contents auto padding_left = format.padding_left_.value(); auto padding_right = format.padding_right_.value(); // Check if input text has embedded \n that are to be respected auto newlines_in_input = Format::split_lines(text, "\n", cell.locale(), cell.is_multi_byte_character_support_enabled()) .size() - 1; std::string word_wrapped_text; // If there are no embedded \n characters, then apply word wrap if (newlines_in_input == 0) { // Apply word wrapping to input text // Then display one word-wrapped line at a time within cell if (column_width > (padding_left + padding_right)) word_wrapped_text = Format::word_wrap(text, column_width - padding_left - padding_right, cell.locale(), cell.is_multi_byte_character_support_enabled()); else { // Configured column width cannot be lower than (padding_left + padding_right) // This is a bad configuration // E.g., the user is trying to force the column width to be 5 // when padding_left and padding_right are each configured to 3 // (padding_left + padding_right) = 6 > column_width } } else { word_wrapped_text = text; // repect the embedded '\n' characters } auto lines = Format::split_lines(word_wrapped_text, "\n", cell.locale(), cell.is_multi_byte_character_support_enabled()); if (row_index - padding_top < lines.size()) { auto line = lines[row_index - padding_top]; // Print left padding characters stream << std::string(padding_left, ' '); // Print word-wrapped line line = Format::trim(line); auto line_with_padding_size = get_sequence_length(line, cell.locale(), cell.is_multi_byte_character_support_enabled()) + padding_left + padding_right; switch (format.font_align_.value()) { case FontAlign::left: print_content_left_aligned(stream, line, format, line_with_padding_size, column_width); break; case FontAlign::center: print_content_center_aligned(stream, line, format, line_with_padding_size, column_width); break; case FontAlign::right: print_content_right_aligned(stream, line, format, line_with_padding_size, column_width); break; } // Print right padding characters stream << std::string(padding_right, ' '); } else stream << std::string(column_width, ' '); } else { // Padding bottom stream << std::string(column_width, ' '); } reset_element_style(stream); if (index.second + 1 == num_columns) { // Print right border after last column if (format.show_border_right_.value()) { apply_element_style(stream, format.border_right_color_.value(), format.border_right_background_color_.value(), {}); stream << format.border_right_.value(); reset_element_style(stream); } } } bool Printer::print_cell_border_top(std::ostream &stream, TableInternal &table, const std::pair<size_t, size_t> &index, const std::pair<size_t, size_t> &dimension, size_t num_columns) { auto cell = table[index.first][index.second]; auto locale = cell.locale(); std::locale::global(std::locale(locale)); auto format = cell.format(); auto column_width = dimension.second; auto corner = format.corner_top_left_.value(); auto corner_color = format.corner_top_left_color_.value(); auto corner_background_color = format.corner_top_left_background_color_.value(); auto border_top = format.border_top_.value(); if ((corner == "" && border_top == "") || !format.show_border_top_.value()) return false; apply_element_style(stream, corner_color, corner_background_color, {}); stream << corner; reset_element_style(stream); for (size_t i = 0; i < column_width; ++i) { apply_element_style(stream, format.border_top_color_.value(), format.border_top_background_color_.value(), {}); stream << border_top; reset_element_style(stream); } if (index.second + 1 == num_columns) { // Print corner after last column corner = format.corner_top_right_.value(); corner_color = format.corner_top_right_color_.value(); corner_background_color = format.corner_top_right_background_color_.value(); apply_element_style(stream, corner_color, corner_background_color, {}); stream << corner; reset_element_style(stream); } return true; } bool Printer::print_cell_border_bottom(std::ostream &stream, TableInternal &table, const std::pair<size_t, size_t> &index, const std::pair<size_t, size_t> &dimension, size_t num_columns) { auto cell = table[index.first][index.second]; auto locale = cell.locale(); std::locale::global(std::locale(locale)); auto format = cell.format(); auto column_width = dimension.second; auto corner = format.corner_bottom_left_.value(); auto corner_color = format.corner_bottom_left_color_.value(); auto corner_background_color = format.corner_bottom_left_background_color_.value(); auto border_bottom = format.border_bottom_.value(); if ((corner == "" && border_bottom == "") || !format.show_border_bottom_.value()) return false; apply_element_style(stream, corner_color, corner_background_color, {}); stream << corner; reset_element_style(stream); for (size_t i = 0; i < column_width; ++i) { apply_element_style(stream, format.border_bottom_color_.value(), format.border_bottom_background_color_.value(), {}); stream << border_bottom; reset_element_style(stream); } if (index.second + 1 == num_columns) { // Print corner after last column corner = format.corner_bottom_right_.value(); corner_color = format.corner_bottom_right_color_.value(); corner_background_color = format.corner_bottom_right_background_color_.value(); apply_element_style(stream, corner_color, corner_background_color, {}); stream << corner; reset_element_style(stream); } return true; } } // namespace tabulate<|endoftext|>
<commit_before>//---------------------------------------------------------------------------- /// \file variant_tree_error.hpp /// \author Serge Aleynikov //---------------------------------------------------------------------------- /// Defines variant_tree_error classes for ease of configuration error reporting //---------------------------------------------------------------------------- // Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-06-21 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is a part of utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_VARIANT_TREE_ERROR_HPP_ #define _UTXX_VARIANT_TREE_ERROR_HPP_ #include <utxx/variant_tree_path.hpp> #include <boost/property_tree/exceptions.hpp> #include <boost/property_tree/detail/file_parser_error.hpp> #include <utxx/error.hpp> #include <stdexcept> namespace utxx { // Errors thrown on bad data typedef boost::property_tree::ptree_bad_data variant_tree_bad_data; typedef boost::property_tree::ptree_bad_path variant_tree_bad_path; typedef boost::property_tree::file_parser_error variant_tree_parser_error; /** * \brief Exception class for configuration related errors. * Example use: * <tt>throw variant_tree_error(a_path, "Test ") << 1 << " result:" << 2;</tt> */ class variant_tree_error : public runtime_error { std::string m_path; void stream() {} template <class T, class... Args> void stream(const T& a, Args... args) { *this << a; stream(args...); } public: variant_tree_error(src_info&& a_si, const std::string& a_path) : runtime_error(std::move(a_si)), m_path(a_path) {} variant_tree_error(const std::string& a_path) : m_path(a_path) {} template <class... Args> variant_tree_error(src_info&& a_si, const std::string& a_path, Args... args) : variant_tree_error(std::move(a_si), a_path) { stream(args...); } template <class... Args> variant_tree_error(const std::string& a_path, Args... args) : variant_tree_error(a_path) { stream(args...); } template <class... Args> variant_tree_error(src_info&& a_si, const tree_path& a_path, Args... args) : variant_tree_error(std::move(a_si), a_path.dump()) { stream(args...); } template <class... Args> variant_tree_error(const tree_path& a_path, Args... args) : variant_tree_error(a_path.dump()) { stream(args...); } virtual ~variant_tree_error() throw() {} const std::string& path() const { return m_path; } virtual std::string str() const { std::stringstream s; s << "Config error [" << m_path << "]: " << m_out->str(); return s.str(); } }; } // namespace utxx #endif // _UTXX_VARIANT_TREE_ERROR_HPP_<commit_msg>Update variant_tree_error.hpp<commit_after>//---------------------------------------------------------------------------- /// \file variant_tree_error.hpp /// \author Serge Aleynikov //---------------------------------------------------------------------------- /// Defines variant_tree_error classes for ease of configuration error reporting //---------------------------------------------------------------------------- // Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-06-21 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is a part of utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #pragma once #include <utxx/variant_tree_path.hpp> #include <boost/property_tree/exceptions.hpp> #include <boost/property_tree/detail/file_parser_error.hpp> #include <utxx/error.hpp> #include <stdexcept> namespace utxx { // Errors thrown on bad data typedef boost::property_tree::ptree_bad_data variant_tree_bad_data; typedef boost::property_tree::ptree_bad_path variant_tree_bad_path; typedef boost::property_tree::file_parser_error variant_tree_parser_error; /** * \brief Exception class for configuration related errors. * Example use: * <tt>throw variant_tree_error(a_path, "Test ") << 1 << " result:" << 2;</tt> */ class variant_tree_error : public runtime_error { std::string m_path; void stream() {} template <class T, class... Args> void stream(const T& a, Args... args) { *this << a; stream(args...); } public: variant_tree_error(src_info&& a_si, const std::string& a_path) : runtime_error(std::move(a_si)), m_path(a_path) {} variant_tree_error(const std::string& a_path) : m_path(a_path) {} template <class... Args> variant_tree_error(src_info&& a_si, const std::string& a_path, Args... args) : variant_tree_error(std::move(a_si), a_path) { stream(args...); } template <class... Args> variant_tree_error(const std::string& a_path, Args... args) : variant_tree_error(a_path) { stream(args...); } template <class... Args> variant_tree_error(src_info&& a_si, const tree_path& a_path, Args... args) : variant_tree_error(std::move(a_si), a_path.dump()) { stream(args...); } template <class... Args> variant_tree_error(const tree_path& a_path, Args... args) : variant_tree_error(a_path.dump()) { stream(args...); } virtual ~variant_tree_error() throw() {} const std::string& path() const { return m_path; } virtual std::string str() const { std::stringstream s; s << "Config error [" << m_path << "]: " << m_out->str(); return s.str(); } }; } // namespace utxx <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include "catch.hpp" #include "variant.hpp" #include <cstdint> #include <limits> #include <string> #include <ostream> #include <memory> using namespace mapbox; template <typename T> struct mutating_visitor : util::static_visitor<> { mutating_visitor(T & val) : val_(val) {} void operator() (T & val) const { val = val_; } template <typename T1> void operator() (T1& ) const {} // no-op T & val_; }; TEST_CASE( "variant version", "[variant]" ) { unsigned int version = VARIANT_VERSION; REQUIRE(version == 100); #if VARIANT_VERSION == 100 REQUIRE(true); #else REQUIRE(false); #endif } TEST_CASE( "variant can be moved into vector", "[variant]" ) { typedef util::variant<bool,std::string> variant_type; variant_type v(std::string("test")); std::vector<variant_type> vec; vec.emplace_back(std::move(v)); REQUIRE(v.get<std::string>() != std::string("test")); REQUIRE(vec.at(0).get<std::string>() == std::string("test")); } TEST_CASE( "variant should support built-in types", "[variant]" ) { SECTION( "bool" ) { util::variant<bool> v(true); REQUIRE(v.valid()); REQUIRE(v.is<bool>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<bool>() == true); v.set<bool>(false); REQUIRE(v.get<bool>() == false); v = true; REQUIRE(v == util::variant<bool>(true)); } SECTION( "nullptr" ) { typedef std::nullptr_t value_type; util::variant<value_type> v(nullptr); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); // TODO: commented since it breaks on windows: 'operator << is ambiguous' //REQUIRE(v.get<value_type>() == nullptr); // FIXME: does not compile: ./variant.hpp:340:14: error: use of overloaded operator '<<' is ambiguous (with operand types 'std::__1::basic_ostream<char>' and 'const nullptr_t') // https://github.com/mapbox/variant/issues/14 //REQUIRE(v == util::variant<value_type>(nullptr)); } SECTION( "unique_ptr" ) { typedef std::unique_ptr<std::string> value_type; util::variant<value_type> v(value_type(new std::string("hello"))); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(*v.get<value_type>().get() == *value_type(new std::string("hello")).get()); } SECTION( "string" ) { typedef std::string value_type; util::variant<value_type> v(value_type("hello")); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == value_type("hello")); v.set<value_type>(value_type("there")); REQUIRE(v.get<value_type>() == value_type("there")); v = value_type("variant"); REQUIRE(v == util::variant<value_type>(value_type("variant"))); } SECTION( "size_t" ) { typedef std::size_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(value_type(0)); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int8_t" ) { typedef std::int8_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int16_t" ) { typedef std::int16_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int32_t" ) { typedef std::int32_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int64_t" ) { typedef std::int64_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } } struct MissionInteger { typedef uint64_t value_type; value_type val_; public: MissionInteger(uint64_t val) : val_(val) {} bool operator==(MissionInteger const& rhs) const { return (val_ == rhs.get()); } uint64_t get() const { return val_; } }; // TODO - remove after https://github.com/mapbox/variant/issues/14 std::ostream& operator<< (std::ostream& os, MissionInteger const& rhs) { os << rhs.get(); return os; } TEST_CASE( "variant should support custom types", "[variant]" ) { // http://www.missionintegers.com/integer/34838300 util::variant<MissionInteger> v(MissionInteger(34838300)); REQUIRE(v.valid()); REQUIRE(v.is<MissionInteger>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<MissionInteger>() == MissionInteger(34838300)); REQUIRE(v.get<MissionInteger>().get() == MissionInteger::value_type(34838300)); // TODO: should both of the set usages below compile? v.set<MissionInteger>(MissionInteger::value_type(0)); v.set<MissionInteger>(MissionInteger(0)); REQUIRE(v.get<MissionInteger>().get() == MissionInteger::value_type(0)); v = MissionInteger(1); REQUIRE(v == util::variant<MissionInteger>(MissionInteger(1))); } // Test internal api TEST_CASE( "variant should correctly index types", "[variant]" ) { typedef util::variant<bool,std::string,std::uint64_t,std::int64_t,double,float> variant_type; // Index is in reverse order REQUIRE(variant_type(true).get_type_index() == 5); REQUIRE(variant_type(std::string("test")).get_type_index() == 4); REQUIRE(variant_type(std::uint64_t(0)).get_type_index() == 3); REQUIRE(variant_type(std::int64_t(0)).get_type_index() == 2); REQUIRE(variant_type(double(0.0)).get_type_index() == 1); REQUIRE(variant_type(float(0.0)).get_type_index() == 0); } struct dummy {}; TEST_CASE( "variant value traits", "[variant::detail]" ) { // Users should not create variants with duplicated types // however our type indexing should still work // Index is in reverse order REQUIRE((util::detail::value_traits<bool, bool, int, double, std::string>::index == 3)); REQUIRE((util::detail::value_traits<int, bool, int, double, std::string>::index == 2)); REQUIRE((util::detail::value_traits<double, bool, int, double, std::string>::index == 1)); REQUIRE((util::detail::value_traits<std::string, bool, int, double, std::string>::index == 0)); REQUIRE((util::detail::value_traits<dummy, bool, int, double, std::string>::index == util::detail::invalid_value)); REQUIRE((util::detail::value_traits<std::vector<int>, bool, int, double, std::string>::index == util::detail::invalid_value)); } TEST_CASE( "variant default constructor", "variant()" ) { // By default variant is initilised with (default constructed) first type in template parameters pack // As a reusult first type in Types... must be defaul constructable // NOTE: index in reverse order -> index = N - 1 REQUIRE((util::variant<int, double, std::string>().get_type_index() == 2)); } TEST_CASE( "variant visitation", "unary visitor" ) { util::variant<int, double, std::string> var(123); REQUIRE(var.get<int>() == 123); int val = 456; mutating_visitor<int> visitor(val); util::apply_visitor(visitor,var); REQUIRE(var.get<int>() == 456); } int main (int argc, char* const argv[]) { int result = Catch::Session().run( argc, argv ); if (!result) printf("\x1b[1;32m ✓ \x1b[0m\n"); return result; } <commit_msg>Fix typos, whitespace and test tags.<commit_after>#define CATCH_CONFIG_RUNNER #include "catch.hpp" #include "variant.hpp" #include <cstdint> #include <limits> #include <string> #include <ostream> #include <memory> using namespace mapbox; template <typename T> struct mutating_visitor : util::static_visitor<> { mutating_visitor(T & val) : val_(val) {} void operator() (T & val) const { val = val_; } template <typename T1> void operator() (T1& ) const {} // no-op T & val_; }; TEST_CASE( "variant version", "[variant]" ) { unsigned int version = VARIANT_VERSION; REQUIRE(version == 100); #if VARIANT_VERSION == 100 REQUIRE(true); #else REQUIRE(false); #endif } TEST_CASE( "variant can be moved into vector", "[variant]" ) { typedef util::variant<bool,std::string> variant_type; variant_type v(std::string("test")); std::vector<variant_type> vec; vec.emplace_back(std::move(v)); REQUIRE(v.get<std::string>() != std::string("test")); REQUIRE(vec.at(0).get<std::string>() == std::string("test")); } TEST_CASE( "variant should support built-in types", "[variant]" ) { SECTION( "bool" ) { util::variant<bool> v(true); REQUIRE(v.valid()); REQUIRE(v.is<bool>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<bool>() == true); v.set<bool>(false); REQUIRE(v.get<bool>() == false); v = true; REQUIRE(v == util::variant<bool>(true)); } SECTION( "nullptr" ) { typedef std::nullptr_t value_type; util::variant<value_type> v(nullptr); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); // TODO: commented since it breaks on windows: 'operator << is ambiguous' //REQUIRE(v.get<value_type>() == nullptr); // FIXME: does not compile: ./variant.hpp:340:14: error: use of overloaded operator '<<' is ambiguous (with operand types 'std::__1::basic_ostream<char>' and 'const nullptr_t') // https://github.com/mapbox/variant/issues/14 //REQUIRE(v == util::variant<value_type>(nullptr)); } SECTION( "unique_ptr" ) { typedef std::unique_ptr<std::string> value_type; util::variant<value_type> v(value_type(new std::string("hello"))); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(*v.get<value_type>().get() == *value_type(new std::string("hello")).get()); } SECTION( "string" ) { typedef std::string value_type; util::variant<value_type> v(value_type("hello")); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == value_type("hello")); v.set<value_type>(value_type("there")); REQUIRE(v.get<value_type>() == value_type("there")); v = value_type("variant"); REQUIRE(v == util::variant<value_type>(value_type("variant"))); } SECTION( "size_t" ) { typedef std::size_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(value_type(0)); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int8_t" ) { typedef std::int8_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int16_t" ) { typedef std::int16_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int32_t" ) { typedef std::int32_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int64_t" ) { typedef std::int64_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } } struct MissionInteger { typedef uint64_t value_type; value_type val_; public: MissionInteger(uint64_t val) : val_(val) {} bool operator==(MissionInteger const& rhs) const { return (val_ == rhs.get()); } uint64_t get() const { return val_; } }; // TODO - remove after https://github.com/mapbox/variant/issues/14 std::ostream& operator<<(std::ostream& os, MissionInteger const& rhs) { os << rhs.get(); return os; } TEST_CASE( "variant should support custom types", "[variant]" ) { // http://www.missionintegers.com/integer/34838300 util::variant<MissionInteger> v(MissionInteger(34838300)); REQUIRE(v.valid()); REQUIRE(v.is<MissionInteger>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<MissionInteger>() == MissionInteger(34838300)); REQUIRE(v.get<MissionInteger>().get() == MissionInteger::value_type(34838300)); // TODO: should both of the set usages below compile? v.set<MissionInteger>(MissionInteger::value_type(0)); v.set<MissionInteger>(MissionInteger(0)); REQUIRE(v.get<MissionInteger>().get() == MissionInteger::value_type(0)); v = MissionInteger(1); REQUIRE(v == util::variant<MissionInteger>(MissionInteger(1))); } // Test internal api TEST_CASE( "variant should correctly index types", "[variant]" ) { typedef util::variant<bool,std::string,std::uint64_t,std::int64_t,double,float> variant_type; // Index is in reverse order REQUIRE(variant_type(true).get_type_index() == 5); REQUIRE(variant_type(std::string("test")).get_type_index() == 4); REQUIRE(variant_type(std::uint64_t(0)).get_type_index() == 3); REQUIRE(variant_type(std::int64_t(0)).get_type_index() == 2); REQUIRE(variant_type(double(0.0)).get_type_index() == 1); REQUIRE(variant_type(float(0.0)).get_type_index() == 0); } struct dummy {}; TEST_CASE( "variant value traits", "[variant::detail]" ) { // Users should not create variants with duplicated types // however our type indexing should still work // Index is in reverse order REQUIRE((util::detail::value_traits<bool, bool, int, double, std::string>::index == 3)); REQUIRE((util::detail::value_traits<int, bool, int, double, std::string>::index == 2)); REQUIRE((util::detail::value_traits<double, bool, int, double, std::string>::index == 1)); REQUIRE((util::detail::value_traits<std::string, bool, int, double, std::string>::index == 0)); REQUIRE((util::detail::value_traits<dummy, bool, int, double, std::string>::index == util::detail::invalid_value)); REQUIRE((util::detail::value_traits<std::vector<int>, bool, int, double, std::string>::index == util::detail::invalid_value)); } TEST_CASE( "variant default constructor", "[variant][default constructor]" ) { // By default variant is initialised with (default constructed) first type in template parameters pack // As a result first type in Types... must be default constructable // NOTE: index in reverse order -> index = N - 1 REQUIRE((util::variant<int, double, std::string>().get_type_index() == 2)); } TEST_CASE( "variant visitation", "[visitor][unary visitor]" ) { util::variant<int, double, std::string> var(123); REQUIRE(var.get<int>() == 123); int val = 456; mutating_visitor<int> visitor(val); util::apply_visitor(visitor, var); REQUIRE(var.get<int>() == 456); } int main (int argc, char* const argv[]) { int result = Catch::Session().run(argc, argv); if (!result) printf("\x1b[1;32m ✓ \x1b[0m\n"); return result; } <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include "catch.hpp" #include "variant.hpp" #include <cstdint> #include <limits> #include <string> #include <ostream> #include <memory> using namespace mapbox; template <typename T> struct mutating_visitor : util::static_visitor<> { mutating_visitor(T & val) : val_(val) {} void operator() (T & val) const { val = val_; } template <typename T1> void operator() (T1& ) const {} // no-op T & val_; }; TEST_CASE( "variant version", "[variant]" ) { unsigned int version = VARIANT_VERSION; REQUIRE(version == 100); #if VARIANT_VERSION == 100 REQUIRE(true); #else REQUIRE(false); #endif } TEST_CASE( "variant can be moved into vector", "[variant]" ) { typedef util::variant<bool,std::string> variant_type; variant_type v(std::string("test")); std::vector<variant_type> vec; vec.emplace_back(std::move(v)); REQUIRE(v.get<std::string>() != std::string("test")); REQUIRE(vec.at(0).get<std::string>() == std::string("test")); } TEST_CASE( "variant should support built-in types", "[variant]" ) { SECTION( "bool" ) { util::variant<bool> v(true); REQUIRE(v.valid()); REQUIRE(v.is<bool>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<bool>() == true); v.set<bool>(false); REQUIRE(v.get<bool>() == false); v = true; REQUIRE(v == util::variant<bool>(true)); } SECTION( "nullptr" ) { typedef std::nullptr_t value_type; util::variant<value_type> v(nullptr); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); // TODO: commented since it breaks on windows: 'operator << is ambiguous' //REQUIRE(v.get<value_type>() == nullptr); // FIXME: does not compile: ./variant.hpp:340:14: error: use of overloaded operator '<<' is ambiguous (with operand types 'std::__1::basic_ostream<char>' and 'const nullptr_t') // https://github.com/mapbox/variant/issues/14 //REQUIRE(v == util::variant<value_type>(nullptr)); } SECTION( "unique_ptr" ) { typedef std::unique_ptr<std::string> value_type; util::variant<value_type> v(value_type(new std::string("hello"))); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(*v.get<value_type>().get() == *value_type(new std::string("hello")).get()); } SECTION( "string" ) { typedef std::string value_type; util::variant<value_type> v(value_type("hello")); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == value_type("hello")); v.set<value_type>(value_type("there")); REQUIRE(v.get<value_type>() == value_type("there")); v = value_type("variant"); REQUIRE(v == util::variant<value_type>(value_type("variant"))); } SECTION( "size_t" ) { typedef std::size_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(value_type(0)); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int8_t" ) { typedef std::int8_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int16_t" ) { typedef std::int16_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int32_t" ) { typedef std::int32_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int64_t" ) { typedef std::int64_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } } struct MissionInteger { typedef uint64_t value_type; value_type val_; public: MissionInteger(uint64_t val) : val_(val) {} bool operator==(MissionInteger const& rhs) const { return (val_ == rhs.get()); } uint64_t get() const { return val_; } }; // TODO - remove after https://github.com/mapbox/variant/issues/14 std::ostream& operator<<(std::ostream& os, MissionInteger const& rhs) { os << rhs.get(); return os; } TEST_CASE( "variant should support custom types", "[variant]" ) { // http://www.missionintegers.com/integer/34838300 util::variant<MissionInteger> v(MissionInteger(34838300)); REQUIRE(v.valid()); REQUIRE(v.is<MissionInteger>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<MissionInteger>() == MissionInteger(34838300)); REQUIRE(v.get<MissionInteger>().get() == MissionInteger::value_type(34838300)); // TODO: should both of the set usages below compile? v.set<MissionInteger>(MissionInteger::value_type(0)); v.set<MissionInteger>(MissionInteger(0)); REQUIRE(v.get<MissionInteger>().get() == MissionInteger::value_type(0)); v = MissionInteger(1); REQUIRE(v == util::variant<MissionInteger>(MissionInteger(1))); } // Test internal api TEST_CASE( "variant should correctly index types", "[variant]" ) { typedef util::variant<bool,std::string,std::uint64_t,std::int64_t,double,float> variant_type; // Index is in reverse order REQUIRE(variant_type(true).get_type_index() == 5); REQUIRE(variant_type(std::string("test")).get_type_index() == 4); REQUIRE(variant_type(std::uint64_t(0)).get_type_index() == 3); REQUIRE(variant_type(std::int64_t(0)).get_type_index() == 2); REQUIRE(variant_type(double(0.0)).get_type_index() == 1); REQUIRE(variant_type(float(0.0)).get_type_index() == 0); } struct dummy {}; TEST_CASE( "variant value traits", "[variant::detail]" ) { // Users should not create variants with duplicated types // however our type indexing should still work // Index is in reverse order REQUIRE((util::detail::value_traits<bool, bool, int, double, std::string>::index == 3)); REQUIRE((util::detail::value_traits<int, bool, int, double, std::string>::index == 2)); REQUIRE((util::detail::value_traits<double, bool, int, double, std::string>::index == 1)); REQUIRE((util::detail::value_traits<std::string, bool, int, double, std::string>::index == 0)); REQUIRE((util::detail::value_traits<dummy, bool, int, double, std::string>::index == util::detail::invalid_value)); REQUIRE((util::detail::value_traits<std::vector<int>, bool, int, double, std::string>::index == util::detail::invalid_value)); } TEST_CASE( "variant default constructor", "[variant][default constructor]" ) { // By default variant is initialised with (default constructed) first type in template parameters pack // As a result first type in Types... must be default constructable // NOTE: index in reverse order -> index = N - 1 REQUIRE((util::variant<int, double, std::string>().get_type_index() == 2)); } TEST_CASE( "variant visitation", "[visitor][unary visitor]" ) { util::variant<int, double, std::string> var(123); REQUIRE(var.get<int>() == 123); int val = 456; mutating_visitor<int> visitor(val); util::apply_visitor(visitor, var); REQUIRE(var.get<int>() == 456); } int main (int argc, char* const argv[]) { int result = Catch::Session().run(argc, argv); if (!result) printf("\x1b[1;32m ✓ \x1b[0m\n"); return result; } <commit_msg>Add tests for implicit conversion and exceptions for wrong types.<commit_after>#define CATCH_CONFIG_RUNNER #include "catch.hpp" #include "variant.hpp" #include <cstdint> #include <limits> #include <string> #include <ostream> #include <memory> using namespace mapbox; template <typename T> struct mutating_visitor : util::static_visitor<> { mutating_visitor(T & val) : val_(val) {} void operator() (T & val) const { val = val_; } template <typename T1> void operator() (T1& ) const {} // no-op T & val_; }; TEST_CASE( "variant version", "[variant]" ) { unsigned int version = VARIANT_VERSION; REQUIRE(version == 100); #if VARIANT_VERSION == 100 REQUIRE(true); #else REQUIRE(false); #endif } TEST_CASE( "variant can be moved into vector", "[variant]" ) { typedef util::variant<bool,std::string> variant_type; variant_type v(std::string("test")); std::vector<variant_type> vec; vec.emplace_back(std::move(v)); REQUIRE(v.get<std::string>() != std::string("test")); REQUIRE(vec.at(0).get<std::string>() == std::string("test")); } TEST_CASE( "variant should support built-in types", "[variant]" ) { SECTION( "bool" ) { util::variant<bool> v(true); REQUIRE(v.valid()); REQUIRE(v.is<bool>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<bool>() == true); v.set<bool>(false); REQUIRE(v.get<bool>() == false); v = true; REQUIRE(v == util::variant<bool>(true)); } SECTION( "nullptr" ) { typedef std::nullptr_t value_type; util::variant<value_type> v(nullptr); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); // TODO: commented since it breaks on windows: 'operator << is ambiguous' //REQUIRE(v.get<value_type>() == nullptr); // FIXME: does not compile: ./variant.hpp:340:14: error: use of overloaded operator '<<' is ambiguous (with operand types 'std::__1::basic_ostream<char>' and 'const nullptr_t') // https://github.com/mapbox/variant/issues/14 //REQUIRE(v == util::variant<value_type>(nullptr)); } SECTION( "unique_ptr" ) { typedef std::unique_ptr<std::string> value_type; util::variant<value_type> v(value_type(new std::string("hello"))); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(*v.get<value_type>().get() == *value_type(new std::string("hello")).get()); } SECTION( "string" ) { typedef std::string value_type; util::variant<value_type> v(value_type("hello")); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == value_type("hello")); v.set<value_type>(value_type("there")); REQUIRE(v.get<value_type>() == value_type("there")); v = value_type("variant"); REQUIRE(v == util::variant<value_type>(value_type("variant"))); } SECTION( "size_t" ) { typedef std::size_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(value_type(0)); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int8_t" ) { typedef std::int8_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int16_t" ) { typedef std::int16_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int32_t" ) { typedef std::int32_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } SECTION( "int64_t" ) { typedef std::int64_t value_type; util::variant<value_type> v(std::numeric_limits<value_type>::max()); REQUIRE(v.valid()); REQUIRE(v.is<value_type>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<value_type>() == std::numeric_limits<value_type>::max()); v.set<value_type>(0); REQUIRE(v.get<value_type>() == value_type(0)); v = value_type(1); REQUIRE(v == util::variant<value_type>(value_type(1))); } } struct MissionInteger { typedef uint64_t value_type; value_type val_; public: MissionInteger(uint64_t val) : val_(val) {} bool operator==(MissionInteger const& rhs) const { return (val_ == rhs.get()); } uint64_t get() const { return val_; } }; // TODO - remove after https://github.com/mapbox/variant/issues/14 std::ostream& operator<<(std::ostream& os, MissionInteger const& rhs) { os << rhs.get(); return os; } TEST_CASE( "variant should support custom types", "[variant]" ) { // http://www.missionintegers.com/integer/34838300 util::variant<MissionInteger> v(MissionInteger(34838300)); REQUIRE(v.valid()); REQUIRE(v.is<MissionInteger>()); REQUIRE(v.get_type_index() == 0); REQUIRE(v.get<MissionInteger>() == MissionInteger(34838300)); REQUIRE(v.get<MissionInteger>().get() == MissionInteger::value_type(34838300)); // TODO: should both of the set usages below compile? v.set<MissionInteger>(MissionInteger::value_type(0)); v.set<MissionInteger>(MissionInteger(0)); REQUIRE(v.get<MissionInteger>().get() == MissionInteger::value_type(0)); v = MissionInteger(1); REQUIRE(v == util::variant<MissionInteger>(MissionInteger(1))); } // Test internal api TEST_CASE( "variant should correctly index types", "[variant]" ) { typedef util::variant<bool,std::string,std::uint64_t,std::int64_t,double,float> variant_type; // Index is in reverse order REQUIRE(variant_type(true).get_type_index() == 5); REQUIRE(variant_type(std::string("test")).get_type_index() == 4); REQUIRE(variant_type(std::uint64_t(0)).get_type_index() == 3); REQUIRE(variant_type(std::int64_t(0)).get_type_index() == 2); REQUIRE(variant_type(double(0.0)).get_type_index() == 1); REQUIRE(variant_type(float(0.0)).get_type_index() == 0); } TEST_CASE( "get with type not in variant type list should throw", "[variant]" ) { typedef util::variant<int> variant_type; variant_type var = 5; REQUIRE(var.get<int>() == 5); REQUIRE_THROWS(var.get<double>()); // XXX shouldn't this be a compile time error? See https://github.com/mapbox/variant/issues/24 } TEST_CASE( "get with wrong type (here: double) should throw", "[variant]" ) { typedef util::variant<int, double> variant_type; variant_type var = 5; REQUIRE(var.get<int>() == 5); REQUIRE_THROWS(var.get<double>()); } TEST_CASE( "get with wrong type (here: int) should throw", "[variant]" ) { typedef util::variant<int, double> variant_type; variant_type var = 5.0; REQUIRE(var.get<double>() == 5.0); REQUIRE_THROWS(var.get<int>()); } TEST_CASE( "implicit conversion", "[variant][implicit conversion]" ) { typedef util::variant<int> variant_type; variant_type var(5.0); // converted to int REQUIRE(var.get<int>() == 5); REQUIRE_THROWS(var.get<double>()); var = 6.0; // works for operator=, too REQUIRE(var.get<int>() == 6); } TEST_CASE( "implicit conversion to first type in variant type list", "[variant][implicit conversion]" ) { typedef util::variant<long, char> variant_type; variant_type var = 5.0; // converted to long REQUIRE(var.get<long>() == 5); REQUIRE_THROWS(var.get<char>()); REQUIRE_THROWS(var.get<double>()); } struct dummy {}; TEST_CASE( "implicit conversion to first type it can convert to even if it doesn't fit", "[variant][implicit conversion]" ) { typedef util::variant<dummy, unsigned char, long> variant_type; variant_type var = 500.0; // converted to unsigned char, even if it doesn't fit REQUIRE(var.get<unsigned char>() == static_cast<unsigned char>(500.0)); REQUIRE_THROWS(var.get<long>()); var = 500; // int converted to unsigned char, even if it doesn't fit REQUIRE(var.get<unsigned char>() == static_cast<unsigned char>(500)); REQUIRE_THROWS(var.get<long>()); var = 500L; // explicit long is okay REQUIRE(var.get<long>() == 500L); REQUIRE_THROWS(var.get<char>()); } TEST_CASE( "variant value traits", "[variant::detail]" ) { // Users should not create variants with duplicated types // however our type indexing should still work // Index is in reverse order REQUIRE((util::detail::value_traits<bool, bool, int, double, std::string>::index == 3)); REQUIRE((util::detail::value_traits<int, bool, int, double, std::string>::index == 2)); REQUIRE((util::detail::value_traits<double, bool, int, double, std::string>::index == 1)); REQUIRE((util::detail::value_traits<std::string, bool, int, double, std::string>::index == 0)); REQUIRE((util::detail::value_traits<dummy, bool, int, double, std::string>::index == util::detail::invalid_value)); REQUIRE((util::detail::value_traits<std::vector<int>, bool, int, double, std::string>::index == util::detail::invalid_value)); } TEST_CASE( "variant default constructor", "[variant][default constructor]" ) { // By default variant is initialised with (default constructed) first type in template parameters pack // As a result first type in Types... must be default constructable // NOTE: index in reverse order -> index = N - 1 REQUIRE((util::variant<int, double, std::string>().get_type_index() == 2)); } TEST_CASE( "variant visitation", "[visitor][unary visitor]" ) { util::variant<int, double, std::string> var(123); REQUIRE(var.get<int>() == 123); int val = 456; mutating_visitor<int> visitor(val); util::apply_visitor(visitor, var); REQUIRE(var.get<int>() == 456); } int main (int argc, char* const argv[]) { int result = Catch::Session().run(argc, argv); if (!result) printf("\x1b[1;32m ✓ \x1b[0m\n"); return result; } <|endoftext|>
<commit_before>#ifndef ORG_EEROS_CONTROL_CONSTANT_HPP_ #define ORG_EEROS_CONTROL_CONSTANT_HPP_ #include <type_traits> #include <eeros/control/Block1o.hpp> #include <eeros/core/System.hpp> namespace eeros { namespace control { template < typename T = double > class Constant : public Block1o<T> { public: Constant() { _clear<T>(); } Constant(T v) { value = v; } virtual void run() { this->out.getSignal().setValue(value); this->out.getSignal().setTimestamp(System::getTimeNs()); } virtual void setValue(T newValue) { value = newValue; } protected: T value; private: template <typename S> typename std::enable_if<std::is_arithmetic<S>::value>::type _clear() { value = 0; } template <typename S> typename std::enable_if<!std::is_arithmetic<S>::value>::type _clear() { value.fill(0); } }; }; }; #endif /* ORG_EEROS_CONTROL_CONSTANT_HPP_ */ <commit_msg>use initializer list<commit_after>#ifndef ORG_EEROS_CONTROL_CONSTANT_HPP_ #define ORG_EEROS_CONTROL_CONSTANT_HPP_ #include <type_traits> #include <eeros/control/Block1o.hpp> #include <eeros/core/System.hpp> namespace eeros { namespace control { template < typename T = double > class Constant : public Block1o<T> { public: Constant() { _clear<T>(); } Constant(T v) : value(v) { } virtual void run() { this->out.getSignal().setValue(value); this->out.getSignal().setTimestamp(System::getTimeNs()); } virtual void setValue(T newValue) { value = newValue; } protected: T value; private: template <typename S> typename std::enable_if<std::is_arithmetic<S>::value>::type _clear() { value = 0; } template <typename S> typename std::enable_if<!std::is_arithmetic<S>::value>::type _clear() { value.fill(0); } }; }; }; #endif /* ORG_EEROS_CONTROL_CONSTANT_HPP_ */ <|endoftext|>
<commit_before>/**************************************************************************** ** Meta object code from reading C++ file 'oldnormalizeobject.h' ** ** Created: Wed Nov 18 11:43:05 2009 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../../../../master/tests/auto/qobject/oldnormalizeobject.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'oldnormalizeobject.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_OldNormalizeObject[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 6, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: signature, parameters, type, tag, flags 24, 20, 19, 19, 0x05, 57, 20, 19, 19, 0x05, 100, 20, 19, 19, 0x05, // slots: signature, parameters, type, tag, flags 149, 20, 19, 19, 0x0a, 180, 20, 19, 19, 0x0a, 221, 20, 19, 19, 0x0a, 0 // eod }; static const char qt_meta_stringdata_OldNormalizeObject[] = { "OldNormalizeObject\0\0ref\0" "typeRefSignal(Template<Class&>&)\0" "constTypeRefSignal(Template<const Class&>)\0" "typeConstRefSignal(Template<const Class&>const&)\0" "typeRefSlot(Template<Class&>&)\0" "constTypeRefSlot(Template<const Class&>)\0" "typeConstRefSlot(Template<const Class&>const&)\0" }; const QMetaObject OldNormalizeObject::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_OldNormalizeObject, qt_meta_data_OldNormalizeObject, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &OldNormalizeObject::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *OldNormalizeObject::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *OldNormalizeObject::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_OldNormalizeObject)) return static_cast<void*>(const_cast< OldNormalizeObject*>(this)); return QObject::qt_metacast(_clname); } int OldNormalizeObject::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: typeRefSignal((*reinterpret_cast< Template<Class&>(*)>(_a[1]))); break; case 1: constTypeRefSignal((*reinterpret_cast< const Template<const Class&>(*)>(_a[1]))); break; case 2: typeConstRefSignal((*reinterpret_cast< Template<const Class&>const(*)>(_a[1]))); break; case 3: typeRefSlot((*reinterpret_cast< Template<Class&>(*)>(_a[1]))); break; case 4: constTypeRefSlot((*reinterpret_cast< const Template<const Class&>(*)>(_a[1]))); break; case 5: typeConstRefSlot((*reinterpret_cast< Template<const Class&>const(*)>(_a[1]))); break; default: ; } _id -= 6; } return _id; } // SIGNAL 0 void OldNormalizeObject::typeRefSignal(Template<Class&> & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void OldNormalizeObject::constTypeRefSignal(const Template<const Class&> & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void OldNormalizeObject::typeConstRefSignal(Template<Class const&> const & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } QT_END_MOC_NAMESPACE <commit_msg>Fix compilation of the QObject test<commit_after>/**************************************************************************** ** Meta object code from reading C++ file 'oldnormalizeobject.h' ** ** Created: Wed Nov 18 11:43:05 2009 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.0) ** *****************************************************************************/ // Yhis file was generated from moc version 4.6 to test binary compatibility // It should *not* be generated by the current moc #include "oldnormalizeobject.h" QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_OldNormalizeObject[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 6, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: signature, parameters, type, tag, flags 24, 20, 19, 19, 0x05, 57, 20, 19, 19, 0x05, 100, 20, 19, 19, 0x05, // slots: signature, parameters, type, tag, flags 149, 20, 19, 19, 0x0a, 180, 20, 19, 19, 0x0a, 221, 20, 19, 19, 0x0a, 0 // eod }; static const char qt_meta_stringdata_OldNormalizeObject[] = { "OldNormalizeObject\0\0ref\0" "typeRefSignal(Template<Class&>&)\0" "constTypeRefSignal(Template<const Class&>)\0" "typeConstRefSignal(Template<const Class&>const&)\0" "typeRefSlot(Template<Class&>&)\0" "constTypeRefSlot(Template<const Class&>)\0" "typeConstRefSlot(Template<const Class&>const&)\0" }; const QMetaObject OldNormalizeObject::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_OldNormalizeObject, qt_meta_data_OldNormalizeObject, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &OldNormalizeObject::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *OldNormalizeObject::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *OldNormalizeObject::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_OldNormalizeObject)) return static_cast<void*>(const_cast< OldNormalizeObject*>(this)); return QObject::qt_metacast(_clname); } int OldNormalizeObject::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: typeRefSignal((*reinterpret_cast< Template<Class&>(*)>(_a[1]))); break; case 1: constTypeRefSignal((*reinterpret_cast< const Template<const Class&>(*)>(_a[1]))); break; case 2: typeConstRefSignal((*reinterpret_cast< Template<const Class&>const(*)>(_a[1]))); break; case 3: typeRefSlot((*reinterpret_cast< Template<Class&>(*)>(_a[1]))); break; case 4: constTypeRefSlot((*reinterpret_cast< const Template<const Class&>(*)>(_a[1]))); break; case 5: typeConstRefSlot((*reinterpret_cast< Template<const Class&>const(*)>(_a[1]))); break; default: ; } _id -= 6; } return _id; } // SIGNAL 0 void OldNormalizeObject::typeRefSignal(Template<Class&> & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void OldNormalizeObject::constTypeRefSignal(const Template<const Class&> & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void OldNormalizeObject::typeConstRefSignal(Template<Class const&> const & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } QT_END_MOC_NAMESPACE <|endoftext|>
<commit_before>//===--- PartialApplyCombiner.cpp -----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SIL/SILValue.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "swift/SILOptimizer/Utils/ValueLifetime.h" using namespace swift; namespace { // Helper class performing the apply{partial_apply(x,y)}(z) -> apply(z,x,y) // peephole. class PartialApplyCombiner { // True if temporaries are not created yet. bool isFirstTime = true; // partial_apply which is being processed. PartialApplyInst *pai; // Temporaries created as copies of alloc_stack arguments of // the partial_apply. SmallVector<SILValue, 8> tmpCopies; // Mapping from the original argument of partial_apply to // the temporary containing its copy. llvm::DenseMap<SILValue, SILValue> argToTmpCopy; // Set of lifetime endpoints for this partial_apply. // // Used to find the last uses of partial_apply, which is need to insert // releases/destroys of temporaries as early as possible. ValueLifetimeAnalysis::Frontier partialApplyFrontier; SILBuilder &builder; InstModCallbacks &callbacks; bool processSingleApply(FullApplySite ai); bool allocateTemporaries(); void deallocateTemporaries(); void destroyTemporaries(); public: PartialApplyCombiner(PartialApplyInst *pai, SILBuilder &builder, InstModCallbacks &callbacks) : isFirstTime(true), pai(pai), builder(builder), callbacks(callbacks) {} SILInstruction *combine(); }; } // end anonymous namespace /// Returns true on success. bool PartialApplyCombiner::allocateTemporaries() { // A partial_apply [stack]'s argument are not owned by the partial_apply and // therefore their lifetime must outlive any uses. if (pai->isOnStack()) { return true; } // Copy the original arguments of the partial_apply into newly created // temporaries and use these temporaries instead of the original arguments // afterwards. // // This is done to "extend" the life-time of original partial_apply arguments, // as they may be destroyed/deallocated before the last use by one of the // apply instructions. // // TODO: Copy arguments of the partial_apply into new temporaries only if the // lifetime of arguments ends before their uses by apply instructions. bool needsDestroys = false; CanSILFunctionType paiTy = pai->getCallee()->getType().getAs<SILFunctionType>(); // Emit a destroy value for each captured closure argument. ArrayRef<SILParameterInfo> paramList = paiTy->getParameters(); auto argList = pai->getArguments(); paramList = paramList.drop_front(paramList.size() - argList.size()); llvm::SmallVector<std::pair<SILValue, uint16_t>, 8> argsToHandle; for (unsigned i : indices(argList)) { SILValue arg = argList[i]; SILParameterInfo param = paramList[i]; if (param.isIndirectMutating()) continue; // Create a temporary and copy the argument into it, if: // - the argument stems from an alloc_stack // - the argument is consumed by the callee and is indirect // (e.g. it is an @in argument) if (isa<AllocStackInst>(arg) || (param.isConsumed() && pai->getSubstCalleeConv().isSILIndirect(param))) { // If the argument has a dependent type, then we can not create a // temporary for it at the beginning of the function, so we must bail. // // TODO: This is because we are inserting alloc_stack at the beginning/end // of functions where the dependent type may not exist yet. if (arg->getType().hasOpenedExistential()) return false; // If the temporary is non-trivial, we need to destroy it later. if (!arg->getType().isTrivial(*pai->getFunction())) needsDestroys = true; argsToHandle.push_back(std::make_pair(arg, i)); } } if (needsDestroys) { // Compute the set of endpoints, which will be used to insert destroys of // temporaries. This may fail if the frontier is located on a critical edge // which we may not split (no CFG changes in SILCombine). ValueLifetimeAnalysis vla(pai); if (!vla.computeFrontier(partialApplyFrontier, ValueLifetimeAnalysis::DontModifyCFG)) return false; } for (auto argWithIdx : argsToHandle) { SILValue Arg = argWithIdx.first; builder.setInsertionPoint(pai->getFunction()->begin()->begin()); // Create a new temporary at the beginning of a function. SILDebugVariable dbgVar(/*Constant*/ true, argWithIdx.second); auto *tmp = builder.createAllocStack(pai->getLoc(), Arg->getType(), dbgVar); builder.setInsertionPoint(pai); // Copy argument into this temporary. builder.createCopyAddr(pai->getLoc(), Arg, tmp, IsTake_t::IsNotTake, IsInitialization_t::IsInitialization); tmpCopies.push_back(tmp); argToTmpCopy.insert(std::make_pair(Arg, tmp)); } return true; } /// Emit dealloc_stack for all temporaries. void PartialApplyCombiner::deallocateTemporaries() { // Insert dealloc_stack instructions at all function exit points. for (SILBasicBlock &block : *pai->getFunction()) { TermInst *term = block.getTerminator(); if (!term->isFunctionExiting()) continue; for (auto copy : tmpCopies) { builder.setInsertionPoint(term); builder.createDeallocStack(pai->getLoc(), copy); } } } /// Emit code to release/destroy temporaries. void PartialApplyCombiner::destroyTemporaries() { // Insert releases and destroy_addrs as early as possible, // because we don't want to keep objects alive longer than // its really needed. for (auto op : tmpCopies) { auto tmpType = op->getType().getObjectType(); if (tmpType.isTrivial(*pai->getFunction())) continue; for (auto *endPoint : partialApplyFrontier) { builder.setInsertionPoint(endPoint); if (!tmpType.isAddressOnly(*pai->getFunction())) { SILValue load = builder.emitLoadValueOperation( pai->getLoc(), op, LoadOwnershipQualifier::Take); builder.emitDestroyValueOperation(pai->getLoc(), load); } else { builder.createDestroyAddr(pai->getLoc(), op); } } } } /// Process an apply instruction which uses a partial_apply /// as its callee. /// Returns true on success. bool PartialApplyCombiner::processSingleApply(FullApplySite paiAI) { builder.setInsertionPoint(paiAI.getInstruction()); builder.setCurrentDebugScope(paiAI.getDebugScope()); // Prepare the args. SmallVector<SILValue, 8> argList; // First the ApplyInst args. for (auto Op : paiAI.getArguments()) argList.push_back(Op); SILInstruction *insertPoint = &*builder.getInsertionPoint(); // Next, the partial apply args. // Pre-process partial_apply arguments only once, lazily. if (isFirstTime) { isFirstTime = false; if (!allocateTemporaries()) return false; } // Now, copy over the partial apply args. for (auto arg : pai->getArguments()) { // If there is new temporary for this argument, use it instead. if (argToTmpCopy.count(arg)) { arg = argToTmpCopy.lookup(arg); } argList.push_back(arg); } builder.setInsertionPoint(insertPoint); builder.setCurrentDebugScope(paiAI.getDebugScope()); // The thunk that implements the partial apply calls the closure function // that expects all arguments to be consumed by the function. However, the // captured arguments are not arguments of *this* apply, so they are not // pre-incremented. When we combine the partial_apply and this apply into // a new apply we need to retain all of the closure non-address type // arguments. auto paramInfo = pai->getSubstCalleeType()->getParameters(); auto partialApplyArgs = pai->getArguments(); // Set of arguments that need to be destroyed after each invocation. SmallVector<SILValue, 8> toBeDestroyedArgs; for (unsigned i : indices(partialApplyArgs)) { auto arg = partialApplyArgs[i]; if (!arg->getType().isAddress()) { // Copy the argument as the callee may consume it. arg = builder.emitCopyValueOperation(pai->getLoc(), arg); // For non consumed parameters (e.g. guaranteed), we also need to // insert destroys after each apply instruction that we create. if (!paramInfo[paramInfo.size() - partialApplyArgs.size() + i] .isConsumed()) toBeDestroyedArgs.push_back(arg); } } auto callee = pai->getCallee(); SubstitutionMap subs = pai->getSubstitutionMap(); // The partial_apply might be substituting in an open existential type. builder.addOpenedArchetypeOperands(pai); FullApplySite nai; if (auto *tai = dyn_cast<TryApplyInst>(paiAI)) nai = builder.createTryApply(paiAI.getLoc(), callee, subs, argList, tai->getNormalBB(), tai->getErrorBB()); else nai = builder.createApply(paiAI.getLoc(), callee, subs, argList, cast<ApplyInst>(paiAI)->isNonThrowing()); // We also need to destroy the partial_apply instruction itself because it is // consumed by the apply_instruction. auto loc = RegularLocation::getAutoGeneratedLocation(); paiAI.insertAfterFullEvaluation([&](SILBasicBlock::iterator insertPt) { SILBuilderWithScope builder(insertPt); for (auto arg : toBeDestroyedArgs) { builder.emitDestroyValueOperation(loc, arg); } if (!pai->hasCalleeGuaranteedContext()) { builder.emitDestroyValueOperation(loc, pai); } }); if (auto *apply = dyn_cast<ApplyInst>(paiAI)) { callbacks.replaceValueUsesWith(SILValue(apply), cast<ApplyInst>(nai.getInstruction())); } callbacks.deleteInst(paiAI.getInstruction()); return true; } /// Perform the apply{partial_apply(x,y)}(z) -> apply(z,x,y) peephole /// by iterating over all uses of the partial_apply and searching /// for the pattern to transform. SILInstruction *PartialApplyCombiner::combine() { // We need to model @unowned_inner_pointer better before we can do the // peephole here. for (auto resultInfo : pai->getSubstCalleeType()->getResults()) if (resultInfo.getConvention() == ResultConvention::UnownedInnerPointer) return nullptr; // Iterate over all uses of the partial_apply // and look for applies that use it as a callee. // Worklist of operands. SmallVector<Operand *, 8> uses(pai->getUses()); // Uses may grow in this loop. for (size_t useIndex = 0; useIndex < uses.size(); ++useIndex) { auto *use = uses[useIndex]; auto *user = use->getUser(); // Recurse through conversions. if (auto *cfi = dyn_cast<ConvertEscapeToNoEscapeInst>(user)) { // TODO: Handle argument conversion. All the code in this file needs to be // cleaned up and generalized. The argument conversion handling in // optimizeApplyOfConvertFunctionInst should apply to any combine // involving an apply, not just a specific pattern. // // For now, just handle conversion to @noescape, which is irrelevant for // direct application of the closure. auto convertCalleeTy = cfi->getType().castTo<SILFunctionType>(); auto escapingCalleeTy = convertCalleeTy->getWithExtInfo( convertCalleeTy->getExtInfo().withNoEscape(false)); assert(use->get()->getType().castTo<SILFunctionType>() == escapingCalleeTy); (void)escapingCalleeTy; llvm::copy(cfi->getUses(), std::back_inserter(uses)); continue; } // Look through mark_dependence users of partial_apply [stack]. if (auto *mdi = dyn_cast<MarkDependenceInst>(user)) { if (mdi->getValue() == use->get() && mdi->getValue()->getType().is<SILFunctionType>() && mdi->getValue()->getType().castTo<SILFunctionType>()->isNoEscape()) { llvm::copy(mdi->getUses(), std::back_inserter(uses)); } continue; } // If this use of a partial_apply is not // an apply which uses it as a callee, bail. auto ai = FullApplySite::isa(user); if (!ai) continue; if (ai.getCallee() != use->get()) continue; // We cannot handle generic apply yet. Bail. if (ai.hasSubstitutions()) continue; if (!processSingleApply(ai)) return nullptr; } // release/destroy and deallocate introduced temporaries. if (!tmpCopies.empty()) { destroyTemporaries(); deallocateTemporaries(); } return nullptr; } //===----------------------------------------------------------------------===// // Top Level Entrypoint //===----------------------------------------------------------------------===// SILInstruction *swift::tryOptimizeApplyOfPartialApply( PartialApplyInst *pai, SILBuilder &builder, InstModCallbacks callbacks) { PartialApplyCombiner combiner(pai, builder, callbacks); return combiner.combine(); } <commit_msg>[pa-combiner] Use llvm::any_of instead of a for loop.<commit_after>//===--- PartialApplyCombiner.cpp -----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SIL/SILValue.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "swift/SILOptimizer/Utils/ValueLifetime.h" using namespace swift; namespace { // Helper class performing the apply{partial_apply(x,y)}(z) -> apply(z,x,y) // peephole. class PartialApplyCombiner { // True if temporaries are not created yet. bool isFirstTime = true; // partial_apply which is being processed. PartialApplyInst *pai; // Temporaries created as copies of alloc_stack arguments of // the partial_apply. SmallVector<SILValue, 8> tmpCopies; // Mapping from the original argument of partial_apply to // the temporary containing its copy. llvm::DenseMap<SILValue, SILValue> argToTmpCopy; // Set of lifetime endpoints for this partial_apply. // // Used to find the last uses of partial_apply, which is need to insert // releases/destroys of temporaries as early as possible. ValueLifetimeAnalysis::Frontier partialApplyFrontier; SILBuilder &builder; InstModCallbacks &callbacks; bool processSingleApply(FullApplySite ai); bool allocateTemporaries(); void deallocateTemporaries(); void destroyTemporaries(); public: PartialApplyCombiner(PartialApplyInst *pai, SILBuilder &builder, InstModCallbacks &callbacks) : isFirstTime(true), pai(pai), builder(builder), callbacks(callbacks) {} SILInstruction *combine(); }; } // end anonymous namespace /// Returns true on success. bool PartialApplyCombiner::allocateTemporaries() { // A partial_apply [stack]'s argument are not owned by the partial_apply and // therefore their lifetime must outlive any uses. if (pai->isOnStack()) { return true; } // Copy the original arguments of the partial_apply into newly created // temporaries and use these temporaries instead of the original arguments // afterwards. // // This is done to "extend" the life-time of original partial_apply arguments, // as they may be destroyed/deallocated before the last use by one of the // apply instructions. // // TODO: Copy arguments of the partial_apply into new temporaries only if the // lifetime of arguments ends before their uses by apply instructions. bool needsDestroys = false; CanSILFunctionType paiTy = pai->getCallee()->getType().getAs<SILFunctionType>(); // Emit a destroy value for each captured closure argument. ArrayRef<SILParameterInfo> paramList = paiTy->getParameters(); auto argList = pai->getArguments(); paramList = paramList.drop_front(paramList.size() - argList.size()); llvm::SmallVector<std::pair<SILValue, uint16_t>, 8> argsToHandle; for (unsigned i : indices(argList)) { SILValue arg = argList[i]; SILParameterInfo param = paramList[i]; if (param.isIndirectMutating()) continue; // Create a temporary and copy the argument into it, if: // - the argument stems from an alloc_stack // - the argument is consumed by the callee and is indirect // (e.g. it is an @in argument) if (isa<AllocStackInst>(arg) || (param.isConsumed() && pai->getSubstCalleeConv().isSILIndirect(param))) { // If the argument has a dependent type, then we can not create a // temporary for it at the beginning of the function, so we must bail. // // TODO: This is because we are inserting alloc_stack at the beginning/end // of functions where the dependent type may not exist yet. if (arg->getType().hasOpenedExistential()) return false; // If the temporary is non-trivial, we need to destroy it later. if (!arg->getType().isTrivial(*pai->getFunction())) needsDestroys = true; argsToHandle.push_back(std::make_pair(arg, i)); } } if (needsDestroys) { // Compute the set of endpoints, which will be used to insert destroys of // temporaries. This may fail if the frontier is located on a critical edge // which we may not split (no CFG changes in SILCombine). ValueLifetimeAnalysis vla(pai); if (!vla.computeFrontier(partialApplyFrontier, ValueLifetimeAnalysis::DontModifyCFG)) return false; } for (auto argWithIdx : argsToHandle) { SILValue Arg = argWithIdx.first; builder.setInsertionPoint(pai->getFunction()->begin()->begin()); // Create a new temporary at the beginning of a function. SILDebugVariable dbgVar(/*Constant*/ true, argWithIdx.second); auto *tmp = builder.createAllocStack(pai->getLoc(), Arg->getType(), dbgVar); builder.setInsertionPoint(pai); // Copy argument into this temporary. builder.createCopyAddr(pai->getLoc(), Arg, tmp, IsTake_t::IsNotTake, IsInitialization_t::IsInitialization); tmpCopies.push_back(tmp); argToTmpCopy.insert(std::make_pair(Arg, tmp)); } return true; } /// Emit dealloc_stack for all temporaries. void PartialApplyCombiner::deallocateTemporaries() { // Insert dealloc_stack instructions at all function exit points. for (SILBasicBlock &block : *pai->getFunction()) { TermInst *term = block.getTerminator(); if (!term->isFunctionExiting()) continue; for (auto copy : tmpCopies) { builder.setInsertionPoint(term); builder.createDeallocStack(pai->getLoc(), copy); } } } /// Emit code to release/destroy temporaries. void PartialApplyCombiner::destroyTemporaries() { // Insert releases and destroy_addrs as early as possible, // because we don't want to keep objects alive longer than // its really needed. for (auto op : tmpCopies) { auto tmpType = op->getType().getObjectType(); if (tmpType.isTrivial(*pai->getFunction())) continue; for (auto *endPoint : partialApplyFrontier) { builder.setInsertionPoint(endPoint); if (!tmpType.isAddressOnly(*pai->getFunction())) { SILValue load = builder.emitLoadValueOperation( pai->getLoc(), op, LoadOwnershipQualifier::Take); builder.emitDestroyValueOperation(pai->getLoc(), load); } else { builder.createDestroyAddr(pai->getLoc(), op); } } } } /// Process an apply instruction which uses a partial_apply /// as its callee. /// Returns true on success. bool PartialApplyCombiner::processSingleApply(FullApplySite paiAI) { builder.setInsertionPoint(paiAI.getInstruction()); builder.setCurrentDebugScope(paiAI.getDebugScope()); // Prepare the args. SmallVector<SILValue, 8> argList; // First the ApplyInst args. for (auto Op : paiAI.getArguments()) argList.push_back(Op); SILInstruction *insertPoint = &*builder.getInsertionPoint(); // Next, the partial apply args. // Pre-process partial_apply arguments only once, lazily. if (isFirstTime) { isFirstTime = false; if (!allocateTemporaries()) return false; } // Now, copy over the partial apply args. for (auto arg : pai->getArguments()) { // If there is new temporary for this argument, use it instead. if (argToTmpCopy.count(arg)) { arg = argToTmpCopy.lookup(arg); } argList.push_back(arg); } builder.setInsertionPoint(insertPoint); builder.setCurrentDebugScope(paiAI.getDebugScope()); // The thunk that implements the partial apply calls the closure function // that expects all arguments to be consumed by the function. However, the // captured arguments are not arguments of *this* apply, so they are not // pre-incremented. When we combine the partial_apply and this apply into // a new apply we need to retain all of the closure non-address type // arguments. auto paramInfo = pai->getSubstCalleeType()->getParameters(); auto partialApplyArgs = pai->getArguments(); // Set of arguments that need to be destroyed after each invocation. SmallVector<SILValue, 8> toBeDestroyedArgs; for (unsigned i : indices(partialApplyArgs)) { auto arg = partialApplyArgs[i]; if (!arg->getType().isAddress()) { // Copy the argument as the callee may consume it. arg = builder.emitCopyValueOperation(pai->getLoc(), arg); // For non consumed parameters (e.g. guaranteed), we also need to // insert destroys after each apply instruction that we create. if (!paramInfo[paramInfo.size() - partialApplyArgs.size() + i] .isConsumed()) toBeDestroyedArgs.push_back(arg); } } auto callee = pai->getCallee(); SubstitutionMap subs = pai->getSubstitutionMap(); // The partial_apply might be substituting in an open existential type. builder.addOpenedArchetypeOperands(pai); FullApplySite nai; if (auto *tai = dyn_cast<TryApplyInst>(paiAI)) nai = builder.createTryApply(paiAI.getLoc(), callee, subs, argList, tai->getNormalBB(), tai->getErrorBB()); else nai = builder.createApply(paiAI.getLoc(), callee, subs, argList, cast<ApplyInst>(paiAI)->isNonThrowing()); // We also need to destroy the partial_apply instruction itself because it is // consumed by the apply_instruction. auto loc = RegularLocation::getAutoGeneratedLocation(); paiAI.insertAfterFullEvaluation([&](SILBasicBlock::iterator insertPt) { SILBuilderWithScope builder(insertPt); for (auto arg : toBeDestroyedArgs) { builder.emitDestroyValueOperation(loc, arg); } if (!pai->hasCalleeGuaranteedContext()) { builder.emitDestroyValueOperation(loc, pai); } }); if (auto *apply = dyn_cast<ApplyInst>(paiAI)) { callbacks.replaceValueUsesWith(SILValue(apply), cast<ApplyInst>(nai.getInstruction())); } callbacks.deleteInst(paiAI.getInstruction()); return true; } /// Perform the apply{partial_apply(x,y)}(z) -> apply(z,x,y) peephole /// by iterating over all uses of the partial_apply and searching /// for the pattern to transform. SILInstruction *PartialApplyCombiner::combine() { // We need to model @unowned_inner_pointer better before we can do the // peephole here. if (llvm::any_of(pai->getSubstCalleeType()->getResults(), [](SILResultInfo resultInfo) { return resultInfo.getConvention() == ResultConvention::UnownedInnerPointer; })) { return nullptr; } // Iterate over all uses of the partial_apply // and look for applies that use it as a callee. // Worklist of operands. SmallVector<Operand *, 8> uses(pai->getUses()); // Uses may grow in this loop. for (size_t useIndex = 0; useIndex < uses.size(); ++useIndex) { auto *use = uses[useIndex]; auto *user = use->getUser(); // Recurse through conversions. if (auto *cfi = dyn_cast<ConvertEscapeToNoEscapeInst>(user)) { // TODO: Handle argument conversion. All the code in this file needs to be // cleaned up and generalized. The argument conversion handling in // optimizeApplyOfConvertFunctionInst should apply to any combine // involving an apply, not just a specific pattern. // // For now, just handle conversion to @noescape, which is irrelevant for // direct application of the closure. auto convertCalleeTy = cfi->getType().castTo<SILFunctionType>(); auto escapingCalleeTy = convertCalleeTy->getWithExtInfo( convertCalleeTy->getExtInfo().withNoEscape(false)); assert(use->get()->getType().castTo<SILFunctionType>() == escapingCalleeTy); (void)escapingCalleeTy; llvm::copy(cfi->getUses(), std::back_inserter(uses)); continue; } // Look through mark_dependence users of partial_apply [stack]. if (auto *mdi = dyn_cast<MarkDependenceInst>(user)) { if (mdi->getValue() == use->get() && mdi->getValue()->getType().is<SILFunctionType>() && mdi->getValue()->getType().castTo<SILFunctionType>()->isNoEscape()) { llvm::copy(mdi->getUses(), std::back_inserter(uses)); } continue; } // If this use of a partial_apply is not // an apply which uses it as a callee, bail. auto ai = FullApplySite::isa(user); if (!ai) continue; if (ai.getCallee() != use->get()) continue; // We cannot handle generic apply yet. Bail. if (ai.hasSubstitutions()) continue; if (!processSingleApply(ai)) return nullptr; } // release/destroy and deallocate introduced temporaries. if (!tmpCopies.empty()) { destroyTemporaries(); deallocateTemporaries(); } return nullptr; } //===----------------------------------------------------------------------===// // Top Level Entrypoint //===----------------------------------------------------------------------===// SILInstruction *swift::tryOptimizeApplyOfPartialApply( PartialApplyInst *pai, SILBuilder &builder, InstModCallbacks callbacks) { PartialApplyCombiner combiner(pai, builder, callbacks); return combiner.combine(); } <|endoftext|>
<commit_before>// C++11 (c) 2014 Vladimír Štill <xstill@fi.muni.cz> /* C++ inteface for libComedi and elevator, based on wrapping * original C interface by Martin Korsgaard (see below) * * Almost the only change is that everything is wrapped in struct * to avoid global variable and hardcoded device name */ // Wrapper for libComedi I/O. // These functions provide and interface to libComedi limited to use in // the real time lab. // // 2006, Martin Korsgaard #include <elevator/io.h> #include <elevator/channels.h> #include <elevator/test.h> #ifdef O_HAVE_LIBCOMEDI #include <comedilib.h> lowlevel::IO::IO( const char *device ){ if ( device == nullptr ) device = "/dev/comedi0"; int status = 0; _comediHandle = comedi_open( device ); assert( _comediHandle != nullptr, "Failed to open device" ); for (int i = 0; i < 8; i++) { status |= comedi_dio_config(_comediHandle, PORT1, i, COMEDI_INPUT); status |= comedi_dio_config(_comediHandle, PORT2, i, COMEDI_OUTPUT); status |= comedi_dio_config(_comediHandle, PORT3, i+8, COMEDI_OUTPUT); status |= comedi_dio_config(_comediHandle, PORT4, i+16, COMEDI_INPUT); } assert(status == 0, "Device failure"); } lowlevel::IO::~IO() { comedi_close( _comediHandle ); } void lowlevel::IO::io_set_bit( int channel, bool value ) { int rc = comedi_dio_write(_comediHandle, channel >> 8, channel & 0xff, int( value ) ); assert_eq( rc, 1, "Comedi failure" ); } void lowlevel::IO::io_write_analog( int channel, int value ) { int rc = comedi_data_write(_comediHandle, channel >> 8, channel & 0xff, 0, AREF_GROUND, value); assert_eq( rc, 1, "Comedi failure" ); } bool lowlevel::IO::io_read_bit( int channel ) { unsigned int data=0; int rc = comedi_dio_read(_comediHandle, channel >> 8, channel & 0xff, &data); assert_eq( rc, 1, "Comedi failure" ); return bool( data ); } int lowlevel::IO::io_read_analog( int channel ) { lsampl_t data = 0; int rc = comedi_data_read(_comediHandle, channel >> 8, channel & 0xff, 0, AREF_GROUND, &data); assert_eq( rc, 1, "Comedi failure" ); return int( data ); } #else // O_HAVE_LIBCOMEDI #warning Using fake comedi library binding #include <map> struct comedi_t_struct { std::map< int, bool > setBits; }; lowlevel::IO::IO( const char * ) { _comediHandle = new comedi_t(); } lowlevel::IO::~IO() { delete _comediHandle; } void lowlevel::IO::io_set_bit( int channel, bool value ) { _comediHandle->setBits[ channel ] = value; } void lowlevel::IO::io_write_analog( int channel, int value ) { std::cout << "write analog, channel " << channel << " value " << value << std::endl; } bool lowlevel::IO::io_read_bit( int channel ) { auto it = _comediHandle->setBits.find( channel ); return it != _comediHandle->setBits.end() ? it->second : false; } int lowlevel::IO::io_read_analog( int /* channel */ ) { assert_unimplemented(); } #endif // O_HAVE_LIBCOMEDI <commit_msg>io: Jailbreak assertions (as libcomedy is messing with us).<commit_after>// C++11 (c) 2014 Vladimír Štill <xstill@fi.muni.cz> /* C++ inteface for libComedi and elevator, based on wrapping * original C interface by Martin Korsgaard (see below) * * Almost the only change is that everything is wrapped in struct * to avoid global variable and hardcoded device name */ // Wrapper for libComedi I/O. // These functions provide and interface to libComedi limited to use in // the real time lab. // // 2006, Martin Korsgaard #include <elevator/io.h> #include <elevator/channels.h> #include <elevator/test.h> #ifdef O_HAVE_LIBCOMEDI #include <comedilib.h> lowlevel::IO::IO( const char *device ){ if ( device == nullptr ) device = "/dev/comedi0"; int status = 0; _comediHandle = comedi_open( device ); assert( _comediHandle != nullptr, "Failed to open device" ); for (int i = 0; i < 8; i++) { status |= comedi_dio_config(_comediHandle, PORT1, i, COMEDI_INPUT); status |= comedi_dio_config(_comediHandle, PORT2, i, COMEDI_OUTPUT); status |= comedi_dio_config(_comediHandle, PORT3, i+8, COMEDI_OUTPUT); status |= comedi_dio_config(_comediHandle, PORT4, i+16, COMEDI_INPUT); } assert(status == 0, "Device failure"); } lowlevel::IO::~IO() { comedi_close( _comediHandle ); } void lowlevel::IO::io_set_bit( int channel, bool value ) { int rc = comedi_dio_write(_comediHandle, channel >> 8, channel & 0xff, int( value ) ); //assert_eq( rc, 1, "Comedi failure" ); } void lowlevel::IO::io_write_analog( int channel, int value ) { int rc = comedi_data_write(_comediHandle, channel >> 8, channel & 0xff, 0, AREF_GROUND, value); //assert_eq( rc, 1, "Comedi failure" ); } bool lowlevel::IO::io_read_bit( int channel ) { unsigned int data=0; int rc = comedi_dio_read(_comediHandle, channel >> 8, channel & 0xff, &data); //assert_eq( rc, 1, "Comedi failure" ); return bool( data ); } int lowlevel::IO::io_read_analog( int channel ) { lsampl_t data = 0; int rc = comedi_data_read(_comediHandle, channel >> 8, channel & 0xff, 0, AREF_GROUND, &data); //assert_eq( rc, 1, "Comedi failure" ); return int( data ); } #else // O_HAVE_LIBCOMEDI #warning Using fake comedi library binding #include <map> struct comedi_t_struct { std::map< int, bool > setBits; }; lowlevel::IO::IO( const char * ) { _comediHandle = new comedi_t(); } lowlevel::IO::~IO() { delete _comediHandle; } void lowlevel::IO::io_set_bit( int channel, bool value ) { _comediHandle->setBits[ channel ] = value; } void lowlevel::IO::io_write_analog( int channel, int value ) { std::cout << "write analog, channel " << channel << " value " << value << std::endl; } bool lowlevel::IO::io_read_bit( int channel ) { auto it = _comediHandle->setBits.find( channel ); return it != _comediHandle->setBits.end() ? it->second : false; } int lowlevel::IO::io_read_analog( int /* channel */ ) { assert_unimplemented(); } #endif // O_HAVE_LIBCOMEDI <|endoftext|>
<commit_before>//===-- X86ATTInstPrinter.cpp - AT&T assembly instruction printing --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file includes code for rendering MCInst instances as AT&T-style // assembly. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "X86ATTInstPrinter.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCExpr.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "../X86GenInstrNames.inc" using namespace llvm; // Include the auto-generated portion of the assembly writer. #define MachineInstr MCInst #define NO_ASM_WRITER_BOILERPLATE #include "X86GenAsmWriter.inc" #undef MachineInstr void X86ATTInstPrinter::printInst(const MCInst *MI) { printInstruction(MI); } void X86ATTInstPrinter::printSSECC(const MCInst *MI, unsigned Op) { switch (MI->getOperand(Op).getImm()) { default: llvm_unreachable("Invalid ssecc argument!"); case 0: O << "eq"; break; case 1: O << "lt"; break; case 2: O << "le"; break; case 3: O << "unord"; break; case 4: O << "neq"; break; case 5: O << "nlt"; break; case 6: O << "nle"; break; case 7: O << "ord"; break; } } void X86ATTInstPrinter::printPICLabel(const MCInst *MI, unsigned Op) { llvm_unreachable("This is only used for MOVPC32r," "should lower before instruction printing!"); } /// print_pcrel_imm - This is used to print an immediate value that ends up /// being encoded as a pc-relative value. These print slightly differently, for /// example, a $ is not emitted. void X86ATTInstPrinter::print_pcrel_imm(const MCInst *MI, unsigned OpNo) { const MCOperand &Op = MI->getOperand(OpNo); if (Op.isImm()) O << Op.getImm(); else { assert(Op.isExpr() && "unknown pcrel immediate operand"); Op.getExpr()->print(O, &MAI); } } void X86ATTInstPrinter::printOperand(const MCInst *MI, unsigned OpNo, const char *Modifier) { assert(Modifier == 0 && "Modifiers should not be used"); const MCOperand &Op = MI->getOperand(OpNo); if (Op.isReg()) { O << '%' << getRegisterName(Op.getReg()); } else if (Op.isImm()) { O << '$' << Op.getImm(); } else { assert(Op.isExpr() && "unknown operand kind in printOperand"); O << '$'; Op.getExpr()->print(O, &MAI); } } void X86ATTInstPrinter::printLeaMemReference(const MCInst *MI, unsigned Op) { const MCOperand &BaseReg = MI->getOperand(Op); const MCOperand &IndexReg = MI->getOperand(Op+2); const MCOperand &DispSpec = MI->getOperand(Op+3); if (DispSpec.isImm()) { int64_t DispVal = DispSpec.getImm(); if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg())) O << DispVal; } else { assert(DispSpec.isExpr() && "non-immediate displacement for LEA?"); DispSpec.getExpr()->print(O, &MAI); } if (IndexReg.getReg() || BaseReg.getReg()) { O << '('; if (BaseReg.getReg()) printOperand(MI, Op); if (IndexReg.getReg()) { O << ','; printOperand(MI, Op+2); unsigned ScaleVal = MI->getOperand(Op+1).getImm(); if (ScaleVal != 1) O << ',' << ScaleVal; } O << ')'; } } void X86ATTInstPrinter::printMemReference(const MCInst *MI, unsigned Op) { // If this has a segment register, print it. if (MI->getOperand(Op+4).getReg()) { printOperand(MI, Op+4); O << ':'; } printLeaMemReference(MI, Op); } <commit_msg>Fix cmake build, which has a different -I that causes the "../foo" to not find the file<commit_after>//===-- X86ATTInstPrinter.cpp - AT&T assembly instruction printing --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file includes code for rendering MCInst instances as AT&T-style // assembly. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "X86ATTInstPrinter.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCExpr.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "X86GenInstrNames.inc" using namespace llvm; // Include the auto-generated portion of the assembly writer. #define MachineInstr MCInst #define NO_ASM_WRITER_BOILERPLATE #include "X86GenAsmWriter.inc" #undef MachineInstr void X86ATTInstPrinter::printInst(const MCInst *MI) { printInstruction(MI); } void X86ATTInstPrinter::printSSECC(const MCInst *MI, unsigned Op) { switch (MI->getOperand(Op).getImm()) { default: llvm_unreachable("Invalid ssecc argument!"); case 0: O << "eq"; break; case 1: O << "lt"; break; case 2: O << "le"; break; case 3: O << "unord"; break; case 4: O << "neq"; break; case 5: O << "nlt"; break; case 6: O << "nle"; break; case 7: O << "ord"; break; } } void X86ATTInstPrinter::printPICLabel(const MCInst *MI, unsigned Op) { llvm_unreachable("This is only used for MOVPC32r," "should lower before instruction printing!"); } /// print_pcrel_imm - This is used to print an immediate value that ends up /// being encoded as a pc-relative value. These print slightly differently, for /// example, a $ is not emitted. void X86ATTInstPrinter::print_pcrel_imm(const MCInst *MI, unsigned OpNo) { const MCOperand &Op = MI->getOperand(OpNo); if (Op.isImm()) O << Op.getImm(); else { assert(Op.isExpr() && "unknown pcrel immediate operand"); Op.getExpr()->print(O, &MAI); } } void X86ATTInstPrinter::printOperand(const MCInst *MI, unsigned OpNo, const char *Modifier) { assert(Modifier == 0 && "Modifiers should not be used"); const MCOperand &Op = MI->getOperand(OpNo); if (Op.isReg()) { O << '%' << getRegisterName(Op.getReg()); } else if (Op.isImm()) { O << '$' << Op.getImm(); } else { assert(Op.isExpr() && "unknown operand kind in printOperand"); O << '$'; Op.getExpr()->print(O, &MAI); } } void X86ATTInstPrinter::printLeaMemReference(const MCInst *MI, unsigned Op) { const MCOperand &BaseReg = MI->getOperand(Op); const MCOperand &IndexReg = MI->getOperand(Op+2); const MCOperand &DispSpec = MI->getOperand(Op+3); if (DispSpec.isImm()) { int64_t DispVal = DispSpec.getImm(); if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg())) O << DispVal; } else { assert(DispSpec.isExpr() && "non-immediate displacement for LEA?"); DispSpec.getExpr()->print(O, &MAI); } if (IndexReg.getReg() || BaseReg.getReg()) { O << '('; if (BaseReg.getReg()) printOperand(MI, Op); if (IndexReg.getReg()) { O << ','; printOperand(MI, Op+2); unsigned ScaleVal = MI->getOperand(Op+1).getImm(); if (ScaleVal != 1) O << ',' << ScaleVal; } O << ')'; } } void X86ATTInstPrinter::printMemReference(const MCInst *MI, unsigned Op) { // If this has a segment register, print it. if (MI->getOperand(Op+4).getReg()) { printOperand(MI, Op+4); O << ':'; } printLeaMemReference(MI, Op); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <dirent.h> int main(int argc, char** argv) { std::string mainMakefile = "CC = g++\nLIBS = -ldl -lpthread\nLDFLAGS=$(LIBS) -rdynamic\nCXXFLAGS=-Wall -pthread $(DEBUG)\nSOURCES=modinterface.cpp server.cpp channel.cpp config.cpp modules.cpp server.cpp socket.cpp user.cpp\n\ndefault: makedepend robobo modules\n\n"; mainMakefile += "makedepend:\n\tfor i in *.cpp; do for inc in $(awk '/^#include \"/ {print $2}' $i | sed 's/\"//g'); do echo \"${i%.cpp}.o: $inc\"; done; done\n\ndebug:\n\tDEBUG=\"-g -O0\" make -C .\n\nrobobo: $(SOURCES:.cpp=.o)\n\n.PHONY: modules clean\n\nmodules:\n\tmake -C modules/\n\nclean:\n\tmake -C modules/ clean\n\trm -f robobo\n\trm -f $(SOURCES:.cpp=.o)"; std::string moduleMakefileBegin = "CXX = g++\nCXXFLAGS=-fPIC -Wall -pipe -ansi -pedantic-errors $(DEBUG)\nLDFLAGS=-shared\nDEPS=modinclude.h ../main.h ../connection.h ../modules.h ../config.cpp ../modules.cpp ../modinterface.cpp\n\nall: "; std::string moduleMakefileEnd = ".PHONY: clean\n\nclean:\n\trm -f *.o *.so"; std::ofstream makeOut; std::string dir = argv[0]; dir = dir.substr(0, dir.find_last_of('/')); std::string moddir = dir + "/modules"; std::string makedir = dir + "/Makefile"; std::string modmakedir = dir + "/modules/Makefile"; makeOut.open(makedir.c_str(), std::ios::out | std::ios::trunc); makeOut << mainMakefile; makeOut.close(); DIR* modulesDir = opendir(moddir.c_str()); std::vector<std::string> moduleFiles; dirent* moduleFile; while (moduleFile = readdir(modulesDir)) { std::string moduleName = moduleFile->d_name; if (moduleName.size() > 4) { if (moduleName.substr(moduleName.size() - 4) == ".cpp") { moduleFiles.push_back(moduleName.substr(0, moduleName.size() - 4)); std::cout << "Found module: " << moduleName << std::endl; } } } makeOut.open(modmakedir.c_str(), std::ios::out | std::ios::trunc); makeOut << moduleMakefileBegin; for (unsigned int i = 0; i < moduleFiles.size(); i++) makeOut << moduleFiles[i] << ".so "; makeOut << "\n\n"; for (unsigned int i = 0; i < moduleFiles.size(); i++) makeOut << moduleFiles[i] << ".so: " << moduleFiles[i] << ".o\n\t$(CXX) $(LDFLAGS) $^ -o $@\n"; for (unsigned int i = 0; i < moduleFiles.size(); i++) makeOut << moduleFiles[i] << ".o: $(DEPS)\n"; makeOut << moduleMakefileEnd; makeOut.close(); }<commit_msg>Remove a flag from module compile<commit_after>#include <iostream> #include <fstream> #include <vector> #include <dirent.h> int main(int argc, char** argv) { std::string mainMakefile = "CC = g++\nLIBS = -ldl -lpthread\nLDFLAGS=$(LIBS) -rdynamic\nCXXFLAGS=-Wall -pthread $(DEBUG)\nSOURCES=modinterface.cpp server.cpp channel.cpp config.cpp modules.cpp server.cpp socket.cpp user.cpp\n\ndefault: makedepend robobo modules\n\n"; mainMakefile += "makedepend:\n\tfor i in *.cpp; do for inc in $(awk '/^#include \"/ {print $2}' $i | sed 's/\"//g'); do echo \"${i%.cpp}.o: $inc\"; done; done\n\ndebug:\n\tDEBUG=\"-g -O0\" make -C .\n\nrobobo: $(SOURCES:.cpp=.o)\n\n.PHONY: modules clean\n\nmodules:\n\tmake -C modules/\n\nclean:\n\tmake -C modules/ clean\n\trm -f robobo\n\trm -f $(SOURCES:.cpp=.o)"; std::string moduleMakefileBegin = "CXX = g++\nCXXFLAGS=-fPIC -Wall -pipe -ansi $(DEBUG)\nLDFLAGS=-shared\nDEPS=modinclude.h ../main.h ../connection.h ../modules.h ../config.cpp ../modules.cpp ../modinterface.cpp\n\nall: "; std::string moduleMakefileEnd = ".PHONY: clean\n\nclean:\n\trm -f *.o *.so"; std::ofstream makeOut; std::string dir = argv[0]; dir = dir.substr(0, dir.find_last_of('/')); std::string moddir = dir + "/modules"; std::string makedir = dir + "/Makefile"; std::string modmakedir = dir + "/modules/Makefile"; makeOut.open(makedir.c_str(), std::ios::out | std::ios::trunc); makeOut << mainMakefile; makeOut.close(); DIR* modulesDir = opendir(moddir.c_str()); std::vector<std::string> moduleFiles; dirent* moduleFile; while (moduleFile = readdir(modulesDir)) { std::string moduleName = moduleFile->d_name; if (moduleName.size() > 4) { if (moduleName.substr(moduleName.size() - 4) == ".cpp") { moduleFiles.push_back(moduleName.substr(0, moduleName.size() - 4)); std::cout << "Found module: " << moduleName << std::endl; } } } makeOut.open(modmakedir.c_str(), std::ios::out | std::ios::trunc); makeOut << moduleMakefileBegin; for (unsigned int i = 0; i < moduleFiles.size(); i++) makeOut << moduleFiles[i] << ".so "; makeOut << "\n\n"; for (unsigned int i = 0; i < moduleFiles.size(); i++) makeOut << moduleFiles[i] << ".so: " << moduleFiles[i] << ".o\n\t$(CXX) $(LDFLAGS) $^ -o $@\n"; for (unsigned int i = 0; i < moduleFiles.size(); i++) makeOut << moduleFiles[i] << ".o: $(DEPS)\n"; makeOut << moduleMakefileEnd; makeOut.close(); }<|endoftext|>
<commit_before>#include "FiltersPage.hpp" #include "controllers/filters/FilterModel.hpp" #include "singletons/Settings.hpp" #include "singletons/WindowManager.hpp" #include "util/LayoutCreator.hpp" #include "widgets/Window.hpp" #include "widgets/dialogs/ChannelFilterEditorDialog.hpp" #include "widgets/helper/EditableModelView.hpp" #include <QTableView> #include <QHeaderView> #define FILTERS_DOCUMENTATION "https://wiki.chatterino.com/Filters/" namespace chatterino { FiltersPage::FiltersPage() { LayoutCreator<FiltersPage> layoutCreator(this); auto layout = layoutCreator.setLayoutType<QVBoxLayout>(); layout.emplace<QLabel>( "Selectively display messages in Splits using channel filters. Set " "filters under a Split menu."); EditableModelView *view = layout .emplace<EditableModelView>( (new FilterModel(nullptr)) ->initialized(&getSettings()->filterRecords)) .getElement(); view->setTitles({"Name", "Filter", "Valid"}); view->getTableView()->horizontalHeader()->setSectionResizeMode( QHeaderView::Interactive); view->getTableView()->horizontalHeader()->setSectionResizeMode( 1, QHeaderView::Stretch); QTimer::singleShot(1, [view] { view->getTableView()->resizeColumnsToContents(); view->getTableView()->setColumnWidth(0, 150); view->getTableView()->setColumnWidth(2, 125); }); view->addButtonPressed.connect([] { ChannelFilterEditorDialog d( static_cast<QWidget *>(&(getApp()->windows->getMainWindow()))); if (d.exec() == QDialog::Accepted) { getSettings()->filterRecords.append( std::make_shared<FilterRecord>(d.getTitle(), d.getFilter())); } }); auto quickAddButton = new QPushButton("Quick Add"); QObject::connect(quickAddButton, &QPushButton::pressed, [] { getSettings()->filterRecords.append(std::make_shared<FilterRecord>( "My filter", "message.content contains \"hello\"")); }); view->addCustomButton(quickAddButton); QObject::connect(view->getTableView(), &QTableView::clicked, [this, view](const QModelIndex &clicked) { this->tableCellClicked(clicked, view); }); auto filterHelpLabel = new QLabel(QString("<a href='%1'><span " "style='color:#99f'>filter info</span></a>") .arg(FILTERS_DOCUMENTATION)); filterHelpLabel->setOpenExternalLinks(true); view->addCustomButton(filterHelpLabel); layout.append( this->createCheckBox("Do not filter my own messages", getSettings()->excludeUserMessagesFromFilter)); } void FiltersPage::onShow() { return; } void FiltersPage::tableCellClicked(const QModelIndex &clicked, EditableModelView *view) { // valid column if (clicked.column() == 2) { QMessageBox popup; filterparser::FilterParser f( view->getModel()->data(clicked.siblingAtColumn(1)).toString()); if (f.valid()) { popup.setIcon(QMessageBox::Icon::Information); popup.setWindowTitle("Valid filter"); popup.setText("Filter is valid"); popup.setInformativeText( QString("Parsed as:\n%1").arg(f.filterString())); } else { popup.setIcon(QMessageBox::Icon::Warning); popup.setWindowTitle("Invalid filter"); popup.setText(QString("Parsing errors occurred:")); popup.setInformativeText(f.errors().join("\n")); } popup.exec(); } } } // namespace chatterino <commit_msg>Fix 'Filter Info' url (#2907)<commit_after>#include "FiltersPage.hpp" #include "controllers/filters/FilterModel.hpp" #include "singletons/Settings.hpp" #include "singletons/WindowManager.hpp" #include "util/LayoutCreator.hpp" #include "widgets/Window.hpp" #include "widgets/dialogs/ChannelFilterEditorDialog.hpp" #include "widgets/helper/EditableModelView.hpp" #include <QTableView> #include <QHeaderView> #define FILTERS_DOCUMENTATION "https://wiki.chatterino.com/Filters" namespace chatterino { FiltersPage::FiltersPage() { LayoutCreator<FiltersPage> layoutCreator(this); auto layout = layoutCreator.setLayoutType<QVBoxLayout>(); layout.emplace<QLabel>( "Selectively display messages in Splits using channel filters. Set " "filters under a Split menu."); EditableModelView *view = layout .emplace<EditableModelView>( (new FilterModel(nullptr)) ->initialized(&getSettings()->filterRecords)) .getElement(); view->setTitles({"Name", "Filter", "Valid"}); view->getTableView()->horizontalHeader()->setSectionResizeMode( QHeaderView::Interactive); view->getTableView()->horizontalHeader()->setSectionResizeMode( 1, QHeaderView::Stretch); QTimer::singleShot(1, [view] { view->getTableView()->resizeColumnsToContents(); view->getTableView()->setColumnWidth(0, 150); view->getTableView()->setColumnWidth(2, 125); }); view->addButtonPressed.connect([] { ChannelFilterEditorDialog d( static_cast<QWidget *>(&(getApp()->windows->getMainWindow()))); if (d.exec() == QDialog::Accepted) { getSettings()->filterRecords.append( std::make_shared<FilterRecord>(d.getTitle(), d.getFilter())); } }); auto quickAddButton = new QPushButton("Quick Add"); QObject::connect(quickAddButton, &QPushButton::pressed, [] { getSettings()->filterRecords.append(std::make_shared<FilterRecord>( "My filter", "message.content contains \"hello\"")); }); view->addCustomButton(quickAddButton); QObject::connect(view->getTableView(), &QTableView::clicked, [this, view](const QModelIndex &clicked) { this->tableCellClicked(clicked, view); }); auto filterHelpLabel = new QLabel(QString("<a href='%1'><span " "style='color:#99f'>filter info</span></a>") .arg(FILTERS_DOCUMENTATION)); filterHelpLabel->setOpenExternalLinks(true); view->addCustomButton(filterHelpLabel); layout.append( this->createCheckBox("Do not filter my own messages", getSettings()->excludeUserMessagesFromFilter)); } void FiltersPage::onShow() { return; } void FiltersPage::tableCellClicked(const QModelIndex &clicked, EditableModelView *view) { // valid column if (clicked.column() == 2) { QMessageBox popup; filterparser::FilterParser f( view->getModel()->data(clicked.siblingAtColumn(1)).toString()); if (f.valid()) { popup.setIcon(QMessageBox::Icon::Information); popup.setWindowTitle("Valid filter"); popup.setText("Filter is valid"); popup.setInformativeText( QString("Parsed as:\n%1").arg(f.filterString())); } else { popup.setIcon(QMessageBox::Icon::Warning); popup.setWindowTitle("Invalid filter"); popup.setText(QString("Parsing errors occurred:")); popup.setInformativeText(f.errors().join("\n")); } popup.exec(); } } } // namespace chatterino <|endoftext|>
<commit_before>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (c) 2014-2018 AscEmu Team <http://www.ascemu.org> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PLAYER_CLASSES_HPP #define PLAYER_CLASSES_HPP #define TOTAL_NORMAL_RUNE_TYPES 3 #define TOTAL_USED_RUNES (TOTAL_NORMAL_RUNE_TYPES * 2) #define MAX_RUNES 6 #define TOTAL_RUNE_TYPES 4 #define MAX_RUNE_VALUE 1 #include "Player.h" enum SPELL_RUNE_TYPES { RUNE_BLOOD = 0, RUNE_FROST = 1, RUNE_UNHOLY = 2, RUNE_DEATH = 3, RUNE_MAX_TYPES = 4 }; const uint8 base_runes[MAX_RUNES] = { RUNE_BLOOD, RUNE_BLOOD, RUNE_FROST, RUNE_FROST, RUNE_UNHOLY, RUNE_UNHOLY }; struct Rune { uint8 type; bool is_used; }; class DeathKnight : public Player { Rune m_runes[MAX_RUNES]; // Holds last slot used uint8 m_last_used_rune_slot; protected: void SendRuneUpdate(uint8 slot); public: DeathKnight(uint32 guid) : Player(guid) { m_last_used_rune_slot = 0; for (uint8 i = 0; i < MAX_RUNES; ++i) { m_runes[i].type = base_runes[i]; m_runes[i].is_used = false; } } bool IsDeathKnight() override { return true; } //************************************************************************************* // RUNES //************************************************************************************* uint8 GetBaseRuneType(uint8 slot); uint8 GetRuneType(uint8 slot); bool GetRuneIsUsed(uint8 slot); void ConvertRune(uint8 slot, uint8 type); uint32 HasRunes(uint8 type, uint32 count); uint32 TakeRunes(uint8 type, uint32 count); void ResetRune(uint8 slot); uint8 GetRuneFlags(); bool IsAllRunesOfTypeInUse(uint8 type); uint8 GetLastUsedUnitSlot() { return m_last_used_rune_slot; } }; class Druid : public Player { public: Druid(uint32 guid) : Player(guid) {} bool IsDruid() override { return true; } }; class Rogue : public Player { public: Rogue(uint32 guid) : Player(guid) {} bool IsRogue() override { return true; } }; class Priest : public Player { public: Priest(uint32 guid) : Player(guid) {} bool IsPriest() override { return true; } }; class Paladin : public Player { public: Paladin(uint32 guid) : Player(guid) {} bool IsPaladin() override { return true; } }; class Warrior : public Player { public: Warrior(uint32 guid) : Player(guid) {} bool IsWarrior() override { return true; } }; class Warlock : public Player { public: Warlock(uint32 guid) : Player(guid) {} bool IsWarlock() override { return true; } }; class Mage : public Player { public: Mage(uint32 guid) : Player(guid) {} bool IsMage() override { return true; } }; class Hunter : public Player { public: Hunter(uint32 guid) : Player(guid) {} bool IsHunter() override { return true; } }; class Shaman : public Player { public: Shaman(uint32 guid) : Player(guid) {} bool IsShaman() override { return true; } }; #endif // PLAYER_CLASSES_HPP<commit_msg>fix: Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions.<commit_after>/* Copyright (c) 2014-2018 AscEmu Team <http://www.ascemu.org> This file is released under the MIT license. See README-MIT for more information. */ #pragma once #include "Player.h" #define TOTAL_NORMAL_RUNE_TYPES 3 #define TOTAL_USED_RUNES (TOTAL_NORMAL_RUNE_TYPES * 2) #define MAX_RUNES 6 #define TOTAL_RUNE_TYPES 4 #define MAX_RUNE_VALUE 1 enum SPELL_RUNE_TYPES { RUNE_BLOOD = 0, RUNE_FROST = 1, RUNE_UNHOLY = 2, RUNE_DEATH = 3, RUNE_MAX_TYPES = 4 }; const uint8 base_runes[MAX_RUNES] = { RUNE_BLOOD, RUNE_BLOOD, RUNE_FROST, RUNE_FROST, RUNE_UNHOLY, RUNE_UNHOLY }; struct Rune { uint8 type; bool is_used; }; class DeathKnight : public Player { Rune m_runes[MAX_RUNES]; // Holds last slot used uint8 m_last_used_rune_slot; protected: void SendRuneUpdate(uint8 slot); public: DeathKnight(uint32 guid) : Player(guid) { m_last_used_rune_slot = 0; for (uint8 i = 0; i < MAX_RUNES; ++i) { m_runes[i].type = base_runes[i]; m_runes[i].is_used = false; } } bool IsDeathKnight() override { return true; } ////////////////////////////////////////////////////////////////////////////////////////// // Runes uint8 GetBaseRuneType(uint8 slot); uint8 GetRuneType(uint8 slot); bool GetRuneIsUsed(uint8 slot); void ConvertRune(uint8 slot, uint8 type); uint32 HasRunes(uint8 type, uint32 count); uint32 TakeRunes(uint8 type, uint32 count); void ResetRune(uint8 slot); uint8 GetRuneFlags(); bool IsAllRunesOfTypeInUse(uint8 type); uint8 GetLastUsedUnitSlot() { return m_last_used_rune_slot; } }; class Druid : public Player { public: explicit Druid(uint32_t guid) : Player(guid) {} bool IsDruid() override { return true; } }; class Rogue : public Player { public: explicit Rogue(uint32_t guid) : Player(guid) {} bool IsRogue() override { return true; } }; class Priest : public Player { public: explicit Priest(uint32_t guid) : Player(guid) {} bool IsPriest() override { return true; } }; class Paladin : public Player { public: explicit Paladin(uint32_t guid) : Player(guid) {} bool IsPaladin() override { return true; } }; class Warrior : public Player { public: explicit Warrior(uint32_t guid) : Player(guid) {} bool IsWarrior() override { return true; } }; class Warlock : public Player { public: explicit Warlock(uint32_t guid) : Player(guid) {} bool IsWarlock() override { return true; } }; class Mage : public Player { public: explicit Mage(uint32_t guid) : Player(guid) {} bool IsMage() override { return true; } }; class Hunter : public Player { public: explicit Hunter(uint32_t guid) : Player(guid) {} bool IsHunter() override { return true; } }; class Shaman : public Player { public: explicit Shaman(uint32_t guid) : Player(guid) {} bool IsShaman() override { return true; } }; <|endoftext|>
<commit_before>/* * Copyright (C) 2011, British Broadcasting Corporation * All Rights Reserved. * * Author: Philip de Nier * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the British Broadcasting Corporation nor the names * of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <cstring> #include <bmx/writer_helper/MPEG2LGWriterHelper.h> #include <bmx/BMXException.h> #include <bmx/Logging.h> using namespace std; using namespace bmx; #define NULL_TEMPORAL_OFFSET 127 MPEG2LGWriterHelper::MPEG2LGWriterHelper() { mPosition = 0; mPrevKeyFramePosition = -1; mKeyFramePosition = -1; mKeyFrameTemporalReference = 0; memset(mGOPTemporalOffsets, NULL_TEMPORAL_OFFSET, sizeof(mGOPTemporalOffsets)); mGOPStartPosition = 0; mFirstGOP = true; mTemporalReference = 0; mHaveTemporalOffset = false; mTemporalOffset = NULL_TEMPORAL_OFFSET; mHavePrevTemporalOffset = false; mPrevTemporalOffset = NULL_TEMPORAL_OFFSET; mKeyFrameOffset = 0; mFlags = 0; mHaveGOPHeader = false; mSingleSequence = true; mBPictureCount = 0; mConstantBFrames = true; mLowDelay = true; mClosedGOP = true; mCurrentGOPClosed = false; mIdenticalGOP = true; mMaxGOP = 0; mUnlimitedGOPSize = false; mMaxBPictureCount = 0; mBitRate = 0; } MPEG2LGWriterHelper::~MPEG2LGWriterHelper() { } void MPEG2LGWriterHelper::ProcessFrame(const unsigned char *data, uint32_t size) { mEssenceParser.ParseFrameInfo(data, size); MPEG2FrameType frame_type = mEssenceParser.GetFrameType(); BMX_CHECK(frame_type != UNKNOWN_FRAME_TYPE); BMX_CHECK(mPosition > 0 || frame_type == I_FRAME); // require first frame to be an I-frame mHaveGOPHeader = mEssenceParser.HaveGOPHeader(); if (mSingleSequence && mPosition > 0 && mEssenceParser.HaveSequenceHeader()) mSingleSequence = false; if (mHaveGOPHeader) { if (!mEssenceParser.IsClosedGOP()) // descriptor closed GOP == true if all sequences are closed GOP mClosedGOP = false; mCurrentGOPClosed = mEssenceParser.IsClosedGOP(); } if (frame_type == B_FRAME) { mBPictureCount++; } else if (mBPictureCount > 0) { if (mMaxBPictureCount > 0 && mBPictureCount != mMaxBPictureCount) mConstantBFrames = false; if (mBPictureCount > mMaxBPictureCount) mMaxBPictureCount = mBPictureCount; mBPictureCount = 0; } if (mHaveGOPHeader && !mUnlimitedGOPSize) { if (mPosition - mGOPStartPosition > 0xffff) { mUnlimitedGOPSize = true; mMaxGOP = 0; } else { uint16_t gop_size = (uint16_t)(mPosition - mGOPStartPosition); if (gop_size > mMaxGOP) mMaxGOP = gop_size; } } if (mEssenceParser.HaveSequenceHeader()) { if (mLowDelay && !mEssenceParser.IsLowDelay()) mLowDelay = false; mBitRate = mEssenceParser.GetBitRate() * 400; // MPEG-2 bit rate is in 400 bits/second units } if (mIdenticalGOP) { if (mFirstGOP && mHaveGOPHeader && mPosition > 0) mFirstGOP = false; if (mFirstGOP) { mGOPStructure.push_back(frame_type); if (mGOPStructure.size() >= 256) { // eg. max gop size for xdcam is 15 log_warn("Unexpected GOP size >= %"PRIszt"\n", mGOPStructure.size()); mIdenticalGOP = false; } } else { size_t pos_in_gop = (mHaveGOPHeader ? 0 : (size_t)(mPosition - mGOPStartPosition)); if (pos_in_gop >= mGOPStructure.size() || mGOPStructure[pos_in_gop] != frame_type) mIdenticalGOP = false; } } mKeyFrameOffset = 0; if (frame_type != I_FRAME) { if (!mCurrentGOPClosed && mKeyFramePosition + mKeyFrameTemporalReference >= mPosition) { BMX_CHECK(mPrevKeyFramePosition - mPosition >= -128); mKeyFrameOffset = (int8_t)(mPrevKeyFramePosition - mPosition); } else { BMX_CHECK(mKeyFramePosition - mPosition >= -128); mKeyFrameOffset = (int8_t)(mKeyFramePosition - mPosition); } } if (mHaveGOPHeader) { if (!CheckTemporalOffsetsComplete(0)) log_warn("Incomplete MPEG-2 temporal offset data in index table\n"); mGOPStartPosition = mPosition; memset(mGOPTemporalOffsets, NULL_TEMPORAL_OFFSET, sizeof(mGOPTemporalOffsets)); } uint8_t gop_start_offset = mPosition - mGOPStartPosition; // temporal reference = display position for current frame mTemporalReference = mEssenceParser.GetTemporalReference(); // temporal offset = offset to frame data required for displaying at the current position BMX_CHECK(mTemporalReference < sizeof(mGOPTemporalOffsets)); mGOPTemporalOffsets[mTemporalReference] = gop_start_offset - mTemporalReference; mHaveTemporalOffset = (mGOPTemporalOffsets[gop_start_offset] != NULL_TEMPORAL_OFFSET); mTemporalOffset = mGOPTemporalOffsets[gop_start_offset]; mHavePrevTemporalOffset = false; if (mTemporalReference < gop_start_offset) { // a temporal offset value for a previous position is now available mHavePrevTemporalOffset = true; mPrevTemporalOffset = mGOPTemporalOffsets[mTemporalReference]; } mFlags = 0x00; if (mEssenceParser.HaveSequenceHeader()) mFlags |= 0x40; // sequence header bit if (frame_type == I_FRAME) { if (mEssenceParser.HaveSequenceHeader() && mHaveGOPHeader && mEssenceParser.IsClosedGOP()) mFlags |= 0x80; // reference frame bit } else if (frame_type == P_FRAME) { mFlags |= 0x22; } else { mFlags |= 0x33; // naive setting - assume forward and backward prediction } if (mKeyFrameOffset + mPosition < 0 || mTemporalOffset + mPosition < 0) mFlags |= 0x0b; // offsets out of range if (frame_type == I_FRAME) { mPrevKeyFramePosition = mKeyFramePosition; mKeyFramePosition = mPosition; mKeyFrameTemporalReference = mTemporalReference; } mPosition++; } bool MPEG2LGWriterHelper::CheckTemporalOffsetsComplete(int64_t end_offset) { // check all temporal offsets are known (end_offset is <= 0) int64_t i; for (i = 0; i < mPosition - mGOPStartPosition + end_offset; i++) { if (mGOPTemporalOffsets[i] == NULL_TEMPORAL_OFFSET) return false; } return true; } <commit_msg>mpeg2 writer helper: check temporal offset values fall within limits<commit_after>/* * Copyright (C) 2011, British Broadcasting Corporation * All Rights Reserved. * * Author: Philip de Nier * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the British Broadcasting Corporation nor the names * of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <cstring> #include <bmx/writer_helper/MPEG2LGWriterHelper.h> #include <bmx/BMXException.h> #include <bmx/Logging.h> using namespace std; using namespace bmx; #define NULL_TEMPORAL_OFFSET 127 MPEG2LGWriterHelper::MPEG2LGWriterHelper() { mPosition = 0; mPrevKeyFramePosition = -1; mKeyFramePosition = -1; mKeyFrameTemporalReference = 0; memset(mGOPTemporalOffsets, NULL_TEMPORAL_OFFSET, sizeof(mGOPTemporalOffsets)); mGOPStartPosition = 0; mFirstGOP = true; mTemporalReference = 0; mHaveTemporalOffset = false; mTemporalOffset = NULL_TEMPORAL_OFFSET; mHavePrevTemporalOffset = false; mPrevTemporalOffset = NULL_TEMPORAL_OFFSET; mKeyFrameOffset = 0; mFlags = 0; mHaveGOPHeader = false; mSingleSequence = true; mBPictureCount = 0; mConstantBFrames = true; mLowDelay = true; mClosedGOP = true; mCurrentGOPClosed = false; mIdenticalGOP = true; mMaxGOP = 0; mUnlimitedGOPSize = false; mMaxBPictureCount = 0; mBitRate = 0; } MPEG2LGWriterHelper::~MPEG2LGWriterHelper() { } void MPEG2LGWriterHelper::ProcessFrame(const unsigned char *data, uint32_t size) { mEssenceParser.ParseFrameInfo(data, size); MPEG2FrameType frame_type = mEssenceParser.GetFrameType(); BMX_CHECK(frame_type != UNKNOWN_FRAME_TYPE); BMX_CHECK(mPosition > 0 || frame_type == I_FRAME); // require first frame to be an I-frame mHaveGOPHeader = mEssenceParser.HaveGOPHeader(); if (mSingleSequence && mPosition > 0 && mEssenceParser.HaveSequenceHeader()) mSingleSequence = false; if (mHaveGOPHeader) { if (!mEssenceParser.IsClosedGOP()) // descriptor closed GOP == true if all sequences are closed GOP mClosedGOP = false; mCurrentGOPClosed = mEssenceParser.IsClosedGOP(); } if (frame_type == B_FRAME) { mBPictureCount++; } else if (mBPictureCount > 0) { if (mMaxBPictureCount > 0 && mBPictureCount != mMaxBPictureCount) mConstantBFrames = false; if (mBPictureCount > mMaxBPictureCount) mMaxBPictureCount = mBPictureCount; mBPictureCount = 0; } if (mHaveGOPHeader && !mUnlimitedGOPSize) { if (mPosition - mGOPStartPosition > 0xffff) { mUnlimitedGOPSize = true; mMaxGOP = 0; } else { uint16_t gop_size = (uint16_t)(mPosition - mGOPStartPosition); if (gop_size > mMaxGOP) mMaxGOP = gop_size; } } if (mEssenceParser.HaveSequenceHeader()) { if (mLowDelay && !mEssenceParser.IsLowDelay()) mLowDelay = false; mBitRate = mEssenceParser.GetBitRate() * 400; // MPEG-2 bit rate is in 400 bits/second units } if (mIdenticalGOP) { if (mFirstGOP && mHaveGOPHeader && mPosition > 0) mFirstGOP = false; if (mFirstGOP) { mGOPStructure.push_back(frame_type); if (mGOPStructure.size() >= 256) { // eg. max gop size for xdcam is 15 log_warn("Unexpected GOP size >= %"PRIszt"\n", mGOPStructure.size()); mIdenticalGOP = false; } } else { size_t pos_in_gop = (mHaveGOPHeader ? 0 : (size_t)(mPosition - mGOPStartPosition)); if (pos_in_gop >= mGOPStructure.size() || mGOPStructure[pos_in_gop] != frame_type) mIdenticalGOP = false; } } mKeyFrameOffset = 0; if (frame_type != I_FRAME) { if (!mCurrentGOPClosed && mKeyFramePosition + mKeyFrameTemporalReference >= mPosition) { BMX_CHECK(mPrevKeyFramePosition - mPosition >= -128); mKeyFrameOffset = (int8_t)(mPrevKeyFramePosition - mPosition); } else { BMX_CHECK(mKeyFramePosition - mPosition >= -128); mKeyFrameOffset = (int8_t)(mKeyFramePosition - mPosition); } } if (mHaveGOPHeader) { if (!CheckTemporalOffsetsComplete(0)) log_warn("Incomplete MPEG-2 temporal offset data in index table\n"); mGOPStartPosition = mPosition; memset(mGOPTemporalOffsets, NULL_TEMPORAL_OFFSET, sizeof(mGOPTemporalOffsets)); } BMX_CHECK(mPosition - mGOPStartPosition <= 0xff); uint8_t gop_start_offset = (uint8_t)(mPosition - mGOPStartPosition); // temporal reference = display position for current frame mTemporalReference = mEssenceParser.GetTemporalReference(); // temporal offset = offset to frame data required for displaying at the current position BMX_CHECK(mTemporalReference < sizeof(mGOPTemporalOffsets)); BMX_CHECK(gop_start_offset - (int64_t)mTemporalReference <= 127 && gop_start_offset - (int64_t)mTemporalReference >= -128); mGOPTemporalOffsets[mTemporalReference] = (int8_t)(gop_start_offset - mTemporalReference); mHaveTemporalOffset = (mGOPTemporalOffsets[gop_start_offset] != NULL_TEMPORAL_OFFSET); mTemporalOffset = mGOPTemporalOffsets[gop_start_offset]; mHavePrevTemporalOffset = false; if (mTemporalReference < gop_start_offset) { // a temporal offset value for a previous position is now available mHavePrevTemporalOffset = true; mPrevTemporalOffset = mGOPTemporalOffsets[mTemporalReference]; } mFlags = 0x00; if (mEssenceParser.HaveSequenceHeader()) mFlags |= 0x40; // sequence header bit if (frame_type == I_FRAME) { if (mEssenceParser.HaveSequenceHeader() && mHaveGOPHeader && mEssenceParser.IsClosedGOP()) mFlags |= 0x80; // reference frame bit } else if (frame_type == P_FRAME) { mFlags |= 0x22; } else { mFlags |= 0x33; // naive setting - assume forward and backward prediction } if (mKeyFrameOffset + mPosition < 0 || mTemporalOffset + mPosition < 0) mFlags |= 0x0b; // offsets out of range if (frame_type == I_FRAME) { mPrevKeyFramePosition = mKeyFramePosition; mKeyFramePosition = mPosition; mKeyFrameTemporalReference = mTemporalReference; } mPosition++; } bool MPEG2LGWriterHelper::CheckTemporalOffsetsComplete(int64_t end_offset) { // check all temporal offsets are known (end_offset is <= 0) int64_t i; for (i = 0; i < mPosition - mGOPStartPosition + end_offset; i++) { if (mGOPTemporalOffsets[i] == NULL_TEMPORAL_OFFSET) return false; } return true; } <|endoftext|>
<commit_before>#ifndef INTERCOM_CPP_MSVC_DATATYPES_H #define INTERCOM_CPP_MSVC_DATATYPES_H #include <cstdint> // Use predefined set if available. #include<WinDef.h> // The generated C++ headers and classes expect the data types in intercom namespace. namespace intercom { namespace _internal { template< typename TTarget, typename TSource > TTarget checked_cast( TSource source ) { if( std::numeric_limits< TTarget >::is_signed && ! std::numeric_limits< TSource >::is_signed ) { // Target signed, Source not signed. // -> No need to check the min bound. // // Min bound check would result in bad checks due to type // conversion to signed, etc. if( source > ( std::numeric_limits< TTarget >::max )() ) { _ASSERTE( false ); throw std::runtime_error( "Value out of range" ); } } else { // Every other case. if( source < ( std::numeric_limits< TTarget >::min )() ) { _ASSERTE( false ); throw std::runtime_error( "Value out of range" ); } if( source > ( std::numeric_limits< TTarget >::max )() ) { _ASSERTE( false ); throw std::runtime_error( "Value out of range" ); } } return static_cast< TTarget >( source ); } } typedef INT8 INT8; typedef UINT8 UINT8; typedef INT16 INT16; typedef UINT16 UINT16; typedef INT32 INT32; typedef UINT32 UINT32; typedef INT64 INT64; typedef UINT64 UINT64; typedef BOOL BOOL; typedef BYTE BYTE; typedef ULONG ULONG; typedef DWORD DWORD; typedef WORD WORD; typedef OLECHAR OLECHAR; typedef BSTR BSTR; typedef HRESULT HRESULT; //! 32-bit reference counter. unsigned long is 32-bit in Windows and 64-bit on Unix. typedef unsigned long REF_COUNT_32; } #endif <commit_msg>Add msvc typedefs to datatypes.hpp<commit_after>#ifndef INTERCOM_CPP_MSVC_DATATYPES_H #define INTERCOM_CPP_MSVC_DATATYPES_H #include <cstdint> // Use predefined set if available. #include<WinDef.h> // The generated C++ headers and classes expect the data types in intercom namespace. namespace intercom { namespace _internal { template< typename TTarget, typename TSource > TTarget checked_cast( TSource source ) { if( std::numeric_limits< TTarget >::is_signed && ! std::numeric_limits< TSource >::is_signed ) { // Target signed, Source not signed. // -> No need to check the min bound. // // Min bound check would result in bad checks due to type // conversion to signed, etc. if( source > ( std::numeric_limits< TTarget >::max )() ) { _ASSERTE( false ); throw std::runtime_error( "Value out of range" ); } } else { // Every other case. if( source < ( std::numeric_limits< TTarget >::min )() ) { _ASSERTE( false ); throw std::runtime_error( "Value out of range" ); } if( source > ( std::numeric_limits< TTarget >::max )() ) { _ASSERTE( false ); throw std::runtime_error( "Value out of range" ); } } return static_cast< TTarget >( source ); } } typedef INT INT; typedef UINT UINT; typedef INT8 INT8; typedef UINT8 UINT8; typedef INT16 INT16; typedef UINT16 UINT16; typedef INT32 INT32; typedef UINT32 UINT32; typedef INT64 INT64; typedef UINT64 UINT64; typedef BOOL BOOL; typedef DWORD DWORD; typedef WORD WORD; typedef CHAR CHAR; typedef SHORT SHORT; typedef LONG LONG; typedef LONGLONG LONGLONG; typedef BYTE BYTE; typedef USHORT USHORT; typedef ULONG ULONG; typedef ULONGLONG ULONGLONG; typedef DOUBLE DOUBLE; typedef FLOAT FLOAT; typedef OLECHAR OLECHAR; typedef BSTR BSTR; typedef HRESULT HRESULT; typedef SCODE SCODE; typedef DATE DATE; typedef VARIANT_BOOL VARIANT_BOOL; typedef CURRENCY CURRENCY; typedef PVOID PVOID; //! 32-bit reference counter. unsigned long is 32-bit in Windows and 64-bit on Unix. typedef unsigned long REF_COUNT_32; } #endif <|endoftext|>
<commit_before>// CommonFunc.cpp -- source file /* * Author: Ivan Chapkailo (septimomend) * Date: 02.07.2017 * * © 2017 Ivan Chapkailo. All rights reserved * e-mail: chapkailo.ivan@gmail.com */ #include "stdafx.h" #include "CommonFunc.h" Common::Common() { m_pAll = tml.getAllControllerObj(); m_pCnfg = m_pAll->getConfigObj(); } Common::Common(AllControllers* all) : m_pCnfg(all->getConfigObj()) { } /* * draws */ void Common::drawRows(Adbfr* abfr); { // TODO } void Common::drawStatusBar(Adbfr* abfr) { // TODO } void Common::drawMessageBar(Adbfr* abfr) { // TODO } /* * operations */ void Common::statusMsg(const char *fmt, ...) { va_list arg; // for unknown number of parameters va_start(arg, fmt); // initialize arg vsnprintf(cnfg.statusMessage, sizeof(cnfg.statusMessage), fmt, arg); // output parameters to statusMessage va_end(arg); // end cnfg.statusMessageTime = time(NULL); // gets time } void Common::updateScreen() { scrolling(); m_abfr = ADBFR_IMPL; // implement to NULL m_abfr.reallocateBfr("\x1b[?25l", 6); // reallocate data m_abfr.reallocateBfr("\x1b[H", 3); // reallocate data /* * draw rows, message bar and status bar */ drawRows(&m_abfr); drawStatusBar(&m_abfr); drawMessageBar(&m_abfr); /* * write to buff cursor | position */ char buff[32]; snprintf(buff, sizeof(buff), "\x1b[%d;%dH", (m_pCnfg->configY - m_pCnfg->disableRow) + 1, (m_pCnfg->rowX - m_pCnfg->disableClr) + 1); m_abfr.reallocateBfr(buff, strlen(buff)); m_abfr.reallocateBfr("\x1b[?25h", 6); /* * update screen */ write(STDOUT_FILENO, ab.b, ab.len); m_abfr.freeBfr(); // free memory } char* Common::callPrompt(char *prompt, void (*callback)(char*, int)) { size_t buffsize = 128; char* bfr = malloc(buffsize); // allocate memory size_t bufflen = 0; // lenght bfr[0] = '\0'; while (1) { statusMsg(prompt, bfr); // set prompt updateScreen(); // and update screen int key = tml.whatKey(); // read key if (key == DELETE_KEY || key == CTRL_KEY('h') || key == BACKSPACE) { if (bufflen != 0) // if buffer is not empty bfr[--bufflen] = '\0'; // set end of row } else if (key == '\x1b') // if this is ESC { statusMsg(""); // erase if (callback) // if callback is not NULL callback(bfr, key); // call func for callback which pointed by callback() free(bfr); // free memory return NULL; // and cancel } else if (key == '\r') // if carriage return (move the cursor at the start of the line) { if (bufflen != 0) // and bufflen is not empty { statusMsg(""); // clean message if (callback) callback(bfr, key); // and get callback return bfr; // returning of buffer } } else if (!iscntrl(key) && key < 128) // checks, whether the argument, transmitted via the parameter сharacter, control character { /* * reallocation of buffer if needs */ if (bufflen == buffsize - 1) { buffsize *= 2; bfr = realloc(bfr, buffsize); } bfr[bufflen++] = key; // write this key to buffer bfr[bufflen] = '\0'; // and end of row } if (callback) callback(bfr, key); // call of callback } } void Common::scrolling() { // TODO } void Common::moveCursor(int key) { // instancing RowController // if empty - to zero position, else to the end of row // RowController* pRowctrl = (m_pCnfg->configY >= m_pCnfg->rowCount) ? NULL : &m_pCnfg->pRowObj[m_pCnfg->configY]; switch (key) { case ARROW_LEFT: if (m_pCnfg->configX != 0) // if horizontal position isn't zero { m_pCnfg->configX--; // move left } else if (m_pCnfg->configY > 0) // else if there is at least 1 row { m_pCnfg->configY--; // move to that row m_pCnfg->configX = m_pCnfg->pRowObj[m_pCnfg->configY].size; // and to the end of that row } break; case ARROW_RIGHT: if (pRowctrl && m_pCnfg->configX < pRowctrl->size) // if there is row and if cursor is not in the end of row { m_pCnfg->configX++; // move cursor right along of row } else if (pRowctrl && m_pCnfg->configX == pRowctrl->size) // if there is row and cursor in the end of this row { m_pCnfg->configY++; // move to next row E.cx = 0; // on zero position } break; case ARROW_UP: if (m_pCnfg->configY != 0) // if there is at least 1 row { m_pCnfg->configY--; // move up } break; case ARROW_DOWN: if (m_pCnfg->configY < m_pCnfg->rowCount) // if cursor is not on last row { m_pCnfg->configY++; // move down } break; } } void Common::processingKeypress() { static int sQuitCounter = EDITORRMEND_QUIT_COUNTER; // counter clicking for exit int key = whatKey(); // read key switch (key) { case '\r': // if carriage return (Enter key) setNewline(); // set newline break; case CTRL_KEY('q'): if (m_pCnfg->smear && sQuitCounter > 0) // if there is any changes and counter > 0 { statusMsg("! File was changed and unsaved and data can be lost after exiting. " "Press Ctrl-Q %d more times to exit.", sQuitCounter); sQuitCounter--; // counter decrement return; } write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); exit(0); break; case CTRL_KEY('s'): save(); // TODO: save changes break; case HOME_KEY: m_pCnfg->configX = 0; // to the row beginning break; case END_KEY: if (m_pCnfg->configY < m_pCnfg->rowCount) // if not last row m_pCnfg->configX = m_pCnfg->pRowObj[m_pCnfg->configY].size; // to the end of row break; case CTRL_KEY('f'): find(); // find func break; case BACKSPACE: case CTRL_KEY('h'): case DELETE_KEY: if (key == DELETE_KEY) moveCursor(ARROW_RIGHT); // move cursor right deleteChar(); // delete char break; // page up/down // case PAGE_UP: case PAGE_DOWN: { if (key == PAGE_UP) { m_pCnfg->configY = m_pCnfg->disableRow; // move page up } else if (key == PAGE_DOWN) { m_pCnfg->configY = m_pCnfg->disableRow + m_pCnfg->enableRow - 1; // move page down if (m_pCnfg->configY > m_pCnfg->rowCount) m_pCnfg->configY = m_pCnfg->rowCount; } int times = m_pCnfg->enableRow; while (times--) moveCursor(key == PAGE_UP ? ARROW_UP : ARROW_DOWN); } break; case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: moveCursor(key); break; case CTRL_KEY('l'): case '\x1b': break; default: setChar(key); // just write chars break; } sQuitCounter = EDITORRMEND_QUIT_COUNTER; } /* * editor operations */ void Common::openFile(char *filename) { free(m_pCnfg->pFilename); // free pFilename becouse strdup uses malloc and in next func // call need to free memory m_pCnfg->pFilename = strdup(filename); // duplicate filename to pFilename m_pAll->pickSyntaxClr(); FILE* fln = fopen(filename, "r"); // open file foe reading if (!fln) // if can't to open file tml.emergencyDestruction("fopen"); // forced closure char* pStr = NULL; size_t strUSZ = 0; // size ssize_t strSSZ; // signed size while ((strSSZ = getline(&pStr, &strUSZ, fln)) != -1) // while strUSZ size of pStr that reads from file fp { while (strSSZ > 0 && (pStr[strSSZ - 1] == '\n' || pStr[strSSZ - 1] == '\r')) // if this is end of line strSSZ--; // decrease line size m_pCnfg->setRow(m_pCnfg->rowCount, pStr, strSSZ); // set rows from file } free(pStr); fclose(fln); // close file m_pCnfg->smear = 0; // no changes in now opened file } void detectCallback(char* query, int key) { // TODO } void Common::save() { if (m_pCnfg->pFilename == NULL) // if no falename { m_pCnfg->pFilename = callPrompt("Save as: %s (ESC - cancel)", NULL); // set message if (m_pCnfg->pFilename == NULL) // if filename still is not { statusMsg("Saving operation is canceled"); // lead out status message about cancelling return; // and go out of save function } m_pAll->pickSyntaxClr(); // colorize text in dependence of filename extension } size_t sz; char *pBuff = m_pCnfg->row2Str(&sz); // get strings and size of these int fd = open(m_pCnfg->pFilename, O_RDWR | O_CREAT, 0644); // open the file for read/write and if the file does not exist, it will be created // 0644 - look here: https://stackoverflow.com/questions/18415904/what-does-mode-t-0644-mean if (fd != -1) { if (ftruncate(fd, sz) != -1) // set file size { if (write(fd, pBuff, sz) == sz) // if writing from buffer to file is success { close(fd); // close free(pBuff); // free memory m_pCnfg->smear = 0; // no changes in syntax after copying to file statusMsg("%d bytes is written successfully", sz); // set status message return; // go out } } close(fd); // if can't change size - close file } free(pBuff); // free buffer statusMsg("Saving operation has error: %s", strerror(errno)); // lead out error about } void Common::find() { // TODO } <commit_msg>defined searching function<commit_after>// CommonFunc.cpp -- source file /* * Author: Ivan Chapkailo (septimomend) * Date: 02.07.2017 * * © 2017 Ivan Chapkailo. All rights reserved * e-mail: chapkailo.ivan@gmail.com */ #include "stdafx.h" #include "CommonFunc.h" Common::Common() { m_pAll = tml.getAllControllerObj(); m_pCnfg = m_pAll->getConfigObj(); } Common::Common(AllControllers* all) : m_pCnfg(all->getConfigObj()) { } /* * draws */ void Common::drawRows(Adbfr* abfr); { // TODO } void Common::drawStatusBar(Adbfr* abfr) { // TODO } void Common::drawMessageBar(Adbfr* abfr) { // TODO } /* * operations */ void Common::statusMsg(const char *fmt, ...) { va_list arg; // for unknown number of parameters va_start(arg, fmt); // initialize arg vsnprintf(cnfg.statusMessage, sizeof(cnfg.statusMessage), fmt, arg); // output parameters to statusMessage va_end(arg); // end cnfg.statusMessageTime = time(NULL); // gets time } void Common::updateScreen() { scrolling(); m_abfr = ADBFR_IMPL; // implement to NULL m_abfr.reallocateBfr("\x1b[?25l", 6); // reallocate data m_abfr.reallocateBfr("\x1b[H", 3); // reallocate data /* * draw rows, message bar and status bar */ drawRows(&m_abfr); drawStatusBar(&m_abfr); drawMessageBar(&m_abfr); /* * write to buff cursor | position */ char buff[32]; snprintf(buff, sizeof(buff), "\x1b[%d;%dH", (m_pCnfg->configY - m_pCnfg->disableRow) + 1, (m_pCnfg->rowX - m_pCnfg->disableClr) + 1); m_abfr.reallocateBfr(buff, strlen(buff)); m_abfr.reallocateBfr("\x1b[?25h", 6); /* * update screen */ write(STDOUT_FILENO, ab.b, ab.len); m_abfr.freeBfr(); // free memory } char* Common::callPrompt(char *prompt, void (*callback)(char*, int)) { size_t buffsize = 128; char* bfr = malloc(buffsize); // allocate memory size_t bufflen = 0; // lenght bfr[0] = '\0'; while (1) { statusMsg(prompt, bfr); // set prompt updateScreen(); // and update screen int key = tml.whatKey(); // read key if (key == DELETE_KEY || key == CTRL_KEY('h') || key == BACKSPACE) { if (bufflen != 0) // if buffer is not empty bfr[--bufflen] = '\0'; // set end of row } else if (key == '\x1b') // if this is ESC { statusMsg(""); // erase if (callback) // if callback is not NULL callback(bfr, key); // call func for callback which pointed by callback() free(bfr); // free memory return NULL; // and cancel } else if (key == '\r') // if carriage return (move the cursor at the start of the line) { if (bufflen != 0) // and bufflen is not empty { statusMsg(""); // clean message if (callback) callback(bfr, key); // and get callback return bfr; // returning of buffer } } else if (!iscntrl(key) && key < 128) // checks, whether the argument, transmitted via the parameter сharacter, control character { /* * reallocation of buffer if needs */ if (bufflen == buffsize - 1) { buffsize *= 2; bfr = realloc(bfr, buffsize); } bfr[bufflen++] = key; // write this key to buffer bfr[bufflen] = '\0'; // and end of row } if (callback) callback(bfr, key); // call of callback } } void Common::scrolling() { // TODO } void Common::moveCursor(int key) { // instancing RowController // if empty - to zero position, else to the end of row // RowController* pRowctrl = (m_pCnfg->configY >= m_pCnfg->rowCount) ? NULL : &m_pCnfg->pRowObj[m_pCnfg->configY]; switch (key) { case ARROW_LEFT: if (m_pCnfg->configX != 0) // if horizontal position isn't zero { m_pCnfg->configX--; // move left } else if (m_pCnfg->configY > 0) // else if there is at least 1 row { m_pCnfg->configY--; // move to that row m_pCnfg->configX = m_pCnfg->pRowObj[m_pCnfg->configY].size; // and to the end of that row } break; case ARROW_RIGHT: if (pRowctrl && m_pCnfg->configX < pRowctrl->size) // if there is row and if cursor is not in the end of row { m_pCnfg->configX++; // move cursor right along of row } else if (pRowctrl && m_pCnfg->configX == pRowctrl->size) // if there is row and cursor in the end of this row { m_pCnfg->configY++; // move to next row E.cx = 0; // on zero position } break; case ARROW_UP: if (m_pCnfg->configY != 0) // if there is at least 1 row { m_pCnfg->configY--; // move up } break; case ARROW_DOWN: if (m_pCnfg->configY < m_pCnfg->rowCount) // if cursor is not on last row { m_pCnfg->configY++; // move down } break; } } void Common::processingKeypress() { static int sQuitCounter = EDITORRMEND_QUIT_COUNTER; // counter clicking for exit int key = whatKey(); // read key switch (key) { case '\r': // if carriage return (Enter key) setNewline(); // set newline break; case CTRL_KEY('q'): if (m_pCnfg->smear && sQuitCounter > 0) // if there is any changes and counter > 0 { statusMsg("! File was changed and unsaved and data can be lost after exiting. " "Press Ctrl-Q %d more times to exit.", sQuitCounter); sQuitCounter--; // counter decrement return; } write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); exit(0); break; case CTRL_KEY('s'): save(); // TODO: save changes break; case HOME_KEY: m_pCnfg->configX = 0; // to the row beginning break; case END_KEY: if (m_pCnfg->configY < m_pCnfg->rowCount) // if not last row m_pCnfg->configX = m_pCnfg->pRowObj[m_pCnfg->configY].size; // to the end of row break; case CTRL_KEY('f'): find(); // find func break; case BACKSPACE: case CTRL_KEY('h'): case DELETE_KEY: if (key == DELETE_KEY) moveCursor(ARROW_RIGHT); // move cursor right deleteChar(); // delete char break; // page up/down // case PAGE_UP: case PAGE_DOWN: { if (key == PAGE_UP) { m_pCnfg->configY = m_pCnfg->disableRow; // move page up } else if (key == PAGE_DOWN) { m_pCnfg->configY = m_pCnfg->disableRow + m_pCnfg->enableRow - 1; // move page down if (m_pCnfg->configY > m_pCnfg->rowCount) m_pCnfg->configY = m_pCnfg->rowCount; } int times = m_pCnfg->enableRow; while (times--) moveCursor(key == PAGE_UP ? ARROW_UP : ARROW_DOWN); } break; case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: moveCursor(key); break; case CTRL_KEY('l'): case '\x1b': break; default: setChar(key); // just write chars break; } sQuitCounter = EDITORRMEND_QUIT_COUNTER; } /* * editor operations */ void Common::openFile(char *filename) { free(m_pCnfg->pFilename); // free pFilename becouse strdup uses malloc and in next func // call need to free memory m_pCnfg->pFilename = strdup(filename); // duplicate filename to pFilename m_pAll->pickSyntaxClr(); FILE* fln = fopen(filename, "r"); // open file foe reading if (!fln) // if can't to open file tml.emergencyDestruction("fopen"); // forced closure char* pStr = NULL; size_t strUSZ = 0; // size ssize_t strSSZ; // signed size while ((strSSZ = getline(&pStr, &strUSZ, fln)) != -1) // while strUSZ size of pStr that reads from file fp { while (strSSZ > 0 && (pStr[strSSZ - 1] == '\n' || pStr[strSSZ - 1] == '\r')) // if this is end of line strSSZ--; // decrease line size m_pCnfg->setRow(m_pCnfg->rowCount, pStr, strSSZ); // set rows from file } free(pStr); fclose(fln); // close file m_pCnfg->smear = 0; // no changes in now opened file } void detectCallback(char* query, int key) { // TODO } void Common::save() { if (m_pCnfg->pFilename == NULL) // if no falename { m_pCnfg->pFilename = callPrompt("Save as: %s (ESC - cancel)", NULL); // set message if (m_pCnfg->pFilename == NULL) // if filename still is not { statusMsg("Saving operation is canceled"); // lead out status message about cancelling return; // and go out of save function } m_pAll->pickSyntaxClr(); // colorize text in dependence of filename extension } size_t sz; char *pBuff = m_pCnfg->row2Str(&sz); // get strings and size of these int fd = open(m_pCnfg->pFilename, O_RDWR | O_CREAT, 0644); // open the file for read/write and if the file does not exist, it will be created // 0644 - look here: https://stackoverflow.com/questions/18415904/what-does-mode-t-0644-mean if (fd != -1) { if (ftruncate(fd, sz) != -1) // set file size { if (write(fd, pBuff, sz) == sz) // if writing from buffer to file is success { close(fd); // close free(pBuff); // free memory m_pCnfg->smear = 0; // no changes in syntax after copying to file statusMsg("%d bytes is written successfully", sz); // set status message return; // go out } } close(fd); // if can't change size - close file } free(pBuff); // free buffer statusMsg("Saving operation has error: %s", strerror(errno)); // lead out error about } void Common::find() { // remember last data // int xsave = m_pCnfg->configX; int ysave = m_pCnfg->configY; int prevclr = m_pCnfg->disableClr; int prevrow = m_pCnfg->disableRow; char* callb = callPrompt("Find: %s (ESC - cancel/Arrows - move/Enter)", detectCallback); // if there are changes returned [enter] if (callb) free(callb); else // else return saved data [esc] { m_pCnfg->configX = xsave; m_pCnfg->configY = ysave; m_pCnfg->disableClr = prevclr; m_pCnfg->disableRow; } } <|endoftext|>
<commit_before>#include <vector> #include <algorithm> #include <getopt.h> #include <sstream> #include <utility> #include <map> #ifndef WIN32 //for using ntohl, ntohs, etc. #include <in.h> #include <errno.h> #endif #include "IpAddress.h" #include "SystemUtils.h" #include "RawPacket.h" #include "ProtocolType.h" #include "Packet.h" #include "EthLayer.h" #include "IPv4Layer.h" #include "UdpLayer.h" #include "DnsLayer.h" #include "PcapFilter.h" #include "PcapLiveDevice.h" #include "PcapLiveDeviceList.h" #include "PlatformSpecificUtils.h" #define EXIT_WITH_ERROR(reason, ...) do { \ printf("DnsSpoofing terminated in error: " reason "\n", ## __VA_ARGS__); \ exit(1); \ } while(0) static struct option DnsSpoofingOptions[] = { {"interface", required_argument, 0, 'i'}, {"spoof-dns-server", required_argument, 0, 'd'}, {"client-ip", required_argument, 0, 'c'}, {"host-list", required_argument, 0, 'o'}, {"help", no_argument, 0, 'h'}, {"list", no_argument, 0, 'l'}, {0, 0, 0, 0} }; /** * A struct that holds all counters that are collected during application runtime */ struct DnsSpoofStats { int numOfSpoofedDnsRequests; std::map<std::string, int> spoofedHosts; DnsSpoofStats() : numOfSpoofedDnsRequests(0) {} }; /** * A struct that holds all arguments passed to handleDnsRequest() */ struct DnsSpoofingArgs { IPv4Address dnsServer; std::vector<std::string> dnsHostsToSpoof; DnsSpoofStats stats; bool shouldStop; DnsSpoofingArgs() : dnsServer(IPv4Address::Zero), shouldStop(false) {} }; /** * The method that is called each time a DNS request is received. This methods turns the DNS request into a DNS response with the * spoofed information and sends it back to the network */ void handleDnsRequest(RawPacket* packet, PcapLiveDevice* dev, void* cookie) { DnsSpoofingArgs* args = (DnsSpoofingArgs*)cookie; // create a parsed packet from the raw packet Packet dnsRequest(packet); if (!dnsRequest.isPacketOfType(DNS) || !dnsRequest.isPacketOfType(IPv4) || !dnsRequest.isPacketOfType(UDP) || !dnsRequest.isPacketOfType(Ethernet)) return; // extract all packet layers EthLayer* ethLayer = dnsRequest.getLayerOfType<EthLayer>(); IPv4Layer* ip4Layer = dnsRequest.getLayerOfType<IPv4Layer>(); UdpLayer* udpLayer = dnsRequest.getLayerOfType<UdpLayer>(); DnsLayer* dnsLayer = dnsRequest.getLayerOfType<DnsLayer>(); // skip DNS requests with more than 1 request or with 0 requests if (dnsLayer->getDnsHeader()->numberOfQuestions != htons(1) || dnsLayer->getFirstQuery() == NULL) return; // skip DNS requests which are not of class IN and type A (IPv4) DnsQuery* dnsQuery = dnsLayer->getFirstQuery(); if (dnsQuery->getDnsType() != DNS_TYPE_A || dnsQuery->getDnsClass() != DNS_CLASS_IN) return; // empty dnsHostsToSpoof means spoofing all hosts if (!args->dnsHostsToSpoof.empty()) { bool hostMatch = false; // go over all hosts in dnsHostsToSpoof list and see if current query matches one of them for (std::vector<std::string>::iterator iter = args->dnsHostsToSpoof.begin(); iter != args->dnsHostsToSpoof.end(); iter++) { if (dnsLayer->getQuery(*iter, false) != NULL) { hostMatch = true; break; } } if (!hostMatch) return; } // create a response out of the request packet // reverse src and dst MAC addresses MacAddress srcMac = ethLayer->getSourceMac(); ethLayer->setSoureMac(ethLayer->getDestMac()); ethLayer->setDestMac(srcMac); // reverse src and dst IP addresses IPv4Address srcIP = ip4Layer->getSrcIpAddress(); ip4Layer->setSrcIpAddress(ip4Layer->getDstIpAddress()); ip4Layer->setDstIpAddress(srcIP); ip4Layer->getIPv4Header()->ipId = 0; // reverse src and dst UDP ports uint16_t srcPort = udpLayer->getUdpHeader()->portSrc; udpLayer->getUdpHeader()->portSrc = udpLayer->getUdpHeader()->portDst; udpLayer->getUdpHeader()->portDst = srcPort; // add DNS response dnsLayer->getDnsHeader()->queryOrResponse = 1; IPv4Address dnsServer = args->dnsServer; if (!dnsLayer->addAnswer(dnsQuery->getName(), DNS_TYPE_A, DNS_CLASS_IN, 1, dnsServer.toString())) return; dnsRequest.computeCalculateFields(); // send DNS response back to the network if (!dev->sendPacket(&dnsRequest)) return; args->stats.numOfSpoofedDnsRequests++; args->stats.spoofedHosts[dnsQuery->getName()]++; } /** * A callback for application interrupted event (ctrl+c): print DNS spoofing summary */ void onApplicationInterrupted(void* cookie) { DnsSpoofingArgs* args = (DnsSpoofingArgs*)cookie; if (args->stats.spoofedHosts.size() == 0) { printf("\nApplication closing. No hosts were spoofed\n"); } else { printf("\nApplication closing\nSummary of spoofed hosts:\n" "-------------------------\n"); for (std::map<std::string, int>::iterator iter = args->stats.spoofedHosts.begin(); iter != args->stats.spoofedHosts.end(); iter++) printf("Host [%s]: spoofed %d times\n", iter->first.c_str(), iter->second); } args->shouldStop = true; } /** * Activate DNS spoofing: prepare the device and start capturing DNS requests */ void doDnsSpoofing(PcapLiveDevice* dev, IPv4Address dnsServer, IPv4Address clientIP, std::vector<std::string> dnsHostsToSpoof) { // open device if (!dev->open()) EXIT_WITH_ERROR("Cannot open capture device"); // set a filter to capture only DNS requests and client IP if provided PortFilter dnsPortFilter(53, DST); if (clientIP == IPv4Address::Zero) { if (!dev->setFilter(dnsPortFilter)) EXIT_WITH_ERROR("Cannot set DNS filter for device"); } else { IPFilter clientIpFilter(clientIP.toString(), SRC); std::vector<GeneralFilter*> filterForAnd; filterForAnd.push_back(&dnsPortFilter); filterForAnd.push_back(&clientIpFilter); AndFilter andFilter(filterForAnd); if (!dev->setFilter(andFilter)) EXIT_WITH_ERROR("Cannot set DNS and client IP filter for device"); } // make args for callback DnsSpoofingArgs args; args.dnsServer = dnsServer; args.dnsHostsToSpoof = dnsHostsToSpoof; // start capturing DNS requests if (!dev->startCapture(handleDnsRequest, &args)) EXIT_WITH_ERROR("Cannot start packet capture"); // register the on app close event to print summary stats on app termination ApplicationEventHandler::getInstance().onApplicationInterrupted(onApplicationInterrupted, &args); // run an endless loop until ctrl+c is pressed while (!args.shouldStop) { printf("Spoofed %d DNS requests so far\n", args.stats.numOfSpoofedDnsRequests); PCAP_SLEEP(5); } } /** * go over all interfaces and output their names */ void listInterfaces() { const std::vector<PcapLiveDevice*>& devList = PcapLiveDeviceList::getInstance().getPcapLiveDevicesList(); printf("\nNetwork interfaces:\n"); for (std::vector<PcapLiveDevice*>::const_iterator iter = devList.begin(); iter != devList.end(); iter++) { printf(" -> Name: '%s' IP address: %s\n", (*iter)->getName(), (*iter)->getIPv4Address().toString().c_str()); } exit(0); } /** * Print application usage */ void printUsage() { printf("\nUsage: DnsSpoofing [-hl] [-o HOST1,HOST2,...,HOST_N] [-c IP_ADDRESS] -i INTERFACE -d IP_ADDRESS\n" "\nOptions:\n\n" " -h|--help : Displays this help message and exits\n" " -l|--list : Print the list of available interfaces\n" " -i|--interface INTERFACE : The interface name or interface IP address to use. Use the -l switch to see all interfaces\n" " -d|--spoof-dns-server IP_ADDRESS : The IPv4 address of the spoofed DNS server (all responses will be sent with this IP address)\n" " -c|--client-ip IP_ADDRESS : Spoof only DNS requests coming from a specific IPv4 address\n" " -o|--host-list HOST1,HOST2,...,HOST_N : A comma-separated list of hosts to spoof. If list is not given, all hosts will be spoofed." " If an host contains '*' all sub-domains will be spoofed, for example: if '*.google.com' is given\n" " then 'mail.google.com', 'tools.google.com', etc. will be spoofed\n\n"); } /** * main method of the application */ int main(int argc, char* argv[]) { int optionIndex = 0; char opt = 0; std::string interfaceNameOrIP(""); IPv4Address dnsServer = IPv4Address::Zero; IPv4Address clientIP = IPv4Address::Zero; bool clientIpSet = false; std::vector<std::string> hostList; while((opt = getopt_long (argc, argv, "i:d:c:o:hl", DnsSpoofingOptions, &optionIndex)) != -1) { switch (opt) { case 0: { break; } case 'h': { printUsage(); exit(0); } case 'l': { listInterfaces(); exit(0); } case 'i': { interfaceNameOrIP = optarg; break; } case 'd': { dnsServer = IPv4Address(optarg); break; } case 'c': { clientIP = IPv4Address(optarg); clientIpSet = true; break; } case 'o': { std::string input = optarg; std::istringstream stream(input); std::string token; while(std::getline(stream, token, ',')) hostList.push_back(token); break; } default: { printUsage(); exit(1); } } } PcapLiveDevice* dev = NULL; // check if interface argument is IP or name and extract the device IPv4Address interfaceIP(interfaceNameOrIP); if (interfaceIP.isValid()) { dev = PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(interfaceIP); if (dev == NULL) EXIT_WITH_ERROR("Couldn't find interface by provided IP"); } else { dev = PcapLiveDeviceList::getInstance().getPcapLiveDeviceByName(interfaceNameOrIP); if (dev == NULL) EXIT_WITH_ERROR("Couldn't find interface by provided name"); } // verify DNS server IP is a valid IPv4 address if (dnsServer == IPv4Address::Zero || !dnsServer.isValid()) EXIT_WITH_ERROR("Spoof DNS server IP provided is empty or not a valid IPv4 address"); // verify client IP is valid if set if (clientIpSet && !clientIP.isValid()) EXIT_WITH_ERROR("Client IP to spoof is invalid"); doDnsSpoofing(dev, dnsServer, clientIP, hostList); } <commit_msg>Small changes in DNS spoofing example<commit_after>/** * DNS spoofing example application * ================================ * This application does simple DNS spoofing. It's provided with interface name or IP and starts capturing DNS requests on that * interface. Each DNS request that matches is edited and turned into a DNS response with a user-provided IPv4 as the resolved IP. * Then it's sent back on the network on the same interface */ #include <vector> #include <algorithm> #include <getopt.h> #include <sstream> #include <utility> #include <map> #ifndef WIN32 //for using ntohl, ntohs, etc. #include <in.h> #include <errno.h> #endif #include "IpAddress.h" #include "SystemUtils.h" #include "RawPacket.h" #include "ProtocolType.h" #include "Packet.h" #include "EthLayer.h" #include "IPv4Layer.h" #include "UdpLayer.h" #include "DnsLayer.h" #include "PcapFilter.h" #include "PcapLiveDevice.h" #include "PcapLiveDeviceList.h" #include "PlatformSpecificUtils.h" #define EXIT_WITH_ERROR(reason, ...) do { \ printf("DnsSpoofing terminated in error: " reason "\n", ## __VA_ARGS__); \ exit(1); \ } while(0) static struct option DnsSpoofingOptions[] = { {"interface", required_argument, 0, 'i'}, {"spoof-dns-server", required_argument, 0, 'd'}, {"client-ip", required_argument, 0, 'c'}, {"host-list", required_argument, 0, 'o'}, {"help", no_argument, 0, 'h'}, {"list", no_argument, 0, 'l'}, {0, 0, 0, 0} }; /** * A struct that holds all counters that are collected during application runtime */ struct DnsSpoofStats { int numOfSpoofedDnsRequests; std::map<std::string, int> spoofedHosts; DnsSpoofStats() : numOfSpoofedDnsRequests(0) {} }; /** * A struct that holds all arguments passed to handleDnsRequest() */ struct DnsSpoofingArgs { IPv4Address dnsServer; std::vector<std::string> dnsHostsToSpoof; DnsSpoofStats stats; bool shouldStop; DnsSpoofingArgs() : dnsServer(IPv4Address::Zero), shouldStop(false) {} }; /** * The method that is called each time a DNS request is received. This methods turns the DNS request into a DNS response with the * spoofed information and sends it back to the network */ void handleDnsRequest(RawPacket* packet, PcapLiveDevice* dev, void* cookie) { DnsSpoofingArgs* args = (DnsSpoofingArgs*)cookie; // create a parsed packet from the raw packet Packet dnsRequest(packet); if (!dnsRequest.isPacketOfType(DNS) || !dnsRequest.isPacketOfType(IPv4) || !dnsRequest.isPacketOfType(UDP) || !dnsRequest.isPacketOfType(Ethernet)) return; // extract all packet layers EthLayer* ethLayer = dnsRequest.getLayerOfType<EthLayer>(); IPv4Layer* ip4Layer = dnsRequest.getLayerOfType<IPv4Layer>(); UdpLayer* udpLayer = dnsRequest.getLayerOfType<UdpLayer>(); DnsLayer* dnsLayer = dnsRequest.getLayerOfType<DnsLayer>(); // skip DNS requests with more than 1 request or with 0 requests if (dnsLayer->getDnsHeader()->numberOfQuestions != htons(1) || dnsLayer->getFirstQuery() == NULL) return; // skip DNS requests which are not of class IN and type A (IPv4) DnsQuery* dnsQuery = dnsLayer->getFirstQuery(); if (dnsQuery->getDnsType() != DNS_TYPE_A || dnsQuery->getDnsClass() != DNS_CLASS_IN) return; // empty dnsHostsToSpoof means spoofing all hosts if (!args->dnsHostsToSpoof.empty()) { bool hostMatch = false; // go over all hosts in dnsHostsToSpoof list and see if current query matches one of them for (std::vector<std::string>::iterator iter = args->dnsHostsToSpoof.begin(); iter != args->dnsHostsToSpoof.end(); iter++) { if (dnsLayer->getQuery(*iter, false) != NULL) { hostMatch = true; break; } } if (!hostMatch) return; } // create a response out of the request packet // reverse src and dst MAC addresses MacAddress srcMac = ethLayer->getSourceMac(); ethLayer->setSoureMac(ethLayer->getDestMac()); ethLayer->setDestMac(srcMac); // reverse src and dst IP addresses IPv4Address srcIP = ip4Layer->getSrcIpAddress(); ip4Layer->setSrcIpAddress(ip4Layer->getDstIpAddress()); ip4Layer->setDstIpAddress(srcIP); ip4Layer->getIPv4Header()->ipId = 0; // reverse src and dst UDP ports uint16_t srcPort = udpLayer->getUdpHeader()->portSrc; udpLayer->getUdpHeader()->portSrc = udpLayer->getUdpHeader()->portDst; udpLayer->getUdpHeader()->portDst = srcPort; // add DNS response dnsLayer->getDnsHeader()->queryOrResponse = 1; IPv4Address dnsServer = args->dnsServer; if (!dnsLayer->addAnswer(dnsQuery->getName(), DNS_TYPE_A, DNS_CLASS_IN, 1, dnsServer.toString())) return; dnsRequest.computeCalculateFields(); // send DNS response back to the network if (!dev->sendPacket(&dnsRequest)) return; args->stats.numOfSpoofedDnsRequests++; args->stats.spoofedHosts[dnsQuery->getName()]++; } /** * A callback for application interrupted event (ctrl+c): print DNS spoofing summary */ void onApplicationInterrupted(void* cookie) { DnsSpoofingArgs* args = (DnsSpoofingArgs*)cookie; if (args->stats.spoofedHosts.size() == 0) { printf("\nApplication closing. No hosts were spoofed\n"); } else { printf("\nApplication closing\nSummary of spoofed hosts:\n" "-------------------------\n"); for (std::map<std::string, int>::iterator iter = args->stats.spoofedHosts.begin(); iter != args->stats.spoofedHosts.end(); iter++) printf("Host [%s]: spoofed %d times\n", iter->first.c_str(), iter->second); } args->shouldStop = true; } /** * Activate DNS spoofing: prepare the device and start capturing DNS requests */ void doDnsSpoofing(PcapLiveDevice* dev, IPv4Address dnsServer, IPv4Address clientIP, std::vector<std::string> dnsHostsToSpoof) { // open device if (!dev->open()) EXIT_WITH_ERROR("Cannot open capture device"); // set a filter to capture only DNS requests and client IP if provided PortFilter dnsPortFilter(53, DST); if (clientIP == IPv4Address::Zero) { if (!dev->setFilter(dnsPortFilter)) EXIT_WITH_ERROR("Cannot set DNS filter for device"); } else { IPFilter clientIpFilter(clientIP.toString(), SRC); std::vector<GeneralFilter*> filterForAnd; filterForAnd.push_back(&dnsPortFilter); filterForAnd.push_back(&clientIpFilter); AndFilter andFilter(filterForAnd); if (!dev->setFilter(andFilter)) EXIT_WITH_ERROR("Cannot set DNS and client IP filter for device"); } // make args for callback DnsSpoofingArgs args; args.dnsServer = dnsServer; args.dnsHostsToSpoof = dnsHostsToSpoof; // start capturing DNS requests if (!dev->startCapture(handleDnsRequest, &args)) EXIT_WITH_ERROR("Cannot start packet capture"); // register the on app close event to print summary stats on app termination ApplicationEventHandler::getInstance().onApplicationInterrupted(onApplicationInterrupted, &args); // run an endless loop until ctrl+c is pressed while (!args.shouldStop) { printf("Spoofed %d DNS requests so far\n", args.stats.numOfSpoofedDnsRequests); PCAP_SLEEP(5); } } /** * go over all interfaces and output their names */ void listInterfaces() { const std::vector<PcapLiveDevice*>& devList = PcapLiveDeviceList::getInstance().getPcapLiveDevicesList(); printf("\nNetwork interfaces:\n"); for (std::vector<PcapLiveDevice*>::const_iterator iter = devList.begin(); iter != devList.end(); iter++) { printf(" -> Name: '%s' IP address: %s\n", (*iter)->getName(), (*iter)->getIPv4Address().toString().c_str()); } exit(0); } /** * Print application usage */ void printUsage() { printf("\nUsage: DnsSpoofing [-hl] [-o HOST1,HOST2,...,HOST_N] [-c IP_ADDRESS] -i INTERFACE -d IP_ADDRESS\n" "\nOptions:\n\n" " -h|--help : Displays this help message and exits\n" " -l|--list : Print the list of available interfaces\n" " -i|--interface INTERFACE : The interface name or interface IP address to use. Use the -l switch to see all interfaces\n" " -d|--spoof-dns-server IP_ADDRESS : The IPv4 address of the spoofed DNS server (all responses will be sent with this IP address)\n" " -c|--client-ip IP_ADDRESS : Spoof only DNS requests coming from a specific IPv4 address\n" " -o|--host-list HOST1,HOST2,...,HOST_N : A comma-separated list of hosts to spoof. If list is not given, all hosts will be spoofed." " If an host contains '*' all sub-domains will be spoofed, for example: if '*.google.com' is given\n" " then 'mail.google.com', 'tools.google.com', etc. will be spoofed\n\n"); } /** * main method of the application */ int main(int argc, char* argv[]) { int optionIndex = 0; char opt = 0; std::string interfaceNameOrIP(""); IPv4Address dnsServer = IPv4Address::Zero; IPv4Address clientIP = IPv4Address::Zero; bool clientIpSet = false; std::vector<std::string> hostList; while((opt = getopt_long (argc, argv, "i:d:c:o:hl", DnsSpoofingOptions, &optionIndex)) != -1) { switch (opt) { case 0: { break; } case 'h': { printUsage(); exit(0); } case 'l': { listInterfaces(); exit(0); } case 'i': { interfaceNameOrIP = optarg; break; } case 'd': { dnsServer = IPv4Address(optarg); break; } case 'c': { clientIP = IPv4Address(optarg); clientIpSet = true; break; } case 'o': { std::string input = optarg; std::istringstream stream(input); std::string token; while(std::getline(stream, token, ',')) hostList.push_back(token); break; } default: { printUsage(); exit(1); } } } PcapLiveDevice* dev = NULL; // check if interface argument is IP or name and extract the device if (interfaceNameOrIP == "") { EXIT_WITH_ERROR("Interface name or IP weren't provided. Please use the -i switch or -h for help"); } IPv4Address interfaceIP(interfaceNameOrIP); if (interfaceIP.isValid()) { dev = PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(interfaceIP); if (dev == NULL) EXIT_WITH_ERROR("Couldn't find interface by provided IP"); } else { dev = PcapLiveDeviceList::getInstance().getPcapLiveDeviceByName(interfaceNameOrIP); if (dev == NULL) EXIT_WITH_ERROR("Couldn't find interface by provided name"); } // verify DNS server IP is a valid IPv4 address if (dnsServer == IPv4Address::Zero || !dnsServer.isValid()) EXIT_WITH_ERROR("Spoof DNS server IP provided is empty or not a valid IPv4 address"); // verify client IP is valid if set if (clientIpSet && !clientIP.isValid()) EXIT_WITH_ERROR("Client IP to spoof is invalid"); doDnsSpoofing(dev, dnsServer, clientIP, hostList); } <|endoftext|>
<commit_before>// See http://herbsutter.com/2009/05/15/effective-concurrency-eliminate-false-sharing/ #include <iostream> #include <algorithm> #include <random> #include <vector> #include <tbb/task_group.h> #include <tbb/task_scheduler_init.h> #include <boost/lexical_cast.hpp> class SquareMatrix { public: SquareMatrix(size_t dim) : m_data(dim*dim, 0), m_dim(dim) {} double* operator[](size_t i) { return &m_data[i*m_dim]; } std::vector<double>::iterator begin() { return m_data.begin(); } std::vector<double>::iterator end() { return m_data.end(); } private: std::vector<double> m_data; size_t m_dim; }; int main(int argc, char* argv[]) { size_t THREADS = 4; if ( argc > 1 ) THREADS = boost::lexical_cast<size_t>(argv[1]); size_t dim = 1024; if ( argc > 2 ) dim = boost::lexical_cast<size_t>(argv[2]); std::uniform_real_distribution<double> distribution(-1,1); std::mt19937 engine; auto generator = [&]{return distribution(engine);}; SquareMatrix m(dim); std::generate(m.begin(),m.end(),generator); std::vector<size_t> perThreadCount(THREADS,0); tbb::task_scheduler_init tsInit(THREADS); tbb::task_group tg; for ( size_t iTask=0; iTask<THREADS; ++iTask ) { tg.run([=,&perThreadCount,&m] { size_t taskSize = dim/THREADS; size_t taskStart = iTask*taskSize; size_t taskEnd = std::min(taskStart+taskSize, dim); for (size_t i=taskStart; i<taskEnd; ++i) { for (size_t j=0; j<dim; ++j) { if (m[i][j]>=0.0) ++perThreadCount[iTask]; } } }); } tg.wait(); auto positiveCount = std::accumulate(perThreadCount.begin(),perThreadCount.end(),0); std::cout << dim << " by " << dim << " matrix has " << positiveCount << " positive entries = " << 100.0*positiveCount/(dim*dim) << "%" << std::endl; } <commit_msg>False sharing example works<commit_after>// See http://herbsutter.com/2009/05/15/effective-concurrency-eliminate-false-sharing/ #include <iostream> #include <algorithm> #include <random> #include <vector> #include <tbb/task_group.h> #include <tbb/task_scheduler_init.h> #include <boost/lexical_cast.hpp> #include <Common/Timer.h> class SquareMatrix { public: SquareMatrix(size_t dim) : m_data(dim*dim, 0), m_dim(dim) {} double* operator[](size_t i) { return &m_data[i*m_dim]; } std::vector<double>::iterator begin() { return m_data.begin(); } std::vector<double>::iterator end() { return m_data.end(); } private: std::vector<double> m_data; size_t m_dim; }; int main(int argc, char* argv[]) { size_t THREADS = 4; if ( argc > 1 ) THREADS = boost::lexical_cast<size_t>(argv[1]); size_t dim = 1024; if ( argc > 2 ) dim = boost::lexical_cast<size_t>(argv[2]); std::uniform_real_distribution<double> distribution(-1,1); std::mt19937 engine; auto generator = [&]{return distribution(engine);}; SquareMatrix m(dim); std::generate(m.begin(),m.end(),generator); std::vector<size_t> perThreadCount(THREADS,0); tbb::task_scheduler_init tsInit(THREADS); tbb::task_group tg; Timer t("Time count"); for ( size_t iTask=0; iTask<THREADS; ++iTask ) { tg.run([=,&perThreadCount,&m] { size_t taskSize = dim/THREADS; size_t taskStart = iTask*taskSize; size_t taskEnd = std::min(taskStart+taskSize, dim); size_t count = 0; for (size_t i=taskStart; i<taskEnd; ++i) { for (size_t j=0; j<dim; ++j) { if (m[i][j]>=0.0) { ++perThreadCount[iTask]; //++count; } } } // perThreadCount[iTask] = count; }); } tg.wait(); auto positiveCount = std::accumulate(perThreadCount.begin(),perThreadCount.end(),0); std::cout << dim << " by " << dim << " matrix has " << positiveCount << " positive entries = " << 100.0*positiveCount/(dim*dim) << "%" << std::endl; } <|endoftext|>
<commit_before>AliEmcalEsdTrackFilterTask* AddTaskEmcalEsdTrackFilter( const char *name = "TrackFilter", const char *trackCuts = "Hybrid_LHC11h", const char *taskName = "AliEmcalEsdTrackFilterTask" ) { enum CutsType { kHybrid = 0, kTpcOnly = 1 }; enum DataSet { kLHC10h = 0, kLHC11a = 1, kLHC11c = 3, kLHC11d = 3, kLHC11h = 3 }; CutsType cutsType = kHybrid; DataSet dataSet = kLHC11h; TString cutsLabel("hybrid tracks"); TString dataSetLabel("LHC11h"); TString strTrackCuts(trackCuts); strTrackCuts.ToLower(); if (strTrackCuts.Contains("hybrid")) { cutsType = kHybrid; } else if (strTrackCuts.Contains("tpconly")) { cutsType = kTpcOnly; cutsLabel = "TPC only constrained tracks"; } else { ::Warning("AddTaskEmcalEsdTpcTrack", "Cuts type not recognized, will assume Hybrid"); } if (strTrackCuts.Contains("lhc10h")) { dataSet = kLHC10h; dataSetLabel = "LHC10h"; } else if (strTrackCuts.Contains("lhc11a") || strTrackCuts.Contains("lhc12a15a")) { dataSet = kLHC11a; dataSetLabel = "LHC11a"; } else if (strTrackCuts.Contains("lhc10e") || strTrackCuts.Contains("lhc10d") || strTrackCuts.Contains("lhc10e20") || strTrackCuts.Contains("lhc10f6a") || strTrackCuts.Contains("lhc11a1a") || strTrackCuts.Contains("lhc11a1b") || strTrackCuts.Contains("lhc11a1c") || strTrackCuts.Contains("lhc11a1d") || strTrackCuts.Contains("lhc11a1e") || strTrackCuts.Contains("lhc11a1f") || strTrackCuts.Contains("lhc11a1g") || strTrackCuts.Contains("lhc11a1h") || strTrackCuts.Contains("lhc11a1i") || strTrackCuts.Contains("lhc11a1j")) { dataSet = kLHC11a; dataSetLabel = "LHC10e"; } else if (strTrackCuts.Contains("lhc11c")) { dataSet = kLHC11c; dataSetLabel = "LHC11c"; } else if (strTrackCuts.Contains("lhc11d")) { dataSet = kLHC11d; dataSetLabel = "LHC11d"; } else if (strTrackCuts.Contains("lhc11h") || strTrackCuts.Contains("lhc12a15e")) { dataSet = kLHC11h; dataSetLabel = "LHC11h"; } else if (strTrackCuts.Contains("lhc12g")) { dataSet = kLHC11h; dataSetLabel = "LHC12g"; } else if (strTrackCuts.Contains("lhc12")) { dataSet = kLHC11h; dataSetLabel = "LHC12"; } else if (strTrackCuts.Contains("lhc13b")) { dataSet = kLHC11h; dataSetLabel = "LHC13b"; } else if (strTrackCuts.Contains("lhc13c")) { dataSet = kLHC11h; dataSetLabel = "LHC13c"; } else if (strTrackCuts.Contains("lhc13d")) { dataSet = kLHC11h; dataSetLabel = "LHC13d"; } else if (strTrackCuts.Contains("lhc13e")) { dataSet = kLHC11h; dataSetLabel = "LHC13e"; } else if (strTrackCuts.Contains("lhc13f")) { dataSet = kLHC11h; dataSetLabel = "LHC13f"; } else if (strTrackCuts.Contains("lhc13g")) { dataSet = kLHC11h; dataSetLabel = "LHC13g"; } else if (strTrackCuts.Contains("lhc12a15f")) { dataSet = kLHC11h; dataSetLabel = "LHC12a15f"; } else if (strTrackCuts.Contains("lhc13b4")) { dataSet = kLHC11h; dataSetLabel = "LHC13b4"; } else if (strTrackCuts.Contains("lhc12a15g")) { dataSet = kLHC11d; dataSetLabel = "LHC12a15g"; } else if (strTrackCuts.Contains("lhc12f2a")) { dataSet = kLHC11d; dataSetLabel = "LHC12f2a"; } else if (strTrackCuts.Contains("lhc12a17")) { dataSet = kLHC11h; dataSetLabel = "LHC12a17"; } else if (strTrackCuts.Contains("lhc14a1")) { dataSet = kLHC11h; dataSetLabel = "LHC14a1"; } else { ::Warning("AddTaskEmcalEsdTpcTrack", "Dataset not recognized, will assume LHC11h"); } // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEmcalEsdTpcTrack", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== AliVEventHandler *evhand = mgr->GetInputEventHandler(); if (!evhand) { ::Error("AddTaskEmcalEsdTpcTrack", "This task requires an input event handler"); return NULL; } if (!evhand->InheritsFrom("AliESDInputHandler")) { ::Info("AddTaskEmcalEsdTpcTrack", "This task is only needed for ESD analysis. No task added."); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- AliEmcalEsdTrackFilterTask *eTask = new AliEmcalEsdTrackFilterTask(taskName); // default is no cut if ((dataSet == kLHC11c && cutsType == kHybrid) || (dataSet == kLHC11d && cutsType == kHybrid) || (dataSet == kLHC11h && cutsType == kHybrid)) { /* hybrid track cuts*/ AliESDtrackCuts *cutsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(10001008); //1000 adds SPD any requirement eTask->SetTrackCuts(cutsp); AliESDtrackCuts *hybsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(10041008); //1004 removes ITSrefit requirement from standard set hybsp->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kOff); eTask->SetHybridTrackCuts(hybsp); eTask->SetIncludeNoITS(kFALSE); } else if ((dataSet == kLHC10h && cutsType == kHybrid) || (dataSet == kLHC11a && cutsType == kHybrid)) { /* hybrid track cuts*/ AliESDtrackCuts *cutsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(10001006); //1000 adds SPD any requirement eTask->SetTrackCuts(cutsp); AliESDtrackCuts *hybsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(10041006); //1004 removes ITSrefit requirement from standard set hybsp->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kOff); eTask->SetHybridTrackCuts(hybsp); eTask->SetIncludeNoITS(kTRUE); } else if (dataSet == kLHC11h && cutsType == kTpcOnly) { /* TPC-only constrained track cuts*/ AliESDtrackCuts *cutsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(2001); //TPC-only loose track cuts eTask->SetTrackCuts(cutsp); eTask->SetHybridTrackCuts(0); } else { ::Error("AddTaskEmcalEsdTrackFilter","Track cuts type / period not recognized! Undefined beahviour will follow!"); } eTask->SetTracksName(name); std::cout << " *** Track selector task configured to select " << cutsLabel << " in dataset "<< dataSetLabel << " *** " << std::endl; //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(eTask); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer(); mgr->ConnectInput(eTask, 0, cinput1); return eTask; } <commit_msg>Add LHC10bcde periods to AddTaskEmcalEsdTrackFilter.C<commit_after>AliEmcalEsdTrackFilterTask* AddTaskEmcalEsdTrackFilter( const char *name = "TrackFilter", const char *trackCuts = "Hybrid_LHC11h", const char *taskName = "AliEmcalEsdTrackFilterTask" ) { enum CutsType { kHybrid = 0, kTpcOnly = 1 }; enum DataSet { kLHC10bcde = 0, kLHC10h = 0, kLHC11a = 1, kLHC11c = 3, kLHC11d = 3, kLHC11h = 3 }; CutsType cutsType = kHybrid; DataSet dataSet = kLHC11h; TString cutsLabel("hybrid tracks"); TString dataSetLabel("LHC11h"); TString strTrackCuts(trackCuts); strTrackCuts.ToLower(); if (strTrackCuts.Contains("hybrid")) { cutsType = kHybrid; } else if (strTrackCuts.Contains("tpconly")) { cutsType = kTpcOnly; cutsLabel = "TPC only constrained tracks"; } else { ::Warning("AddTaskEmcalEsdTrackFilter", "Cuts type not recognized, will assume Hybrid"); } if (strTrackCuts.Contains("lhc10h")) { dataSet = kLHC10h; dataSetLabel = "LHC10h"; } else if (strTrackCuts.Contains("lhc10b") || strTrackCuts.Contains("lhc10c") || strTrackCuts.Contains("lhc10d") || strTrackCuts.Contains("lhc10e")) { dataSet = kLHC10bcde; dataSetLabel = "LHC10bcde"; } else if (strTrackCuts.Contains("lhc11a") || strTrackCuts.Contains("lhc12a15a")) { dataSet = kLHC11a; dataSetLabel = "LHC11a"; } else if (strTrackCuts.Contains("lhc11a1a") || strTrackCuts.Contains("lhc11a1b") || strTrackCuts.Contains("lhc11a1c") || strTrackCuts.Contains("lhc11a1d") || strTrackCuts.Contains("lhc11a1e") || strTrackCuts.Contains("lhc11a1f") || strTrackCuts.Contains("lhc11a1g") || strTrackCuts.Contains("lhc11a1h") || strTrackCuts.Contains("lhc11a1i") || strTrackCuts.Contains("lhc11a1j")) { dataSet = kLHC11a; dataSetLabel = "LHC11a"; } else if (strTrackCuts.Contains("lhc11c")) { dataSet = kLHC11c; dataSetLabel = "LHC11c"; } else if (strTrackCuts.Contains("lhc11d")) { dataSet = kLHC11d; dataSetLabel = "LHC11d"; } else if (strTrackCuts.Contains("lhc11h") || strTrackCuts.Contains("lhc12a15e")) { dataSet = kLHC11h; dataSetLabel = "LHC11h"; } else if (strTrackCuts.Contains("lhc12g")) { dataSet = kLHC11h; dataSetLabel = "LHC12g"; } else if (strTrackCuts.Contains("lhc12")) { dataSet = kLHC11h; dataSetLabel = "LHC12"; } else if (strTrackCuts.Contains("lhc13b")) { dataSet = kLHC11h; dataSetLabel = "LHC13b"; } else if (strTrackCuts.Contains("lhc13c")) { dataSet = kLHC11h; dataSetLabel = "LHC13c"; } else if (strTrackCuts.Contains("lhc13d")) { dataSet = kLHC11h; dataSetLabel = "LHC13d"; } else if (strTrackCuts.Contains("lhc13e")) { dataSet = kLHC11h; dataSetLabel = "LHC13e"; } else if (strTrackCuts.Contains("lhc13f")) { dataSet = kLHC11h; dataSetLabel = "LHC13f"; } else if (strTrackCuts.Contains("lhc13g")) { dataSet = kLHC11h; dataSetLabel = "LHC13g"; } else if (strTrackCuts.Contains("lhc12a15f")) { dataSet = kLHC11h; dataSetLabel = "LHC12a15f"; } else if (strTrackCuts.Contains("lhc13b4")) { dataSet = kLHC11h; dataSetLabel = "LHC13b4"; } else if (strTrackCuts.Contains("lhc12a15g")) { dataSet = kLHC11d; dataSetLabel = "LHC12a15g"; } else if (strTrackCuts.Contains("lhc12f2a")) { dataSet = kLHC11d; dataSetLabel = "LHC12f2a"; } else if (strTrackCuts.Contains("lhc12a17")) { dataSet = kLHC11h; dataSetLabel = "LHC12a17"; } else if (strTrackCuts.Contains("lhc14a1")) { dataSet = kLHC11h; dataSetLabel = "LHC14a1"; } else { ::Warning("AddTaskEmcalEsdTrackFilter", "Dataset not recognized, will assume LHC11h"); } // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEmcalEsdTrackFilter", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== AliVEventHandler *evhand = mgr->GetInputEventHandler(); if (!evhand) { ::Error("AddTaskEmcalEsdTrackFilter", "This task requires an input event handler"); return NULL; } if (!evhand->InheritsFrom("AliESDInputHandler")) { ::Info("AddTaskEmcalEsdTrackFilter", "This task is only needed for ESD analysis. No task added."); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- AliEmcalEsdTrackFilterTask *eTask = new AliEmcalEsdTrackFilterTask(taskName); // default is no cut if ((dataSet == kLHC11c && cutsType == kHybrid) || (dataSet == kLHC11d && cutsType == kHybrid) || (dataSet == kLHC11h && cutsType == kHybrid)) { /* hybrid track cuts*/ AliESDtrackCuts *cutsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(10001008); //1000 adds SPD any requirement eTask->SetTrackCuts(cutsp); AliESDtrackCuts *hybsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(10041008); //1004 removes ITSrefit requirement from standard set hybsp->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kOff); eTask->SetHybridTrackCuts(hybsp); eTask->SetIncludeNoITS(kFALSE); } else if ((dataSet == kLHC10h && cutsType == kHybrid) || (dataSet == kLHC11a && cutsType == kHybrid)) { /* hybrid track cuts*/ AliESDtrackCuts *cutsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(10001006); //1000 adds SPD any requirement eTask->SetTrackCuts(cutsp); AliESDtrackCuts *hybsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(10041006); //1004 removes ITSrefit requirement from standard set hybsp->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kOff); eTask->SetHybridTrackCuts(hybsp); eTask->SetIncludeNoITS(kTRUE); } else if (dataSet == kLHC11h && cutsType == kTpcOnly) { /* TPC-only constrained track cuts*/ AliESDtrackCuts *cutsp = AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(2001); //TPC-only loose track cuts eTask->SetTrackCuts(cutsp); eTask->SetHybridTrackCuts(0); } else { ::Error("AddTaskEmcalEsdTrackFilter","Track cuts type / period not recognized! Undefined beahviour will follow!"); } eTask->SetTracksName(name); std::cout << " *** Track selector task configured to select " << cutsLabel << " in dataset "<< dataSetLabel << " *** " << std::endl; //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(eTask); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer(); mgr->ConnectInput(eTask, 0, cinput1); return eTask; } <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: sysinfo.C,v 1.14 2005/03/01 14:54:52 amoll Exp $ // #include <BALL/SYSTEM/sysinfo.h> #ifdef BALL_HAS_SYS_SYSINFO_H # include <sys/sysinfo.h> # include <BALL/SYSTEM/file.h> #else # ifdef BALL_PLATFORM_WINDOWS # define WIN32_LEAN_AND_MEAN # include <windows.h> # endif # ifdef BALL_OS_DARWIN # include <sys/sysctl.h> # endif #endif namespace BALL { namespace SysInfo { #ifdef BALL_HAS_SYS_SYSINFO_H LongIndex getAvailableMemory() { LongIndex mem = getFreeMemory(); return mem; } LongIndex getFreeMemory() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) { return result; } return info.freeram * info.mem_unit; } LongIndex getTotalMemory() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) { return result; } return info.totalram * info.mem_unit; } LongIndex getBufferedMemory() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) return result; return info.bufferram * info.mem_unit; } Time getUptime() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) return result; return info.uptime; } Index getNumberOfProcessors() { return get_nprocs(); } LongIndex getFreeSwapSpace() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) return result; return info.freeswap * info.mem_unit; } #else #ifdef BALL_PLATFORM_WINDOWS LongIndex getAvailableMemory() { return getFreeMemory(); } LongIndex getFreeMemory() { MEMORYSTATUSEX statex; GlobalMemoryStatusEx (&statex); return static_cast<LongIndex>(statex.ullAvailPhys); } LongIndex getTotalMemory() { MEMORYSTATUSEX statex; GlobalMemoryStatusEx (&statex); return static_cast<LongIndex>(statex.ullTotalPhys); } LongIndex getBufferedMemory() { return 0; } Time getUptime() { return -1; } Index getNumberOfProcessors() { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; } LongIndex getFreeSwapSpace() { MEMORYSTATUSEX statex; GlobalMemoryStatusEx (&statex); return (LongIndex) statex.ullAvailPageFile; } #else #ifdef BALL_OS_DARWIN LongIndex getAvailableMemory() { LongIndex mem = getFreeMemory(); return mem; } LongIndex getFreeMemory() { return -1; } LongIndex getTotalMemory() { return -1; } LongIndex getBufferedMemory() { return -1; } Time getUptime() { return -1; } Index getNumberOfProcessors() { int mib[2] = { CTL_HW, HW_NCPU }; int num_proc = 0; size_t len = sizeof(num_proc); sysctl(mib, 2, &num_proc, &len, NULL, 0); return (Index)num_proc; } LongIndex getFreeSwapSpace() { return -1; } #else // We have no idea how to retrieve that information on this // platform, so we just return -1 everywhere LongIndex getAvailableMemory() { return -1; } LongIndex getFreeMemory() { return -1; } LongIndex getTotalMemory() { return -1; } LongIndex getBufferedMemory() { return -1; } Time getUptime() { return -1; } Index getNumberOfProcessors() { return -1; } #endif #endif #endif } // namespace SysInfo } // namespace BALL <commit_msg>added support for solaris<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: sysinfo.C,v 1.15 2005/03/10 16:57:39 amoll Exp $ // #include <BALL/SYSTEM/sysinfo.h> // #define BALL_PLATFORM_SOLARIS #ifdef BALL_PLATFORM_SOLARIS # undef BALL_HAS_SYS_SYSINFO_H # include <stdlib.h> # include <stdio.h> # include <kstat.h> # include <sys/sysinfo.h> # include <sys/stat.h> # include <sys/swap.h> # include <sys/param.h> # include <unistd.h> #endif #ifdef BALL_HAS_SYS_SYSINFO_H # include <sys/sysinfo.h> # include <BALL/SYSTEM/file.h> #else # ifdef BALL_PLATFORM_WINDOWS # define WIN32_LEAN_AND_MEAN # include <windows.h> # endif # ifdef BALL_OS_DARWIN # include <sys/sysctl.h> # endif #endif namespace BALL { namespace SysInfo { #ifdef BALL_HAS_SYS_SYSINFO_H LongIndex getAvailableMemory() { LongIndex mem = getFreeMemory(); return mem; } LongIndex getFreeMemory() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) { return result; } return info.freeram * info.mem_unit; } LongIndex getTotalMemory() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) { return result; } return info.totalram * info.mem_unit; } LongIndex getBufferedMemory() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) return result; return info.bufferram * info.mem_unit; } Time getUptime() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) return result; return info.uptime; } Index getNumberOfProcessors() { return get_nprocs(); } LongIndex getFreeSwapSpace() { struct sysinfo info; LongIndex result = sysinfo(&info); if (result == -1) return result; return info.freeswap * info.mem_unit; } #else #ifdef BALL_PLATFORM_WINDOWS LongIndex getAvailableMemory() { return getFreeMemory(); } LongIndex getFreeMemory() { MEMORYSTATUSEX statex; GlobalMemoryStatusEx (&statex); return static_cast<LongIndex>(statex.ullAvailPhys); } LongIndex getTotalMemory() { MEMORYSTATUSEX statex; GlobalMemoryStatusEx (&statex); return static_cast<LongIndex>(statex.ullTotalPhys); } LongIndex getBufferedMemory() { return 0; } Time getUptime() { return -1; } Index getNumberOfProcessors() { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; } LongIndex getFreeSwapSpace() { MEMORYSTATUSEX statex; GlobalMemoryStatusEx (&statex); return (LongIndex) statex.ullAvailPageFile; } #else #ifdef BALL_PLATFORM_SOLARIS LongIndex getFreeMemory() { return ((LongIndex)sysconf(_SC_AVPHYS_PAGES)) * sysconf(_SC_PAGE_SIZE); } Index getNumberOfProcessors() { return sysconf(_SC_NPROCESSORS_CONF); } LongIndex getTotalMemory() { return ((LongIndex)sysconf(_SC_PHYS_PAGES)) * sysconf(_SC_PAGE_SIZE); } LongIndex getAvailableMemory() { return getFreeMemory(); } LongIndex getFreeSwapSpace() { long pgsize_in_kbytes = sysconf(_SC_PAGE_SIZE) / 1024L; int swap_count=swapctl(SC_GETNSWP, NULL); if (swap_count == -1 || swap_count == 0) return swap_count; /* * Although it's not particularly clear in the documentation, you're * responsible for creating a variable length structure (ie. the * array is within the struct rather than being pointed to * by the struct). Also, it is necessary for you to allocate space * for the path strings (see /usr/include/sys/swap.h). */ swaptbl_t* st = (swaptbl_t*)malloc(sizeof(int) + swap_count * sizeof(struct swapent)); if (st == NULL) return -1; st->swt_n = swap_count; for (int i=0; i < swap_count; i++) { if ((st->swt_ent[i].ste_path = (char*)malloc(MAXPATHLEN)) == NULL) { return -1; } } swap_count = swapctl(SC_LIST, (void*)st); if (swap_count == -1) return -1; long swap_avail = 0; for (int i = 0; i < swap_count; i++) { swap_avail += st->swt_ent[i].ste_free * pgsize_in_kbytes; } delete st; return ((LongIndex)swap_avail) * 1024; } LongIndex getBufferedMemory() { return 0; } Time getUptime() { return -1; } #else #ifdef BALL_OS_DARWIN LongIndex getAvailableMemory() { return getFreeMemory(); } LongIndex getFreeMemory() { return -1; } LongIndex getTotalMemory() { return -1; } LongIndex getBufferedMemory() { return -1; } Time getUptime() { return -1; } Index getNumberOfProcessors() { int mib[2] = { CTL_HW, HW_NCPU }; int num_proc = 0; size_t len = sizeof(num_proc); sysctl(mib, 2, &num_proc, &len, NULL, 0); return (Index)num_proc; } LongIndex getFreeSwapSpace() { return -1; } #else // We have no idea how to retrieve that information on this // platform, so we just return -1 everywhere LongIndex getAvailableMemory() { return -1; } LongIndex getFreeMemory() { return -1; } LongIndex getTotalMemory() { return -1; } LongIndex getBufferedMemory() { return -1; } Time getUptime() { return -1; } Index getNumberOfProcessors() { return -1; } #endif #endif #endif #endif } // namespace SysInfo } // namespace BALL <|endoftext|>
<commit_before>// $Id: File_test.C,v 1.9 2000/10/19 20:00:45 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/SYSTEM/file.h> #include <sys/types.h> #include <sys/stat.h> /////////////////////////// START_TEST(class_name, "$Id: File_test.C,v 1.9 2000/10/19 20:00:45 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; using namespace std; File* f1; CHECK(File()) f1 = new File(); TEST_NOT_EQUAL(f1, 0) RESULT CHECK(~File()) delete f1; RESULT CHECK(File::OpenMode) TEST_EQUAL(File::IN, std::ios::in) TEST_EQUAL(File::APP, std::ios::app) TEST_EQUAL(File::OUT, std::ios::out) TEST_EQUAL(File::ATE, std::ios::ate) TEST_EQUAL(File::TRUNC, std::ios::trunc) TEST_EQUAL(File::BINARY, std::ios::binary) RESULT CHECK(File(const String& name, OpenMode open_mode = File::IN)) File f("data/File_test.txt"); TEST_EQUAL(f.getSize(), 100) TEST_EXCEPTION(Exception::FileNotFound, File f2("")) TEST_EXCEPTION(Exception::FileNotFound, File f2("sdffsdf")) RESULT File f("data/File_test.txt"); CHECK(File(const File& file)) File f1(f); TEST_EQUAL(f1 == f, true) File f2; TEST_EXCEPTION(Exception::FileNotFound, File f3(f2)) RESULT CHECK(close()) TEST_EQUAL(f.getSize(), 100) f.close(); TEST_EQUAL(f.isClosed(), true) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(open(const String& name, OpenMode open_mode = File::IN)) f.open("data/File_test.txt"); TEST_EQUAL(f.isOpen(), true) TEST_EQUAL(f.getSize(), 100) File f1(f); TEST_EXCEPTION(Exception::FileNotFound, f1.open("")) RESULT CHECK(reopen()) f.close(); f.reopen(); f.reopen(); TEST_EQUAL(f.isOpen(), true) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(getName()) TEST_EQUAL(f.getName(), "data/File_test.txt") TEST_EQUAL(f.getSize(), 100) RESULT CHECK(getSize()) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(static getSize(String filename)) TEST_EQUAL(f.getSize("data/File_test.txt"), 100) TEST_EXCEPTION(Exception::FileNotFound, f.getSize("XXX")) RESULT CHECK(int getOpenMode() const) TEST_EQUAL(f.getOpenMode(), File::IN) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(static Type getType(String name, bool trace_link)) TEST_EQUAL(f.getType("data/File_test.txt", false), 4) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(Type getType(bool trace_link) const;) TEST_EQUAL(f.getType(false), 4) TEST_EQUAL(f.getType(true), 4) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(std::fstream& getFileStream();) // fstream fs; // FILE file; // file = f.getFileStream(); //!!! TEST_EQUAL(f.getSize(), 100) RESULT CHECK(copy(String source_name, String destination_name, Size buffer_size = 4096)) TEST_EQUAL(f.copy("data/File_test.txt", "data/File_test.txt"), false) TEST_EQUAL(f.copy("", "data/File_test.txt"), false) TEST_EQUAL(f.copy("data/File_test.txt", ""), false) TEST_EQUAL(f.copy("", ""), false) TEST_EQUAL(f.copy("ZZZZZZZZZZ", "XXX"), false) TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true) TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true) TEST_EQUAL(f.getSize(), 100) TEST_EQUAL(f.getSize("XXX"), 100) f.remove("XXX"); TEST_EQUAL(f.copy("", "X"), false) TEST_EQUAL(f.copy("data/File_test.txt", ""), false) RESULT CHECK(copyTo(const String& destination_name, Size buffer_size = 4096)) TEST_EQUAL(f.copyTo("data/File_test.txt"), false) TEST_EQUAL(f.copyTo(""), false) TEST_EQUAL(f.copyTo("XXX"), true) TEST_EQUAL(f.copyTo("XXX"), true) TEST_EQUAL(f.getSize(), 100) TEST_EQUAL(f.getSize("XXX"), 100) f.remove("XXX"); TEST_EQUAL(f.copyTo(""), false) RESULT CHECK(move(const String& source_name, const String& destination_name)) TEST_EQUAL(f.copyTo("XXX"), true) TEST_EQUAL(f.copyTo("YYY"), true) TEST_EQUAL(f.move("XXX", "XXX"), false) TEST_EQUAL(f.move("", "XXX"), false) TEST_EQUAL(f.move("XXX", ""), false) TEST_EQUAL(f.move("XXX", "YYY"), true) TEST_EQUAL(f.isAccessible("XXX"), false) TEST_EQUAL(f.getSize("YYY"), 100) f.copyTo("XXX"); TEST_EQUAL(f.move("XXX", "YYY"), true) TEST_EQUAL(f.getSize(), 100) TEST_EQUAL(f.move("YYY", ""), false) TEST_EQUAL(f.move("", "XXX"), false) f.remove("XXX"); f.remove("YYY"); RESULT CHECK(moveTo(const String& destination_name)) f.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.moveTo("XXX"), false) TEST_EQUAL(f1.moveTo(""), false) TEST_EQUAL(f1.moveTo("YYY"), true) TEST_EQUAL(f1.isAccessible(), true) TEST_EQUAL(f1.moveTo("YYY"), false) TEST_EQUAL(f1.isAccessible(), true) TEST_EQUAL(f.getSize("YYY"), 100) TEST_EQUAL(f1.moveTo(""), false) RESULT CHECK(remove(String name)) f.copyTo("XXX"); TEST_EQUAL(f.remove("XXX"), true) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(remove()) f.copyTo("XXX"); File f1 = File("XXX"); f1.remove(); TEST_EQUAL(f1.isAccessible(), false) RESULT CHECK(rename(String old_path, String new_path)) f.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.rename("XXX", "XXX"), true) TEST_EQUAL(f1.rename("XXX", "YYY"), true) TEST_EQUAL(f1.isAccessible("XXX"), false) TEST_EQUAL(f1.isAccessible("YYY"), true) f1.remove(); TEST_EQUAL(f.getSize(), 100) f.remove("YYY"); TEST_EXCEPTION(Exception::FileNotFound, f1.rename("", "XXX")) TEST_EXCEPTION(Exception::FileNotFound, f1.rename("XXX", "")) RESULT CHECK(renameTo(const String& new_path)) f.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.renameTo("XXX"), true) TEST_EQUAL(f1.isAccessible("XXX"), true) TEST_EQUAL(f1.renameTo("YYY"), true) TEST_EQUAL(f1.isAccessible("XXX"), false) TEST_EQUAL(f1.isAccessible("YYY"), true) f1.remove(); RESULT CHECK(truncate(String path, Size size = 0)) f.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.truncate("XXX", 50), true) TEST_EQUAL(f1.getSize(), 50) TEST_EQUAL(f1.truncate("XXX", 0), true) TEST_EQUAL(f1.getSize(), 0) f1.remove(); TEST_EXCEPTION(Exception::FileNotFound, f1.truncate("", 50)) RESULT CHECK(truncate(Size size = 0)) f.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.truncate(50), true) TEST_EQUAL(f1.getSize(), 50) TEST_EQUAL(f1.truncate(0), true) TEST_EQUAL(f1.getSize(), 0) f1.remove(); RESULT CHECK(createTemporaryFilename(String& temporary)) String s; TEST_EQUAL(f.createTemporaryFilename(s), true) TEST_NOT_EQUAL(s, "") RESULT CHECK(operator == (const File& file)) File f1(f); TEST_EQUAL(f1 == f, true) f.copyTo("XXX"); File f2("XXX"); TEST_EQUAL(f2 == f, false) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(operator != (const File& file)) File f1(f); TEST_EQUAL(f1 != f, false) f.copyTo("XXX"); File f2("XXX"); TEST_EQUAL(f2 != f, true) TEST_EQUAL(f.getSize(), 100) RESULT CHECK(isOpen()) f.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.isOpen(), true) f1.close(); TEST_EQUAL(f1.isOpen(), false) RESULT CHECK(isClosed()) f.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.isClosed(), false) f1.close(); TEST_EQUAL(f1.isClosed(), true) RESULT CHECK(isAccessible(String name)) TEST_EQUAL(f.isAccessible("data/File_test.txt"), true) f.remove("XXX"); TEST_EQUAL(f.isAccessible("XXX"), false) RESULT CHECK(isAccessible()) TEST_EQUAL(f.isAccessible(), true) f.copyTo("XXX"); File f1("XXX"); f1.remove(); TEST_EQUAL(f1.isAccessible(), false) RESULT CHECK(isCanonized()) File f1("../TEST/data/File_test.txt"); TEST_EQUAL(f1.isValid(), true) TEST_EQUAL(f1.isCanonized(), true) File f2("data//File_test.txt"); TEST_EQUAL(f2.isValid(), true) TEST_EQUAL(f2.isCanonized(), true) File f4("data/../data/File_test.txt"); TEST_EQUAL(f4.isValid(), true) TEST_EQUAL(f4.isCanonized(), true) /* File f5("./data/File_test.txt"); TEST_EQUAL(f5.isValid(), true) TEST_EQUAL(f5.isCanonized(), true) File f6("data/File_test.txt"); TEST_EQUAL(f6.isValid(), true) TEST_EQUAL(f6.isCanonized(), true) File f7("~/File_test.txt"); TEST_EQUAL(f7.isCanonized(), true)*/ RESULT CHECK(isReadable(String name)) TEST_EQUAL(f.isReadable("File_test.C"), true) RESULT CHECK(isReadable()) File f2("File_test.C"); TEST_EQUAL(f2.isReadable(), true) RESULT CHECK(isWritable(String name)) TEST_EQUAL(f.isWritable("File_test.C"), true) RESULT CHECK(isWritable()) File f2("File_test.C"); TEST_EQUAL(f2.isWritable(), true) RESULT CHECK(isExecutable(String name)) TEST_EQUAL(f.isExecutable(BALL_PATH "/source/configure"), true) TEST_EQUAL(f.isExecutable("File_test.C"), false) RESULT CHECK(isExecutable()) File f1(BALL_PATH "/source/configure"); TEST_EQUAL(f1.isExecutable(), true) File f2("File_test.C"); TEST_EQUAL(f2.isExecutable(), false) RESULT CHECK(isValid()) TEST_EQUAL(f.isValid(), true) File f1; TEST_EXCEPTION(Exception::FileNotFound, f1 = File("XXX")) TEST_EQUAL(f1.isValid(), true) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed many tests after changes in file<commit_after>// $Id: File_test.C,v 1.10 2000/10/20 15:00:11 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/SYSTEM/file.h> #include <sys/types.h> #include <sys/stat.h> /////////////////////////// START_TEST(class_name, "$Id: File_test.C,v 1.10 2000/10/20 15:00:11 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; using namespace std; File* f1; CHECK(File()) f1 = new File(); TEST_NOT_EQUAL(f1, 0) RESULT CHECK(~File()) delete f1; RESULT CHECK(File::OpenMode) TEST_EQUAL(File::IN, std::ios::in) TEST_EQUAL(File::APP, std::ios::app) TEST_EQUAL(File::OUT, std::ios::out) TEST_EQUAL(File::ATE, std::ios::ate) TEST_EQUAL(File::TRUNC, std::ios::trunc) TEST_EQUAL(File::BINARY, std::ios::binary) RESULT CHECK(File(const String& name, OpenMode open_mode = File::IN)) File f("data/File_test.txt"); TEST_EQUAL(f.getSize(), 100) TEST_EXCEPTION(Exception::FileNotFound, File f2("")) TEST_EXCEPTION(Exception::FileNotFound, File f2("sdffsdf")) RESULT File file("data/File_test.txt"); const File& f = file; CHECK(File(const File& file)) File f1(f); TEST_EQUAL(f1 == f, true) File f2; TEST_EXCEPTION(Exception::FileNotFound, File f3(f2)) RESULT CHECK(close()) TEST_EQUAL(file.getSize(), 100) file.close(); TEST_EQUAL(f.isClosed(), true) TEST_EQUAL(file.getSize(), 100) RESULT CHECK(open(const String& name, OpenMode open_mode = File::IN)) file.open("data/File_test.txt"); TEST_EQUAL(f.isOpen(), true) TEST_EQUAL(file.getSize(), 100) File f1(f); TEST_EXCEPTION(Exception::FileNotFound, f1.open("")) RESULT CHECK(reopen()) file.close(); file.reopen(); file.reopen(); TEST_EQUAL(f.isOpen(), true) TEST_EQUAL(file.getSize(), 100) RESULT CHECK(getName()) TEST_EQUAL(f.getName(), "data/File_test.txt") TEST_EQUAL(file.getSize(), 100) RESULT CHECK(getSize()) TEST_EQUAL(file.getSize(), 100) RESULT CHECK(static getSize(String filename)) TEST_EQUAL(f.getSize("data/File_test.txt"), 100) TEST_EXCEPTION(Exception::FileNotFound, f.getSize("XXX")) RESULT CHECK(int getOpenMode() const) TEST_EQUAL(f.getOpenMode(), File::IN) TEST_EQUAL(file.getSize(), 100) RESULT CHECK(static Type getType(String name, bool trace_link)) TEST_EQUAL(f.getType("data/File_test.txt", false), 4) TEST_EQUAL(file.getSize(), 100) RESULT CHECK(Type getType(bool trace_link) const;) TEST_EQUAL(f.getType(false), 4) TEST_EQUAL(f.getType(true), 4) TEST_EQUAL(file.getSize(), 100) RESULT CHECK(copy(String source_name, String destination_name, Size buffer_size = 4096)) TEST_EQUAL(file.copy("data/File_test.txt", "data/File_test.txt"), false) TEST_EQUAL(file.copy("", "data/File_test.txt"), false) TEST_EQUAL(file.copy("data/File_test.txt", ""), false) TEST_EQUAL(file.copy("", ""), false) TEST_EXCEPTION(Exception::FileNotFound, file.copy("ZZZZZZZZZZ", "XXX")) TEST_EQUAL(file.copy("data/File_test.txt", "XXX"), true) TEST_EQUAL(file.copy("data/File_test.txt", "XXX"), true) TEST_EQUAL(file.getSize(), 100) TEST_EQUAL(f.getSize("XXX"), 100) f.remove("XXX"); TEST_EQUAL(file.copy("", "X"), false) TEST_EQUAL(file.copy("data/File_test.txt", ""), false) RESULT CHECK(copyTo(const String& destination_name, Size buffer_size = 4096)) TEST_EQUAL(file.copyTo("data/File_test.txt"), false) TEST_EQUAL(file.copyTo(""), false) TEST_EQUAL(file.copyTo("XXX"), true) TEST_EQUAL(file.copyTo("XXX"), true) TEST_EQUAL(file.getSize(), 100) TEST_EQUAL(f.getSize("XXX"), 100) f.remove("XXX"); TEST_EQUAL(file.copyTo(""), false) RESULT CHECK(move(const String& source_name, const String& destination_name)) TEST_EQUAL(file.copyTo("XXX"), true) TEST_EQUAL(file.copyTo("YYY"), true) TEST_EQUAL(f.move("XXX", "XXX"), false) TEST_EQUAL(f.move("", "XXX"), false) TEST_EQUAL(f.move("XXX", ""), false) TEST_EQUAL(f.move("XXX", "YYY"), true) TEST_EQUAL(f.isAccessible("XXX"), false) TEST_EQUAL(f.getSize("YYY"), 100) file.copyTo("XXX"); TEST_EQUAL(f.move("XXX", "YYY"), true) TEST_EQUAL(file.getSize(), 100) TEST_EQUAL(f.move("YYY", ""), false) TEST_EQUAL(f.move("", "XXX"), false) f.remove("XXX"); f.remove("YYY"); TEST_EXCEPTION(Exception::FileNotFound, f.move("ZZZZZZZZZZ", "XXX")) RESULT CHECK(moveTo(const String& destination_name)) file.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.moveTo("XXX"), false) TEST_EQUAL(f1.moveTo(""), false) TEST_EQUAL(f1.moveTo("YYY"), true) TEST_EQUAL(f1.isAccessible(), true) TEST_EQUAL(f1.moveTo("YYY"), false) TEST_EQUAL(f1.isAccessible(), true) TEST_EQUAL(f.getSize("YYY"), 100) TEST_EQUAL(f1.moveTo(""), false) TEST_EQUAL(f.remove("YYY"), true) TEST_EXCEPTION(Exception::FileNotFound, f1.moveTo("XXX")) RESULT CHECK(remove(String name)) file.copyTo("XXX"); TEST_EQUAL(f.remove("XXX"), true) TEST_EQUAL(file.getSize(), 100) TEST_EQUAL(f.remove("XXX"), false) RESULT CHECK(remove()) file.copyTo("XXX"); File f1 = File("XXX"); TEST_EQUAL(f1.remove(), true) TEST_EQUAL(f1.remove(), false) TEST_EQUAL(f1.isAccessible(), false) RESULT CHECK(rename(String old_path, String new_path)) file.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.rename("XXX", "XXX"), true) TEST_EQUAL(f1.rename("XXX", "YYY"), true) TEST_EQUAL(f1.isAccessible("XXX"), false) TEST_EQUAL(f1.isAccessible("YYY"), true) f1.remove(); TEST_EQUAL(file.getSize(), 100) f.remove("YYY"); TEST_EXCEPTION(Exception::FileNotFound, f1.rename("", "XXX")) TEST_EXCEPTION(Exception::FileNotFound, f1.rename("XXX", "")) RESULT CHECK(renameTo(const String& new_path)) file.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.renameTo("XXX"), true) TEST_EQUAL(f1.isAccessible("XXX"), true) TEST_EQUAL(f1.renameTo("YYY"), true) TEST_EQUAL(f1.isAccessible("XXX"), false) TEST_EQUAL(f1.isAccessible("YYY"), true) f1.remove(); RESULT CHECK(truncate(String path, Size size = 0)) file.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.truncate("XXX", 50), true) TEST_EQUAL(f1.getSize(), 50) TEST_EQUAL(f1.truncate("XXX", 0), true) TEST_EQUAL(f1.getSize(), 0) f1.remove(); TEST_EXCEPTION(Exception::FileNotFound, f1.truncate("", 50)) RESULT CHECK(truncate(Size size = 0)) file.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.truncate(50), true) TEST_EQUAL(f1.getSize(), 50) TEST_EQUAL(f1.truncate(0), true) TEST_EQUAL(f1.getSize(), 0) f1.remove(); RESULT CHECK(createTemporaryFilename(String& temporary)) String s; TEST_EQUAL(f.createTemporaryFilename(s), true) TEST_NOT_EQUAL(s, "") RESULT CHECK(operator == (const File& file)) File f1(f); TEST_EQUAL(f1 == f, true) file.copyTo("XXX"); File f2("XXX"); TEST_EQUAL(f2 == f, false) TEST_EQUAL(file.getSize(), 100) RESULT CHECK(operator != (const File& file)) File f1(f); TEST_EQUAL(f1 != f, false) file.copyTo("XXX"); File f2("XXX"); TEST_EQUAL(f2 != f, true) TEST_EQUAL(file.getSize(), 100) RESULT CHECK(isOpen()) file.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.isOpen(), true) f1.close(); TEST_EQUAL(f1.isOpen(), false) RESULT CHECK(isClosed()) file.copyTo("XXX"); File f1("XXX"); TEST_EQUAL(f1.isClosed(), false) f1.close(); TEST_EQUAL(f1.isClosed(), true) RESULT CHECK(isAccessible(String name)) TEST_EQUAL(f.isAccessible("data/File_test.txt"), true) f.remove("XXX"); TEST_EQUAL(f.isAccessible("XXX"), false) RESULT CHECK(isAccessible()) TEST_EQUAL(f.isAccessible(), true) file.copyTo("XXX"); File f1("XXX"); f1.remove(); TEST_EQUAL(f1.isAccessible(), false) RESULT CHECK(isCanonized()) File f1("../TEST/data/File_test.txt"); TEST_EQUAL(f1.isValid(), true) TEST_EQUAL(f1.isCanonized(), true) File f2("data//File_test.txt"); TEST_EQUAL(f2.isValid(), true) TEST_EQUAL(f2.isCanonized(), true) File f4("data/../data/File_test.txt"); TEST_EQUAL(f4.isValid(), true) TEST_EQUAL(f4.isCanonized(), true) /* File f5("./data/File_test.txt"); TEST_EQUAL(f5.isValid(), true) TEST_EQUAL(f5.isCanonized(), true) File f6("data/File_test.txt"); TEST_EQUAL(f6.isValid(), true) TEST_EQUAL(f6.isCanonized(), true) File f7("~/File_test.txt"); TEST_EQUAL(f7.isCanonized(), true)*/ RESULT CHECK(isReadable(String name)) TEST_EQUAL(f.isReadable("File_test.C"), true) RESULT CHECK(isReadable()) File f2("File_test.C"); TEST_EQUAL(f2.isReadable(), true) RESULT CHECK(isWritable(String name)) TEST_EQUAL(f.isWritable("File_test.C"), true) RESULT CHECK(isWritable()) File f2("File_test.C"); TEST_EQUAL(f2.isWritable(), true) RESULT CHECK(isExecutable(String name)) TEST_EQUAL(f.isExecutable(BALL_PATH "/source/configure"), true) TEST_EQUAL(f.isExecutable("File_test.C"), false) RESULT CHECK(isExecutable()) File f1(BALL_PATH "/source/configure"); TEST_EQUAL(f1.isExecutable(), true) File f2("File_test.C"); TEST_EQUAL(f2.isExecutable(), false) RESULT CHECK(isValid()) TEST_EQUAL(f.isValid(), true) File f1; TEST_EXCEPTION(Exception::FileNotFound, f1 = File("XXX")) TEST_EQUAL(f1.isValid(), true) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>// Fill out your copyright notice in the Description page of Project Settings. #include "SemLogPrivatePCH.h" #include "SLManager.h" #include "SLContactTriggerBox.h" // Set default values ASLContactTriggerBox::ASLContactTriggerBox() { // Create raster bCreateRaster = false; // Number of rows in the raster RasterNrRows = 1; // Number of columns in the raster RasterNrColumns = 1; // Raster visibility bRasterHiddenInGame = true; // Particle collision update frequency RasterUpdateRate = 1.0f; } // Destructor ASLContactTriggerBox::~ASLContactTriggerBox() { } // Called when the games starts or when spawned void ASLContactTriggerBox::BeginPlay() { Super::BeginPlay(); // Set the semantic events exporter for (TActorIterator<ASLManager> SLManagerItr(GetWorld()); SLManagerItr; ++SLManagerItr) { SemEventsExporter = SLManagerItr->GetEventsExporter(); break; } if (!Parent) { UE_LOG(SemLog, Error, TEXT(" !! SLContactTriggerBox: %s s parent is not set!"), *GetName()); } if (!SemEventsExporter) { UE_LOG(SemLog, Error, TEXT(" !! SLContactTriggerBox: %s s SemEventsExporter is not set!"), *GetName()); } // Check if parent and the semantic events exporter is set if (Parent && SemEventsExporter) { // Bind overlap events OnActorBeginOverlap.AddDynamic(this, &ASLContactTriggerBox::BeginSemanticContact); OnActorEndOverlap.AddDynamic(this, &ASLContactTriggerBox::EndSemanticContact); // Create raster if required if (bCreateRaster) { ASLContactTriggerBox::CreateRaster(); } } else { UE_LOG(SemLog, Error, TEXT(" !! SLContactTriggerBox: %s s parent, or the events exporter is not set!"), *GetName()); } } // Callback on start overlap, end the semantic contact void ASLContactTriggerBox::BeginSemanticContact( AActor* Self, AActor* OtherActor) { if (SemEventsExporter) { SemEventsExporter->BeginTouchingEvent( Parent, OtherActor, GetWorld()->GetTimeSeconds()); } } // Callback on end overlap, end the semantic contact void ASLContactTriggerBox::EndSemanticContact( AActor* Self, AActor* OtherActor) { if (SemEventsExporter) { SemEventsExporter->BeginTouchingEvent( Parent, OtherActor, GetWorld()->GetTimeSeconds()); } } // Create raster void ASLContactTriggerBox::CreateRaster() { // Get the bounding box of the parent const FBox ParentBB = Parent->GetComponentsBoundingBox(); const FVector ParentExtent = ParentBB.GetExtent(); const FVector ParentCenter = ParentBB.GetCenter(); const FVector RasterOrigin = ParentCenter - ParentExtent; // Trigger box extent size (radii size) const float TriggerBoxExtentX = ParentExtent.X / RasterNrRows; const float TriggerBoxExtentY = ParentExtent.Y / RasterNrColumns; // Set root component location at the top of parent RootComponent->SetWorldLocation(ParentCenter + FVector(0.f, 0.f, ParentExtent.Z)); // Trigger box initial offset FVector TriggerBoxOffset = FVector(TriggerBoxExtentX, TriggerBoxExtentY, 2 * ParentExtent.Z); // Create the trigger box rasters for (uint32 i = 1; i <= RasterNrRows; ++i) { for (uint32 j = 1; j <= RasterNrColumns; ++j) { const FString TBName = GetName() + "_M_" + FString::FromInt(i) + "_" + FString::FromInt(j); // Create trigger box component UBoxComponent* CurrTB = NewObject<UBoxComponent>(this, *TBName); //UBoxComponent::StaticClass()); // Attach to the root component CurrTB->SetupAttachment(RootComponent); // Set location CurrTB->SetWorldLocation(RasterOrigin + TriggerBoxOffset); // Set box size (radii size) CurrTB->InitBoxExtent(FVector(TriggerBoxExtentX, TriggerBoxExtentY, 0.5)); // Set visibility CurrTB->SetHiddenInGame(bRasterHiddenInGame); // Generate overlap events CurrTB->bGenerateOverlapEvents = true; // Count particle collisions //CurrTB->bFlexEnableParticleCounter = true; CurrTB->SetCollisionProfileName("Trigger"); // Register component CurrTB->RegisterComponent(); // Add box to array RasterTriggerBoxes.Add(CurrTB); // Update offset on the columns (Y axis) TriggerBoxOffset.Y += TriggerBoxExtentY * 2; } // Reset the Y offset TriggerBoxOffset.Y = TriggerBoxExtentY; // Update offset on the rows (X axis) TriggerBoxOffset.X += TriggerBoxExtentX * 2; } // Set visibility SetActorHiddenInGame(bRasterHiddenInGame); // Update collision checking with the given frequency //GetWorldTimerManager().SetTimer( // TimerHandle, this, &ASLContactTriggerBox::CheckParticleCount, RasterUpdateRate, true); } // Check particle collisions void ASLContactTriggerBox::CheckParticleCount() { //UE_LOG(LogTemp, Warning, TEXT(" **** < --- ")); //for (const auto TriggerBoxItr : RasterTriggerBoxes) //{ // if (TriggerBoxItr->FlexParticleCount > 0) // { // UE_LOG(LogTemp, Warning, TEXT(" **** TriggerBox: %s, FlexParticleCount: %i"), // *TriggerBoxItr->GetName(), TriggerBoxItr->FlexParticleCount); // } //} //UE_LOG(LogTemp, Warning, TEXT(" --- > **** ")); }<commit_msg>bug, at contact end event was calling begin event<commit_after>// Fill out your copyright notice in the Description page of Project Settings. #include "SemLogPrivatePCH.h" #include "SLManager.h" #include "SLContactTriggerBox.h" // Set default values ASLContactTriggerBox::ASLContactTriggerBox() { // Create raster bCreateRaster = false; // Number of rows in the raster RasterNrRows = 1; // Number of columns in the raster RasterNrColumns = 1; // Raster visibility bRasterHiddenInGame = true; // Particle collision update frequency RasterUpdateRate = 1.0f; } // Destructor ASLContactTriggerBox::~ASLContactTriggerBox() { } // Called when the games starts or when spawned void ASLContactTriggerBox::BeginPlay() { Super::BeginPlay(); // Set the semantic events exporter for (TActorIterator<ASLManager> SLManagerItr(GetWorld()); SLManagerItr; ++SLManagerItr) { SemEventsExporter = SLManagerItr->GetEventsExporter(); break; } if (!Parent) { UE_LOG(SemLog, Error, TEXT(" !! SLContactTriggerBox: %s s parent is not set!"), *GetName()); } if (!SemEventsExporter) { UE_LOG(SemLog, Error, TEXT(" !! SLContactTriggerBox: %s s SemEventsExporter is not set!"), *GetName()); } // Check if parent and the semantic events exporter is set if (Parent && SemEventsExporter) { // Bind overlap events OnActorBeginOverlap.AddDynamic(this, &ASLContactTriggerBox::BeginSemanticContact); OnActorEndOverlap.AddDynamic(this, &ASLContactTriggerBox::EndSemanticContact); // Create raster if required if (bCreateRaster) { ASLContactTriggerBox::CreateRaster(); } } else { UE_LOG(SemLog, Error, TEXT(" !! SLContactTriggerBox: %s s parent, or the events exporter is not set!"), *GetName()); } } // Callback on start overlap, end the semantic contact void ASLContactTriggerBox::BeginSemanticContact( AActor* Self, AActor* OtherActor) { if (SemEventsExporter) { SemEventsExporter->BeginTouchingEvent( Parent, OtherActor, GetWorld()->GetTimeSeconds()); } } // Callback on end overlap, end the semantic contact void ASLContactTriggerBox::EndSemanticContact( AActor* Self, AActor* OtherActor) { if (SemEventsExporter) { SemEventsExporter->EndTouchingEvent( Parent, OtherActor, GetWorld()->GetTimeSeconds()); } } // Create raster void ASLContactTriggerBox::CreateRaster() { // Get the bounding box of the parent const FBox ParentBB = Parent->GetComponentsBoundingBox(); const FVector ParentExtent = ParentBB.GetExtent(); const FVector ParentCenter = ParentBB.GetCenter(); const FVector RasterOrigin = ParentCenter - ParentExtent; // Trigger box extent size (radii size) const float TriggerBoxExtentX = ParentExtent.X / RasterNrRows; const float TriggerBoxExtentY = ParentExtent.Y / RasterNrColumns; // Set root component location at the top of parent RootComponent->SetWorldLocation(ParentCenter + FVector(0.f, 0.f, ParentExtent.Z)); // Trigger box initial offset FVector TriggerBoxOffset = FVector(TriggerBoxExtentX, TriggerBoxExtentY, 2 * ParentExtent.Z); // Create the trigger box rasters for (uint32 i = 1; i <= RasterNrRows; ++i) { for (uint32 j = 1; j <= RasterNrColumns; ++j) { const FString TBName = GetName() + "_M_" + FString::FromInt(i) + "_" + FString::FromInt(j); // Create trigger box component UBoxComponent* CurrTB = NewObject<UBoxComponent>(this, *TBName); //UBoxComponent::StaticClass()); // Attach to the root component CurrTB->SetupAttachment(RootComponent); // Set location CurrTB->SetWorldLocation(RasterOrigin + TriggerBoxOffset); // Set box size (radii size) CurrTB->InitBoxExtent(FVector(TriggerBoxExtentX, TriggerBoxExtentY, 0.5)); // Set visibility CurrTB->SetHiddenInGame(bRasterHiddenInGame); // Generate overlap events CurrTB->bGenerateOverlapEvents = true; // Count particle collisions //CurrTB->bFlexEnableParticleCounter = true; CurrTB->SetCollisionProfileName("Trigger"); // Register component CurrTB->RegisterComponent(); // Add box to array RasterTriggerBoxes.Add(CurrTB); // Update offset on the columns (Y axis) TriggerBoxOffset.Y += TriggerBoxExtentY * 2; } // Reset the Y offset TriggerBoxOffset.Y = TriggerBoxExtentY; // Update offset on the rows (X axis) TriggerBoxOffset.X += TriggerBoxExtentX * 2; } // Set visibility SetActorHiddenInGame(bRasterHiddenInGame); // Update collision checking with the given frequency //GetWorldTimerManager().SetTimer( // TimerHandle, this, &ASLContactTriggerBox::CheckParticleCount, RasterUpdateRate, true); } // Check particle collisions void ASLContactTriggerBox::CheckParticleCount() { //UE_LOG(LogTemp, Warning, TEXT(" **** < --- ")); //for (const auto TriggerBoxItr : RasterTriggerBoxes) //{ // if (TriggerBoxItr->FlexParticleCount > 0) // { // UE_LOG(LogTemp, Warning, TEXT(" **** TriggerBox: %s, FlexParticleCount: %i"), // *TriggerBoxItr->GetName(), TriggerBoxItr->FlexParticleCount); // } //} //UE_LOG(LogTemp, Warning, TEXT(" --- > **** ")); }<|endoftext|>
<commit_before>/* The GC superclass methods, used by both GCs. */ #include "object_utils.hpp" #include "gc/gc.hpp" #include "objectmemory.hpp" #include "gc/object_mark.hpp" #include "builtin/class.hpp" #include "builtin/tuple.hpp" #include "builtin/module.hpp" #include "builtin/symbol.hpp" #include "builtin/weakref.hpp" #include "builtin/compiledcode.hpp" #include "call_frame.hpp" #include "builtin/variable_scope.hpp" #include "builtin/constantscope.hpp" #include "builtin/block_environment.hpp" #include "capi/handle.hpp" #ifdef ENABLE_LLVM #include "llvm/state.hpp" #endif #include "instruments/tooling.hpp" #include "arguments.hpp" #include "object_watch.hpp" namespace rubinius { GCData::GCData(VM* state) : roots_(state->globals().roots) , handles_(state->shared.global_handles()) , cached_handles_(state->shared.cached_handles()) , global_cache_(state->shared.global_cache) , threads_(state->shared.threads()) , global_handle_locations_(state->shared.global_handle_locations()) , gc_token_(0) #ifdef ENABLE_LLVM , llvm_state_(LLVMState::get_if_set(state)) #endif {} GCData::GCData(VM* state, GCToken gct) : roots_(state->globals().roots) , handles_(state->shared.global_handles()) , cached_handles_(state->shared.cached_handles()) , global_cache_(state->shared.global_cache) , threads_(state->shared.threads()) , global_handle_locations_(state->shared.global_handle_locations()) , gc_token_(&gct) #ifdef ENABLE_LLVM , llvm_state_(LLVMState::get_if_set(state)) #endif {} GarbageCollector::GarbageCollector(ObjectMemory *om) :object_memory_(om), weak_refs_(NULL) { } VM* GarbageCollector::state() { return object_memory_->state(); } /** * Scans the specified Object +obj+ for references to other Objects, and * marks those Objects as reachable. Understands how to read the inside of * an Object and find all references located within. For each reference * found, it marks the object pointed to as live (which may trigger * movement of the object in a copying garbage collector), but does not * recursively scan into the referenced object (since such recursion could * be arbitrarily deep, depending on the object graph, and this could cause * the stack to blow up). * /param obj The Object to be scanned for references to other Objects. */ void GarbageCollector::scan_object(Object* obj) { Object* slot; #ifdef ENABLE_OBJECT_WATCH if(watched_p(obj)) { std::cout << "detected " << obj << " during scan_object.\n"; } #endif // Check and update an inflated header if(obj->inflated_header_p()) { obj->inflated_header()->reset_object(obj); } slot = saw_object(obj->klass()); if(slot) obj->klass(object_memory_, force_as<Class>(slot)); if(obj->ivars()->reference_p()) { slot = saw_object(obj->ivars()); if(slot) obj->ivars(object_memory_, slot); } // Handle Tuple directly, because it's so common if(Tuple* tup = try_as<Tuple>(obj)) { native_int size = tup->num_fields(); for(native_int i = 0; i < size; i++) { slot = tup->field[i]; if(slot->reference_p()) { slot = saw_object(slot); if(slot) { tup->field[i] = slot; object_memory_->write_barrier(tup, slot); } } } } else { TypeInfo* ti = object_memory_->type_info[obj->type_id()]; ObjectMark mark(this); ti->mark(obj, mark); } } /** * Removes a mature object from the remembered set, ensuring it will not keep * alive any young objects if no other live references to those objects exist. */ void GarbageCollector::delete_object(Object* obj) { if(obj->remembered_p()) { object_memory_->unremember_object(obj); } } void GarbageCollector::saw_variable_scope(CallFrame* call_frame, StackVariables* scope) { scope->self_ = mark_object(scope->self()); scope->block_ = mark_object(scope->block()); scope->module_ = (Module*)mark_object(scope->module()); int locals = call_frame->compiled_code->machine_code()->number_of_locals; for(int i = 0; i < locals; i++) { Object* local = scope->get_local(i); if(local->reference_p()) { scope->set_local(i, mark_object(local)); } } if(scope->last_match_ && scope->last_match_->reference_p()) { scope->last_match_ = mark_object(scope->last_match_); } VariableScope* parent = scope->parent(); if(parent) { scope->parent_ = (VariableScope*)mark_object(parent); } VariableScope* heap = scope->on_heap(); if(heap) { scope->on_heap_ = (VariableScope*)mark_object(heap); } } template <typename T> T displace(T ptr, AddressDisplacement* dis) { if(!dis) return ptr; return dis->displace(ptr); } /** * Walks the chain of objects accessible from the specified CallFrame. */ void GarbageCollector::walk_call_frame(CallFrame* top_call_frame, AddressDisplacement* offset) { CallFrame* call_frame = top_call_frame; while(call_frame) { call_frame = displace(call_frame, offset); // Skip synthetic, non CompiledCode frames if(!call_frame->compiled_code) { call_frame = call_frame->previous; continue; } if(call_frame->custom_constant_scope_p() && call_frame->constant_scope_ && call_frame->constant_scope_->reference_p()) { call_frame->constant_scope_ = (ConstantScope*)mark_object(call_frame->constant_scope_); } if(call_frame->compiled_code && call_frame->compiled_code->reference_p()) { call_frame->compiled_code = (CompiledCode*)mark_object(call_frame->compiled_code); } if(call_frame->compiled_code && call_frame->stk) { native_int stack_size = call_frame->compiled_code->stack_size()->to_native(); for(native_int i = 0; i < stack_size; i++) { Object* obj = call_frame->stk[i]; if(obj && obj->reference_p()) { call_frame->stk[i] = mark_object(obj); } } } if(call_frame->multiple_scopes_p() && call_frame->top_scope_) { call_frame->top_scope_ = (VariableScope*)mark_object(call_frame->top_scope_); } if(BlockEnvironment* env = call_frame->block_env()) { call_frame->set_block_env((BlockEnvironment*)mark_object(env)); } Arguments* args = displace(call_frame->arguments, offset); if(!call_frame->inline_method_p() && args) { args->set_recv(mark_object(args->recv())); args->set_block(mark_object(args->block())); if(Tuple* tup = args->argument_container()) { args->update_argument_container((Tuple*)mark_object(tup)); } else { Object** ary = displace(args->arguments(), offset); for(uint32_t i = 0; i < args->total(); i++) { ary[i] = mark_object(ary[i]); } } } #ifdef ENABLE_LLVM if(jit::RuntimeDataHolder* jd = call_frame->jit_data()) { jd->set_mark(); ObjectMark mark(this); jd->mark_all(0, mark); } if(jit::RuntimeData* rd = call_frame->runtime_data()) { rd->method_ = (CompiledCode*)mark_object(rd->method()); rd->name_ = (Symbol*)mark_object(rd->name()); rd->module_ = (Module*)mark_object(rd->module()); } #endif saw_variable_scope(call_frame, displace(call_frame->scope, offset)); call_frame = call_frame->previous; } } void GarbageCollector::scan(ManagedThread* thr, bool young_only) { for(Roots::Iterator ri(thr->roots()); ri.more(); ri.advance()) { ri->set(saw_object(ri->get())); } scan(thr->variable_root_buffers(), young_only); scan(thr->root_buffers(), young_only); if(VM* vm = thr->as_vm()) { vm->gc_scan(this); } std::list<ObjectHeader*>& los = thr->locked_objects(); for(std::list<ObjectHeader*>::iterator i = los.begin(); i != los.end(); ++i) { *i = saw_object((Object*)*i); } } void GarbageCollector::scan(VariableRootBuffers& buffers, bool young_only, AddressDisplacement* offset) { VariableRootBuffer* vrb = displace(buffers.front(), offset); while(vrb) { Object*** buffer = displace(vrb->buffer(), offset); for(int idx = 0; idx < vrb->size(); idx++) { Object** var = displace(buffer[idx], offset); Object* tmp = *var; if(tmp && tmp->reference_p() && (!young_only || tmp->young_object_p())) { *var = saw_object(tmp); } } vrb = displace((VariableRootBuffer*)vrb->next(), offset); } } void GarbageCollector::scan(RootBuffers& buffers, bool young_only) { for(RootBuffers::Iterator i(buffers); i.more(); i.advance()) { Object** buffer = i->buffer(); for(int idx = 0; idx < i->size(); idx++) { Object* tmp = buffer[idx]; if(tmp->reference_p() && (!young_only || tmp->young_object_p())) { buffer[idx] = saw_object(tmp); } } } } void GarbageCollector::clean_weakrefs(bool check_forwards) { if(!weak_refs_) return; for(ObjectArray::iterator i = weak_refs_->begin(); i != weak_refs_->end(); ++i) { WeakRef* ref = try_as<WeakRef>(*i); if(!ref) continue; // WTF. Object* obj = ref->object(); if(!obj->reference_p()) continue; if(check_forwards) { if(obj->young_object_p()) { if(!obj->forwarded_p()) { ref->set_object(object_memory_, cNil); } else { ref->set_object(object_memory_, obj->forward()); } } } else if(!obj->marked_p(object_memory_->mark())) { ref->set_object(object_memory_, cNil); } } delete weak_refs_; weak_refs_ = NULL; } } <commit_msg>Use static_cast instead of C style cast<commit_after>/* The GC superclass methods, used by both GCs. */ #include "object_utils.hpp" #include "gc/gc.hpp" #include "objectmemory.hpp" #include "gc/object_mark.hpp" #include "builtin/class.hpp" #include "builtin/tuple.hpp" #include "builtin/module.hpp" #include "builtin/symbol.hpp" #include "builtin/weakref.hpp" #include "builtin/compiledcode.hpp" #include "call_frame.hpp" #include "builtin/variable_scope.hpp" #include "builtin/constantscope.hpp" #include "builtin/block_environment.hpp" #include "capi/handle.hpp" #ifdef ENABLE_LLVM #include "llvm/state.hpp" #endif #include "instruments/tooling.hpp" #include "arguments.hpp" #include "object_watch.hpp" namespace rubinius { GCData::GCData(VM* state) : roots_(state->globals().roots) , handles_(state->shared.global_handles()) , cached_handles_(state->shared.cached_handles()) , global_cache_(state->shared.global_cache) , threads_(state->shared.threads()) , global_handle_locations_(state->shared.global_handle_locations()) , gc_token_(0) #ifdef ENABLE_LLVM , llvm_state_(LLVMState::get_if_set(state)) #endif {} GCData::GCData(VM* state, GCToken gct) : roots_(state->globals().roots) , handles_(state->shared.global_handles()) , cached_handles_(state->shared.cached_handles()) , global_cache_(state->shared.global_cache) , threads_(state->shared.threads()) , global_handle_locations_(state->shared.global_handle_locations()) , gc_token_(&gct) #ifdef ENABLE_LLVM , llvm_state_(LLVMState::get_if_set(state)) #endif {} GarbageCollector::GarbageCollector(ObjectMemory *om) :object_memory_(om), weak_refs_(NULL) { } VM* GarbageCollector::state() { return object_memory_->state(); } /** * Scans the specified Object +obj+ for references to other Objects, and * marks those Objects as reachable. Understands how to read the inside of * an Object and find all references located within. For each reference * found, it marks the object pointed to as live (which may trigger * movement of the object in a copying garbage collector), but does not * recursively scan into the referenced object (since such recursion could * be arbitrarily deep, depending on the object graph, and this could cause * the stack to blow up). * /param obj The Object to be scanned for references to other Objects. */ void GarbageCollector::scan_object(Object* obj) { Object* slot; #ifdef ENABLE_OBJECT_WATCH if(watched_p(obj)) { std::cout << "detected " << obj << " during scan_object.\n"; } #endif // Check and update an inflated header if(obj->inflated_header_p()) { obj->inflated_header()->reset_object(obj); } slot = saw_object(obj->klass()); if(slot) obj->klass(object_memory_, force_as<Class>(slot)); if(obj->ivars()->reference_p()) { slot = saw_object(obj->ivars()); if(slot) obj->ivars(object_memory_, slot); } // Handle Tuple directly, because it's so common if(Tuple* tup = try_as<Tuple>(obj)) { native_int size = tup->num_fields(); for(native_int i = 0; i < size; i++) { slot = tup->field[i]; if(slot->reference_p()) { slot = saw_object(slot); if(slot) { tup->field[i] = slot; object_memory_->write_barrier(tup, slot); } } } } else { TypeInfo* ti = object_memory_->type_info[obj->type_id()]; ObjectMark mark(this); ti->mark(obj, mark); } } /** * Removes a mature object from the remembered set, ensuring it will not keep * alive any young objects if no other live references to those objects exist. */ void GarbageCollector::delete_object(Object* obj) { if(obj->remembered_p()) { object_memory_->unremember_object(obj); } } void GarbageCollector::saw_variable_scope(CallFrame* call_frame, StackVariables* scope) { scope->self_ = mark_object(scope->self()); scope->block_ = mark_object(scope->block()); scope->module_ = (Module*)mark_object(scope->module()); int locals = call_frame->compiled_code->machine_code()->number_of_locals; for(int i = 0; i < locals; i++) { Object* local = scope->get_local(i); if(local->reference_p()) { scope->set_local(i, mark_object(local)); } } if(scope->last_match_ && scope->last_match_->reference_p()) { scope->last_match_ = mark_object(scope->last_match_); } VariableScope* parent = scope->parent(); if(parent) { scope->parent_ = (VariableScope*)mark_object(parent); } VariableScope* heap = scope->on_heap(); if(heap) { scope->on_heap_ = (VariableScope*)mark_object(heap); } } template <typename T> T displace(T ptr, AddressDisplacement* dis) { if(!dis) return ptr; return dis->displace(ptr); } /** * Walks the chain of objects accessible from the specified CallFrame. */ void GarbageCollector::walk_call_frame(CallFrame* top_call_frame, AddressDisplacement* offset) { CallFrame* call_frame = top_call_frame; while(call_frame) { call_frame = displace(call_frame, offset); // Skip synthetic, non CompiledCode frames if(!call_frame->compiled_code) { call_frame = call_frame->previous; continue; } if(call_frame->custom_constant_scope_p() && call_frame->constant_scope_ && call_frame->constant_scope_->reference_p()) { call_frame->constant_scope_ = (ConstantScope*)mark_object(call_frame->constant_scope_); } if(call_frame->compiled_code && call_frame->compiled_code->reference_p()) { call_frame->compiled_code = (CompiledCode*)mark_object(call_frame->compiled_code); } if(call_frame->compiled_code && call_frame->stk) { native_int stack_size = call_frame->compiled_code->stack_size()->to_native(); for(native_int i = 0; i < stack_size; i++) { Object* obj = call_frame->stk[i]; if(obj && obj->reference_p()) { call_frame->stk[i] = mark_object(obj); } } } if(call_frame->multiple_scopes_p() && call_frame->top_scope_) { call_frame->top_scope_ = (VariableScope*)mark_object(call_frame->top_scope_); } if(BlockEnvironment* env = call_frame->block_env()) { call_frame->set_block_env((BlockEnvironment*)mark_object(env)); } Arguments* args = displace(call_frame->arguments, offset); if(!call_frame->inline_method_p() && args) { args->set_recv(mark_object(args->recv())); args->set_block(mark_object(args->block())); if(Tuple* tup = args->argument_container()) { args->update_argument_container((Tuple*)mark_object(tup)); } else { Object** ary = displace(args->arguments(), offset); for(uint32_t i = 0; i < args->total(); i++) { ary[i] = mark_object(ary[i]); } } } #ifdef ENABLE_LLVM if(jit::RuntimeDataHolder* jd = call_frame->jit_data()) { jd->set_mark(); ObjectMark mark(this); jd->mark_all(0, mark); } if(jit::RuntimeData* rd = call_frame->runtime_data()) { rd->method_ = (CompiledCode*)mark_object(rd->method()); rd->name_ = (Symbol*)mark_object(rd->name()); rd->module_ = (Module*)mark_object(rd->module()); } #endif saw_variable_scope(call_frame, displace(call_frame->scope, offset)); call_frame = call_frame->previous; } } void GarbageCollector::scan(ManagedThread* thr, bool young_only) { for(Roots::Iterator ri(thr->roots()); ri.more(); ri.advance()) { ri->set(saw_object(ri->get())); } scan(thr->variable_root_buffers(), young_only); scan(thr->root_buffers(), young_only); if(VM* vm = thr->as_vm()) { vm->gc_scan(this); } std::list<ObjectHeader*>& los = thr->locked_objects(); for(std::list<ObjectHeader*>::iterator i = los.begin(); i != los.end(); ++i) { *i = saw_object(static_cast<Object*>(*i)); } } void GarbageCollector::scan(VariableRootBuffers& buffers, bool young_only, AddressDisplacement* offset) { VariableRootBuffer* vrb = displace(buffers.front(), offset); while(vrb) { Object*** buffer = displace(vrb->buffer(), offset); for(int idx = 0; idx < vrb->size(); idx++) { Object** var = displace(buffer[idx], offset); Object* tmp = *var; if(tmp && tmp->reference_p() && (!young_only || tmp->young_object_p())) { *var = saw_object(tmp); } } vrb = displace((VariableRootBuffer*)vrb->next(), offset); } } void GarbageCollector::scan(RootBuffers& buffers, bool young_only) { for(RootBuffers::Iterator i(buffers); i.more(); i.advance()) { Object** buffer = i->buffer(); for(int idx = 0; idx < i->size(); idx++) { Object* tmp = buffer[idx]; if(tmp->reference_p() && (!young_only || tmp->young_object_p())) { buffer[idx] = saw_object(tmp); } } } } void GarbageCollector::clean_weakrefs(bool check_forwards) { if(!weak_refs_) return; for(ObjectArray::iterator i = weak_refs_->begin(); i != weak_refs_->end(); ++i) { WeakRef* ref = try_as<WeakRef>(*i); if(!ref) continue; // WTF. Object* obj = ref->object(); if(!obj->reference_p()) continue; if(check_forwards) { if(obj->young_object_p()) { if(!obj->forwarded_p()) { ref->set_object(object_memory_, cNil); } else { ref->set_object(object_memory_, obj->forward()); } } } else if(!obj->marked_p(object_memory_->mark())) { ref->set_object(object_memory_, cNil); } } delete weak_refs_; weak_refs_ = NULL; } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <stdexcept> #include <vexcl/vexcl.hpp> #include <boost/compute.hpp> #include <algorithm> #include <QtGui> #include <QtOpenGL> #include <boost/compute/command_queue.hpp> #include <boost/compute/kernel.hpp> #include <boost/compute/program.hpp> #include <boost/compute/source.hpp> #include <boost/compute/system.hpp> #include <boost/compute/interop/opengl.hpp> using namespace std; namespace compute = boost::compute; int main (int argc, char* argv[]) { // get the default compute device compute::device gpu = compute::system::default_device(); // create a compute context and command queue compute::context ctx(gpu); compute::command_queue queue(ctx, gpu); //set some default values for when no commandline arguments are given int accuracy = 90; int polygons = 50; int vertices = 6; //read input commandline arguments for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "-a") { //initialise desired accuracy variable according to commandline argument -a accuracy = ; } if (std::string(argv[i]) == "-p") { //initialise maximum polygons variable according to commandline argument -p polygons = ; } if (std::string(argv[i]) == "-v") { //initialise maximum verices per polygon variable according to commandline argument -v vertices = ; } } //initialise variables in gpu //create leaderDNA variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create mutatedDNA variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create leaderDNArender variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create mutatedDNArender variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create original image variable + load image into gpu memory if (std::string(argv[i]) == "") { //load file according to commandline argument into gpu vector //get x(max), y(max). (image dimensions) //make image vector on device compute::vector<float> originalimage(ctx, n); // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); } //initialise DNA with a random seed //create random leader dna // generate random dna vector on the host std::vector<float> host_vector(1000000); std::generate(host_vector.begin(), host_vector.end(), rand); // create vector on the device compute::vector<float> device_vector(1000000, ctx); // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); //run render loop until desired accuracy is reached while (leaderaccuracy<accuracy) { //calculate leader fitness leaderfitness = computefitness(mutatedDNA,originalimage) while () { //mutate from the leaderDNA mutatedDNA = mutateDNA(leaderDNA) //compute fitness of mutation vs leaderDNA //check if it is fitter, if so overwrite leaderDNA if (computefitness(mutatedDNA,originalimage) < leaderfitness)) { //overwrite leaderDNA leaderDNA = mutatedDNA; //save dna to disk // start by writing a temp file. pFile = fopen ("volution.dna.temp","w"); fprintf (pFile, DNA); fclose (pFile); // Then rename the real backup to a secondary backup. result = rename("volution.dna","volution_2.dna"); // Then rename the temp file to the primary backup result = rename("volution.dna.temp","volution.dna"); // Then delete the temp file result = remove("volution.dna.temp"); } } //perform final render, output svg and raster image //render DNA and save resulting image to disk as .svg file and raster image (.png) //render image from DNA renderDNA(DNA); //save resultant image to disk as svg and png files } int computefitness (DNA, originalimage) { //compute what % match DNAimage is to original image boost::compute::function<int (int)> computefitnesspercent = boost::compute::make_function_from_source<int (int)>( "computefitnesspercent", "int computefitnesspercent(int x) { //read leader dna //compare input dna to leader dna to find changed polygons compareDNA(leaderDNA,DNA); //create bounding box containing changed polygons //render leader dna within bounding box leaderrender = renderDNA(leaderDNA,boundx,boundy); //render input dna within bounding box inputrender = renderDNA(DNA,boundx,boundy); //compare leader and input dna rendered bounding boxes compareimage(leaderrender,inputrender); //returns % match }" ); } int compareDNA(DNA0,DNA1) { //compare DNA0 to DNA1 to find changed polygons boost::compute::function<int (int)> compareDNA = boost::compute::make_function_from_source<int (int)>( "compareDNA", "int compareDNA(int x) { return x + 4; }" ); } int renderDNA (DNA, boundx0, boundy0, boundx1, boundy1) { //render input DNA to a raster image boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); } int renderSVG (DNA, boundx0, boundy0, boundx1, boundy1) { //render input DNA to a vector image in an opengl texture boost::compute::function<int (int)> renderSVG = boost::compute::make_function_from_source<int (int)>( "renderSVG", "int renderSVG(int x) { //for each shape in dna { //add shape to svg file } }" ); } } int mutateDNA (DNA) { //mutate dna boost::compute::function<int (int)> mutateDNA = boost::compute::make_function_from_source<int (int)>( "mutateDNA", "int mutateDNA(int DNA) { //mutate input DNA randomly mutated_shape = RANDINT(NUM_SHAPES); double roulette = RANDDOUBLE(2.8); double drastic = RANDDOUBLE(2); // mutate color if(roulette<1) { if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid || roulette<0.25) { if(drastic < 1) { dna_test[mutated_shape].a += RANDDOUBLE(0.1); dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0); } else dna_test[mutated_shape].a = RANDDOUBLE(1.0); } else if(roulette<0.50) { if(drastic < 1) { dna_test[mutated_shape].r += RANDDOUBLE(0.1); dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0); } else dna_test[mutated_shape].r = RANDDOUBLE(1.0); } else if(roulette<0.75) { if(drastic < 1) { dna_test[mutated_shape].g += RANDDOUBLE(0.1); dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0); } else dna_test[mutated_shape].g = RANDDOUBLE(1.0); } else { if(drastic < 1) { dna_test[mutated_shape].b += RANDDOUBLE(0.1); dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0); } else dna_test[mutated_shape].b = RANDDOUBLE(1.0); } } // mutate shape else if(roulette < 2.0) { int point_i = RANDINT(NUM_POINTS); if(roulette<1.5) { if(drastic < 1) { dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0); dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1); } else dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH); } else { if(drastic < 1) { dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0); dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1); } else dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT); } } // mutate stacking else { int destination = RANDINT(NUM_SHAPES); shape_t s = dna_test[mutated_shape]; dna_test[mutated_shape] = dna_test[destination]; dna_test[destination] = s; return destination; } return -1; }" ); } <commit_msg>tidying<commit_after>#include <iostream> #include <string> #include <vector> #include <stdexcept> #include <vexcl/vexcl.hpp> #include <boost/compute.hpp> #include <algorithm> #include <QtGui> #include <QtOpenGL> #include <boost/compute/command_queue.hpp> #include <boost/compute/kernel.hpp> #include <boost/compute/program.hpp> #include <boost/compute/source.hpp> #include <boost/compute/system.hpp> #include <boost/compute/interop/opengl.hpp> using namespace std; namespace compute = boost::compute; int main (int argc, char* argv[]) { // get the default compute device compute::device gpu = compute::system::default_device(); // create a compute context and command queue compute::context ctx(gpu); compute::command_queue queue(ctx, gpu); //set some default values for when no commandline arguments are given int accuracy = 90; int polygons = 50; int vertices = 6; //read input commandline arguments for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "-a") { //initialise desired accuracy variable according to commandline argument -a accuracy = ; } if (std::string(argv[i]) == "-p") { //initialise maximum polygons variable according to commandline argument -p polygons = ; } if (std::string(argv[i]) == "-v") { //initialise maximum verices per polygon variable according to commandline argument -v vertices = ; } } //initialise variables in gpu //create leaderDNA variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create mutatedDNA variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create leaderDNArender variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create mutatedDNArender variable // create data array on host int host_data[] = { 1, 3, 5, 7, 9 }; // create vector on device compute::vector<int> device_vector(5); // copy from host to device compute::copy(host_data, host_data + 5, device_vector.begin()); //create original image variable + load image into gpu memory if (std::string(argv[i]) == "") { //load file according to commandline argument into gpu vector //get x(max), y(max). (image dimensions) //make image vector on device compute::vector<float> originalimage(ctx, n); // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); } //initialise DNA with a random seed //create random leader dna // generate random dna vector on the host std::vector<float> host_vector(1000000); std::generate(host_vector.begin(), host_vector.end(), rand); // create vector on the device compute::vector<float> device_vector(1000000, ctx); // copy data to the device compute::copy( host_vector.begin(), host_vector.end(), device_vector.begin(), queue ); //run render loop until desired accuracy is reached while (leaderaccuracy<accuracy) { //render leader DNA to a raster image in opengl texture boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); //calculate leader fitness leaderfitness = computefitness(mutatedDNA,originalimage) while () { //mutate from the leaderDNA boost::compute::function<int (int)> mutateDNA = boost::compute::make_function_from_source<int (int)>( "mutateDNA", "int mutateDNA(int DNA) { //mutate input DNA randomly mutated_shape = RANDINT(NUM_SHAPES); double roulette = RANDDOUBLE(2.8); double drastic = RANDDOUBLE(2); // mutate color if(roulette<1) { if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid || roulette<0.25) { if(drastic < 1) { dna_test[mutated_shape].a += RANDDOUBLE(0.1); dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0); } else dna_test[mutated_shape].a = RANDDOUBLE(1.0); } else if(roulette<0.50) { if(drastic < 1) { dna_test[mutated_shape].r += RANDDOUBLE(0.1); dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0); } else dna_test[mutated_shape].r = RANDDOUBLE(1.0); } else if(roulette<0.75) { if(drastic < 1) { dna_test[mutated_shape].g += RANDDOUBLE(0.1); dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0); } else dna_test[mutated_shape].g = RANDDOUBLE(1.0); } else { if(drastic < 1) { dna_test[mutated_shape].b += RANDDOUBLE(0.1); dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0); } else dna_test[mutated_shape].b = RANDDOUBLE(1.0); } } // mutate shape else if(roulette < 2.0) { int point_i = RANDINT(NUM_POINTS); if(roulette<1.5) { if(drastic < 1) { dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0); dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1); } else dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH); } else { if(drastic < 1) { dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0); dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1); } else dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT); } } // mutate stacking else { int destination = RANDINT(NUM_SHAPES); shape_t s = dna_test[mutated_shape]; dna_test[mutated_shape] = dna_test[destination]; dna_test[destination] = s; return destination; } return -1; }" ); //render mutated DNA to a raster image in opengl texture boost::compute::function<int (int)> renderDNA = boost::compute::make_function_from_source<int (int)>( "renderDNA", "int renderDNA(int x) { //for each shape in dna { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_texture_); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(0, 1); glVertex2f(0, h); glTexCoord2f(1, 1); glVertex2f(w, h); glTexCoord2f(1, 0); glVertex2f(w, 0); glEnd(); } }" ); //compute fitness of mutated dna image vs leader dna image //compute what % match DNAimage is to original image boost::compute::function<int (int)> computefitnesspercent = boost::compute::make_function_from_source<int (int)>( "computefitnesspercent", "int computefitnesspercent(int x) { //read leader dna //compare input dna to leader dna to find changed polygons compareDNA(leaderDNA,DNA); //create bounding box containing changed polygons //render leader dna within bounding box leaderrender = renderDNA(leaderDNA,boundx,boundy); //render input dna within bounding box inputrender = renderDNA(DNA,boundx,boundy); //compare leader and input dna rendered bounding boxes compareimage(leaderrender,inputrender); //returns % match }" ); //check if it is fitter, if so overwrite leaderDNA while (fitness(mutatedDNA,originalimage) < leaderfitness)) { //overwrite leaderDNA leaderDNA = mutatedDNA; //save dna to disk // start by writing a temp file. pFile = fopen ("volution.dna.temp","w"); fprintf (pFile, DNA); fclose (pFile); // Then rename the real backup to a secondary backup. result = rename("volution.dna","volution_2.dna"); // Then rename the temp file to the primary backup result = rename("volution.dna.temp","volution.dna"); // Then delete the temp file result = remove("volution.dna.temp"); } } //perform final render, output svg and raster image //render DNA and save resulting image to disk as .svg file and raster image (.png) //render image from DNA renderDNA(DNA); //save resultant image to disk as svg and png files //render input DNA to an svg file boost::compute::function<int (int)> renderSVG = boost::compute::make_function_from_source<int (int)>( "renderSVG", "int renderSVG(int x) { //for each shape in dna { //add shape to svg file } }" ); }<|endoftext|>
<commit_before>/** * $ g++ solution.cpp && ./a.out * Day 15! * Part 1: 631 * Part 2: 279 */ #include <iostream> #include <string> #include <stdint.h> using namespace std; const uint64_t FACTOR_A = 16807; const uint64_t FACTOR_B = 48271; const uint64_t DIVISOR = 2147483647; // Generator A starts with 873 // Generator B starts with 583 const uint64_t START_A = 873; const uint64_t START_B = 583; // TESTING: // const uint64_t START_A = 65; // const uint64_t START_B = 8921; int part1() { const int NUM_ROUNDS = 40000000; // const int NUM_ROUNDS = 5; int count = 0; uint64_t a = START_A; uint64_t b = START_B; // string str_a; // string str_b; for (int round = 1; round <= NUM_ROUNDS; round++) { // if (round % 100000 == 0) { // cout << "round " << round << endl; // } a = (a * FACTOR_A) % DIVISOR; b = (b * FACTOR_B) % DIVISOR; // cout << a << "\t" << b << endl; // str_a = dec_to_binary(a); // str_b = dec_to_binary(b); // cout << str_a << endl; // cout << str_b << "\n" << endl; // if (str_a.substr(16, 16) == str_b.substr(16, 16)) { // count++; // } if (bitset<16>(a) == bitset<16>(b)) { count++; } } return count; } int part2() { const int NUM_ROUNDS = 5000000; int count = 0; uint64_t a = START_A; uint64_t b = START_B; for (int round = 1; round <= NUM_ROUNDS; round++) { // if (round % 100000 == 0) { // cout << "round " << round << endl; // } // Divisible by 4 do { a = (a * FACTOR_A) % DIVISOR; } while (bitset<2>(a) != 0); // Divisible by 8 do { b = (b * FACTOR_B) % DIVISOR; } while (bitset<3>(b) != 0); if (bitset<16>(a) == bitset<16>(b)) { count++; } } return count; } int main() { cout << "Day 15!" << endl; // cout << 16807 << " " << bitset<32>(16807) << " " << bitset<4>(16807) << endl; // cout << bitset<8>(17) << " " << bitset<8>(33) << endl; // cout << bitset<3>(17) << " " << bitset<3>(33) << endl; // bool yas = (bitset<3>(17) == bitset<3>(33)); // cout << yas << endl; cout << "Part 1: " << part1() << endl; // cout << (bitset<3>(4) == 0) << endl; cout << "Part 2: " << part2() << endl; } <commit_msg>Day 15 cleanup<commit_after>/** * $ g++ solution.cpp && ./a.out * Day 15! * Part 1: 631 * Part 2: 279 */ #include <iostream> #include <string> #include <stdint.h> using namespace std; const uint64_t FACTOR_A = 16807; const uint64_t FACTOR_B = 48271; const uint64_t DIVISOR = 2147483647; // Generator A starts with 873 // Generator B starts with 583 const uint64_t START_A = 873; const uint64_t START_B = 583; // TESTING: // const uint64_t START_A = 65; // const uint64_t START_B = 8921; int part1() { const int NUM_ROUNDS = 40000000; int count = 0; uint64_t a = START_A; uint64_t b = START_B; for (int round = 1; round <= NUM_ROUNDS; round++) { a = (a * FACTOR_A) % DIVISOR; b = (b * FACTOR_B) % DIVISOR; if (bitset<16>(a) == bitset<16>(b)) { count++; } } return count; } int part2() { const int NUM_ROUNDS = 5000000; int count = 0; uint64_t a = START_A; uint64_t b = START_B; for (int round = 1; round <= NUM_ROUNDS; round++) { // Divisible by 4 do { a = (a * FACTOR_A) % DIVISOR; } while (bitset<2>(a) != 0); // Divisible by 8 do { b = (b * FACTOR_B) % DIVISOR; } while (bitset<3>(b) != 0); if (bitset<16>(a) == bitset<16>(b)) { count++; } } return count; } int main() { cout << "Day 15!" << endl; cout << "Part 1: " << part1() << endl; cout << "Part 2: " << part2() << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F2.cpp * Author : Kazune Takahashi * Created : 2/11/2020, 12:10:07 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { int N; ll D, A; cin >> N >> D >> A; using Monster = tuple<ll, ll>; vector<Monster> V(N); for (auto i = 0; i < N; ++i) { cin >> get<0>(V[i]) >> get<1>(V[i]); } sort(V.begin(), V.end()); using Info = tuple<int, ll>; queue<Info> Q; ll ans{0}; ll total{0}; for (auto i = 0; i < N; ++i) { ll X, H; tie(X, H) = V[i]; while (!Q.empty() && get<0>(Q.front()) <= X) { total -= get<1>(Q.front()); Q.pop(); } ll cnt{max(0LL, (H - total + A - 1) / A)}; ans += cnt; total += A * cnt; Q.emplace(X + 2 * D + 2, A * cnt); } cout << ans << endl; } <commit_msg>submit F2.cpp to 'F - Silver Fox vs Monster' (abc153) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : F2.cpp * Author : Kazune Takahashi * Created : 2/11/2020, 12:10:07 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { int N; ll D, A; cin >> N >> D >> A; using Monster = tuple<ll, ll>; vector<Monster> V(N); for (auto i = 0; i < N; ++i) { cin >> get<0>(V[i]) >> get<1>(V[i]); } sort(V.begin(), V.end()); using Info = tuple<int, ll>; queue<Info> Q; ll ans{0}; ll total{0}; for (auto i = 0; i < N; ++i) { ll X, H; tie(X, H) = V[i]; while (!Q.empty() && get<0>(Q.front()) <= X) { total -= get<1>(Q.front()); Q.pop(); } ll cnt{max(0LL, (H - total + A - 1) / A)}; ans += cnt; total += A * cnt; Q.emplace(X + 2 * D + 1, A * cnt); } cout << ans << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D2.cpp * Author : Kazune Takahashi * Created : 4/20/2020, 12:13:08 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { string S; cin >> S; int Q; cin >> Q; stringstream prefix, suffix; bool reversed{false}; for (auto q = 0; q < Q; ++q) { int t; cin >> t; if (t == 1) { reversed = !reversed; } else { int f; char c; cin >> f >> c; if ((f == 1) ^ reversed) { #if DEBUG == 1 cerr << "suffix" << endl; #endif suffix << c; } else { #if DEBUG == 1 cerr << "prefix" << endl; #endif prefix << c; } } } string pre{prefix.str()}; string suf{suffix.str()}; reverse(pre.begin(), pre.end()); string ans{pre + S + suf}; if (reversed) { reverse(ans.begin(), ans.end()); } cout << ans << endl; } <commit_msg>submit D2.cpp to 'D - String Formation' (abc158) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : D2.cpp * Author : Kazune Takahashi * Created : 4/20/2020, 12:13:08 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint &operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint &operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { string S; cin >> S; int Q; cin >> Q; stringstream prefix, suffix; bool reversed{false}; for (auto q = 0; q < Q; ++q) { int t; cin >> t; if (t == 1) { reversed = !reversed; } else { int f; char c; cin >> f >> c; if ((f == 1) ^ reversed) { prefix << c; } else { suffix << c; } } } string pre{prefix.str()}; string suf{suffix.str()}; reverse(pre.begin(), pre.end()); string ans{pre + S + suf}; if (reversed) { reverse(ans.begin(), ans.end()); } cout << ans << endl; } <|endoftext|>
<commit_before>/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <svx/sidebar/ColorControl.hxx> #include "svx/svxids.hrc" #include "svx/drawitem.hxx" #include "svx/xtable.hxx" #include "svx/dialmgr.hxx" #include "svx/xflclit.hxx" #include <tools/resid.hxx> #include <sfx2/sidebar/Theme.hxx> #include <sfx2/objsh.hxx> #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> #include <vcl/floatwin.hxx> #include <unotools/pathoptions.hxx> #include <editeng/editrids.hrc> using ::sfx2::sidebar::Theme; namespace svx { namespace sidebar { namespace { short GetItemId_Imp( ValueSet& rValueSet, const Color& rCol ) { if(rCol == COL_AUTO) return 0; bool bFound = false; sal_uInt16 nCount = rValueSet.GetItemCount(); sal_uInt16 n = 1; while ( !bFound && n <= nCount ) { Color aValCol = rValueSet.GetItemColor(n); bFound = ( aValCol.GetRed() == rCol.GetRed() && aValCol.GetGreen() == rCol.GetGreen() && aValCol.GetBlue() == rCol.GetBlue() ); if ( !bFound ) n++; } return bFound ? n : -1; } XColorListRef GetColorTable (void) { SfxObjectShell* pDocSh = SfxObjectShell::Current(); DBG_ASSERT(pDocSh!=NULL, "DocShell not found!"); if (pDocSh != NULL) { const SfxPoolItem* pItem = pDocSh->GetItem(SID_COLOR_TABLE); if (pItem != NULL) { XColorListRef xTable = ((SvxColorListItem*)pItem)->GetColorList(); if (xTable.is()) return xTable; } } return XColorList::GetStdColorList(); } } // end of anonymous namespace ColorControl::ColorControl ( Window* pParent, SfxBindings* /* pBindings */, const ResId& rControlResId, const ResId& rValueSetResId, const ::boost::function<Color(void)>& rNoColorGetter, const ::boost::function<void(OUString&,Color)>& rColorSetter, FloatingWindow* pFloatingWindow, const ResId* pNoColorStringResId) // const sal_uInt32 nNoColorStringResId) : PopupControl(pParent, rControlResId), maVSColor(this, rValueSetResId), mpFloatingWindow(pFloatingWindow), msNoColorString( pNoColorStringResId ? pNoColorStringResId->toString() : OUString()), maNoColorGetter(rNoColorGetter), maColorSetter(rColorSetter) { FreeResource(); FillColors(); } ColorControl::~ColorControl (void) { } void ColorControl::FillColors (void) { XColorListRef xColorTable (GetColorTable()); if (xColorTable.is()) { const long nColorCount(xColorTable->Count()); if (nColorCount <= 0) return; const WinBits aWinBits(maVSColor.GetStyle() | WB_TABSTOP | WB_ITEMBORDER | WB_NAMEFIELD | WB_NO_DIRECTSELECT | WB_MENUSTYLEVALUESET); maVSColor.SetStyle(aWinBits); // neds to be done *before* layouting if(!msNoColorString.isEmpty()) { maVSColor.SetStyle(maVSColor.GetStyle() | WB_NONEFIELD); maVSColor.SetText(msNoColorString); } const Size aNewSize(maVSColor.layoutAllVisible(nColorCount)); maVSColor.SetOutputSizePixel(aNewSize); static sal_Int32 nAdd = 4; SetOutputSizePixel(Size(aNewSize.Width() + nAdd, aNewSize.Height() + nAdd)); Link aLink = LINK(this, ColorControl, VSSelectHdl); maVSColor.SetSelectHdl(aLink); // Now, after all calls to SetStyle, we can change the // background color. maVSColor.SetBackground(Theme::GetWallpaper(Theme::Paint_DropDownBackground)); // add entrties maVSColor.Clear(); maVSColor.addEntriesForXColorList(*xColorTable); } maVSColor.Show(); } void ColorControl::GetFocus (void) { maVSColor.GrabFocus(); } void ColorControl::SetCurColorSelect (Color aCol, bool bAvailable) { // FillColors(); short nCol = GetItemId_Imp( maVSColor, aCol ); if(! bAvailable) { maVSColor.SetNoSelection(); return; } //if not found if( nCol == -1) { maVSColor.SetNoSelection(); } else { // remove selection first to force evtl. scroll when scroll is needed maVSColor.SetNoSelection(); maVSColor.SelectItem(nCol); } } IMPL_LINK(ColorControl, VSSelectHdl, void *, pControl) { if(pControl == &maVSColor) { sal_uInt16 iPos = maVSColor.GetSelectItemId(); Color aColor = maVSColor.GetItemColor( iPos ); OUString aTmpStr = maVSColor.GetItemText( iPos ); // react when the WB_NONEFIELD created entry is selected if (aColor.GetColor() == 0 && aTmpStr.isEmpty()) { if (maNoColorGetter) aColor = maNoColorGetter(); } if (maColorSetter) maColorSetter(aTmpStr, aColor); if (mpFloatingWindow!=NULL && mpFloatingWindow->IsInPopupMode()) mpFloatingWindow->EndPopupMode(); } return 0; } } } // end of namespace svx::sidebar <commit_msg>I guess const was intended here.<commit_after>/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <svx/sidebar/ColorControl.hxx> #include "svx/svxids.hrc" #include "svx/drawitem.hxx" #include "svx/xtable.hxx" #include "svx/dialmgr.hxx" #include "svx/xflclit.hxx" #include <tools/resid.hxx> #include <sfx2/sidebar/Theme.hxx> #include <sfx2/objsh.hxx> #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> #include <vcl/floatwin.hxx> #include <unotools/pathoptions.hxx> #include <editeng/editrids.hrc> using ::sfx2::sidebar::Theme; namespace svx { namespace sidebar { namespace { short GetItemId_Imp( ValueSet& rValueSet, const Color& rCol ) { if(rCol == COL_AUTO) return 0; bool bFound = false; sal_uInt16 nCount = rValueSet.GetItemCount(); sal_uInt16 n = 1; while ( !bFound && n <= nCount ) { Color aValCol = rValueSet.GetItemColor(n); bFound = ( aValCol.GetRed() == rCol.GetRed() && aValCol.GetGreen() == rCol.GetGreen() && aValCol.GetBlue() == rCol.GetBlue() ); if ( !bFound ) n++; } return bFound ? n : -1; } XColorListRef GetColorTable (void) { SfxObjectShell* pDocSh = SfxObjectShell::Current(); DBG_ASSERT(pDocSh!=NULL, "DocShell not found!"); if (pDocSh != NULL) { const SfxPoolItem* pItem = pDocSh->GetItem(SID_COLOR_TABLE); if (pItem != NULL) { XColorListRef xTable = ((SvxColorListItem*)pItem)->GetColorList(); if (xTable.is()) return xTable; } } return XColorList::GetStdColorList(); } } // end of anonymous namespace ColorControl::ColorControl ( Window* pParent, SfxBindings* /* pBindings */, const ResId& rControlResId, const ResId& rValueSetResId, const ::boost::function<Color(void)>& rNoColorGetter, const ::boost::function<void(OUString&,Color)>& rColorSetter, FloatingWindow* pFloatingWindow, const ResId* pNoColorStringResId) // const sal_uInt32 nNoColorStringResId) : PopupControl(pParent, rControlResId), maVSColor(this, rValueSetResId), mpFloatingWindow(pFloatingWindow), msNoColorString( pNoColorStringResId ? pNoColorStringResId->toString() : OUString()), maNoColorGetter(rNoColorGetter), maColorSetter(rColorSetter) { FreeResource(); FillColors(); } ColorControl::~ColorControl (void) { } void ColorControl::FillColors (void) { XColorListRef xColorTable (GetColorTable()); if (xColorTable.is()) { const long nColorCount(xColorTable->Count()); if (nColorCount <= 0) return; const WinBits aWinBits(maVSColor.GetStyle() | WB_TABSTOP | WB_ITEMBORDER | WB_NAMEFIELD | WB_NO_DIRECTSELECT | WB_MENUSTYLEVALUESET); maVSColor.SetStyle(aWinBits); // neds to be done *before* layouting if(!msNoColorString.isEmpty()) { maVSColor.SetStyle(maVSColor.GetStyle() | WB_NONEFIELD); maVSColor.SetText(msNoColorString); } const Size aNewSize(maVSColor.layoutAllVisible(nColorCount)); maVSColor.SetOutputSizePixel(aNewSize); const sal_Int32 nAdd = 4; SetOutputSizePixel(Size(aNewSize.Width() + nAdd, aNewSize.Height() + nAdd)); Link aLink = LINK(this, ColorControl, VSSelectHdl); maVSColor.SetSelectHdl(aLink); // Now, after all calls to SetStyle, we can change the // background color. maVSColor.SetBackground(Theme::GetWallpaper(Theme::Paint_DropDownBackground)); // add entrties maVSColor.Clear(); maVSColor.addEntriesForXColorList(*xColorTable); } maVSColor.Show(); } void ColorControl::GetFocus (void) { maVSColor.GrabFocus(); } void ColorControl::SetCurColorSelect (Color aCol, bool bAvailable) { // FillColors(); short nCol = GetItemId_Imp( maVSColor, aCol ); if(! bAvailable) { maVSColor.SetNoSelection(); return; } //if not found if( nCol == -1) { maVSColor.SetNoSelection(); } else { // remove selection first to force evtl. scroll when scroll is needed maVSColor.SetNoSelection(); maVSColor.SelectItem(nCol); } } IMPL_LINK(ColorControl, VSSelectHdl, void *, pControl) { if(pControl == &maVSColor) { sal_uInt16 iPos = maVSColor.GetSelectItemId(); Color aColor = maVSColor.GetItemColor( iPos ); OUString aTmpStr = maVSColor.GetItemText( iPos ); // react when the WB_NONEFIELD created entry is selected if (aColor.GetColor() == 0 && aTmpStr.isEmpty()) { if (maNoColorGetter) aColor = maNoColorGetter(); } if (maColorSetter) maColorSetter(aTmpStr, aColor); if (mpFloatingWindow!=NULL && mpFloatingWindow->IsInPopupMode()) mpFloatingWindow->EndPopupMode(); } return 0; } } } // end of namespace svx::sidebar <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cancellablejob.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2007-07-18 13:30:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CANCELLABLEJOB_HXX #define _CANCELLABLEJOB_HXX #include "sal/config.h" #include "cppuhelper/implbase1.hxx" #include "com/sun/star/util/XCancellable.hpp" #include <rtl/ref.hxx> class ObservableThread; class CancellableJob : public ::cppu::WeakImplHelper1<com::sun::star::util::XCancellable> { public: explicit CancellableJob( const ::rtl::Reference< ObservableThread >& rThread ); ~CancellableJob() {} // ::com::sun::star::util::XCancellable: virtual void SAL_CALL cancel() throw (com::sun::star::uno::RuntimeException); private: CancellableJob( CancellableJob& ); // not defined void operator =( CancellableJob& ); // not defined ::rtl::Reference< ObservableThread > mrThread; }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.342); FILE MERGED 2008/03/31 16:53:49 rt 1.2.342.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cancellablejob.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CANCELLABLEJOB_HXX #define _CANCELLABLEJOB_HXX #include "sal/config.h" #include "cppuhelper/implbase1.hxx" #include "com/sun/star/util/XCancellable.hpp" #include <rtl/ref.hxx> class ObservableThread; class CancellableJob : public ::cppu::WeakImplHelper1<com::sun::star::util::XCancellable> { public: explicit CancellableJob( const ::rtl::Reference< ObservableThread >& rThread ); ~CancellableJob() {} // ::com::sun::star::util::XCancellable: virtual void SAL_CALL cancel() throw (com::sun::star::uno::RuntimeException); private: CancellableJob( CancellableJob& ); // not defined void operator =( CancellableJob& ); // not defined ::rtl::Reference< ObservableThread > mrThread; }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLRangeHelper.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-05-22 16:33:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //!! //!! This file is an exact copy of the same file in chart2 project //!! #ifndef XMLRANGEHELPER_HXX #define XMLRANGEHELPER_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif //namespace chart //{ namespace XMLRangeHelper { struct Cell { sal_Int32 nColumn; sal_Int32 nRow; bool bRelativeColumn; bool bRelativeRow; bool bIsEmpty; Cell() : nColumn(0), nRow(0), bRelativeColumn(false), bRelativeRow(false), bIsEmpty(true) {} inline bool empty() const { return bIsEmpty; } }; struct CellRange { Cell aUpperLeft; Cell aLowerRight; ::rtl::OUString aTableName; }; CellRange getCellRangeFromXMLString( const ::rtl::OUString & rXMLString ); ::rtl::OUString getXMLStringFromCellRange( const CellRange & rRange ); } // namespace XMLRangeHelper //} // namespace chart // XMLRANGEHELPER_HXX #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.428); FILE MERGED 2008/04/01 15:57:35 thb 1.2.428.2: #i85898# Stripping all external header guards 2008/03/31 16:55:13 rt 1.2.428.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLRangeHelper.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ //!! //!! This file is an exact copy of the same file in chart2 project //!! #ifndef XMLRANGEHELPER_HXX #define XMLRANGEHELPER_HXX #include <sal/types.h> #include <rtl/ustring.hxx> //namespace chart //{ namespace XMLRangeHelper { struct Cell { sal_Int32 nColumn; sal_Int32 nRow; bool bRelativeColumn; bool bRelativeRow; bool bIsEmpty; Cell() : nColumn(0), nRow(0), bRelativeColumn(false), bRelativeRow(false), bIsEmpty(true) {} inline bool empty() const { return bIsEmpty; } }; struct CellRange { Cell aUpperLeft; Cell aLowerRight; ::rtl::OUString aTableName; }; CellRange getCellRangeFromXMLString( const ::rtl::OUString & rXMLString ); ::rtl::OUString getXMLStringFromCellRange( const CellRange & rRange ); } // namespace XMLRangeHelper //} // namespace chart // XMLRANGEHELPER_HXX #endif <|endoftext|>
<commit_before>// See LICENSE file for copyright and license details. #include "ui_opengl/event/move.h" #include <cassert> #include <SDL/SDL_opengl.h> #include "core/misc.h" #include "core/v2i.h" #include "core/dir.h" #include "core/core.h" #include "core/path.h" #include "ui_opengl/v2f.h" #include "ui_opengl/vertex_array.h" #include "ui_opengl/game.h" int getLastEventMoveIndex(Game& game, const Event &e) { UNUSED(game); auto eventMove = dynamic_cast<const EventMove*>(&e); return (eventMove->path.size() - 1) * moveSpeed; } void getCurrentMovingNodes( Game& game, const EventMove& e, V2i* from, V2i* to) { int i = game.currentMoveIndex(); auto& p = e.path; // shortcut unsigned int j; // node id assert(from); assert(to); for (j = 0; j < p.size() - 2; j++) { i -= moveSpeed; if (i < 0) { break; } } *from = p[j]; *to = p[j + 1]; } static void endMovement(Game& game, const EventMove& e, const V2i& pos) { Unit* u = game.core().id2unit(e.unitID); game.setUiMode(UIMode::NORMAL); u->pos = pos; if (game.core().selectedUnit()) { game.core().pathfinder().fillMap(*u); game.setVaWalkableMap(game.buildWalkableArray()); game.core().calculateFow(); game.setVaFogOfWar(game.buildFowArray()); } game.core().applyEvent(game.core().currentEvent()); game.core().setCurrentEvent(nullptr); if (u->playerID == game.core().currentPlayer().id) { if (game.core().selectedUnit()) { game.core().pathfinder().fillMap(*game.core().selectedUnit()); game.setVaWalkableMap(game.buildWalkableArray()); } game.setVaFogOfWar(game.buildFowArray()); } } static int getNodeIndex(Game& game, const EventMove& e) { auto& p = e.path; // shortcut int last = 0; int current = 0; for (unsigned int j = 0; j < p.size() - 2; j++) { current += moveSpeed; if (current > game.currentMoveIndex()) { break; } last = current; } return game.currentMoveIndex() - last; } void drawMovingUnit(Game& game, const EventMove& e) { Unit *u = game.core().id2unit(e.unitID); V2i fromI, toI; V2f diff; V2f p; getCurrentMovingNodes(game, e, &fromI, &toI); V2f fromF = game.v2iToV2f(fromI); V2f toF = game.v2iToV2f(toI); int nodeIndex = getNodeIndex(game, e); diff.setX((toF.x() - fromF.x()) / moveSpeed); diff.setY((toF.y() - fromF.y()) / moveSpeed); p.setX(fromF.x() + diff.x() * nodeIndex); p.setY(fromF.y() + diff.y() * nodeIndex); glPushMatrix(); glTranslatef(p.x(), p.y(), 0.0f); // TODO: Remove '+ 4'! Rotate obj files! glRotatef( Dir(fromI, toI).toInt() * 60.0f + 120.0f, 0, 0, 1); game.drawUnitModel(*u); game.drawUnitCircle(*u); glPopMatrix(); game.setCurrentMoveIndex(game.currentMoveIndex() + 1); if (game.currentMoveIndex() == game.lastMoveIndex()) { endMovement(game, e, toI); } } <commit_msg>Simplified a bit ui_opengl/event/move.cpp<commit_after>// See LICENSE file for copyright and license details. #include "ui_opengl/event/move.h" #include <cassert> #include <SDL/SDL_opengl.h> #include "core/misc.h" #include "core/v2i.h" #include "core/dir.h" #include "core/core.h" #include "core/path.h" #include "ui_opengl/v2f.h" #include "ui_opengl/vertex_array.h" #include "ui_opengl/game.h" int getLastEventMoveIndex(Game& game, const Event &e) { UNUSED(game); auto eventMove = dynamic_cast<const EventMove*>(&e); return (eventMove->path.size() - 1) * moveSpeed; } void getCurrentMovingNodes( Game& game, const EventMove& e, V2i* from, V2i* to) { int i = game.currentMoveIndex(); auto& p = e.path; // shortcut unsigned int j; // node id assert(from); assert(to); for (j = 0; j < p.size() - 2; j++) { i -= moveSpeed; if (i < 0) { break; } } *from = p[j]; *to = p[j + 1]; } static void endMovement(Game& game, const EventMove& e, const V2i& pos) { Unit* u = game.core().id2unit(e.unitID); game.setUiMode(UIMode::NORMAL); u->pos = pos; if (game.core().selectedUnit()) { game.core().pathfinder().fillMap(*u); game.setVaWalkableMap(game.buildWalkableArray()); game.core().calculateFow(); game.setVaFogOfWar(game.buildFowArray()); } game.core().applyEvent(game.core().currentEvent()); game.core().setCurrentEvent(nullptr); if (u->playerID == game.core().currentPlayer().id) { if (game.core().selectedUnit()) { game.core().pathfinder().fillMap(*game.core().selectedUnit()); game.setVaWalkableMap(game.buildWalkableArray()); } game.setVaFogOfWar(game.buildFowArray()); } } static int getNodeIndex(Game& game, const EventMove& e) { int last = 0; int current = 0; for (unsigned int j = 0; j < e.path.size() - 2; j++) { current += moveSpeed; if (current > game.currentMoveIndex()) { break; } last = current; } return game.currentMoveIndex() - last; } void drawMovingUnit(Game& game, const EventMove& e) { Unit* u = game.core().id2unit(e.unitID); V2i fromI, toI; getCurrentMovingNodes(game, e, &fromI, &toI); V2f fromF = game.v2iToV2f(fromI); V2f toF = game.v2iToV2f(toI); int nodeIndex = getNodeIndex(game, e); V2f diff = (toF - fromF) / moveSpeed; V2f p = fromF + diff * nodeIndex; glPushMatrix(); glTranslatef(p.x(), p.y(), 0.0f); // TODO: Remove '+ 4'! Rotate obj files! glRotatef( Dir(fromI, toI).toInt() * 60.0f + 120.0f, 0, 0, 1); game.drawUnitModel(*u); game.drawUnitCircle(*u); glPopMatrix(); game.setCurrentMoveIndex(game.currentMoveIndex() + 1); if (game.currentMoveIndex() == game.lastMoveIndex()) { endMovement(game, e, toI); } } <|endoftext|>
<commit_before>/* $Id$ a node in a MIME tree. Copyright (C) 2002 by Klarlvdalens Datakonsult AB This code is licensed under the GPL, blah, blah, blah... */ #include <config.h> #include "partNode.h" #include <klocale.h> #include <kdebug.h> #include "kmcomposewin.h" #include "kmmimeparttree.h" /* =========================================================================== S T A R T O F T E M P O R A R Y M I M E C O D E =========================================================================== N O T E : The partNode structure will most likely be replaced by KMime. It's purpose: Speed optimization for KDE 3. (khz, 28.11.01) =========================================================================== */ void partNode::buildObjectTree( bool processSiblings ) { partNode* curNode = this; while( curNode && curNode->dwPart() ) { //dive into multipart messages while( DwMime::kTypeMultipart == curNode->type() ) { partNode* newNode = curNode->setFirstChild( new partNode( curNode->dwPart()->Body().FirstBodyPart() ) ); curNode = newNode; } // go up in the tree until reaching a node with next // (or the last top-level node) while( curNode && !( curNode->dwPart() && curNode->dwPart()->Next() ) ) { curNode = curNode->mRoot; } // we might have to leave when all children have been processed if( this == curNode && !processSiblings ) return; // store next node if( curNode && curNode->dwPart() && curNode->dwPart()->Next() ) { partNode* nextNode = new partNode( curNode->dwPart()->Next() ); curNode = curNode->setNext( nextNode ); } else curNode = 0; } } KMMsgEncryptionState partNode::overallEncryptionState() const { KMMsgEncryptionState myState = KMMsgEncryptionStateUnknown; if( mIsEncrypted ) myState = KMMsgFullyEncrypted; else { // NOTE: children are tested ONLY when parent is not encrypted if( mChild ) myState = mChild->overallEncryptionState(); else myState = KMMsgNotEncrypted; } // siblings are tested allways if( mNext ) KMMsgEncryptionState otherState = mNext->overallEncryptionState(); { switch( otherState ) { case KMMsgEncryptionStateUnknown: break; case KMMsgNotEncrypted: if( myState == KMMsgFullyEncrypted ) myState = KMMsgPartiallyEncrypted; else if( myState != KMMsgPartiallyEncrypted ) myState = KMMsgNotEncrypted; break; case KMMsgPartiallyEncrypted: myState = KMMsgPartiallyEncrypted; break; case KMMsgFullyEncrypted: if( myState != KMMsgFullyEncrypted ) myState = KMMsgPartiallyEncrypted; break; } } kdDebug(5006) << "\n\n KMMsgEncryptionState: " << myState << endl; return myState; } KMMsgSignatureState partNode::overallSignatureState() const { KMMsgSignatureState myState KMMsgSignatureState if( mIsSigned ) myState = KMMsgFullySigned; else { // children are tested ONLY when parent is not signed if( mChild ) myState = mChild->overallSignatureState(); else myState = KMMsgNotSigned; } // siblings are tested allways if( mNext ) { KMMsgSignatureState otherState = mNext->overallSignatureState(); switch( otherState ) { case KMMsgSignatureStateUnknown: break; case KMMsgNotSigned: if( myState == KMMsgFullySigned ) myState = KMMsgPartiallySigned; else if( myState != KMMsgPartiallySigned ) myState = KMMsgNotSigned; break; case KMMsgPartiallySigned: myState = KMMsgPartiallySigned; break; case KMMsgFullySigned: if( myState != KMMsgFullySigned ) myState = KMMsgPartiallySigned; break; } } kdDebug(5006) << "\n\n KMMsgSignatureState: " << myState << endl; return myState; } int partNode::nodeId() { partNode* rootNode = this; while( rootNode->mRoot ) rootNode = rootNode->mRoot; return rootNode->calcNodeIdOrFindNode( 0, this, 0, 0 ); } partNode* partNode::findId( int id ) { partNode* rootNode = this; while( rootNode->mRoot ) rootNode = rootNode->mRoot; partNode* foundNode; rootNode->calcNodeIdOrFindNode( 0, 0, id, &foundNode ); return foundNode; } int partNode::calcNodeIdOrFindNode( int oldId, const partNode* findNode, int findId, partNode** foundNode ) { // We use the same algorithm to determine the id of a node and // to find the node when id is known. int myId = oldId+1; // check for node ? if( findNode && this == findNode ) return myId; // check for id ? if( foundNode && myId == findId ) { *foundNode = this; return myId; } if( mChild ) return mChild->calcNodeIdOrFindNode( myId, findNode, findId, foundNode ); if( mNext ) return mNext->calcNodeIdOrFindNode( myId, findNode, findId, foundNode ); if( foundNode ) *foundNode = 0; return -1; } partNode* partNode::findType( int type, int subType, bool deep, bool wide ) { if( (mType != DwMime::kTypeUnknown) && ( (type == DwMime::kTypeUnknown) || (type == mType) ) && ( (subType == DwMime::kSubtypeUnknown) || (subType == mSubType) ) ) return this; else if( mChild && deep ) return mChild->findType( type, subType, deep, wide ); else if( mNext && wide ) return mNext->findType( type, subType, deep, wide ); else return 0; } partNode* partNode::findTypeNot( int type, int subType, bool deep, bool wide ) { if( (mType != DwMime::kTypeUnknown) && ( (type == DwMime::kTypeUnknown) || (type != mType) ) && ( (subType == DwMime::kSubtypeUnknown) || (subType != mSubType) ) ) return this; else if( mChild && deep ) return mChild->findTypeNot( type, subType, deep, wide ); else if( mNext && wide ) return mNext->findTypeNot( type, subType, deep, wide ); else return 0; } void partNode::fillMimePartTree( KMMimePartTreeItem* parentItem, KMMimePartTree* mimePartTree, QString labelDescr, QString labelCntType, QString labelEncoding, QString labelSize ) { if( parentItem || mimePartTree ) { if( mNext ) mNext->fillMimePartTree( parentItem, mimePartTree ); QString cntDesc, cntType, cntEnc, cntSize; if( labelDescr.isEmpty() ) { DwHeaders* headers = 0; if( mDwPart && mDwPart->hasHeaders() ) headers = &mDwPart->Headers(); if( headers && headers->HasSubject() ) cntDesc = headers->Subject().AsString().c_str(); if( headers && headers->HasContentType()) { cntType = headers->ContentType().TypeStr().c_str(); cntType += '/'; cntType += headers->ContentType().SubtypeStr().c_str(); if( 0 < headers->ContentType().Name().length() ) { if( !cntDesc.isEmpty() ) cntDesc += ", "; cntDesc = headers->ContentType().Name().c_str(); } } else cntType = "text/plain"; if( headers && headers->HasContentDescription()) { if( !cntDesc.isEmpty() ) cntDesc += ", "; cntDesc = headers->ContentDescription().AsString().c_str(); } if( cntDesc.isEmpty() ) { bool bOk = false; if( headers && headers->HasContentDisposition() ) { QCString dispo = headers->ContentDisposition().AsString().c_str(); int i = dispo.find("filename=", 0, false); if( -1 < i ) { // 123456789 QCString s = dispo.mid( i + 9 ).stripWhiteSpace(); if( '\"' == s[0]) s.remove( 0, 1 ); if( '\"' == s[s.length()-1]) s.truncate( s.length()-1 ); if( !s.isEmpty() ) { cntDesc = "file: "; cntDesc += s; bOk = true; } } } if( !bOk ) { if( mRoot && mRoot->mRoot ) cntDesc = i18n("internal part"); else cntDesc = i18n("body part"); } } if( mDwPart && mDwPart->hasHeaders() && mDwPart->Headers().HasContentTransferEncoding() ) cntEnc = mDwPart->Headers().ContentTransferEncoding().AsString().c_str(); else cntEnc = "7bit"; if( mDwPart ) cntSize = QString::number( mDwPart->Body().AsString().length() ); } else { cntDesc = labelDescr; cntType = labelCntType; cntEnc = labelEncoding; cntSize = labelSize; } cntType = KMComposeWin::prettyMimeType( cntType ); cntDesc += " "; cntType += " "; cntEnc += " "; kdDebug(5006) << " Inserting one item into MimePartTree" << endl; kdDebug(5006) << " Content-Type: " << cntType << endl; if( parentItem ) mMimePartTreeItem = new KMMimePartTreeItem( *parentItem, this, cntDesc, cntType, cntEnc, cntSize ); else if( mimePartTree ) mMimePartTreeItem = new KMMimePartTreeItem( *mimePartTree, this, cntDesc, cntType, cntEnc, cntSize ); mMimePartTreeItem->setOpen( true ); if( mChild ) mChild->fillMimePartTree( mMimePartTreeItem, 0 ); } } void partNode::adjustDefaultType( partNode* node ) { // Only bodies of 'Multipart/Digest' objects have // default type 'Message/RfC822'. All other bodies // have default type 'Text/Plain' (khz, 5.12.2001) if( node && DwMime::kTypeUnknown == node->type() ) { if( node->mRoot && DwMime::kTypeMultipart == node->mRoot->type() && DwMime::kSubtypeDigest == node->mRoot->subType() ) { node->setType( DwMime::kTypeMessage ); node->setSubType( DwMime::kSubtypeRfc822 ); } else { node->setType( DwMime::kTypeText ); node->setSubType( DwMime::kSubtypePlain ); } } } bool partNode::isAttachment() const { if (!dwPart()) return false; DwHeaders& headers = dwPart()->Headers(); if( headers.HasContentDisposition() ) return (headers.ContentDisposition().DispositionType() == DwMime::kDispTypeAttachment); else return false; } const QString& partNode::trueFromAddress() const { const partNode* node = this; while( node->mFromAddress.isEmpty() && node->mRoot ) node = node->mRoot; return node->mFromAddress; } <commit_msg>oops<commit_after>/* $Id$ a node in a MIME tree. Copyright (C) 2002 by Klarlvdalens Datakonsult AB This code is licensed under the GPL, blah, blah, blah... */ #include <config.h> #include "partNode.h" #include <klocale.h> #include <kdebug.h> #include "kmcomposewin.h" #include "kmmimeparttree.h" /* =========================================================================== S T A R T O F T E M P O R A R Y M I M E C O D E =========================================================================== N O T E : The partNode structure will most likely be replaced by KMime. It's purpose: Speed optimization for KDE 3. (khz, 28.11.01) =========================================================================== */ void partNode::buildObjectTree( bool processSiblings ) { partNode* curNode = this; while( curNode && curNode->dwPart() ) { //dive into multipart messages while( DwMime::kTypeMultipart == curNode->type() ) { partNode* newNode = curNode->setFirstChild( new partNode( curNode->dwPart()->Body().FirstBodyPart() ) ); curNode = newNode; } // go up in the tree until reaching a node with next // (or the last top-level node) while( curNode && !( curNode->dwPart() && curNode->dwPart()->Next() ) ) { curNode = curNode->mRoot; } // we might have to leave when all children have been processed if( this == curNode && !processSiblings ) return; // store next node if( curNode && curNode->dwPart() && curNode->dwPart()->Next() ) { partNode* nextNode = new partNode( curNode->dwPart()->Next() ); curNode = curNode->setNext( nextNode ); } else curNode = 0; } } KMMsgEncryptionState partNode::overallEncryptionState() const { KMMsgEncryptionState myState = KMMsgEncryptionStateUnknown; if( mIsEncrypted ) myState = KMMsgFullyEncrypted; else { // NOTE: children are tested ONLY when parent is not encrypted if( mChild ) myState = mChild->overallEncryptionState(); else myState = KMMsgNotEncrypted; } // siblings are tested allways if( mNext ) { KMMsgEncryptionState otherState = mNext->overallEncryptionState(); switch( otherState ) { case KMMsgEncryptionStateUnknown: break; case KMMsgNotEncrypted: if( myState == KMMsgFullyEncrypted ) myState = KMMsgPartiallyEncrypted; else if( myState != KMMsgPartiallyEncrypted ) myState = KMMsgNotEncrypted; break; case KMMsgPartiallyEncrypted: myState = KMMsgPartiallyEncrypted; break; case KMMsgFullyEncrypted: if( myState != KMMsgFullyEncrypted ) myState = KMMsgPartiallyEncrypted; break; } } kdDebug(5006) << "\n\n KMMsgEncryptionState: " << myState << endl; return myState; } KMMsgSignatureState partNode::overallSignatureState() const { KMMsgSignatureState myState = KMMsgSignatureState; if( mIsSigned ) myState = KMMsgFullySigned; else { // children are tested ONLY when parent is not signed if( mChild ) myState = mChild->overallSignatureState(); else myState = KMMsgNotSigned; } // siblings are tested allways if( mNext ) { KMMsgSignatureState otherState = mNext->overallSignatureState(); switch( otherState ) { case KMMsgSignatureStateUnknown: break; case KMMsgNotSigned: if( myState == KMMsgFullySigned ) myState = KMMsgPartiallySigned; else if( myState != KMMsgPartiallySigned ) myState = KMMsgNotSigned; break; case KMMsgPartiallySigned: myState = KMMsgPartiallySigned; break; case KMMsgFullySigned: if( myState != KMMsgFullySigned ) myState = KMMsgPartiallySigned; break; } } kdDebug(5006) << "\n\n KMMsgSignatureState: " << myState << endl; return myState; } int partNode::nodeId() { partNode* rootNode = this; while( rootNode->mRoot ) rootNode = rootNode->mRoot; return rootNode->calcNodeIdOrFindNode( 0, this, 0, 0 ); } partNode* partNode::findId( int id ) { partNode* rootNode = this; while( rootNode->mRoot ) rootNode = rootNode->mRoot; partNode* foundNode; rootNode->calcNodeIdOrFindNode( 0, 0, id, &foundNode ); return foundNode; } int partNode::calcNodeIdOrFindNode( int oldId, const partNode* findNode, int findId, partNode** foundNode ) { // We use the same algorithm to determine the id of a node and // to find the node when id is known. int myId = oldId+1; // check for node ? if( findNode && this == findNode ) return myId; // check for id ? if( foundNode && myId == findId ) { *foundNode = this; return myId; } if( mChild ) return mChild->calcNodeIdOrFindNode( myId, findNode, findId, foundNode ); if( mNext ) return mNext->calcNodeIdOrFindNode( myId, findNode, findId, foundNode ); if( foundNode ) *foundNode = 0; return -1; } partNode* partNode::findType( int type, int subType, bool deep, bool wide ) { if( (mType != DwMime::kTypeUnknown) && ( (type == DwMime::kTypeUnknown) || (type == mType) ) && ( (subType == DwMime::kSubtypeUnknown) || (subType == mSubType) ) ) return this; else if( mChild && deep ) return mChild->findType( type, subType, deep, wide ); else if( mNext && wide ) return mNext->findType( type, subType, deep, wide ); else return 0; } partNode* partNode::findTypeNot( int type, int subType, bool deep, bool wide ) { if( (mType != DwMime::kTypeUnknown) && ( (type == DwMime::kTypeUnknown) || (type != mType) ) && ( (subType == DwMime::kSubtypeUnknown) || (subType != mSubType) ) ) return this; else if( mChild && deep ) return mChild->findTypeNot( type, subType, deep, wide ); else if( mNext && wide ) return mNext->findTypeNot( type, subType, deep, wide ); else return 0; } void partNode::fillMimePartTree( KMMimePartTreeItem* parentItem, KMMimePartTree* mimePartTree, QString labelDescr, QString labelCntType, QString labelEncoding, QString labelSize ) { if( parentItem || mimePartTree ) { if( mNext ) mNext->fillMimePartTree( parentItem, mimePartTree ); QString cntDesc, cntType, cntEnc, cntSize; if( labelDescr.isEmpty() ) { DwHeaders* headers = 0; if( mDwPart && mDwPart->hasHeaders() ) headers = &mDwPart->Headers(); if( headers && headers->HasSubject() ) cntDesc = headers->Subject().AsString().c_str(); if( headers && headers->HasContentType()) { cntType = headers->ContentType().TypeStr().c_str(); cntType += '/'; cntType += headers->ContentType().SubtypeStr().c_str(); if( 0 < headers->ContentType().Name().length() ) { if( !cntDesc.isEmpty() ) cntDesc += ", "; cntDesc = headers->ContentType().Name().c_str(); } } else cntType = "text/plain"; if( headers && headers->HasContentDescription()) { if( !cntDesc.isEmpty() ) cntDesc += ", "; cntDesc = headers->ContentDescription().AsString().c_str(); } if( cntDesc.isEmpty() ) { bool bOk = false; if( headers && headers->HasContentDisposition() ) { QCString dispo = headers->ContentDisposition().AsString().c_str(); int i = dispo.find("filename=", 0, false); if( -1 < i ) { // 123456789 QCString s = dispo.mid( i + 9 ).stripWhiteSpace(); if( '\"' == s[0]) s.remove( 0, 1 ); if( '\"' == s[s.length()-1]) s.truncate( s.length()-1 ); if( !s.isEmpty() ) { cntDesc = "file: "; cntDesc += s; bOk = true; } } } if( !bOk ) { if( mRoot && mRoot->mRoot ) cntDesc = i18n("internal part"); else cntDesc = i18n("body part"); } } if( mDwPart && mDwPart->hasHeaders() && mDwPart->Headers().HasContentTransferEncoding() ) cntEnc = mDwPart->Headers().ContentTransferEncoding().AsString().c_str(); else cntEnc = "7bit"; if( mDwPart ) cntSize = QString::number( mDwPart->Body().AsString().length() ); } else { cntDesc = labelDescr; cntType = labelCntType; cntEnc = labelEncoding; cntSize = labelSize; } cntType = KMComposeWin::prettyMimeType( cntType ); cntDesc += " "; cntType += " "; cntEnc += " "; kdDebug(5006) << " Inserting one item into MimePartTree" << endl; kdDebug(5006) << " Content-Type: " << cntType << endl; if( parentItem ) mMimePartTreeItem = new KMMimePartTreeItem( *parentItem, this, cntDesc, cntType, cntEnc, cntSize ); else if( mimePartTree ) mMimePartTreeItem = new KMMimePartTreeItem( *mimePartTree, this, cntDesc, cntType, cntEnc, cntSize ); mMimePartTreeItem->setOpen( true ); if( mChild ) mChild->fillMimePartTree( mMimePartTreeItem, 0 ); } } void partNode::adjustDefaultType( partNode* node ) { // Only bodies of 'Multipart/Digest' objects have // default type 'Message/RfC822'. All other bodies // have default type 'Text/Plain' (khz, 5.12.2001) if( node && DwMime::kTypeUnknown == node->type() ) { if( node->mRoot && DwMime::kTypeMultipart == node->mRoot->type() && DwMime::kSubtypeDigest == node->mRoot->subType() ) { node->setType( DwMime::kTypeMessage ); node->setSubType( DwMime::kSubtypeRfc822 ); } else { node->setType( DwMime::kTypeText ); node->setSubType( DwMime::kSubtypePlain ); } } } bool partNode::isAttachment() const { if (!dwPart()) return false; DwHeaders& headers = dwPart()->Headers(); if( headers.HasContentDisposition() ) return (headers.ContentDisposition().DispositionType() == DwMime::kDispTypeAttachment); else return false; } const QString& partNode::trueFromAddress() const { const partNode* node = this; while( node->mFromAddress.isEmpty() && node->mRoot ) node = node->mRoot; return node->mFromAddress; } <|endoftext|>
<commit_before>#include <opencv2/imgcodecs/imgcodecs.hpp> #include <opencv2/core/core.hpp> #include <string> #include <iostream> const unsigned int defaultWidth = 640; const unsigned int defaultHeight = 480; void fillWithShadingGain(cv::Mat &image) { for (unsigned int y = 0; y < image.rows; y++) { for (unsigned int x = 0; x < image.cols; x++) { } } } void prepareSourceImage(int argc, char**argv, cv::Mat& image) { std::string filename; if (argc >= 2) { filename = std::string(argv[1]); } else { filename = ""; } if (filename != std::string("")) { image = cv::imread(filename, cv::IMREAD_GRAYSCALE); } else { image = cv::Mat(defaultHeight, defaultWidth, CV_8UC1); fillWithShadingGain(image); } } int main(int argc, char** argv) { cv::Mat image; return 0; } <commit_msg>prepare to prepare the gain image * make a gain image if now input file provided<commit_after>#include <opencv2/imgcodecs/imgcodecs.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <string> #include <iostream> const unsigned int defaultWidth = 640; const unsigned int defaultHeight = 480; void fillWithShadingGain(cv::Mat &image) { cv::Point2d center(image.cols/2, image.rows/2); double maxDistance = sqrt(center.x*center.x+center.y*center.y); for (int y = 0; y < image.rows; y++) { for (int x = 0; x < image.cols; x++) { double dx = center.x - x; double dy = center.y - y; double distance = sqrt(dx * dx + dy * dy); double ratio = 1.0f - (distance / maxDistance); image.data[y*image.cols+x] = (unsigned char)(255 * ratio); } } } void prepareSourceImage(int argc, char**argv, cv::Mat& image) { std::string filename; if (argc >= 2) { filename = std::string(argv[1]); } else { filename = ""; } if (filename != std::string("")) { image = cv::imread(filename, cv::IMREAD_GRAYSCALE); } else { image = cv::Mat(defaultHeight, defaultWidth, CV_8UC1); fillWithShadingGain(image); } } int main(int argc, char** argv) { cv::Mat image; prepareSourceImage(argc, argv, image); return 0; } <|endoftext|>
<commit_before>// c++ -std=c++11 converter.cpp -o converter -I/usr/local/include -L/usr/local/lib -lassimp -g -Wall #define SAVE_RIG 1 #include <iostream> #include <fstream> #include <algorithm> // pair #include <unordered_map> #include <cassert> #include <assimp/Exporter.hpp> #include <assimp/cimport.h> #include <assimp/scene.h> #include <assimp/postprocess.h> namespace { /// From my: stl.h // Behaves like the python os.path.split() function. inline std::pair< std::string, std::string > os_path_split( const std::string& path ) { const std::string::size_type split = path.find_last_of( "/" ); if( split == std::string::npos ) return std::make_pair( std::string(), path ); else { std::string::size_type split_start = split; // Remove multiple trailing slashes. while( split_start > 0 && path[ split_start-1 ] == '/' ) split_start -= 1; // Don't remove the leading slash. if( split_start == 0 ) split_start = 1; return std::make_pair( path.substr( 0, split_start ), path.substr( split+1 ) ); } } // Behaves like the python os.path.splitext() function. inline std::pair< std::string, std::string > os_path_splitext( const std::string& path ) { const std::string::size_type split_dot = path.find_last_of( "." ); const std::string::size_type split_slash = path.find_last_of( "/" ); if( split_dot != std::string::npos && (split_slash == std::string::npos || split_slash < split_dot) ) return std::make_pair( path.substr( 0, split_dot ), path.substr( split_dot ) ); else return std::make_pair( path, std::string() ); } /// From: http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c bool os_path_exists( const std::string& name ) { std::ifstream f(name.c_str()); if (f.good()) { f.close(); return true; } else { f.close(); return false; } } } void print_importers( std::ostream& out ) { out << "## Importers:\n"; aiString s; aiGetExtensionList( &s ); out << s.C_Str() << std::endl; } void print_exporters( std::ostream& out ) { out << "## Exporters:\n"; Assimp::Exporter exporter; const size_t count = exporter.GetExportFormatCount(); for( size_t i = 0; i < count; ++i ) { const aiExportFormatDesc* desc = exporter.GetExportFormatDescription( i ); assert( desc ); out << desc->fileExtension << ": " << desc->description << " (id: " << desc->id << ")" << std::endl; } } const char* IdFromExtension( const std::string& extension ) { Assimp::Exporter exporter; const size_t count = exporter.GetExportFormatCount(); for( size_t i = 0; i < count; ++i ) { const aiExportFormatDesc* desc = exporter.GetExportFormatDescription( i ); assert( desc ); if( extension == desc->fileExtension ) { std::cout << "Found a match for extension: " << extension << std::endl; std::cout << desc->fileExtension << ": " << desc->description << " (id: " << desc->id << ")" << std::endl; return desc->id; } } return nullptr; } #if SAVE_RIG void save_rig( const aiMesh* mesh ) { assert( mesh ); // Iterate over the bones of the mesh. for( int bone_index = 0; bone_index < mesh->mNumBones; ++bone_index ) { const aiBone* bone = mesh->mBones[ bone_index ]; // Save the vertex weights for the bone. // Lookup the index for the bone by its name. } } aiMatrix4x4 FilterNodeTransformation( const aiMatrix4x4& transformation ) { // return transformation; // Decompose the transformation matrix into translation, rotation, and scaling. aiVector3D scaling, translation_vector; aiQuaternion rotation; transformation.Decompose( scaling, rotation, translation_vector ); rotation.Normalize(); // Convert the translation into a matrix. aiMatrix4x4 translation_matrix; aiMatrix4x4::Translation( translation_vector, translation_matrix ); // Keep the rotation times the translation. aiMatrix4x4 keep( aiMatrix4x4( rotation.GetMatrix() ) * translation_matrix ); return keep; } typedef std::unordered_map< std::string, aiMatrix4x4 > StringToMatrix4x4; // typedef std::unordered_map< std::string, std::string > StringToString; void recurse( const aiNode* node, const aiMatrix4x4& parent_transformation, StringToMatrix4x4& name2transformation ) { assert( node ); assert( name2transformation.find( node->mName.C_Str() ) == name2transformation.end() ); aiMatrix4x4 node_transformation = FilterNodeTransformation( node->mTransformation ); // node_transformation.Transpose(); const aiMatrix4x4 transformation_so_far = parent_transformation * node_transformation; name2transformation[ node->mName.C_Str() ] = transformation_so_far; for( int child_index = 0; child_index < node->mNumChildren; ++child_index ) { recurse( node->mChildren[ child_index ], transformation_so_far, name2transformation ); } } void print( const StringToMatrix4x4& name2transformation ) { for( const auto& iter : name2transformation ) { std::cout << iter.first << ":\n"; std::cout << ' ' << iter.second.a1 << ' ' << iter.second.a2 << ' ' << iter.second.a3 << ' ' << iter.second.a4 << '\n'; std::cout << ' ' << iter.second.b1 << ' ' << iter.second.b2 << ' ' << iter.second.b3 << ' ' << iter.second.b4 << '\n'; std::cout << ' ' << iter.second.c1 << ' ' << iter.second.c2 << ' ' << iter.second.c3 << ' ' << iter.second.c4 << '\n'; std::cout << ' ' << iter.second.d1 << ' ' << iter.second.d2 << ' ' << iter.second.d3 << ' ' << iter.second.d4 << '\n'; } } void save_rig( const aiScene* scene ) { printf( "# Saving the rig.\n" ); assert( scene ); assert( scene->mRootNode ); StringToMatrix4x4 node2transformation; const aiMatrix4x4 I; recurse( scene->mRootNode, I, node2transformation ); print( node2transformation ); /// 1 Find the immediate parent of each bone // TODO: Save the bones. There should be some kind of nodes with their // names and positions. (We might also need the offsetmatrix from the bone itself). // Store a map of name to index. // See (maybe): http://ogldev.atspace.co.uk/www/tutorial38/tutorial38.html /* import pyassimp filename = '/Users/yotam/Work/ext/three.js/examples/models/collada/monster/monster.dae' scene = pyassimp.load( filename ) spaces = 0 def recurse( node ): global spaces print (' '*spaces), node.name #, node.transformation spaces += 1 for child in node.children: recurse( child ) spaces -= 1 recurse( scene.rootnode ) */ // Meshes have bones. Iterate over meshes. for( int mesh_index = 0; mesh_index < scene->mNumMeshes; ++mesh_index ) { printf( "Mesh %d\n", mesh_index ); save_rig( scene->mMeshes[ mesh_index ] ); } } #endif void usage( const char* argv0, std::ostream& out ) { out << "Usage: " << argv0 << " path/to/input path/to/output" << std::endl; out << std::endl; print_importers( out ); out << std::endl; print_exporters( out ); } int main( int argc, char* argv[] ) { /// We need three arguments: the program, the input path, and the output path. if( 3 != argc ) { usage( argv[0], std::cerr ); return -1; } /// Store the input and output paths. const char* inpath = argv[1]; const char* outpath = argv[2]; // Exit if the output path already exists. if( os_path_exists( outpath ) ) { std::cerr << "ERROR: Output path exists. Not clobbering: " << outpath << std::endl; usage( argv[0], std::cerr ); return -1; } /// Get the extension of the output path and its corresponding ASSIMP id. std::string extension = os_path_splitext( outpath ).second; // os_path_splitext.second returns an extension of the form ".obj". // We want the substring from position 1 to the end. if( extension.size() <= 1 ) { std::cerr << "ERROR: No extension detected on the output path: " << extension << std::endl; usage( argv[0], std::cerr ); return -1; } extension = extension.substr(1); const char* exportId = IdFromExtension( extension ); // Exit if we couldn't find a corresponding ASSIMP id. if( nullptr == exportId ) { std::cerr << "ERROR: Output extension unsupported: " << extension << std::endl; usage( argv[0], std::cerr ); return -1; } /// Load the scene. const aiScene* scene = aiImportFile( inpath, 0 ); if( nullptr == scene ) { std::cerr << "ERROR: " << aiGetErrorString() << std::endl; } std::cout << "Loaded: " << inpath << std::endl; /// Save the scene. const aiReturn result = aiExportScene( scene, exportId, outpath, 0 ); if( aiReturn_SUCCESS != result ) { std::cerr << "ERROR: Could not save the scene: " << ( (aiReturn_OUTOFMEMORY == result) ? "Out of memory" : "Unknown reason" ) << std::endl; } std::cout << "Saved: " << outpath << std::endl; #if SAVE_RIG /// Save the rig. save_rig( scene ); #endif // Cleanup. aiReleaseImport( scene ); return 0; } <commit_msg>I am computing an Offset Matrix that matches ASSIMPs<commit_after>// c++ -std=c++11 converter.cpp -o converter -I/usr/local/include -L/usr/local/lib -lassimp -g -Wall #define SAVE_RIG 1 #include <iostream> #include <fstream> #include <algorithm> // pair #include <unordered_map> #include <cassert> #include <assimp/Exporter.hpp> #include <assimp/cimport.h> #include <assimp/scene.h> #include <assimp/postprocess.h> namespace { /// From my: stl.h // Behaves like the python os.path.split() function. inline std::pair< std::string, std::string > os_path_split( const std::string& path ) { const std::string::size_type split = path.find_last_of( "/" ); if( split == std::string::npos ) return std::make_pair( std::string(), path ); else { std::string::size_type split_start = split; // Remove multiple trailing slashes. while( split_start > 0 && path[ split_start-1 ] == '/' ) split_start -= 1; // Don't remove the leading slash. if( split_start == 0 ) split_start = 1; return std::make_pair( path.substr( 0, split_start ), path.substr( split+1 ) ); } } // Behaves like the python os.path.splitext() function. inline std::pair< std::string, std::string > os_path_splitext( const std::string& path ) { const std::string::size_type split_dot = path.find_last_of( "." ); const std::string::size_type split_slash = path.find_last_of( "/" ); if( split_dot != std::string::npos && (split_slash == std::string::npos || split_slash < split_dot) ) return std::make_pair( path.substr( 0, split_dot ), path.substr( split_dot ) ); else return std::make_pair( path, std::string() ); } /// From: http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c bool os_path_exists( const std::string& name ) { std::ifstream f(name.c_str()); if (f.good()) { f.close(); return true; } else { f.close(); return false; } } } void print_importers( std::ostream& out ) { out << "## Importers:\n"; aiString s; aiGetExtensionList( &s ); out << s.C_Str() << std::endl; } void print_exporters( std::ostream& out ) { out << "## Exporters:\n"; Assimp::Exporter exporter; const size_t count = exporter.GetExportFormatCount(); for( size_t i = 0; i < count; ++i ) { const aiExportFormatDesc* desc = exporter.GetExportFormatDescription( i ); assert( desc ); out << desc->fileExtension << ": " << desc->description << " (id: " << desc->id << ")" << std::endl; } } const char* IdFromExtension( const std::string& extension ) { Assimp::Exporter exporter; const size_t count = exporter.GetExportFormatCount(); for( size_t i = 0; i < count; ++i ) { const aiExportFormatDesc* desc = exporter.GetExportFormatDescription( i ); assert( desc ); if( extension == desc->fileExtension ) { std::cout << "Found a match for extension: " << extension << std::endl; std::cout << desc->fileExtension << ": " << desc->description << " (id: " << desc->id << ")" << std::endl; return desc->id; } } return nullptr; } #if SAVE_RIG typedef std::unordered_map< std::string, aiMatrix4x4 > StringToMatrix4x4; void print( const aiMatrix4x4& matrix ) { std::cout << ' ' << matrix.a1 << ' ' << matrix.a2 << ' ' << matrix.a3 << ' ' << matrix.a4 << '\n'; std::cout << ' ' << matrix.b1 << ' ' << matrix.b2 << ' ' << matrix.b3 << ' ' << matrix.b4 << '\n'; std::cout << ' ' << matrix.c1 << ' ' << matrix.c2 << ' ' << matrix.c3 << ' ' << matrix.c4 << '\n'; std::cout << ' ' << matrix.d1 << ' ' << matrix.d2 << ' ' << matrix.d3 << ' ' << matrix.d4 << '\n'; } void print( const StringToMatrix4x4& name2matrix ) { for( const auto& iter : name2matrix ) { std::cout << iter.first << ":\n"; print( iter.second ); } } void save_rig( const aiMesh* mesh ) { assert( mesh ); // Iterate over the bones of the mesh. for( int bone_index = 0; bone_index < mesh->mNumBones; ++bone_index ) { const aiBone* bone = mesh->mBones[ bone_index ]; // Save the vertex weights for the bone. // Lookup the index for the bone by its name. std::cout << "bone.offset for bone.name: " << bone->mName.C_Str() << std::endl; print( bone->mOffsetMatrix ); } } aiMatrix4x4 FilterNodeTransformation( const aiMatrix4x4& transformation ) { return transformation; // Decompose the transformation matrix into translation, rotation, and scaling. aiVector3D scaling, translation_vector; aiQuaternion rotation; transformation.Decompose( scaling, rotation, translation_vector ); rotation.Normalize(); // Convert the translation into a matrix. aiMatrix4x4 translation_matrix; aiMatrix4x4::Translation( translation_vector, translation_matrix ); // Keep the rotation times the translation. aiMatrix4x4 keep( aiMatrix4x4( rotation.GetMatrix() ) * translation_matrix ); return keep; } // typedef std::unordered_map< std::string, std::string > StringToString; void recurse( const aiNode* node, const aiMatrix4x4& parent_transformation, StringToMatrix4x4& name2transformation, StringToMatrix4x4& name2offset, StringToMatrix4x4& name2offset_skelmeshbuilder ) { assert( node ); assert( name2transformation.find( node->mName.C_Str() ) == name2transformation.end() ); assert( name2offset.find( node->mName.C_Str() ) == name2offset.end() ); assert( name2offset_skelmeshbuilder.find( node->mName.C_Str() ) == name2offset_skelmeshbuilder.end() ); const std::string name( node->mName.C_Str() ); aiMatrix4x4 node_transformation = FilterNodeTransformation( node->mTransformation ); // node_transformation.Transpose(); const aiMatrix4x4 transformation_so_far = parent_transformation * node_transformation; name2transformation[ name ] = transformation_so_far; // Make a copy and invert it. That should be the offset matrix. aiMatrix4x4 offset = transformation_so_far; offset.Inverse(); name2offset[ name ] = offset; // Calculate the offset matrix the way SkeletonMeshBuilder.cpp:179--182 does. { // calculate the bone offset matrix by concatenating the inverse transformations of all parents aiMatrix4x4 offset_skelmeshbuilder = aiMatrix4x4( node->mTransformation ).Inverse(); for( aiNode* parent = node->mParent; parent != NULL; parent = parent->mParent ) { offset_skelmeshbuilder = offset_skelmeshbuilder * aiMatrix4x4( parent->mTransformation ).Inverse(); } name2offset_skelmeshbuilder[ name ] = offset_skelmeshbuilder; } for( int child_index = 0; child_index < node->mNumChildren; ++child_index ) { recurse( node->mChildren[ child_index ], transformation_so_far, name2transformation, name2offset, name2offset_skelmeshbuilder ); } } void save_rig( const aiScene* scene ) { printf( "# Saving the rig.\n" ); assert( scene ); assert( scene->mRootNode ); StringToMatrix4x4 node2transformation, node2offset, name2offset_skelmeshbuilder; const aiMatrix4x4 I; recurse( scene->mRootNode, I, node2transformation, node2offset, name2offset_skelmeshbuilder ); std::cout << "## name2transformation\n"; print( node2transformation ); std::cout << "## name2offset\n"; print( node2offset ); std::cout << "## name2offset the way SkeletonMeshBuilder does it\n"; print( name2offset_skelmeshbuilder ); /// 1 Find the immediate parent of each bone // TODO: Save the bones. There should be some kind of nodes with their // names and positions. (We might also need the offsetmatrix from the bone itself). // Store a map of name to index. // See (maybe): http://ogldev.atspace.co.uk/www/tutorial38/tutorial38.html /* import pyassimp filename = '/Users/yotam/Work/ext/three.js/examples/models/collada/monster/monster.dae' scene = pyassimp.load( filename ) spaces = 0 def recurse( node ): global spaces print (' '*spaces), node.name #, node.transformation spaces += 1 for child in node.children: recurse( child ) spaces -= 1 recurse( scene.rootnode ) */ // Meshes have bones. Iterate over meshes. for( int mesh_index = 0; mesh_index < scene->mNumMeshes; ++mesh_index ) { printf( "Mesh %d\n", mesh_index ); save_rig( scene->mMeshes[ mesh_index ] ); } } #endif void usage( const char* argv0, std::ostream& out ) { out << "Usage: " << argv0 << " path/to/input path/to/output" << std::endl; out << std::endl; print_importers( out ); out << std::endl; print_exporters( out ); } int main( int argc, char* argv[] ) { /// We need three arguments: the program, the input path, and the output path. if( 3 != argc ) { usage( argv[0], std::cerr ); return -1; } /// Store the input and output paths. const char* inpath = argv[1]; const char* outpath = argv[2]; // Exit if the output path already exists. if( os_path_exists( outpath ) ) { std::cerr << "ERROR: Output path exists. Not clobbering: " << outpath << std::endl; usage( argv[0], std::cerr ); return -1; } /// Get the extension of the output path and its corresponding ASSIMP id. std::string extension = os_path_splitext( outpath ).second; // os_path_splitext.second returns an extension of the form ".obj". // We want the substring from position 1 to the end. if( extension.size() <= 1 ) { std::cerr << "ERROR: No extension detected on the output path: " << extension << std::endl; usage( argv[0], std::cerr ); return -1; } extension = extension.substr(1); const char* exportId = IdFromExtension( extension ); // Exit if we couldn't find a corresponding ASSIMP id. if( nullptr == exportId ) { std::cerr << "ERROR: Output extension unsupported: " << extension << std::endl; usage( argv[0], std::cerr ); return -1; } /// Load the scene. const aiScene* scene = aiImportFile( inpath, 0 ); if( nullptr == scene ) { std::cerr << "ERROR: " << aiGetErrorString() << std::endl; } std::cout << "Loaded: " << inpath << std::endl; /// Save the scene. const aiReturn result = aiExportScene( scene, exportId, outpath, 0 ); if( aiReturn_SUCCESS != result ) { std::cerr << "ERROR: Could not save the scene: " << ( (aiReturn_OUTOFMEMORY == result) ? "Out of memory" : "Unknown reason" ) << std::endl; } std::cout << "Saved: " << outpath << std::endl; #if SAVE_RIG /// Save the rig. save_rig( scene ); #endif // Cleanup. aiReleaseImport( scene ); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef FILE_DESC_HH_ #define FILE_DESC_HH_ #include "sstring.hh" #include <sys/types.h> #include <unistd.h> #include <assert.h> #include <utility> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/eventfd.h> #include <sys/timerfd.h> #include <sys/socket.h> #include <sys/epoll.h> #include <sys/mman.h> #include <signal.h> #include <system_error> #include <boost/optional.hpp> #include <pthread.h> #include <memory> #include "net/api.hh" inline void throw_system_error_on(bool condition); template <typename T> inline void throw_kernel_error(T r); struct mmap_deleter { size_t _size; void operator()(void* ptr) const; }; using mmap_area = std::unique_ptr<char[], mmap_deleter>; mmap_area mmap_anonymous(void* addr, size_t length, int prot, int flags); class file_desc { int _fd; public: file_desc() = delete; file_desc(const file_desc&) = delete; file_desc(file_desc&& x) : _fd(x._fd) { x._fd = -1; } ~file_desc() { if (_fd != -1) { ::close(_fd); } } void operator=(const file_desc&) = delete; file_desc& operator=(file_desc&& x) { if (this != &x) { std::swap(_fd, x._fd); if (x._fd != -1) { x.close(); } } return *this; } void close() { assert(_fd != -1); auto r = ::close(_fd); throw_system_error_on(r == -1); _fd = -1; } int get() const { return _fd; } static file_desc open(sstring name, int flags, mode_t mode = 0) { int fd = ::open(name.c_str(), flags, mode); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc socket(int family, int type, int protocol = 0) { int fd = ::socket(family, type, protocol); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc eventfd(unsigned initval, int flags) { int fd = ::eventfd(initval, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc epoll_create(int flags = 0) { int fd = ::epoll_create1(flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc timerfd_create(int clockid, int flags) { int fd = ::timerfd_create(clockid, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc temporary(sstring directory); file_desc dup() const { int fd = ::dup(get()); throw_system_error_on(fd == -1); return file_desc(fd); } file_desc accept(sockaddr& sa, socklen_t& sl, int flags = 0) { auto ret = ::accept4(_fd, &sa, &sl, flags); throw_system_error_on(ret == -1); return file_desc(ret); } void truncate(size_t size) { auto ret = ::ftruncate(_fd, size); throw_system_error_on(ret); } int ioctl(int request) { return ioctl(request, 0); } int ioctl(int request, int value) { int r = ::ioctl(_fd, request, value); throw_system_error_on(r == -1); return r; } int ioctl(int request, unsigned int value) { int r = ::ioctl(_fd, request, value); throw_system_error_on(r == -1); return r; } template <class X> int ioctl(int request, X& data) { int r = ::ioctl(_fd, request, &data); throw_system_error_on(r == -1); return r; } template <class X> int ioctl(int request, X&& data) { int r = ::ioctl(_fd, request, &data); throw_system_error_on(r == -1); return r; } template <class X> int setsockopt(int level, int optname, X&& data) { int r = ::setsockopt(_fd, level, optname, &data, sizeof(data)); throw_system_error_on(r == -1); return r; } int setsockopt(int level, int optname, const char* data) { int r = ::setsockopt(_fd, level, optname, data, strlen(data) + 1); throw_system_error_on(r == -1); return r; } template <class X> int getsockopt(int level, int optname, X&& data) { socklen_t len = sizeof(data); int r = ::getsockopt(_fd, level, optname, &data, &len); throw_system_error_on(r == -1); return r; } int getsockopt(int level, int optname, char* data, socklen_t len) { int r = ::getsockopt(_fd, level, optname, data, &len); throw_system_error_on(r == -1); return r; } size_t size() { struct stat buf; auto r = ::fstat(_fd, &buf); throw_system_error_on(r == -1); return buf.st_size; } boost::optional<size_t> read(void* buffer, size_t len) { auto r = ::read(_fd, buffer, len); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<ssize_t> recv(void* buffer, size_t len, int flags) { auto r = ::recv(_fd, buffer, len, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { r }; } boost::optional<size_t> recvmsg(msghdr* mh, int flags) { auto r = ::recvmsg(_fd, mh, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> send(const void* buffer, size_t len, int flags) { auto r = ::send(_fd, buffer, len, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> sendto(socket_address& addr, const void* buf, size_t len, int flags) { auto r = ::sendto(_fd, buf, len, flags, &addr.u.sa, sizeof(addr.u.sas)); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> sendmsg(const msghdr* msg, int flags) { auto r = ::sendmsg(_fd, msg, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } void bind(sockaddr& sa, socklen_t sl) { auto r = ::bind(_fd, &sa, sl); throw_system_error_on(r == -1); } void connect(sockaddr& sa, socklen_t sl) { auto r = ::connect(_fd, &sa, sl); if (r == -1 && errno == EINPROGRESS) { return; } throw_system_error_on(r == -1); } socket_address get_address() { socket_address addr; auto len = (socklen_t) sizeof(addr.u.sas); auto r = ::getsockname(_fd, &addr.u.sa, &len); throw_system_error_on(r == -1); return addr; } void listen(int backlog) { auto fd = ::listen(_fd, backlog); throw_system_error_on(fd == -1); } boost::optional<size_t> write(const void* buf, size_t len) { auto r = ::write(_fd, buf, len); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> writev(const iovec *iov, int iovcnt) { auto r = ::writev(_fd, iov, iovcnt); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } void timerfd_settime(int flags, const itimerspec& its) { auto r = ::timerfd_settime(_fd, flags, &its, NULL); throw_system_error_on(r == -1); } mmap_area map(size_t size, unsigned prot, unsigned flags, size_t offset, void* addr = nullptr) { void *x = mmap(addr, size, prot, flags, _fd, offset); throw_system_error_on(x == MAP_FAILED); return mmap_area(static_cast<char*>(x), mmap_deleter{size}); } mmap_area map_shared_rw(size_t size, size_t offset) { return map(size, PROT_READ | PROT_WRITE, MAP_SHARED, offset); } mmap_area map_shared_ro(size_t size, size_t offset) { return map(size, PROT_READ, MAP_SHARED, offset); } mmap_area map_private_rw(size_t size, size_t offset) { return map(size, PROT_READ | PROT_WRITE, MAP_PRIVATE, offset); } mmap_area map_private_ro(size_t size, size_t offset) { return map(size, PROT_READ, MAP_PRIVATE, offset); } private: file_desc(int fd) : _fd(fd) {} }; class posix_thread { public: class attr; private: // must allocate, since this class is moveable std::unique_ptr<std::function<void ()>> _func; pthread_t _pthread; bool _valid = true; mmap_area _stack; private: static void* start_routine(void* arg); public: posix_thread(std::function<void ()> func); posix_thread(attr a, std::function<void ()> func); posix_thread(posix_thread&& x); ~posix_thread(); void join(); public: class attr { public: struct stack_size { size_t size = 0; }; attr() = default; template <typename... A> attr(A... a) { set(std::forward<A>(a)...); } void set() {} template <typename A, typename... Rest> void set(A a, Rest... rest) { set(std::forward<A>(a)); set(std::forward<Rest>(rest)...); } void set(stack_size ss) { _stack_size = ss; } private: stack_size _stack_size; friend class posix_thread; }; }; inline void throw_system_error_on(bool condition) { if (condition) { throw std::system_error(errno, std::system_category()); } } template <typename T> inline void throw_kernel_error(T r) { static_assert(std::is_signed<T>::value, "kernel error variables must be signed"); if (r < 0) { throw std::system_error(-r, std::system_category()); } } inline sigset_t make_sigset_mask(int signo) { sigset_t set; sigemptyset(&set); sigaddset(&set, signo); return set; } inline sigset_t make_full_sigset_mask() { sigset_t set; sigfillset(&set); return set; } inline sigset_t make_empty_sigset_mask() { sigset_t set; sigemptyset(&set); return set; } void pin_this_thread(unsigned cpu_id); #endif /* FILE_DESC_HH_ */ <commit_msg>posix: implement pread() interface<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef FILE_DESC_HH_ #define FILE_DESC_HH_ #include "sstring.hh" #include <sys/types.h> #include <unistd.h> #include <assert.h> #include <utility> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/eventfd.h> #include <sys/timerfd.h> #include <sys/socket.h> #include <sys/epoll.h> #include <sys/mman.h> #include <signal.h> #include <system_error> #include <boost/optional.hpp> #include <pthread.h> #include <memory> #include "net/api.hh" inline void throw_system_error_on(bool condition); template <typename T> inline void throw_kernel_error(T r); struct mmap_deleter { size_t _size; void operator()(void* ptr) const; }; using mmap_area = std::unique_ptr<char[], mmap_deleter>; mmap_area mmap_anonymous(void* addr, size_t length, int prot, int flags); class file_desc { int _fd; public: file_desc() = delete; file_desc(const file_desc&) = delete; file_desc(file_desc&& x) : _fd(x._fd) { x._fd = -1; } ~file_desc() { if (_fd != -1) { ::close(_fd); } } void operator=(const file_desc&) = delete; file_desc& operator=(file_desc&& x) { if (this != &x) { std::swap(_fd, x._fd); if (x._fd != -1) { x.close(); } } return *this; } void close() { assert(_fd != -1); auto r = ::close(_fd); throw_system_error_on(r == -1); _fd = -1; } int get() const { return _fd; } static file_desc open(sstring name, int flags, mode_t mode = 0) { int fd = ::open(name.c_str(), flags, mode); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc socket(int family, int type, int protocol = 0) { int fd = ::socket(family, type, protocol); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc eventfd(unsigned initval, int flags) { int fd = ::eventfd(initval, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc epoll_create(int flags = 0) { int fd = ::epoll_create1(flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc timerfd_create(int clockid, int flags) { int fd = ::timerfd_create(clockid, flags); throw_system_error_on(fd == -1); return file_desc(fd); } static file_desc temporary(sstring directory); file_desc dup() const { int fd = ::dup(get()); throw_system_error_on(fd == -1); return file_desc(fd); } file_desc accept(sockaddr& sa, socklen_t& sl, int flags = 0) { auto ret = ::accept4(_fd, &sa, &sl, flags); throw_system_error_on(ret == -1); return file_desc(ret); } void truncate(size_t size) { auto ret = ::ftruncate(_fd, size); throw_system_error_on(ret); } int ioctl(int request) { return ioctl(request, 0); } int ioctl(int request, int value) { int r = ::ioctl(_fd, request, value); throw_system_error_on(r == -1); return r; } int ioctl(int request, unsigned int value) { int r = ::ioctl(_fd, request, value); throw_system_error_on(r == -1); return r; } template <class X> int ioctl(int request, X& data) { int r = ::ioctl(_fd, request, &data); throw_system_error_on(r == -1); return r; } template <class X> int ioctl(int request, X&& data) { int r = ::ioctl(_fd, request, &data); throw_system_error_on(r == -1); return r; } template <class X> int setsockopt(int level, int optname, X&& data) { int r = ::setsockopt(_fd, level, optname, &data, sizeof(data)); throw_system_error_on(r == -1); return r; } int setsockopt(int level, int optname, const char* data) { int r = ::setsockopt(_fd, level, optname, data, strlen(data) + 1); throw_system_error_on(r == -1); return r; } template <class X> int getsockopt(int level, int optname, X&& data) { socklen_t len = sizeof(data); int r = ::getsockopt(_fd, level, optname, &data, &len); throw_system_error_on(r == -1); return r; } int getsockopt(int level, int optname, char* data, socklen_t len) { int r = ::getsockopt(_fd, level, optname, data, &len); throw_system_error_on(r == -1); return r; } size_t size() { struct stat buf; auto r = ::fstat(_fd, &buf); throw_system_error_on(r == -1); return buf.st_size; } boost::optional<size_t> read(void* buffer, size_t len) { auto r = ::read(_fd, buffer, len); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<ssize_t> recv(void* buffer, size_t len, int flags) { auto r = ::recv(_fd, buffer, len, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { r }; } boost::optional<size_t> recvmsg(msghdr* mh, int flags) { auto r = ::recvmsg(_fd, mh, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> send(const void* buffer, size_t len, int flags) { auto r = ::send(_fd, buffer, len, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> sendto(socket_address& addr, const void* buf, size_t len, int flags) { auto r = ::sendto(_fd, buf, len, flags, &addr.u.sa, sizeof(addr.u.sas)); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> sendmsg(const msghdr* msg, int flags) { auto r = ::sendmsg(_fd, msg, flags); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } void bind(sockaddr& sa, socklen_t sl) { auto r = ::bind(_fd, &sa, sl); throw_system_error_on(r == -1); } void connect(sockaddr& sa, socklen_t sl) { auto r = ::connect(_fd, &sa, sl); if (r == -1 && errno == EINPROGRESS) { return; } throw_system_error_on(r == -1); } socket_address get_address() { socket_address addr; auto len = (socklen_t) sizeof(addr.u.sas); auto r = ::getsockname(_fd, &addr.u.sa, &len); throw_system_error_on(r == -1); return addr; } void listen(int backlog) { auto fd = ::listen(_fd, backlog); throw_system_error_on(fd == -1); } boost::optional<size_t> write(const void* buf, size_t len) { auto r = ::write(_fd, buf, len); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } boost::optional<size_t> writev(const iovec *iov, int iovcnt) { auto r = ::writev(_fd, iov, iovcnt); if (r == -1 && errno == EAGAIN) { return {}; } throw_system_error_on(r == -1); return { size_t(r) }; } size_t pread(void* buf, size_t len, off_t off) { auto r = ::pread(_fd, buf, len, off); throw_system_error_on(r == -1); return size_t(r); } void timerfd_settime(int flags, const itimerspec& its) { auto r = ::timerfd_settime(_fd, flags, &its, NULL); throw_system_error_on(r == -1); } mmap_area map(size_t size, unsigned prot, unsigned flags, size_t offset, void* addr = nullptr) { void *x = mmap(addr, size, prot, flags, _fd, offset); throw_system_error_on(x == MAP_FAILED); return mmap_area(static_cast<char*>(x), mmap_deleter{size}); } mmap_area map_shared_rw(size_t size, size_t offset) { return map(size, PROT_READ | PROT_WRITE, MAP_SHARED, offset); } mmap_area map_shared_ro(size_t size, size_t offset) { return map(size, PROT_READ, MAP_SHARED, offset); } mmap_area map_private_rw(size_t size, size_t offset) { return map(size, PROT_READ | PROT_WRITE, MAP_PRIVATE, offset); } mmap_area map_private_ro(size_t size, size_t offset) { return map(size, PROT_READ, MAP_PRIVATE, offset); } private: file_desc(int fd) : _fd(fd) {} }; class posix_thread { public: class attr; private: // must allocate, since this class is moveable std::unique_ptr<std::function<void ()>> _func; pthread_t _pthread; bool _valid = true; mmap_area _stack; private: static void* start_routine(void* arg); public: posix_thread(std::function<void ()> func); posix_thread(attr a, std::function<void ()> func); posix_thread(posix_thread&& x); ~posix_thread(); void join(); public: class attr { public: struct stack_size { size_t size = 0; }; attr() = default; template <typename... A> attr(A... a) { set(std::forward<A>(a)...); } void set() {} template <typename A, typename... Rest> void set(A a, Rest... rest) { set(std::forward<A>(a)); set(std::forward<Rest>(rest)...); } void set(stack_size ss) { _stack_size = ss; } private: stack_size _stack_size; friend class posix_thread; }; }; inline void throw_system_error_on(bool condition) { if (condition) { throw std::system_error(errno, std::system_category()); } } template <typename T> inline void throw_kernel_error(T r) { static_assert(std::is_signed<T>::value, "kernel error variables must be signed"); if (r < 0) { throw std::system_error(-r, std::system_category()); } } inline sigset_t make_sigset_mask(int signo) { sigset_t set; sigemptyset(&set); sigaddset(&set, signo); return set; } inline sigset_t make_full_sigset_mask() { sigset_t set; sigfillset(&set); return set; } inline sigset_t make_empty_sigset_mask() { sigset_t set; sigemptyset(&set); return set; } void pin_this_thread(unsigned cpu_id); #endif /* FILE_DESC_HH_ */ <|endoftext|>
<commit_before>#ifndef GNR_COROUTINE_HPP # define GNR_COROUTINE_HPP # pragma once #include <cassert> #include <cstdint> #include <functional> #include <memory> #include "savestate.hpp" namespace gnr { namespace { enum : std::size_t { anon_default_stack_size = 512 * 1024 }; } template < std::size_t N = anon_default_stack_size, template <typename> class Function = std::function > class coroutine { public: enum : std::size_t { default_stack_size = anon_default_stack_size }; enum : std::size_t { stack_size = N }; enum status : std::uint8_t { INITIALIZED, RUNNING, TERMINATED }; private: statebuf env_in_; statebuf env_out_; enum status status_{TERMINATED}; std::unique_ptr<char[]> stack_; Function<void()> f_; public: explicit coroutine() : stack_(new char[stack_size]) { } template <typename F> explicit coroutine(F&& f) : coroutine() { assign(std::forward<F>(f)); } coroutine(coroutine&&) = default; coroutine& operator=(coroutine&&) = default; template <typename F> coroutine& operator=(F&& f) { assign(std::forward<F>(f)); return *this; } auto status() const noexcept { return status_; } auto is_terminated() const noexcept { return TERMINATED == status_; } template <typename F> void assign(F&& f) { f_ = [this, f = std::forward<F>(f)]() { status_ = RUNNING; f(*this); status_ = TERMINATED; yield(); }; status_ = INITIALIZED; } #if defined(__GNUC__) void yield() noexcept __attribute__ ((noinline)) #elif defined(_MSC_VER) __declspec(noinline) void yield() noexcept #else # error "unsupported compiler" #endif { #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi"); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #elif defined(__arm__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #endif #endif if (!savestate(env_out_)) { restorestate(env_in_); } // else do nothing } #if defined(__GNUC__) void resume() noexcept __attribute__ ((noinline)) #elif defined(_MSC_VER) __declspec(noinline) void resume() noexcept #else # error "unsupported compiler" #endif { #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi"); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #elif defined(__arm__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #endif #endif assert(TERMINATED != status()); if (savestate(env_in_)) { return; } else if (RUNNING == status()) { restorestate(env_out_); } else { #if defined(__GNUC__) // stack switch #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile( "movl %0, %%esp" : : "r" (stack_.get() + stack_size) ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile( "movq %0, %%rsp" : : "r" (stack_.get() + stack_size) ); #elif defined(__arm__) asm volatile( "mov sp, %0" : : "r" (stack_.get() + stack_size) ); #else #error "can't switch stack frame" #endif #elif defined(_MSC_VER) auto const p(stack_.get() + stack_size); _asm mov esp, p #else #error "can't switch stack frame" #endif f_(); } } }; } #endif // GNR_COROUTINE_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_COROUTINE_HPP # define GNR_COROUTINE_HPP # pragma once #include <cassert> #include <cstdint> #include <functional> #include <memory> #include "savestate.hpp" namespace gnr { namespace { enum : std::size_t { anon_default_stack_size = 512 * 1024 }; } template < std::size_t N = anon_default_stack_size, template <typename> class Function = std::function > class coroutine { public: enum : std::size_t { default_stack_size = anon_default_stack_size }; enum : std::size_t { stack_size = N }; enum status : std::uint8_t { INITIALIZED, RUNNING, TERMINATED }; private: statebuf env_in_; statebuf env_out_; enum status status_{TERMINATED}; std::unique_ptr<char[]> stack_; Function<void()> f_; public: explicit coroutine() : stack_(new char[stack_size]) { } template <typename F> explicit coroutine(F&& f) : coroutine() { assign(std::forward<F>(f)); } coroutine(coroutine&&) = default; coroutine& operator=(coroutine&&) = default; template <typename F> coroutine& operator=(F&& f) { assign(std::forward<F>(f)); return *this; } auto status() const noexcept { return status_; } auto is_terminated() const noexcept { return TERMINATED == status_; } template <typename F> void assign(F&& f) { f_ = [this, f = std::forward<F>(f)]() { status_ = RUNNING; f(*this); status_ = TERMINATED; yield(); }; status_ = INITIALIZED; } #if defined(__GNUC__) void yield() noexcept __attribute__ ((noinline)) #elif defined(_MSC_VER) __declspec(noinline) void yield() noexcept #else # error "unsupported compiler" #endif { #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi"); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #elif defined(__arm__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11"); #endif #endif if (!savestate(env_out_)) { restorestate(env_in_); } // else do nothing } #if defined(__GNUC__) void resume() noexcept __attribute__ ((noinline)) #elif defined(_MSC_VER) __declspec(noinline) void resume() noexcept #else # error "unsupported compiler" #endif { #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi"); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #elif defined(__arm__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11"); #endif #endif assert(TERMINATED != status()); if (savestate(env_in_)) { return; } else if (RUNNING == status()) { restorestate(env_out_); } else { #if defined(__GNUC__) // stack switch #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile( "movl %0, %%esp" : : "r" (stack_.get() + stack_size) ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile( "movq %0, %%rsp" : : "r" (stack_.get() + stack_size) ); #elif defined(__arm__) asm volatile( "mov sp, %0" : : "r" (stack_.get() + stack_size) ); #else #error "can't switch stack frame" #endif #elif defined(_MSC_VER) auto const p(stack_.get() + stack_size); _asm mov esp, p #else #error "can't switch stack frame" #endif f_(); } } }; } #endif // GNR_COROUTINE_HPP <|endoftext|>
<commit_before>/*************************************************************************** optionconvertertestcase.cpp ------------------- begin : 2004/01/20 email : mcatan@free.fr ***************************************************************************/ /*************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * * * This software is published under the terms of the Apache Software * * License version 1.1, a copy of which has been included with this * * distribution in the license.apl file. * ***************************************************************************/ #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/helpers/properties.h> #include <log4cxx/helpers/system.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define MAX 1000 class OptionConverterTestCase : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(OptionConverterTestCase); CPPUNIT_TEST(varSubstTest1); CPPUNIT_TEST(varSubstTest2); CPPUNIT_TEST(varSubstTest3); CPPUNIT_TEST(varSubstTest4); CPPUNIT_TEST(varSubstTest5); CPPUNIT_TEST_SUITE_END(); Properties props; Properties nullProperties; public: void setUp() { props.setProperty(_T("TOTO"), _T("wonderful")); props.setProperty(_T("key1"), _T("value1")); props.setProperty(_T("key2"), _T("value2")); System::setProperties(props); } void tearDown() { } void varSubstTest1() { String r; r = OptionConverter::substVars(_T("hello world."), nullProperties); //CPPUNIT_ASSERT_EQUAL(String(_T("hello world.")), r); r = OptionConverter::substVars(_T("hello ${TOTO} world."), nullProperties); //CPPUNIT_ASSERT_EQUAL(String(_T("hello wonderful world.")), r); } void varSubstTest2() { String r; r = OptionConverter::substVars(_T("Test2 ${key1} mid ${key2} end."), nullProperties); CPPUNIT_ASSERT(r == _T("Test2 value1 mid value2 end.")); } void varSubstTest3() { String r; r = OptionConverter::substVars( _T("Test3 ${unset} mid ${key1} end."), nullProperties); CPPUNIT_ASSERT(r == _T("Test3 mid value1 end.")); } void varSubstTest4() { String res; String val = _T("Test4 ${incomplete "); try { res = OptionConverter::substVars(val, nullProperties); } catch(IllegalArgumentException& e) { String errorMsg = e.getMessage(); CPPUNIT_ASSERT(errorMsg == String(_T("\""))+val + _T("\" has no closing brace. Opening brace at position 6.")); } } void varSubstTest5() { Properties props; props.setProperty(_T("p1"), _T("x1")); props.setProperty(_T("p2"), _T("${p1}")); String res = OptionConverter::substVars(_T("${p2}"), props); CPPUNIT_ASSERT(res == _T("x1")); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OptionConverterTestCase); <commit_msg>uncomment test<commit_after>/*************************************************************************** optionconvertertestcase.cpp ------------------- begin : 2004/01/20 email : mcatan@free.fr ***************************************************************************/ /*************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * * * This software is published under the terms of the Apache Software * * License version 1.1, a copy of which has been included with this * * distribution in the license.apl file. * ***************************************************************************/ #include <cppunit/TestFixture.h> #include <cppunit/extensions/HelperMacros.h> #include <log4cxx/helpers/optionconverter.h> #include <log4cxx/helpers/properties.h> #include <log4cxx/helpers/system.h> using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::spi; #define MAX 1000 class OptionConverterTestCase : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(OptionConverterTestCase); CPPUNIT_TEST(varSubstTest1); CPPUNIT_TEST(varSubstTest2); CPPUNIT_TEST(varSubstTest3); CPPUNIT_TEST(varSubstTest4); CPPUNIT_TEST(varSubstTest5); CPPUNIT_TEST_SUITE_END(); Properties props; Properties nullProperties; public: void setUp() { props.setProperty(_T("TOTO"), _T("wonderful")); props.setProperty(_T("key1"), _T("value1")); props.setProperty(_T("key2"), _T("value2")); System::setProperties(props); } void tearDown() { } void varSubstTest1() { String r; r = OptionConverter::substVars(_T("hello world."), nullProperties); CPPUNIT_ASSERT(r == _T("hello world.")); r = OptionConverter::substVars(_T("hello ${TOTO} world."), nullProperties); CPPUNIT_ASSERT(r == _T("hello wonderful world.")); } void varSubstTest2() { String r; r = OptionConverter::substVars(_T("Test2 ${key1} mid ${key2} end."), nullProperties); CPPUNIT_ASSERT(r == _T("Test2 value1 mid value2 end.")); } void varSubstTest3() { String r; r = OptionConverter::substVars( _T("Test3 ${unset} mid ${key1} end."), nullProperties); CPPUNIT_ASSERT(r == _T("Test3 mid value1 end.")); } void varSubstTest4() { String res; String val = _T("Test4 ${incomplete "); try { res = OptionConverter::substVars(val, nullProperties); } catch(IllegalArgumentException& e) { String errorMsg = e.getMessage(); CPPUNIT_ASSERT(errorMsg == String(_T("\""))+val + _T("\" has no closing brace. Opening brace at position 6.")); } } void varSubstTest5() { Properties props; props.setProperty(_T("p1"), _T("x1")); props.setProperty(_T("p2"), _T("${p1}")); String res = OptionConverter::substVars(_T("${p2}"), props); CPPUNIT_ASSERT(res == _T("x1")); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OptionConverterTestCase); <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ut_mextensionarea.h" #include "mextensionarea.h" #include "mextensionareaview.h" #include "mextensionarea_p.h" #include "mappletid_stub.h" #include "mapplication.h" #include "mappletinstancemanager_stub.h" #include "mockdatastore.h" #include "mobjectmenu_stub.h" #include "mstylesheet.h" #include <QtTest/QtTest> #include <mwidgetcreator.h> M_REGISTER_WIDGET(TestExtensionArea); //To prevent crashing MStyleSheet::~MStyleSheet() { } // TestExtensionArea class TestExtensionArea : public MExtensionArea { public: TestExtensionArea() : MExtensionArea() { } virtual ~TestExtensionArea() { } void addWidget(MWidget *widget, MDataStore &store) { MExtensionArea::addWidget(widget, store); } void removeWidget(MWidget *widget) { MExtensionArea::removeWidget(widget); } }; // The test class void Ut_MExtensionArea::init() { area = new TestExtensionArea(); gMAppletInstanceManagerStub->stubReset(); } void Ut_MExtensionArea::cleanup() { // Destroy the extension area. delete area; } void Ut_MExtensionArea::initTestCase() { // MApplications must be created manually due to theme system changes static int argc = 1; static char *app_name = (char *)"./ut_mextensionarea"; app = new MApplication(argc, &app_name); } void Ut_MExtensionArea::cleanupTestCase() { delete app; } void Ut_MExtensionArea::testAddition() { QSignalSpy spy(area->model(), SIGNAL(modified(QList<const char *>))); MWidget *widget1 = new MWidget; MockDataStore store1; MWidget *widget2 = new MWidget; MockDataStore store2; // Add one widget and ensure that the model was modified. area->addWidget(widget1, store1); QCOMPARE(spy.count(), 1); QCOMPARE(area->model()->dataStores()->keys().count(), 1); QVERIFY(area->model()->dataStores()->contains(widget1)); spy.clear(); // Add another widget. Ensure that both widgets are in the model. area->addWidget(widget2, store2); QCOMPARE(spy.count(), 1); QCOMPARE(area->model()->dataStores()->keys().count(), 2); QVERIFY(area->model()->dataStores()->contains(widget1)); QVERIFY(area->model()->dataStores()->contains(widget2)); spy.clear(); // Add the first widget again. The model should not be modified. area->addWidget(widget1, store1); QCOMPARE(spy.count(), 0); QCOMPARE(area->model()->dataStores()->keys().count(), 2); } void Ut_MExtensionArea::testRemoval() { QSignalSpy spy(area->model(), SIGNAL(modified(QList<const char *>))); MWidget *widget1 = new MWidget; MockDataStore store1; MWidget *widget2 = new MWidget; MockDataStore store2; MWidget *widget3 = new MWidget; MockDataStore store3; // Add three widgets and ensure that they're in the model. area->addWidget(widget1, store1); area->addWidget(widget2, store2); area->addWidget(widget3, store3); QCOMPARE(spy.count(), 3); QCOMPARE(area->model()->dataStores()->keys().count(), 3); QVERIFY(area->model()->dataStores()->contains(widget1)); QVERIFY(area->model()->dataStores()->contains(widget2)); QVERIFY(area->model()->dataStores()->contains(widget3)); spy.clear(); // Remove widget2 and verify that the rest are in the model. area->removeWidget(widget2); QCOMPARE(spy.count(), 1); QCOMPARE(area->model()->dataStores()->keys().count(), 2); QVERIFY(area->model()->dataStores()->contains(widget1)); QVERIFY(!area->model()->dataStores()->contains(widget2)); QVERIFY(area->model()->dataStores()->contains(widget3)); spy.clear(); // Remove widget2 again and verify that the model was not changed. area->removeWidget(widget2); QCOMPARE(spy.count(), 0); QCOMPARE(area->model()->dataStores()->keys().count(), 2); QVERIFY(area->model()->dataStores()->contains(widget1)); QVERIFY(!area->model()->dataStores()->contains(widget2)); QVERIFY(area->model()->dataStores()->contains(widget3)); spy.clear(); } QTEST_APPLESS_MAIN(Ut_MExtensionArea) <commit_msg>Changes: Fixes ut_mextensionarea abort RevBy:TrustMe , tested on device Details: Don't know how to handle 'QList*>', use qRegisterMetaType to register it.<commit_after>/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ut_mextensionarea.h" #include "mextensionarea.h" #include "mextensionareaview.h" #include "mextensionarea_p.h" #include "mappletid_stub.h" #include "mapplication.h" #include "mappletinstancemanager_stub.h" #include "mockdatastore.h" #include "mobjectmenu_stub.h" #include "mstylesheet.h" #include <QtTest/QtTest> #include <mwidgetcreator.h> M_REGISTER_WIDGET(TestExtensionArea); //To prevent crashing MStyleSheet::~MStyleSheet() { } // TestExtensionArea class TestExtensionArea : public MExtensionArea { public: TestExtensionArea() : MExtensionArea() { } virtual ~TestExtensionArea() { } void addWidget(MWidget *widget, MDataStore &store) { MExtensionArea::addWidget(widget, store); } void removeWidget(MWidget *widget) { MExtensionArea::removeWidget(widget); } }; // The test class void Ut_MExtensionArea::init() { area = new TestExtensionArea(); gMAppletInstanceManagerStub->stubReset(); } void Ut_MExtensionArea::cleanup() { // Destroy the extension area. delete area; } void Ut_MExtensionArea::initTestCase() { // MApplications must be created manually due to theme system changes static int argc = 1; static char *app_name = (char *)"./ut_mextensionarea"; app = new MApplication(argc, &app_name); } void Ut_MExtensionArea::cleanupTestCase() { delete app; } void Ut_MExtensionArea::testAddition() { qRegisterMetaType< QList<const char *> >("QList<const char *>"); QSignalSpy spy(area->model(), SIGNAL(modified(QList<const char *>))); MWidget *widget1 = new MWidget; MockDataStore store1; MWidget *widget2 = new MWidget; MockDataStore store2; // Add one widget and ensure that the model was modified. area->addWidget(widget1, store1); QCOMPARE(spy.count(), 1); QCOMPARE(area->model()->dataStores()->keys().count(), 1); QVERIFY(area->model()->dataStores()->contains(widget1)); spy.clear(); // Add another widget. Ensure that both widgets are in the model. area->addWidget(widget2, store2); QCOMPARE(spy.count(), 1); QCOMPARE(area->model()->dataStores()->keys().count(), 2); QVERIFY(area->model()->dataStores()->contains(widget1)); QVERIFY(area->model()->dataStores()->contains(widget2)); spy.clear(); // Add the first widget again. The model should not be modified. area->addWidget(widget1, store1); QCOMPARE(spy.count(), 0); QCOMPARE(area->model()->dataStores()->keys().count(), 2); } void Ut_MExtensionArea::testRemoval() { QSignalSpy spy(area->model(), SIGNAL(modified(QList<const char *>))); MWidget *widget1 = new MWidget; MockDataStore store1; MWidget *widget2 = new MWidget; MockDataStore store2; MWidget *widget3 = new MWidget; MockDataStore store3; // Add three widgets and ensure that they're in the model. area->addWidget(widget1, store1); area->addWidget(widget2, store2); area->addWidget(widget3, store3); QCOMPARE(spy.count(), 3); QCOMPARE(area->model()->dataStores()->keys().count(), 3); QVERIFY(area->model()->dataStores()->contains(widget1)); QVERIFY(area->model()->dataStores()->contains(widget2)); QVERIFY(area->model()->dataStores()->contains(widget3)); spy.clear(); // Remove widget2 and verify that the rest are in the model. area->removeWidget(widget2); QCOMPARE(spy.count(), 1); QCOMPARE(area->model()->dataStores()->keys().count(), 2); QVERIFY(area->model()->dataStores()->contains(widget1)); QVERIFY(!area->model()->dataStores()->contains(widget2)); QVERIFY(area->model()->dataStores()->contains(widget3)); spy.clear(); // Remove widget2 again and verify that the model was not changed. area->removeWidget(widget2); QCOMPARE(spy.count(), 0); QCOMPARE(area->model()->dataStores()->keys().count(), 2); QVERIFY(area->model()->dataStores()->contains(widget1)); QVERIFY(!area->model()->dataStores()->contains(widget2)); QVERIFY(area->model()->dataStores()->contains(widget3)); spy.clear(); } QTEST_APPLESS_MAIN(Ut_MExtensionArea) <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_THERMALBLOCK_HH #define DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_THERMALBLOCK_HH // system #include <vector> #include <string> // dune-common #include <dune/common/shared_ptr.hh> // dune-stuff #include <dune/stuff/function/expression.hh> #include <dune/stuff/function/interface.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/print.hh> // local #include "interface.hh" namespace Dune { namespace Detailed { namespace Solvers { namespace Stationary { namespace Linear { namespace Elliptic { namespace Model { template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class Thermalblock : public Interface < DomainFieldImp, domainDim, RangeFieldImp, rangeDim > { public: typedef DomainFieldImp DomainFieldType; static const int dimDomain = domainDim; typedef RangeFieldImp RangeFieldType; static const int dimRange = rangeDim; typedef Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > BaseType; typedef Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange > ThisType; static const std::string id; private: class Diffusion : public Dune::Stuff::Function::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > { public: typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType; typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType; Diffusion(const DomainType lowerLeft, const DomainType upperRight, const std::vector< unsigned int > numElements, const std::vector< RangeFieldType > components) : lowerLeft_(lowerLeft) , upperRight_(upperRight) , numElements_(numElements) , components_(components) { // get total number of subdomains unsigned int totalSubdomains = 1; static const unsigned int dim = numElements_.size(); for (unsigned int d = 0; d < dim; ++d) { totalSubdomains *= numElements_[d]; } assert(totalSubdomains <= components_.size() && "Please provide at least as many components as subdomains!"); } Diffusion(const Diffusion& other) : lowerLeft_(other.lowerLeft_) , upperRight_(other.upperRight_) , numElements_(other.numElements_) , components_(other.components_) { // get total number of subdomains unsigned int totalSubdomains = 1; static const unsigned int dim = numElements_.size(); for (unsigned int d = 0; d < dim; ++d) { totalSubdomains *= numElements_[d]; } assert(totalSubdomains <= components_.size() && "Please provide at least as many components as subdomains!"); } virtual void evaluate(const DomainType& x, RangeType& ret) const { // decide on the subdomain the point x belongs to std::vector< unsigned int > whichPartition; for (unsigned int d = 0; d < dim; ++d) { whichPartition.push_back(std::floor(numElements_[d]*((x[d] - lowerLeft_[d])/(upperRight_[d] - lowerLeft_[d])))); } unsigned int subdomain = 0; if (dim == 1) subdomain = whichPartition[0]; else if (dim == 2) subdomain = whichPartition[0] + whichPartition[1]*numElements_[0]; else if (dim == 3) subdomain = whichPartition[0] + whichPartition[1]*numElements_[0] + whichPartition[2]*numElements_[1]*numElements_[0]; else { std::stringstream msg; msg << "Error in " << id << ": not implemented for grid dimensions other than 1, 2 or 3!"; DUNE_THROW(Dune::NotImplemented, msg.str()); } // decide on the subdomain the point x belongs to // return the component that belongs to the subdomain of x ret = components_[subdomain]; } // virtual void evaluate(const DomainType& x, RangeType& ret) const private: const DomainType lowerLeft_; const DomainType upperRight_; const std::vector< unsigned int > numElements_; const std::vector< RangeFieldType > components_; }; // class Diffusion public: typedef typename BaseType::DiffusionType DiffusionType; typedef typename BaseType::ForceType ForceType; typedef typename BaseType::DirichletType DirichletType; Thermalblock(const Dune::Stuff::Common::ExtendedParameterTree paramTree) : diffusionOrder_(-1) , forceOrder_(-1) , dirichletOrder_(-1) { // check parametertree paramTree.assertSub("diffusion", id); paramTree.assertSub("force", id); paramTree.assertSub("dirichlet", id); paramTree.assertKey("diffusion.order", id); paramTree.assertKey("force.order", id); paramTree.assertKey("dirichlet.order", id); // build functions typedef Dune::Stuff::Function::Expression< DomainFieldType, dimDomain, RangeFieldType, dimRange > ExpressionFunctionType; force_ = Dune::shared_ptr< ForceType >(new ExpressionFunctionType(paramTree.sub("force"))); dirichlet_ = Dune::shared_ptr< DirichletType >(new ExpressionFunctionType(paramTree.sub("dirichlet"))); // build the thermalblock diffusion Dune::FieldVector< DomainFieldType, dimDomain > lowerLeft(DomainFieldType(0)); Dune::FieldVector< DomainFieldType, dimDomain > upperRight(DomainFieldType(1)); std::vector< unsigned int > numElements(dimDomain, 0); std::vector< RangeFieldType > components; Dune::Stuff::Common::ExtendedParameterTree paramTreeDiffusion = paramTree.sub("diffusion"); // get number of subdomains per direction, total number of subdomains and coordinates of lowerLeft and upperRight corners of the cube unsigned int totalSubdomains = 1; for (unsigned int d = 0; d < dimDomain; ++d) { std::string low = "lowerLeft." + std::to_string(d); std::string up = "upperRight." + std::to_string(d); std::string el = "numElements." + std::to_string(d); lowerLeft[d] = paramTreeDiffusion.get(low, 0); upperRight[d] = paramTreeDiffusion.get(up, 1); numElements[d] = paramTreeDiffusion.get(el, 0); totalSubdomains *= numElements[d]; } for (unsigned int i = 0; i < totalSubdomains; ++i) { std::string com = "component." + std::to_string(i); const RangeFieldType tmp = paramTreeDiffusion.get(com, 1.0); components.push_back(tmp); } diffusion_ = Dune::shared_ptr< DiffusionType >(new Diffusion(lowerLeft, upperRight, numElements, components)); // set orders diffusionOrder_ = paramTree.sub("diffusion").get("order", -1); forceOrder_ = paramTree.sub("force").get("order", -1); dirichletOrder_ = paramTree.sub("dirichlet").get("order", -1); } Thermalblock(const ThisType& other) : diffusionOrder_(other.diffusionOrder_) , forceOrder_(other.forceOrder_) , dirichletOrder_(other.dirichletOrder_) , diffusion_(other.diffusion_) , force_(other.force_) , dirichlet_(other.dirichlet_) {} virtual const Dune::shared_ptr< const DiffusionType > diffusion() const { return diffusion_; } virtual int diffusionOrder() const { return diffusionOrder_; } virtual const Dune::shared_ptr< const ForceType > force() const { return force_; } virtual int forceOrder() const { return forceOrder_; } virtual const Dune::shared_ptr< const DirichletType > dirichlet() const { return dirichlet_; } virtual int dirichletOrder() const { return dirichletOrder_; } private: ThisType& operator=(const ThisType&); int diffusionOrder_; int forceOrder_; int dirichletOrder_; Dune::shared_ptr< DiffusionType > diffusion_; Dune::shared_ptr< ForceType > force_; Dune::shared_ptr< DirichletType > dirichlet_; }; // class Thermalblock template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange > const std::string Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange >::id = "detailed.solvers.stationary.linear.elliptic.model.thermalblock"; } // namespace Model } // namespace Elliptic } // namespace Linear } // namespace Stationary } // namespace Solvers } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_THERMALBLOCK_HH <commit_msg>[...elliptic.model.thermalblock] fixed minor problem<commit_after>#ifndef DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_THERMALBLOCK_HH #define DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_THERMALBLOCK_HH // system #include <vector> #include <string> // dune-common #include <dune/common/shared_ptr.hh> // dune-stuff #include <dune/stuff/function/expression.hh> #include <dune/stuff/function/interface.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/print.hh> // local #include "interface.hh" namespace Dune { namespace Detailed { namespace Solvers { namespace Stationary { namespace Linear { namespace Elliptic { namespace Model { template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class Thermalblock : public Interface < DomainFieldImp, domainDim, RangeFieldImp, rangeDim > { public: typedef DomainFieldImp DomainFieldType; static const int dimDomain = domainDim; typedef RangeFieldImp RangeFieldType; static const int dimRange = rangeDim; typedef Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > BaseType; typedef Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange > ThisType; static const std::string id; private: class Diffusion : public Dune::Stuff::Function::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > { public: typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType; typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType; Diffusion(const DomainType lowerLeft, const DomainType upperRight, const std::vector< unsigned int > numElements, const std::vector< RangeFieldType > components) : lowerLeft_(lowerLeft) , upperRight_(upperRight) , numElements_(numElements) , components_(components) { // get total number of subdomains unsigned int totalSubdomains = 1; static const unsigned int dim = numElements_.size(); for (unsigned int d = 0; d < dim; ++d) { totalSubdomains *= numElements_[d]; } assert(totalSubdomains <= components_.size() && "Please provide at least as many components as subdomains!"); } Diffusion(const Diffusion& other) : lowerLeft_(other.lowerLeft_) , upperRight_(other.upperRight_) , numElements_(other.numElements_) , components_(other.components_) { // get total number of subdomains unsigned int totalSubdomains = 1; static const unsigned int dim = numElements_.size(); for (unsigned int d = 0; d < dim; ++d) { totalSubdomains *= numElements_[d]; } assert(totalSubdomains <= components_.size() && "Please provide at least as many components as subdomains!"); } virtual void evaluate(const DomainType& x, RangeType& ret) const { // decide on the subdomain the point x belongs to std::vector< unsigned int > whichPartition; for (unsigned int d = 0; d < dimDomain; ++d) { whichPartition.push_back(std::floor(numElements_[d]*((x[d] - lowerLeft_[d])/(upperRight_[d] - lowerLeft_[d])))); } unsigned int subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1]*numElements_[0]; else if (dimDomain == 3) subdomain = whichPartition[0] + whichPartition[1]*numElements_[0] + whichPartition[2]*numElements_[1]*numElements_[0]; else { std::stringstream msg; msg << "Error in " << id << ": not implemented for grid dimensions other than 1, 2 or 3!"; DUNE_THROW(Dune::NotImplemented, msg.str()); } // decide on the subdomain the point x belongs to // return the component that belongs to the subdomain of x ret = components_[subdomain]; } // virtual void evaluate(const DomainType& x, RangeType& ret) const private: const DomainType lowerLeft_; const DomainType upperRight_; const std::vector< unsigned int > numElements_; const std::vector< RangeFieldType > components_; }; // class Diffusion public: typedef typename BaseType::DiffusionType DiffusionType; typedef typename BaseType::ForceType ForceType; typedef typename BaseType::DirichletType DirichletType; Thermalblock(const Dune::Stuff::Common::ExtendedParameterTree paramTree) : diffusionOrder_(-1) , forceOrder_(-1) , dirichletOrder_(-1) { // check parametertree paramTree.assertSub("diffusion", id); paramTree.assertSub("force", id); paramTree.assertSub("dirichlet", id); paramTree.assertKey("diffusion.order", id); paramTree.assertKey("force.order", id); paramTree.assertKey("dirichlet.order", id); // build functions typedef Dune::Stuff::Function::Expression< DomainFieldType, dimDomain, RangeFieldType, dimRange > ExpressionFunctionType; force_ = Dune::shared_ptr< ForceType >(new ExpressionFunctionType(paramTree.sub("force"))); dirichlet_ = Dune::shared_ptr< DirichletType >(new ExpressionFunctionType(paramTree.sub("dirichlet"))); // build the thermalblock diffusion Dune::FieldVector< DomainFieldType, dimDomain > lowerLeft(DomainFieldType(0)); Dune::FieldVector< DomainFieldType, dimDomain > upperRight(DomainFieldType(1)); std::vector< unsigned int > numElements(dimDomain, 0); std::vector< RangeFieldType > components; Dune::Stuff::Common::ExtendedParameterTree paramTreeDiffusion = paramTree.sub("diffusion"); // get number of subdomains per direction, total number of subdomains and coordinates of lowerLeft and upperRight corners of the cube unsigned int totalSubdomains = 1; for (unsigned int d = 0; d < dimDomain; ++d) { std::string low = "lowerLeft." + std::to_string(d); std::string up = "upperRight." + std::to_string(d); std::string el = "numElements." + std::to_string(d); lowerLeft[d] = paramTreeDiffusion.get(low, 0); upperRight[d] = paramTreeDiffusion.get(up, 1); numElements[d] = paramTreeDiffusion.get(el, 0); totalSubdomains *= numElements[d]; } for (unsigned int i = 0; i < totalSubdomains; ++i) { std::string com = "component." + std::to_string(i); const RangeFieldType tmp = paramTreeDiffusion.get(com, 1.0); components.push_back(tmp); } diffusion_ = Dune::shared_ptr< DiffusionType >(new Diffusion(lowerLeft, upperRight, numElements, components)); // set orders diffusionOrder_ = paramTree.sub("diffusion").get("order", -1); forceOrder_ = paramTree.sub("force").get("order", -1); dirichletOrder_ = paramTree.sub("dirichlet").get("order", -1); } Thermalblock(const ThisType& other) : diffusionOrder_(other.diffusionOrder_) , forceOrder_(other.forceOrder_) , dirichletOrder_(other.dirichletOrder_) , diffusion_(other.diffusion_) , force_(other.force_) , dirichlet_(other.dirichlet_) {} virtual const Dune::shared_ptr< const DiffusionType > diffusion() const { return diffusion_; } virtual int diffusionOrder() const { return diffusionOrder_; } virtual const Dune::shared_ptr< const ForceType > force() const { return force_; } virtual int forceOrder() const { return forceOrder_; } virtual const Dune::shared_ptr< const DirichletType > dirichlet() const { return dirichlet_; } virtual int dirichletOrder() const { return dirichletOrder_; } private: ThisType& operator=(const ThisType&); int diffusionOrder_; int forceOrder_; int dirichletOrder_; Dune::shared_ptr< DiffusionType > diffusion_; Dune::shared_ptr< ForceType > force_; Dune::shared_ptr< DirichletType > dirichlet_; }; // class Thermalblock template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange > const std::string Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange >::id = "detailed.solvers.stationary.linear.elliptic.model.thermalblock"; } // namespace Model } // namespace Elliptic } // namespace Linear } // namespace Stationary } // namespace Solvers } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_THERMALBLOCK_HH <|endoftext|>
<commit_before>#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; constexpr bool debug = true; using UInt = unsigned int; template <typename Container> void printContainer(const Container& c, const string& name) { cout << "Printing container - " << name << " of size = " << c.size() << " : ["; for (auto i = 0; i < c.size()-1; ++i) { cout << c[i] << ","; } cout << c[c.size()-1] << "]" << endl; } UInt findChange(UInt change, const vector<UInt>& coins) { } int main() { auto change = static_cast<UInt>(0); cin >> change; auto nCoins = static_cast<UInt>(0); cin >> nCoins; vector<UInt> coins; for (auto i = 0; i < nCoins; ++i) { auto coin = static_cast<UInt>(0); cin >> coin; coins.push_back(coin); } if (debug) printContainer(coins, "coins"); sort(coins.begin(), coins.end()); auto nChange = findChange(change, coins); cout << nChange << endl; return 0; }<commit_msg>first try at coin change<commit_after>#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; constexpr bool debug = true; using UInt = unsigned int; template <typename Container> void printContainer(const Container& c, const string& name) { cout << "Printing container - " << name << " of size = " << c.size() << " : ["; for (auto i = 0; i < c.size()-1; ++i) { cout << c[i] << ","; } cout << c[c.size()-1] << "]" << endl; } void findChange(UInt change, const vector<UInt>& coins, UInt& solutions) { if (change != 0) { for (auto coin : coins) { if (debug) { cout << "found " << solutions << " solutions and remaining change is = " << change << endl; } if (change > coin) { findChange(change - coin, coins, solutions); } else if (change - coin == 0) { ++solutions; } } } } int main() { auto change = static_cast<UInt>(0); cin >> change; auto nCoins = static_cast<UInt>(0); cin >> nCoins; vector<UInt> coins; for (auto i = 0; i < nCoins; ++i) { auto coin = static_cast<UInt>(0); cin >> coin; coins.push_back(coin); } sort(coins.begin(), coins.end()); if (debug) printContainer(coins, "coins (sorted)"); UInt solutions; findChange(change, coins, solutions); cout << solutions << endl; return 0; }<|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- dialogs/certificateselectiondialog.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "certificateselectiondialog.h" #include <view/searchbar.h> #include <view/tabwidget.h> #include <models/keylistmodel.h> #include <models/keycache.h> #include <commands/reloadkeyscommand.h> #include <gpgme++/key.h> #include <KLocale> #include <KConfigGroup> #include <KSharedConfig> #include <KDebug> #include <QLabel> #include <QPushButton> #include <QDialogButtonBox> #include <QLayout> #include <QItemSelectionModel> #include <QAbstractItemView> #include <QPointer> #include <boost/bind.hpp> #include <algorithm> using namespace Kleo; using namespace Kleo::Dialogs; using namespace boost; using namespace GpgME; class CertificateSelectionDialog::Private { friend class ::Kleo::Dialogs::CertificateSelectionDialog; CertificateSelectionDialog * const q; public: explicit Private( CertificateSelectionDialog * qq ); private: void reload(); void slotReloaded(); void slotCurrentViewChanged( QAbstractItemView * newView ); void slotSelectionChanged(); void slotDoubleClicked( const QModelIndex & idx ); private: bool acceptable( const std::vector<Key> & keys ) { return !keys.empty(); } void filterAllowedKeys( std::vector<Key> & keys ); void updateLabelText() { ui.label.setText( !customLabelText.isEmpty() ? customLabelText : (options & MultiSelection) ? i18n( "Please select one or more of the following certificates:" ) : i18n( "Please select one of the following certificates:" ) ); } private: QPointer<QAbstractItemView> lastView; QString customLabelText; Options options; struct UI { QLabel label; SearchBar searchBar; TabWidget tabWidget; QDialogButtonBox buttonBox; QVBoxLayout vlay; explicit UI( CertificateSelectionDialog * q ) : label( q ), searchBar( q ), tabWidget( q ), buttonBox( q ), vlay( q ) { KDAB_SET_OBJECT_NAME( label ); KDAB_SET_OBJECT_NAME( searchBar ); KDAB_SET_OBJECT_NAME( tabWidget ); KDAB_SET_OBJECT_NAME( buttonBox ); KDAB_SET_OBJECT_NAME( vlay ); vlay.addWidget( &label ); vlay.addWidget( &searchBar ); vlay.addWidget( &tabWidget, 1 ); vlay.addWidget( &buttonBox ); QPushButton * const ok = buttonBox.addButton( QDialogButtonBox::Ok ); ok->setEnabled( false ); QPushButton * const cancel = buttonBox.addButton( QDialogButtonBox::Close ); QPushButton * const reload = buttonBox.addButton( i18n("&Reload Certificates"), QDialogButtonBox::ActionRole ); connect( &buttonBox, SIGNAL(accepted()), q, SLOT(accept()) ); connect( &buttonBox, SIGNAL(rejected()), q, SLOT(reject()) ); connect( reload, SIGNAL(clicked()), q, SLOT(reload()) ); } } ui; }; CertificateSelectionDialog::Private::Private( CertificateSelectionDialog * qq ) : q( qq ), ui( q ) { ui.tabWidget.setFlatModel( AbstractKeyListModel::createFlatKeyListModel() ); ui.tabWidget.setHierarchicalModel( AbstractKeyListModel::createHierarchicalKeyListModel() ); ui.tabWidget.connectSearchBar( &ui.searchBar ); connect( &ui.tabWidget, SIGNAL(currentViewChanged(QAbstractItemView*)), q, SLOT(slotCurrentViewChanged(QAbstractItemView*)) ); updateLabelText(); q->setWindowTitle( i18n( "Certificate Selection" ) ); } CertificateSelectionDialog::CertificateSelectionDialog( QWidget * parent, Qt::WindowFlags f ) : QDialog( parent, f ), d( new Private( this ) ) { const KSharedConfig::Ptr config = KSharedConfig::openConfig( "kleopatracertificateselectiondialogrc" ); d->ui.tabWidget.loadViews( config.data() ); const KConfigGroup geometry( config, "Geometry" ); resize( geometry.readEntry( "size", size() ) ); d->slotReloaded(); } CertificateSelectionDialog::~CertificateSelectionDialog() {} void CertificateSelectionDialog::setCustomLabelText( const QString & txt ) { if ( txt == d->customLabelText ) return; d->customLabelText = txt; d->updateLabelText(); } QString CertificateSelectionDialog::customLabelText() const { return d->customLabelText; } void CertificateSelectionDialog::setOptions( Options options ) { if ( d->options == options ) return; d->options = options; d->ui.tabWidget.setMultiSelection( options & MultiSelection ); d->slotReloaded(); } CertificateSelectionDialog::Options CertificateSelectionDialog::options() const { return d->options; } void CertificateSelectionDialog::setStringFilter( const QString & filter ) { d->ui.tabWidget.setStringFilter( filter ); } void CertificateSelectionDialog::setKeyFilter( const shared_ptr<KeyFilter> & filter ) { d->ui.tabWidget.setKeyFilter( filter ); } void CertificateSelectionDialog::selectCertificates( const std::vector<Key> & keys ) { const QAbstractItemView * const view = d->ui.tabWidget.currentView(); if ( !view ) return; const KeyListModelInterface * const model = dynamic_cast<KeyListModelInterface*>( view->model() ); assert( model ); QItemSelectionModel * const sm = view->selectionModel(); assert( sm ); Q_FOREACH( const QModelIndex & idx, model->indexes( keys ) ) if ( idx.isValid() ) sm->select( idx, QItemSelectionModel::Select | QItemSelectionModel::Rows ); } void CertificateSelectionDialog::selectCertificate( const Key & key ) { selectCertificates( std::vector<Key>( 1, key ) ); } std::vector<Key> CertificateSelectionDialog::selectedCertificates() const { const QAbstractItemView * const view = d->ui.tabWidget.currentView(); if ( !view ) return std::vector<Key>(); const KeyListModelInterface * const model = dynamic_cast<KeyListModelInterface*>( view->model() ); assert( model ); const QItemSelectionModel * const sm = view->selectionModel(); assert( sm ); return model->keys( sm->selectedRows() ); } Key CertificateSelectionDialog::selectedCertificate() const { const std::vector<Key> keys = selectedCertificates(); return keys.empty() ? Key() : keys.front() ; } void CertificateSelectionDialog::hideEvent( QHideEvent * e ) { KSharedConfig::Ptr config = KSharedConfig::openConfig( "kleopatracertificateselectiondialogrc" ); d->ui.tabWidget.saveViews( config.data() ); KConfigGroup geometry( config, "Geometry" ); geometry.writeEntry( "size", size() ); QDialog::hideEvent( e ); } void CertificateSelectionDialog::Private::reload() { Command * const cmd = new ReloadKeysCommand( 0 ); connect( cmd, SIGNAL(finsihed()), q, SLOT(slotReloaded()) ); cmd->start(); } void CertificateSelectionDialog::Private::slotReloaded() { q->setEnabled( true ); std::vector<Key> keys = (options & SecretKeys) ? KeyCache::instance()->secretKeys() : KeyCache::instance()->keys() ; filterAllowedKeys( keys ); const std::vector<Key> selected = q->selectedCertificates(); if ( AbstractKeyListModel * const model = ui.tabWidget.flatModel() ) model->addKeys( keys ); if ( AbstractKeyListModel * const model = ui.tabWidget.hierarchicalModel() ) model->addKeys( keys ); q->selectCertificates( selected ); } void CertificateSelectionDialog::Private::filterAllowedKeys( std::vector<Key> & keys ) { std::vector<Key>::iterator end = keys.end(); switch ( options & AnyFormat ) { case OpenPGPFormat: end = std::remove_if( keys.begin(), end, bind( &Key::protocol, _1 ) != GpgME::OpenPGP ); break; case CMSFormat: end = std::remove_if( keys.begin(), end, bind( &Key::protocol, _1 ) != GpgME::CMS ); break; default: case AnyFormat: ; } switch ( options & AnyCertificate ) { case SignOnly: end = std::remove_if( keys.begin(), end, !bind( &Key::canSign, _1 ) ); break; case EncryptOnly: end = std::remove_if( keys.begin(), end, !bind( &Key::canEncrypt, _1 ) ); break; default: case AnyCertificate: ; } if ( options & SecretKeys ) end = std::remove_if( keys.begin(), end, !bind( &Key::hasSecret, _1 ) ); keys.erase( end, keys.end() ); } void CertificateSelectionDialog::Private::slotCurrentViewChanged( QAbstractItemView * newView ) { if ( lastView ) { disconnect( lastView, SIGNAL(doubleClicked(QModelIndex)), q, SLOT(slotDoubleClicked(QModelIndex)) ); assert( lastView->selectionModel() ); disconnect( lastView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SLOT(slotSelectionChanged()) ); } lastView = newView; if ( newView ) { connect( newView, SIGNAL(doubleClicked(QModelIndex)), q, SLOT(slotDoubleClicked(QModelIndex)) ); assert( newView->selectionModel() ); connect( newView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SLOT(slotSelectionChanged()) ); } slotSelectionChanged(); } void CertificateSelectionDialog::Private::slotSelectionChanged() { if ( QPushButton * const pb = ui.buttonBox.button( QDialogButtonBox::Ok ) ) pb->setEnabled( acceptable( q->selectedCertificates() ) ); } void CertificateSelectionDialog::Private::slotDoubleClicked( const QModelIndex & idx ) { QAbstractItemView * const view = ui.tabWidget.currentView(); assert( view ); const KeyListModelInterface * const model = dynamic_cast<KeyListModelInterface*>( view->model() ); assert( model ); QItemSelectionModel * const sm = view->selectionModel(); assert( sm ); sm->select( idx, QItemSelectionModel::ClearAndSelect ); QMetaObject::invokeMethod( q, "accept", Qt::QueuedConnection ); } void CertificateSelectionDialog::accept() { if ( d->acceptable( selectedCertificates() ) ) QDialog::accept(); } #include "moc_certificateselectiondialog.cpp" <commit_msg>Fix leave-on-doubleclick<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- dialogs/certificateselectiondialog.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "certificateselectiondialog.h" #include <view/searchbar.h> #include <view/tabwidget.h> #include <models/keylistmodel.h> #include <models/keycache.h> #include <commands/reloadkeyscommand.h> #include <gpgme++/key.h> #include <KLocale> #include <KConfigGroup> #include <KSharedConfig> #include <KDebug> #include <QLabel> #include <QPushButton> #include <QDialogButtonBox> #include <QLayout> #include <QItemSelectionModel> #include <QAbstractItemView> #include <QPointer> #include <boost/bind.hpp> #include <algorithm> using namespace Kleo; using namespace Kleo::Dialogs; using namespace boost; using namespace GpgME; class CertificateSelectionDialog::Private { friend class ::Kleo::Dialogs::CertificateSelectionDialog; CertificateSelectionDialog * const q; public: explicit Private( CertificateSelectionDialog * qq ); private: void reload(); void slotReloaded(); void slotCurrentViewChanged( QAbstractItemView * newView ); void slotSelectionChanged(); void slotDoubleClicked( const QModelIndex & idx ); private: bool acceptable( const std::vector<Key> & keys ) { return !keys.empty(); } void filterAllowedKeys( std::vector<Key> & keys ); void updateLabelText() { ui.label.setText( !customLabelText.isEmpty() ? customLabelText : (options & MultiSelection) ? i18n( "Please select one or more of the following certificates:" ) : i18n( "Please select one of the following certificates:" ) ); } private: QPointer<QAbstractItemView> lastView; QString customLabelText; Options options; struct UI { QLabel label; SearchBar searchBar; TabWidget tabWidget; QDialogButtonBox buttonBox; QVBoxLayout vlay; explicit UI( CertificateSelectionDialog * q ) : label( q ), searchBar( q ), tabWidget( q ), buttonBox( q ), vlay( q ) { KDAB_SET_OBJECT_NAME( label ); KDAB_SET_OBJECT_NAME( searchBar ); KDAB_SET_OBJECT_NAME( tabWidget ); KDAB_SET_OBJECT_NAME( buttonBox ); KDAB_SET_OBJECT_NAME( vlay ); vlay.addWidget( &label ); vlay.addWidget( &searchBar ); vlay.addWidget( &tabWidget, 1 ); vlay.addWidget( &buttonBox ); QPushButton * const ok = buttonBox.addButton( QDialogButtonBox::Ok ); ok->setEnabled( false ); QPushButton * const cancel = buttonBox.addButton( QDialogButtonBox::Close ); QPushButton * const reload = buttonBox.addButton( i18n("&Reload Certificates"), QDialogButtonBox::ActionRole ); connect( &buttonBox, SIGNAL(accepted()), q, SLOT(accept()) ); connect( &buttonBox, SIGNAL(rejected()), q, SLOT(reject()) ); connect( reload, SIGNAL(clicked()), q, SLOT(reload()) ); } } ui; }; CertificateSelectionDialog::Private::Private( CertificateSelectionDialog * qq ) : q( qq ), ui( q ) { ui.tabWidget.setFlatModel( AbstractKeyListModel::createFlatKeyListModel() ); ui.tabWidget.setHierarchicalModel( AbstractKeyListModel::createHierarchicalKeyListModel() ); ui.tabWidget.connectSearchBar( &ui.searchBar ); connect( &ui.tabWidget, SIGNAL(currentViewChanged(QAbstractItemView*)), q, SLOT(slotCurrentViewChanged(QAbstractItemView*)) ); updateLabelText(); q->setWindowTitle( i18n( "Certificate Selection" ) ); } CertificateSelectionDialog::CertificateSelectionDialog( QWidget * parent, Qt::WindowFlags f ) : QDialog( parent, f ), d( new Private( this ) ) { const KSharedConfig::Ptr config = KSharedConfig::openConfig( "kleopatracertificateselectiondialogrc" ); d->ui.tabWidget.loadViews( config.data() ); const KConfigGroup geometry( config, "Geometry" ); resize( geometry.readEntry( "size", size() ) ); d->slotReloaded(); } CertificateSelectionDialog::~CertificateSelectionDialog() {} void CertificateSelectionDialog::setCustomLabelText( const QString & txt ) { if ( txt == d->customLabelText ) return; d->customLabelText = txt; d->updateLabelText(); } QString CertificateSelectionDialog::customLabelText() const { return d->customLabelText; } void CertificateSelectionDialog::setOptions( Options options ) { if ( d->options == options ) return; d->options = options; d->ui.tabWidget.setMultiSelection( options & MultiSelection ); d->slotReloaded(); } CertificateSelectionDialog::Options CertificateSelectionDialog::options() const { return d->options; } void CertificateSelectionDialog::setStringFilter( const QString & filter ) { d->ui.tabWidget.setStringFilter( filter ); } void CertificateSelectionDialog::setKeyFilter( const shared_ptr<KeyFilter> & filter ) { d->ui.tabWidget.setKeyFilter( filter ); } void CertificateSelectionDialog::selectCertificates( const std::vector<Key> & keys ) { const QAbstractItemView * const view = d->ui.tabWidget.currentView(); if ( !view ) return; const KeyListModelInterface * const model = dynamic_cast<KeyListModelInterface*>( view->model() ); assert( model ); QItemSelectionModel * const sm = view->selectionModel(); assert( sm ); Q_FOREACH( const QModelIndex & idx, model->indexes( keys ) ) if ( idx.isValid() ) sm->select( idx, QItemSelectionModel::Select | QItemSelectionModel::Rows ); } void CertificateSelectionDialog::selectCertificate( const Key & key ) { selectCertificates( std::vector<Key>( 1, key ) ); } std::vector<Key> CertificateSelectionDialog::selectedCertificates() const { const QAbstractItemView * const view = d->ui.tabWidget.currentView(); if ( !view ) return std::vector<Key>(); const KeyListModelInterface * const model = dynamic_cast<KeyListModelInterface*>( view->model() ); assert( model ); const QItemSelectionModel * const sm = view->selectionModel(); assert( sm ); return model->keys( sm->selectedRows() ); } Key CertificateSelectionDialog::selectedCertificate() const { const std::vector<Key> keys = selectedCertificates(); return keys.empty() ? Key() : keys.front() ; } void CertificateSelectionDialog::hideEvent( QHideEvent * e ) { KSharedConfig::Ptr config = KSharedConfig::openConfig( "kleopatracertificateselectiondialogrc" ); d->ui.tabWidget.saveViews( config.data() ); KConfigGroup geometry( config, "Geometry" ); geometry.writeEntry( "size", size() ); QDialog::hideEvent( e ); } void CertificateSelectionDialog::Private::reload() { Command * const cmd = new ReloadKeysCommand( 0 ); connect( cmd, SIGNAL(finsihed()), q, SLOT(slotReloaded()) ); cmd->start(); } void CertificateSelectionDialog::Private::slotReloaded() { q->setEnabled( true ); std::vector<Key> keys = (options & SecretKeys) ? KeyCache::instance()->secretKeys() : KeyCache::instance()->keys() ; filterAllowedKeys( keys ); const std::vector<Key> selected = q->selectedCertificates(); if ( AbstractKeyListModel * const model = ui.tabWidget.flatModel() ) model->addKeys( keys ); if ( AbstractKeyListModel * const model = ui.tabWidget.hierarchicalModel() ) model->addKeys( keys ); q->selectCertificates( selected ); } void CertificateSelectionDialog::Private::filterAllowedKeys( std::vector<Key> & keys ) { std::vector<Key>::iterator end = keys.end(); switch ( options & AnyFormat ) { case OpenPGPFormat: end = std::remove_if( keys.begin(), end, bind( &Key::protocol, _1 ) != GpgME::OpenPGP ); break; case CMSFormat: end = std::remove_if( keys.begin(), end, bind( &Key::protocol, _1 ) != GpgME::CMS ); break; default: case AnyFormat: ; } switch ( options & AnyCertificate ) { case SignOnly: end = std::remove_if( keys.begin(), end, !bind( &Key::canSign, _1 ) ); break; case EncryptOnly: end = std::remove_if( keys.begin(), end, !bind( &Key::canEncrypt, _1 ) ); break; default: case AnyCertificate: ; } if ( options & SecretKeys ) end = std::remove_if( keys.begin(), end, !bind( &Key::hasSecret, _1 ) ); keys.erase( end, keys.end() ); } void CertificateSelectionDialog::Private::slotCurrentViewChanged( QAbstractItemView * newView ) { if ( lastView ) { disconnect( lastView, SIGNAL(doubleClicked(QModelIndex)), q, SLOT(slotDoubleClicked(QModelIndex)) ); assert( lastView->selectionModel() ); disconnect( lastView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SLOT(slotSelectionChanged()) ); } lastView = newView; if ( newView ) { connect( newView, SIGNAL(doubleClicked(QModelIndex)), q, SLOT(slotDoubleClicked(QModelIndex)) ); assert( newView->selectionModel() ); connect( newView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SLOT(slotSelectionChanged()) ); } slotSelectionChanged(); } void CertificateSelectionDialog::Private::slotSelectionChanged() { if ( QPushButton * const pb = ui.buttonBox.button( QDialogButtonBox::Ok ) ) pb->setEnabled( acceptable( q->selectedCertificates() ) ); } void CertificateSelectionDialog::Private::slotDoubleClicked( const QModelIndex & idx ) { QAbstractItemView * const view = ui.tabWidget.currentView(); assert( view ); const KeyListModelInterface * const model = dynamic_cast<KeyListModelInterface*>( view->model() ); assert( model ); QItemSelectionModel * const sm = view->selectionModel(); assert( sm ); sm->select( idx, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows ); QMetaObject::invokeMethod( q, "accept", Qt::QueuedConnection ); } void CertificateSelectionDialog::accept() { if ( d->acceptable( selectedCertificates() ) ) QDialog::accept(); } #include "moc_certificateselectiondialog.cpp" <|endoftext|>
<commit_before>// draw the 1st sensor of every ladder of requested layers (axis directions - thin arrows) // and the tracking frame of each sensor (axis directions - thick arrows) void drawLr(int layMin=1,int layMax=1) { gSystem->Load("libITSUpgradeBase.so"); gSystem->Load("libITSUpgradeSim.so"); gSystem->Load("libITSUpgradeRec.so"); AliGeomManager::LoadGeometry("geometry.root"); // Apply misaligment ... ;-) const char *ocdb="local://$ALICE_ROOT/OCDB"; AliCDBManager::Instance()->SetDefaultStorage(ocdb); Int_t run = 1; AliCDBManager::Instance()->SetRun(run); AliCDBManager::Instance()->SetSpecificStorage("ITS/Align/Data", Form("local://%s",gSystem->pwd())); AliCDBEntry *entry = AliCDBManager::Instance()->Get("ITS/Align/Data"); TClonesArray *array = (TClonesArray*)entry->GetObject(); AliGeomManager::ApplyAlignObjsToGeom(*array); gGeoManager->LockGeometry(); AliITSUGeomTGeo* gm = new AliITSUGeomTGeo(kTRUE); TObjArray segmArr; AliITSUSegmentationPix::LoadSegmentations(&segmArr, AliITSUGeomTGeo::GetITSsegmentationFileName()); // int nlr = gm->GetNLayers(); if (layMin<0) layMin = 0; if (layMax<0) layMax = nlr-1; else if (layMax>=nlr) layMax = nlr-1; // TH2* hh = new TH2F("hh","hh",100,-70,70,100,-70,70); hh->Draw(); gStyle->SetOptStat(0); // double rmax = 0; TGeoHMatrix *msens=0, *mttr=0; double loc[3]={0,0,0},glo[3],glo1[3],glo2[3],trk[3]; // Int_t mod=0; for (Int_t lay=layMin;lay<=layMax;lay++) { // AliITSUSegmentationPix* segm = (AliITSUSegmentationPix*)segmArr.At(gm->GetLayerDetTypeID(lay)); for (int ild=0;ild<gm->GetNLadders(lay);ild++) { // Sensor Matrices printf("Layer %d Ladder %d\n",lay,ild); msens = gm->GetMatrixSens(lay,ild,mod); printf("Sensor Matrix: "); msens->Print(); mttr = gm->GetMatrixT2L(lay,ild,mod); printf("T2L Matrix: "); mttr->Print(); // loc[0]=loc[1]=loc[2] = 0; msens->LocalToMaster(loc,glo); mttr->MasterToLocal(loc,trk); printf("SensorCenter in Lab: "); for (int i=0;i<3;i++) printf("%+9.4f ",glo[i]); printf("\n"); printf("SensorCenter in TRK: "); for (int i=0;i<3;i++) printf("%+9.4f ",trk[i]); printf("\n"); // loc[0]=-segm->Dx()/2; msens->LocalToMaster(loc,glo); loc[0]= segm->Dx()/2;; msens->LocalToMaster(loc,glo1); TArrow* linS = new TArrow(glo[0],glo[1],glo1[0],glo1[1],0.012); // sensor with pos local X direction linS->SetLineColor((ild+1)%4+1); linS->Draw(); // for (int j=3;j--;) glo[j] = 0.5*(glo[j]+glo1[j]); // double r = TMath::Sqrt(glo[0]*glo[0]+glo[1]*glo[1]); if (rmax<r) rmax = r; loc[0]=0; loc[1]=rmax*0.1; msens->LocalToMaster(loc,glo2); //lin->Print(); linS = new TArrow(glo[0],glo[1],glo2[0],glo2[1],0.012); // pos local Y axis linS->SetLineColor((ild+1)%4+1); linS->Draw(); // TMarker* mrk = new TMarker(glo[0],glo[1],31); mrk->SetMarkerColor((ild+1)%4+1); mrk->Draw(); // TLatex *latx = new TLatex( (glo[0])*1.2,(glo[1])*1.2,Form("%d",ild)); latx->SetTextColor((ild+1)%4+1); latx->SetTextSize(0.02); latx->Draw(); // // Check Tracking to Local Matrix ------- // // Draw sensors tracking frame trk[0]=trk[1]=0; mttr->LocalToMaster(trk,loc); msens->LocalToMaster(loc,glo1); TMarker* mrk = new TMarker(glo1[0],glo1[1],24); mrk->SetMarkerColor((ild+1)%4+1); mrk->Draw(); // // normal to sensor plane TLine* linN = new TLine(0,0,glo1[0],glo1[1]); linN->SetLineWidth(1); linN->SetLineStyle(2); linN->SetLineColor((ild+1)%4+1); linN->Draw(); // // direction of X axis of the tracking plane trk[0]=rmax*0.1; mttr->LocalToMaster(trk,loc); msens->LocalToMaster(loc,glo); TArrow* linX = new TArrow(glo1[0],glo1[1],glo[0],glo[1],0.012); linX->SetLineWidth(2); linX->SetLineStyle(1); linX->SetLineColor((ild+1)%4+1); linX->Draw(); // trk[0] = 0; // direction of tracking Y axis double dx = glo[0]-glo1[0]; double dy = glo[1]-glo1[1]; double dst = TMath::Sqrt(dx*dx+dy*dy); trk[1]=-dst; mttr->LocalToMaster(trk,loc); msens->LocalToMaster(loc,glo); trk[1]= dst; mttr->LocalToMaster(trk,loc); msens->LocalToMaster(loc,glo1); // TArrow* linT = new TArrow(glo[0],glo[1],glo1[0],glo1[1],0.012); // normal to sensor plane, pox Y of tracking frame linT->SetLineWidth(2); linT->SetLineStyle(1); linT->SetLineColor((ild+1)%4+1); linT->Draw(); // printf("Layer %d Ladder %d\n",lay,ild); mttr->Print(); } } // rmax = 1.3*rmax; hh->GetXaxis()->SetRangeUser(-rmax,rmax); hh->GetYaxis()->SetRangeUser(-rmax,rmax); gPad->Modified(); gPad->Update(); } <commit_msg>show connection for loc and tracking frame origins<commit_after>// draw the 1st sensor of every ladder of requested layers (axis directions - thin arrows) // and the tracking frame of each sensor (axis directions - thick arrows) void drawLr(int layMin=1,int layMax=1) { gSystem->Load("libITSUpgradeBase.so"); gSystem->Load("libITSUpgradeSim.so"); gSystem->Load("libITSUpgradeRec.so"); AliGeomManager::LoadGeometry("geometry.root"); // Apply misaligment ... ;-) const char *ocdb="local://$ALICE_ROOT/OCDB"; AliCDBManager::Instance()->SetDefaultStorage(ocdb); Int_t run = 1; AliCDBManager::Instance()->SetRun(run); AliCDBManager::Instance()->SetSpecificStorage("ITS/Align/Data", Form("local://%s",gSystem->pwd())); AliCDBEntry *entry = AliCDBManager::Instance()->Get("ITS/Align/Data"); TClonesArray *array = (TClonesArray*)entry->GetObject(); AliGeomManager::ApplyAlignObjsToGeom(*array); gGeoManager->LockGeometry(); AliITSUGeomTGeo* gm = new AliITSUGeomTGeo(kTRUE); TObjArray segmArr; AliITSUSegmentationPix::LoadSegmentations(&segmArr, AliITSUGeomTGeo::GetITSsegmentationFileName()); // int nlr = gm->GetNLayers(); if (layMin<0) layMin = 0; if (layMax<0) layMax = nlr-1; else if (layMax>=nlr) layMax = nlr-1; // TH2* hh = new TH2F("hh","hh",100,-70,70,100,-70,70); hh->Draw(); gStyle->SetOptStat(0); // double rmax = 0; TGeoHMatrix *msens=0, *mttr=0; double loc[3]={0,0,0},gloC[3],glo[3],glo1[3],glo2[3],trk[3]; // Int_t mod=0; for (Int_t lay=layMin;lay<=layMax;lay++) { // AliITSUSegmentationPix* segm = (AliITSUSegmentationPix*)segmArr.At(gm->GetLayerDetTypeID(lay)); for (int ild=0;ild<gm->GetNLadders(lay);ild++) { // Sensor Matrices printf("Layer %d Ladder %d\n",lay,ild); msens = gm->GetMatrixSens(lay,ild,mod); printf("Sensor Matrix: "); msens->Print(); mttr = gm->GetMatrixT2L(lay,ild,mod); printf("T2L Matrix: "); mttr->Print(); // loc[0]=loc[1]=loc[2] = 0; msens->LocalToMaster(loc,gloC); mttr->MasterToLocal(loc,trk); printf("SensorCenter in Lab: "); for (int i=0;i<3;i++) printf("%+9.4f ",gloC[i]); printf("\n"); printf("SensorCenter in TRK: "); for (int i=0;i<3;i++) printf("%+9.4f ",trk[i]); printf("\n"); // double r = TMath::Sqrt(gloC[0]*gloC[0]+gloC[1]*gloC[1]); if (rmax<r) rmax = r; // loc[0]=-segm->Dx()/2; msens->LocalToMaster(loc,glo); loc[0]= segm->Dx()/2;; msens->LocalToMaster(loc,glo1); TArrow* linS = new TArrow(glo[0],glo[1],glo1[0],glo1[1],0.012); // sensor with pos local X direction linS->SetLineColor((ild+1)%4+1); linS->Draw(); // loc[0]=0; loc[1]=rmax*0.1; msens->LocalToMaster(loc,glo2); // //lin->Print(); linS = new TArrow(gloC[0],gloC[1],glo2[0],glo2[1],0.012); // pos local Y axis linS->SetLineColor((ild+1)%4+1); linS->Draw(); // TMarker* mrk = new TMarker(gloC[0],gloC[1],31); mrk->SetMarkerColor((ild+1)%4+1); mrk->Draw(); // TLatex *latx = new TLatex( gloC[0]*1.2,gloC[1]*1.2,Form("%d",ild)); latx->SetTextColor((ild+1)%4+1); latx->SetTextSize(0.02); latx->Draw(); // // Check Tracking to Local Matrix ------- // // Draw sensors tracking frame trk[0]=trk[1]=0; mttr->LocalToMaster(trk,loc); msens->LocalToMaster(loc,glo1); TMarker* mrk = new TMarker(glo1[0],glo1[1],24); mrk->SetMarkerColor((ild+1)%4+1); mrk->Draw(); // // normal to sensor plane TLine* linN = new TLine(0,0,glo1[0],glo1[1]); linN->SetLineWidth(1); linN->SetLineStyle(2); linN->SetLineColor((ild+1)%4+1); linN->Draw(); // // connect tracking and local frame TLine* linNP = new TLine(gloC[0],gloC[1],glo1[0],glo1[1]); linNP->SetLineWidth(1); linNP->SetLineStyle(2); linNP->SetLineColor((ild+1)%4+1); linNP->Draw(); // // direction of X axis of the tracking plane trk[0]=rmax*0.1; mttr->LocalToMaster(trk,loc); msens->LocalToMaster(loc,glo); TArrow* linX = new TArrow(glo1[0],glo1[1],glo[0],glo[1],0.012); linX->SetLineWidth(2); linX->SetLineStyle(1); linX->SetLineColor((ild+1)%4+1); linX->Draw(); // trk[0] = 0; // direction of tracking Y axis double dx = glo[0]-glo1[0]; double dy = glo[1]-glo1[1]; double dst = TMath::Sqrt(dx*dx+dy*dy); trk[1]=-dst; mttr->LocalToMaster(trk,loc); msens->LocalToMaster(loc,glo); trk[1]= dst; mttr->LocalToMaster(trk,loc); msens->LocalToMaster(loc,glo1); // TArrow* linT = new TArrow(glo[0],glo[1],glo1[0],glo1[1],0.012); // normal to sensor plane, pox Y of tracking frame linT->SetLineWidth(2); linT->SetLineStyle(1); linT->SetLineColor((ild+1)%4+1); linT->Draw(); // printf("Layer %d Ladder %d\n",lay,ild); mttr->Print(); } } // rmax = 1.3*rmax; hh->GetXaxis()->SetRangeUser(-rmax,rmax); hh->GetYaxis()->SetRangeUser(-rmax,rmax); gPad->Modified(); gPad->Update(); } <|endoftext|>
<commit_before>/* * Source: http://codility.com/demo/take-sample-test/peaks/ * Result: 36/100 @ https://codility.com/demo/results/demoQ8W6PM-VFP/ * Result: 9/100 @ https://codility.com/demo/results/demoA7NMY2-HX9/ * * A non-empty zero-indexed array A consisting of N integers is given. * * A peak is an array element which is larger than its neighbors. More * precisely, it is an index P such that 0 < P < N − 1, A[P − 1] < A[P] * and A[P] > A[P + 1]. * * For example, the following array A: * * A[0] = 1 * A[1] = 2 * A[2] = 3 * A[3] = 4 * A[4] = 3 * A[5] = 4 * A[6] = 1 * A[7] = 2 * A[8] = 3 * A[9] = 4 * A[10] = 6 * A[11] = 2 * * has exactly three peaks: 3, 5, 10. * * We want to divide this array into blocks containing the same number * of elements. More precisely, we want to choose a number K that will * yield the following blocks: * * A[0], A[1], ..., A[K − 1], * A[K], A[K + 1], ..., A[2K − 1], * ... * A[N − K], A[N − K + 1], ..., A[N − 1]. * * What's more, every block should contain at least one peak. Notice * that extreme elements of the blocks (for example A[K − 1] or A[K]) * can also be peaks, but only if they have both neighbors (including * one in an adjacent blocks). * * The goal is to find the maximum number of blocks into which the array * A can be divided. * * Array A can be divided into blocks as follows: * * - one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block * contains three peaks. * - two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block * has a peak. * - three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block * has a peak. Notice in particular that the first block (1, 2, 3, 4) * has a peak at A[3], because A[2] < A[3] > A[4], even though A[4] * is in the adjacent block. * * However, array A cannot be divided into four blocks, (1, 2, 3), * (4, 3, 4), (1, 2, 3) and (4, 6, 2), because the (1, 2, 3) blocks do * not contain a peak. Notice in particular that the (4, 3, 4) block * contains two peaks: A[3] and A[5]. * * The maximum number of blocks that array A can be divided into is * three. * * Write a function: * * int solution(vector<int> &A); * * that, given a non-empty zero-indexed array A consisting of N * integers, returns the maximum number of blocks into which A can be * divided. * * If A cannot be divided into some number of blocks, the function * should return 0. * * For example, given: * * A[0] = 1 * A[1] = 2 * A[2] = 3 * A[3] = 4 * A[4] = 3 * A[5] = 4 * A[6] = 1 * A[7] = 2 * A[8] = 3 * A[9] = 4 * A[10] = 6 * A[11] = 2 * * the function should return 3, as explained above. * * Assume that: * * N is an integer within the range [1..100,000]; * each element of array A is an integer within the range * [0..1,000,000,000]. * * Complexity: * * expected worst-case time complexity is O(N*log(log(N))); * expected worst-case space complexity is O(N), beyond input * storage (not counting the storage required for input * arguments). * * Elements of input arrays can be modified. */ // some problems in logics of all the thing, hope to fix next time #include <vector> #include <algorithm> // std::max int solution(vector<int> &A) { //step 1: find maximal distance between two peaks // O(N) int N = A.size(), old_peak_pos = -1, peaks_number = 0, max_dist_peaks = 0; for (int i = 1; i < N-1; i++) { //current peak if ((A[i] > A[i-1]) && (A[i] > A[i+1])) { //very first peak if (old_peak_pos == -1) { old_peak_pos = i; } else { max_dist_peaks = max(i - old_peak_pos - 1,max_dist_peaks); old_peak_pos = i; } peaks_number++; } } max_dist_peaks++; // step2: while looping through all divisors of N // the minimal interval length is the largest divisor // that is smaller than max_dist_peaks + 1 // O(log(log(N))) int num_of_blocks = 2; int old_num_of_blocks = 1; while (num_of_blocks * num_of_blocks < N) { if (N % num_of_blocks == 0) { //direct case if ((N / old_num_of_blocks > max_dist_peaks) && (N / num_of_blocks < max_dist_peaks)) { return num_of_blocks; } //inverse case if ((old_num_of_blocks < max_dist_peaks) && (num_of_blocks > max_dist_peaks)) { return N / old_num_of_blocks; } //anyway old_num_of_blocks = num_of_blocks; } num_of_blocks++; } // N is j*j case if (N == num_of_blocks * num_of_blocks) { if (num_of_blocks == peaks_number) { return num_of_blocks; } } return 1; } <commit_msg>More progress on Peaks problem (still to improve)<commit_after>/* * Source: http://codility.com/demo/take-sample-test/peaks/ * Result: 36/100 @ https://codility.com/demo/results/demoQ8W6PM-VFP/ * Result: 9/100 @ https://codility.com/demo/results/demoA7NMY2-HX9/ * Result: 63/100 @ https://codility.com/demo/results/demoRJG4MS-G3T/ * * A non-empty zero-indexed array A consisting of N integers is given. * * A peak is an array element which is larger than its neighbors. More * precisely, it is an index P such that 0 < P < N − 1, A[P − 1] < A[P] * and A[P] > A[P + 1]. * * For example, the following array A: * * A[0] = 1 * A[1] = 2 * A[2] = 3 * A[3] = 4 * A[4] = 3 * A[5] = 4 * A[6] = 1 * A[7] = 2 * A[8] = 3 * A[9] = 4 * A[10] = 6 * A[11] = 2 * * has exactly three peaks: 3, 5, 10. * * We want to divide this array into blocks containing the same number * of elements. More precisely, we want to choose a number K that will * yield the following blocks: * * A[0], A[1], ..., A[K − 1], * A[K], A[K + 1], ..., A[2K − 1], * ... * A[N − K], A[N − K + 1], ..., A[N − 1]. * * What's more, every block should contain at least one peak. Notice * that extreme elements of the blocks (for example A[K − 1] or A[K]) * can also be peaks, but only if they have both neighbors (including * one in an adjacent blocks). * * The goal is to find the maximum number of blocks into which the array * A can be divided. * * Array A can be divided into blocks as follows: * * - one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block * contains three peaks. * - two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block * has a peak. * - three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block * has a peak. Notice in particular that the first block (1, 2, 3, 4) * has a peak at A[3], because A[2] < A[3] > A[4], even though A[4] * is in the adjacent block. * * However, array A cannot be divided into four blocks, (1, 2, 3), * (4, 3, 4), (1, 2, 3) and (4, 6, 2), because the (1, 2, 3) blocks do * not contain a peak. Notice in particular that the (4, 3, 4) block * contains two peaks: A[3] and A[5]. * * The maximum number of blocks that array A can be divided into is * three. * * Write a function: * * int solution(vector<int> &A); * * that, given a non-empty zero-indexed array A consisting of N * integers, returns the maximum number of blocks into which A can be * divided. * * If A cannot be divided into some number of blocks, the function * should return 0. * * For example, given: * * A[0] = 1 * A[1] = 2 * A[2] = 3 * A[3] = 4 * A[4] = 3 * A[5] = 4 * A[6] = 1 * A[7] = 2 * A[8] = 3 * A[9] = 4 * A[10] = 6 * A[11] = 2 * * the function should return 3, as explained above. * * Assume that: * * N is an integer within the range [1..100,000]; * each element of array A is an integer within the range * [0..1,000,000,000]. * * Complexity: * * expected worst-case time complexity is O(N*log(log(N))); * expected worst-case space complexity is O(N), beyond input * storage (not counting the storage required for input * arguments). * * Elements of input arrays can be modified. */ // currently there are problems with chaotic/large sequences // smth wrong with conditions (too many)? #include <deque> int solution(vector<int> &A) { int N = A.size(); if (N < 3) return 0; deque<int> divisors; deque<int>::iterator mid = divisors.begin(); int j = 2; while (j * j < N) { if (N % j == 0) { if (divisors.empty()) { divisors.push_front(j); divisors.push_back(N/j); } else { divisors.insert(mid,j); ++mid; divisors.insert(mid,N/j); ++mid; } } j++; } if (j * j == N) { divisors.insert(mid,j); } //counting peaks int peaks_cnt = 0; for(int i = 1; i < N-1; i++) { if ( (A[i-1] < A[i]) && (A[i] > A[i+1]) ) { peaks_cnt++; } } if (peaks_cnt == 0 ) return 0; if (divisors.empty()) return 1; int D = divisors.size(); int cur_len; bool has_peak_this = false; bool has_peak_each = true; for (int i = D-1; i >= 0 ; i--) { //can't be more intervals than peaks if (divisors[i] <= peaks_cnt) { cur_len = N / divisors[i]; //loop througn A for each interval for (int q = 0; q <= N - cur_len; q+=cur_len) { //loop through elements of an interval //CAREFUL: peaks can be on borders for(int p = q; p < q + cur_len ; p++) { //excluding 2 borders if ((p > 0) && (p < N-1) ) { //at least one peak in the interval if ( (A[p-1] < A[p]) && (A[p] > A[p+1]) ) { has_peak_this = true; break; // we leave the interval with positive info } } } //we have just left the interval has_peak_each &= has_peak_this; has_peak_this = false; if (!has_peak_each) break; } // at this point we passed all intervals for current divisor if (has_peak_each) return divisors[i]; } } return 1; } <|endoftext|>
<commit_before>// // LinearProbing.cpp // HashTables // // Created by Sunil on 4/29/17. // Copyright © 2017 Sunil. All rights reserved. // #include "HashTable.hpp" #include "CollisionResolver.hpp" LinearProbingResolver::LinearProbingResolver(CollisionCounter* counter) : counter(counter) { } void LinearProbingResolver::add(HashTable* map, HashEntry* entry, int index) { // collision. look for a new slot by linear probing. int begin = 0; auto capacity = map->capacity; auto key = entry->player.key(); while (begin++ < capacity) { // new entry if (!map->table[index]) { map->table[index] = entry; return; } // update the existing entry if (map->table[index]->player.areSame(entry->player)) { map->table[index]->player.addMoreInfo(entry->player); return; } // // if (map->table[index]->player.key() == entry->player.key()) { // map->table[index]->player.show(); // entry->player.show(); // } // index = (index+1) % capacity; // track the add collisions if (counter) counter->addCollisions++; } cout << "(linear probe): Unable to find a spot to add value!" << endl; entry->player.show(); } PlayerInfo* LinearProbingResolver::get(HashTable* map, string key, int index){ auto begin = 0; auto capacity = map->capacity; while (begin++ < capacity) { if (map->table[index]->player.key() == key) return &map->table[index]->player; index = (index+1) % capacity; // track the look up collisions if (counter) counter->lookupCollisions++; } return nullptr; } void LinearProbingResolver::Delete(HashEntry* entry) { delete entry; } LinearProbingResolver::~LinearProbingResolver() { // linear probe doesn't own collision counter. // So it shouldn't free it up! Just lose reference. counter = nullptr; } <commit_msg>bug fix chaining<commit_after>// // LinearProbing.cpp // HashTables // // Created by Sunil on 4/29/17. // Copyright © 2017 Sunil. All rights reserved. // #include "HashTable.hpp" #include "CollisionResolver.hpp" LinearProbingResolver::LinearProbingResolver(CollisionCounter* counter) : counter(counter) { } void LinearProbingResolver::add(HashTable* map, HashEntry* entry, int index) { // collision. look for a new slot by linear probing. int begin = 0; auto capacity = map->capacity; auto key = entry->player.key(); while (begin++ < capacity) { // new entry if (!map->table[index]) { map->table[index] = entry; return; } // update the existing entry if (map->table[index]->player.areSame(entry->player)) { map->table[index]->player.addMoreInfo(entry->player); return; } // // if (map->table[index]->player.key() == entry->player.key()) { // map->table[index]->player.show(); // entry->player.show(); // } // index = (index+1) % capacity; // track the add collisions if (counter) counter->addCollisions++; } cout << "(linear probe): Unable to find a spot to add value!" << endl; entry->player.show(); } PlayerInfo* LinearProbingResolver::get(HashTable* map, string key, int index){ auto begin = 0; auto capacity = map->capacity; while (begin++ < capacity) { if (map->table[index] && map->table[index]->player.key() == key) return &map->table[index]->player; index = (index+1) % capacity; // track the look up collisions if (counter) counter->lookupCollisions++; } return nullptr; } void LinearProbingResolver::Delete(HashEntry* entry) { delete entry; } LinearProbingResolver::~LinearProbingResolver() { // linear probe doesn't own collision counter. // So it shouldn't free it up! Just lose reference. counter = nullptr; } <|endoftext|>
<commit_before>//= ValueState.cpp - Path-Sens. "State" for tracking valuues -----*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This files defines SymbolID, VarBindKey, and ValueState. // //===----------------------------------------------------------------------===// #include "ValueState.h" using namespace clang; bool ValueState::isNotEqual(SymbolID sym, const llvm::APSInt& V) const { // First, retrieve the NE-set associated with the given symbol. ConstantNotEqTy::TreeTy* T = Data->ConstantNotEq.SlimFind(sym); if (!T) return false; // Second, see if V is present in the NE-set. return T->getValue().second.contains(&V); } const llvm::APSInt* ValueState::getSymVal(SymbolID sym) const { ConstantEqTy::TreeTy* T = Data->ConstantEq.SlimFind(sym); return T ? T->getValue().second : NULL; } RValue ValueStateManager::GetValue(const StateTy& St, const LValue& LV) { switch (LV.getSubKind()) { case lval::DeclValKind: { StateTy::VariableBindingsTy::TreeTy* T = St.getImpl()->VariableBindings.SlimFind(cast<lval::DeclVal>(LV).getDecl()); return T ? T->getValue().second : InvalidValue(); } default: assert (false && "Invalid LValue."); break; } return InvalidValue(); } ValueStateManager::StateTy ValueStateManager::AddNE(StateTy St, SymbolID sym, const llvm::APSInt& V) { // First, retrieve the NE-set associated with the given symbol. ValueState::ConstantNotEqTy::TreeTy* T = St.getImpl()->ConstantNotEq.SlimFind(sym); ValueState::IntSetTy S = T ? T->getValue().second : ISetFactory.GetEmptySet(); // Now add V to the NE set. S = ISetFactory.Add(S, &V); // Create a new state with the old binding replaced. ValueStateImpl NewStateImpl = *St.getImpl(); NewStateImpl.ConstantNotEq = CNEFactory.Add(NewStateImpl.ConstantNotEq, sym, S); // Get the persistent copy. return getPersistentState(NewStateImpl); } ValueStateManager::StateTy ValueStateManager::AddEQ(StateTy St, SymbolID sym, const llvm::APSInt& V) { // Create a new state with the old binding replaced. ValueStateImpl NewStateImpl = *St.getImpl(); NewStateImpl.ConstantEq = CEFactory.Add(NewStateImpl.ConstantEq, sym, &V); // Get the persistent copy. return getPersistentState(NewStateImpl); } RValue ValueStateManager::GetValue(const StateTy& St, Stmt* S, bool* hasVal) { for (;;) { switch (S->getStmtClass()) { // ParenExprs are no-ops. case Stmt::ParenExprClass: S = cast<ParenExpr>(S)->getSubExpr(); continue; // DeclRefExprs can either evaluate to an LValue or a Non-LValue // (assuming an implicit "load") depending on the context. In this // context we assume that we are retrieving the value contained // within the referenced variables. case Stmt::DeclRefExprClass: return GetValue(St, lval::DeclVal(cast<DeclRefExpr>(S)->getDecl())); // Integer literals evaluate to an RValue. Simply retrieve the // RValue for the literal. case Stmt::IntegerLiteralClass: return NonLValue::GetValue(ValMgr, cast<IntegerLiteral>(S)); // Casts where the source and target type are the same // are no-ops. We blast through these to get the descendant // subexpression that has a value. case Stmt::ImplicitCastExprClass: { ImplicitCastExpr* C = cast<ImplicitCastExpr>(S); if (C->getType() == C->getSubExpr()->getType()) { S = C->getSubExpr(); continue; } break; } case Stmt::CastExprClass: { CastExpr* C = cast<CastExpr>(S); if (C->getType() == C->getSubExpr()->getType()) { S = C->getSubExpr(); continue; } break; } // Handle all other Stmt* using a lookup. default: break; }; break; } StateTy::VariableBindingsTy::TreeTy* T = St.getImpl()->VariableBindings.SlimFind(S); if (T) { if (hasVal) *hasVal = true; return T->getValue().second; } else { if (hasVal) *hasVal = false; return InvalidValue(); } } LValue ValueStateManager::GetLValue(const StateTy& St, Stmt* S) { while (ParenExpr* P = dyn_cast<ParenExpr>(S)) S = P->getSubExpr(); if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(S)) return lval::DeclVal(DR->getDecl()); return cast<LValue>(GetValue(St, S)); } ValueStateManager::StateTy ValueStateManager::SetValue(StateTy St, Stmt* S, bool isBlkExpr, const RValue& V) { assert (S); return V.isValid() ? Add(St, VarBindKey(S, isBlkExpr), V) : St; } ValueStateManager::StateTy ValueStateManager::SetValue(StateTy St, const LValue& LV, const RValue& V) { switch (LV.getSubKind()) { case lval::DeclValKind: return V.isValid() ? Add(St, cast<lval::DeclVal>(LV).getDecl(), V) : Remove(St, cast<lval::DeclVal>(LV).getDecl()); default: assert ("SetValue for given LValue type not yet implemented."); return St; } } ValueStateManager::StateTy ValueStateManager::Remove(StateTy St, VarBindKey K) { // Create a new state with the old binding removed. ValueStateImpl NewStateImpl = *St.getImpl(); NewStateImpl.VariableBindings = VBFactory.Remove(NewStateImpl.VariableBindings, K); // Get the persistent copy. return getPersistentState(NewStateImpl); } ValueStateManager::StateTy ValueStateManager::Add(StateTy St, VarBindKey K, const RValue& V) { // Create a new state with the old binding removed. ValueStateImpl NewStateImpl = *St.getImpl(); NewStateImpl.VariableBindings = VBFactory.Add(NewStateImpl.VariableBindings, K, V); // Get the persistent copy. return getPersistentState(NewStateImpl); } ValueStateManager::StateTy ValueStateManager::getInitialState() { // Create a state with empty variable bindings. ValueStateImpl StateImpl(VBFactory.GetEmptyMap(), CNEFactory.GetEmptyMap(), CEFactory.GetEmptyMap()); return getPersistentState(StateImpl); } ValueStateManager::StateTy ValueStateManager::getPersistentState(const ValueStateImpl &State) { llvm::FoldingSetNodeID ID; State.Profile(ID); void* InsertPos; if (ValueStateImpl* I = StateSet.FindNodeOrInsertPos(ID, InsertPos)) return I; ValueStateImpl* I = (ValueStateImpl*) Alloc.Allocate<ValueState>(); new (I) ValueStateImpl(State); StateSet.InsertNode(I, InsertPos); return I; } <commit_msg>Fixed bug when allocating a ValueStateImpl object in getPersistentState() using the bump-pointer allocator and a placed new; we accidentally allocated a ValueStateImpl* instead, causing an overrun when we did a placed new().<commit_after>//= ValueState.cpp - Path-Sens. "State" for tracking valuues -----*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This files defines SymbolID, VarBindKey, and ValueState. // //===----------------------------------------------------------------------===// #include "ValueState.h" using namespace clang; bool ValueState::isNotEqual(SymbolID sym, const llvm::APSInt& V) const { // First, retrieve the NE-set associated with the given symbol. ConstantNotEqTy::TreeTy* T = Data->ConstantNotEq.SlimFind(sym); if (!T) return false; // Second, see if V is present in the NE-set. return T->getValue().second.contains(&V); } const llvm::APSInt* ValueState::getSymVal(SymbolID sym) const { ConstantEqTy::TreeTy* T = Data->ConstantEq.SlimFind(sym); return T ? T->getValue().second : NULL; } RValue ValueStateManager::GetValue(const StateTy& St, const LValue& LV) { switch (LV.getSubKind()) { case lval::DeclValKind: { StateTy::VariableBindingsTy::TreeTy* T = St.getImpl()->VariableBindings.SlimFind(cast<lval::DeclVal>(LV).getDecl()); return T ? T->getValue().second : InvalidValue(); } default: assert (false && "Invalid LValue."); break; } return InvalidValue(); } ValueStateManager::StateTy ValueStateManager::AddNE(StateTy St, SymbolID sym, const llvm::APSInt& V) { // First, retrieve the NE-set associated with the given symbol. ValueState::ConstantNotEqTy::TreeTy* T = St.getImpl()->ConstantNotEq.SlimFind(sym); ValueState::IntSetTy S = T ? T->getValue().second : ISetFactory.GetEmptySet(); // Now add V to the NE set. S = ISetFactory.Add(S, &V); // Create a new state with the old binding replaced. ValueStateImpl NewStateImpl = *St.getImpl(); NewStateImpl.ConstantNotEq = CNEFactory.Add(NewStateImpl.ConstantNotEq, sym, S); // Get the persistent copy. return getPersistentState(NewStateImpl); } ValueStateManager::StateTy ValueStateManager::AddEQ(StateTy St, SymbolID sym, const llvm::APSInt& V) { // Create a new state with the old binding replaced. ValueStateImpl NewStateImpl = *St.getImpl(); NewStateImpl.ConstantEq = CEFactory.Add(NewStateImpl.ConstantEq, sym, &V); // Get the persistent copy. return getPersistentState(NewStateImpl); } RValue ValueStateManager::GetValue(const StateTy& St, Stmt* S, bool* hasVal) { for (;;) { switch (S->getStmtClass()) { // ParenExprs are no-ops. case Stmt::ParenExprClass: S = cast<ParenExpr>(S)->getSubExpr(); continue; // DeclRefExprs can either evaluate to an LValue or a Non-LValue // (assuming an implicit "load") depending on the context. In this // context we assume that we are retrieving the value contained // within the referenced variables. case Stmt::DeclRefExprClass: return GetValue(St, lval::DeclVal(cast<DeclRefExpr>(S)->getDecl())); // Integer literals evaluate to an RValue. Simply retrieve the // RValue for the literal. case Stmt::IntegerLiteralClass: return NonLValue::GetValue(ValMgr, cast<IntegerLiteral>(S)); // Casts where the source and target type are the same // are no-ops. We blast through these to get the descendant // subexpression that has a value. case Stmt::ImplicitCastExprClass: { ImplicitCastExpr* C = cast<ImplicitCastExpr>(S); if (C->getType() == C->getSubExpr()->getType()) { S = C->getSubExpr(); continue; } break; } case Stmt::CastExprClass: { CastExpr* C = cast<CastExpr>(S); if (C->getType() == C->getSubExpr()->getType()) { S = C->getSubExpr(); continue; } break; } // Handle all other Stmt* using a lookup. default: break; }; break; } StateTy::VariableBindingsTy::TreeTy* T = St.getImpl()->VariableBindings.SlimFind(S); if (T) { if (hasVal) *hasVal = true; return T->getValue().second; } else { if (hasVal) *hasVal = false; return InvalidValue(); } } LValue ValueStateManager::GetLValue(const StateTy& St, Stmt* S) { while (ParenExpr* P = dyn_cast<ParenExpr>(S)) S = P->getSubExpr(); if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(S)) return lval::DeclVal(DR->getDecl()); return cast<LValue>(GetValue(St, S)); } ValueStateManager::StateTy ValueStateManager::SetValue(StateTy St, Stmt* S, bool isBlkExpr, const RValue& V) { assert (S); return V.isValid() ? Add(St, VarBindKey(S, isBlkExpr), V) : St; } ValueStateManager::StateTy ValueStateManager::SetValue(StateTy St, const LValue& LV, const RValue& V) { switch (LV.getSubKind()) { case lval::DeclValKind: return V.isValid() ? Add(St, cast<lval::DeclVal>(LV).getDecl(), V) : Remove(St, cast<lval::DeclVal>(LV).getDecl()); default: assert ("SetValue for given LValue type not yet implemented."); return St; } } ValueStateManager::StateTy ValueStateManager::Remove(StateTy St, VarBindKey K) { // Create a new state with the old binding removed. ValueStateImpl NewStateImpl = *St.getImpl(); NewStateImpl.VariableBindings = VBFactory.Remove(NewStateImpl.VariableBindings, K); // Get the persistent copy. return getPersistentState(NewStateImpl); } ValueStateManager::StateTy ValueStateManager::Add(StateTy St, VarBindKey K, const RValue& V) { // Create a new state with the old binding removed. ValueStateImpl NewStateImpl = *St.getImpl(); NewStateImpl.VariableBindings = VBFactory.Add(NewStateImpl.VariableBindings, K, V); // Get the persistent copy. return getPersistentState(NewStateImpl); } ValueStateManager::StateTy ValueStateManager::getInitialState() { // Create a state with empty variable bindings. ValueStateImpl StateImpl(VBFactory.GetEmptyMap(), CNEFactory.GetEmptyMap(), CEFactory.GetEmptyMap()); return getPersistentState(StateImpl); } ValueStateManager::StateTy ValueStateManager::getPersistentState(const ValueStateImpl &State) { llvm::FoldingSetNodeID ID; State.Profile(ID); void* InsertPos; if (ValueStateImpl* I = StateSet.FindNodeOrInsertPos(ID, InsertPos)) return I; ValueStateImpl* I = (ValueStateImpl*) Alloc.Allocate<ValueStateImpl>(); new (I) ValueStateImpl(State); StateSet.InsertNode(I, InsertPos); return I; } <|endoftext|>
<commit_before>// // QC.cpp // // Class to compute QC metrics on .sim files // Metrics include: Sample magnitude (normalized by probe), sample xydiff // // // Author: Iain Bancarz <ib5@sanger.ac.uk> // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the Genome Research Ltd nor the names of its contributors // may be used to endorse or promote products derived from software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. EVENT SHALL GENOME RESEARCH LTD. BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #include <cmath> #include <cstdio> #include <iostream> #include <stdlib.h> #include <string.h> #include "QC.h" #include "Sim.h" using namespace std; QC::QC(string simPath) { qcsim = new Sim(); if (!qcsim->errorMsg.empty()) { cout << qcsim->errorMsg << endl; exit(1); } qcsim->open(simPath); cout << "Opened .sim file " << simPath << endl; } void QC::writeMagnitude(string outPath) { // compute normalized magnitudes by sample, write to given file FILE *outFile = fopen(outPath.c_str(), "w"); qcsim->reset(); // return read position to first sample float *magByProbe; magByProbe = (float *) calloc(qcsim->numProbes, sizeof(float)); magnitudeByProbe(magByProbe); float *magBySample; magBySample = (float *) calloc(qcsim->numSamples, sizeof(float)); char sampleNames[qcsim->numSamples][Sim::SAMPLE_NAME_SIZE+1]; qcsim->reset(); magnitudeBySample(magBySample, magByProbe, sampleNames); for (unsigned int i=0; i<qcsim->numSamples; i++) { // use fprintf to control number of decimal places fprintf(outFile, "%s\t%.6f\n", sampleNames[i], magBySample[i]); } fclose(outFile); } void QC::writeXydiff(string outPath) { // compute XY intensity difference by sample, write to given file if (qcsim->numChannels!=2) { cerr << "Error: XY intensity difference is only defined for exactly " "two intensity channels." << endl; exit(1); } FILE *outFile = fopen(outPath.c_str(), "w"); qcsim->reset(); // return read position to first sample float *xydBySample; xydBySample = (float *) calloc(qcsim->numSamples, sizeof(float)); char sampleNames[qcsim->numSamples][Sim::SAMPLE_NAME_SIZE+1]; xydiffBySample(xydBySample, sampleNames); for (unsigned int i=0; i<qcsim->numSamples; i++) { // use fprintf to control number of decimal places fprintf(outFile, "%s\t%.6f\n", sampleNames[i], magBySample[i]); } fclose(outFile); } void QC::getNextMagnitudes(float magnitudes[], char *sampleName, Sim *sim) { // compute magnitudes for each probe from next sample in .sim input // can handle arbitrarily many intensity channels; also reads sample name vector<uint16_t> *intensity_int = new vector<uint16_t>; vector<float> *intensity_float = new vector<float>; if (sim->numberFormat == 0) { sim->getNextRecord(sampleName, intensity_float); } else { sim->getNextRecord(sampleName, intensity_int); } for (unsigned int i=0; i < sim->numProbes; i++) { float total = 0.0; // running total of squared intensities for (int j=0; j<sim->numChannels; j++) { int index = i*sim->numChannels + j; float signal; if (sim->numberFormat == 0) signal = intensity_float->at(index); else signal = intensity_int->at(index); total += signal * signal; } magnitudes[i] = sqrt(total); } } void QC::magnitudeByProbe(float magByProbe[]) { // iterate over samples; update running totals of magnitude by probe // then divide to find mean for each probe float *magnitudes; magnitudes = (float *) calloc(qcsim->numProbes, sizeof(float)); char *sampleName; // placeholder; name used in magnitudeBySample sampleName = new char[qcsim->sampleNameSize]; for(unsigned int i=0; i < qcsim->numSamples; i++) { getNextMagnitudes(magnitudes, sampleName, qcsim); for (unsigned int j=0; j < qcsim->numProbes; j++) { magByProbe[j] += magnitudes[j]; } } for (unsigned int i=0; i < qcsim->numProbes; i++) { magByProbe[i] = magByProbe[i] / qcsim->numSamples; } } void QC::magnitudeBySample(float magBySample[], float magByProbe[], char sampleNames[][Sim::SAMPLE_NAME_SIZE+1]) { // find mean sample magnitude, normalized for each probe // also read sample names float *magnitudes; magnitudes = (float *) calloc(qcsim->numProbes, sizeof(float)); for(unsigned int i=0; i < qcsim->numSamples; i++) { char *sampleName; sampleName = new char[qcsim->sampleNameSize]; getNextMagnitudes(magnitudes, sampleName, qcsim); strcpy(sampleNames[i], sampleName); float mag = 0; for (unsigned int j=0; j < qcsim->numProbes; j++) { mag += magnitudes[j]/magByProbe[j]; } magBySample[i] = mag / qcsim -> numProbes; } } void QC::xydiffBySample(float xydBySample[], char sampleNames[][Sim::SAMPLE_NAME_SIZE+1]) { // find xydiff and read sample names for(unsigned int i=0; i < qcsim->numSamples; i++) { char *sampleName; sampleName = new char[qcsim->sampleNameSize]; float xydTotal = 0.0; // running total of xy difference vector<uint16_t> *intensity_int = new vector<uint16_t>; vector<float> *intensity_float = new vector<float>; if (qcsim->numberFormat == 0) { qcsim->getNextRecord(sampleName, intensity_float); } else { qcsim->getNextRecord(sampleName, intensity_int); } strcpy(sampleNames[i], sampleName); for (unsigned int j=0; j<qcsim->numProbes; j++) { int index = j*qcsim->numChannels; float xyd; if (qcsim->numberFormat == 0) { xyd = intensity_float->at(index+1) - intensity_float->at(index); } else { xyd = intensity_int->at(index+1) - intensity_int->at(index); } xydTotal += xyd; } xydBySample[i] = xydTotal / qcsim->numProbes; } } <commit_msg>Changed variable names for greater clarity<commit_after>// // QC.cpp // // Class to compute QC metrics on .sim files // Metrics include: Sample magnitude (normalized by probe), sample xydiff // // // Author: Iain Bancarz <ib5@sanger.ac.uk> // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the Genome Research Ltd nor the names of its contributors // may be used to endorse or promote products derived from software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. EVENT SHALL GENOME RESEARCH LTD. BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #include <cmath> #include <cstdio> #include <iostream> #include <stdlib.h> #include <string.h> #include "QC.h" #include "Sim.h" using namespace std; QC::QC(string simPath) { qcsim = new Sim(); if (!qcsim->errorMsg.empty()) { cout << qcsim->errorMsg << endl; exit(1); } qcsim->open(simPath); cout << "Opened .sim file " << simPath << endl; } void QC::writeMagnitude(string outPath) { // compute normalized magnitudes by sample, write to given file FILE *outFile = fopen(outPath.c_str(), "w"); qcsim->reset(); // return read position to first sample float *probeMagArray; probeMagArray = (float *) calloc(qcsim->numProbes, sizeof(float)); magnitudeByProbe(probeMagArray); float *sampleMagArray; sampleMagArray = (float *) calloc(qcsim->numSamples, sizeof(float)); char sampleNames[qcsim->numSamples][Sim::SAMPLE_NAME_SIZE+1]; qcsim->reset(); magnitudeBySample(sampleMagArray, probeMagArray, sampleNames); for (unsigned int i=0; i<qcsim->numSamples; i++) { // use fprintf to control number of decimal places fprintf(outFile, "%s\t%.6f\n", sampleNames[i], sampleMagArray[i]); } fclose(outFile); } void QC::writeXydiff(string outPath) { // compute XY intensity difference by sample, write to given file if (qcsim->numChannels!=2) { cerr << "Error: XY intensity difference is only defined for exactly " "two intensity channels." << endl; exit(1); } FILE *outFile = fopen(outPath.c_str(), "w"); qcsim->reset(); // return read position to first sample float *xydArray; xydArray = (float *) calloc(qcsim->numSamples, sizeof(float)); char sampleNames[qcsim->numSamples][Sim::SAMPLE_NAME_SIZE+1]; xydiffBySample(xydArray, sampleNames); for (unsigned int i=0; i<qcsim->numSamples; i++) { // use fprintf to control number of decimal places fprintf(outFile, "%s\t%.6f\n", sampleNames[i], xydArray[i]); } fclose(outFile); } void QC::getNextMagnitudes(float magnitudes[], char *sampleName, Sim *sim) { // compute magnitudes for each probe from next sample in .sim input // can handle arbitrarily many intensity channels; also reads sample name vector<uint16_t> *intensity_int = new vector<uint16_t>; vector<float> *intensity_float = new vector<float>; if (sim->numberFormat == 0) { sim->getNextRecord(sampleName, intensity_float); } else { sim->getNextRecord(sampleName, intensity_int); } for (unsigned int i=0; i < sim->numProbes; i++) { float total = 0.0; // running total of squared intensities for (int j=0; j<sim->numChannels; j++) { int index = i*sim->numChannels + j; float signal; if (sim->numberFormat == 0) signal = intensity_float->at(index); else signal = intensity_int->at(index); total += signal * signal; } magnitudes[i] = sqrt(total); } } void QC::magnitudeByProbe(float magByProbe[]) { // iterate over samples; update running totals of magnitude by probe // then divide to find mean for each probe float *magnitudes; magnitudes = (float *) calloc(qcsim->numProbes, sizeof(float)); char *sampleName; // placeholder; name used in magnitudeBySample sampleName = new char[qcsim->sampleNameSize]; for(unsigned int i=0; i < qcsim->numSamples; i++) { getNextMagnitudes(magnitudes, sampleName, qcsim); for (unsigned int j=0; j < qcsim->numProbes; j++) { magByProbe[j] += magnitudes[j]; } } for (unsigned int i=0; i < qcsim->numProbes; i++) { magByProbe[i] = magByProbe[i] / qcsim->numSamples; } } void QC::magnitudeBySample(float magBySample[], float magByProbe[], char sampleNames[][Sim::SAMPLE_NAME_SIZE+1]) { // find mean sample magnitude, normalized for each probe // also read sample names float *magnitudes; magnitudes = (float *) calloc(qcsim->numProbes, sizeof(float)); for(unsigned int i=0; i < qcsim->numSamples; i++) { char *sampleName; sampleName = new char[qcsim->sampleNameSize]; getNextMagnitudes(magnitudes, sampleName, qcsim); strcpy(sampleNames[i], sampleName); float mag = 0; for (unsigned int j=0; j < qcsim->numProbes; j++) { mag += magnitudes[j]/magByProbe[j]; } magBySample[i] = mag / qcsim -> numProbes; } } void QC::xydiffBySample(float xydBySample[], char sampleNames[][Sim::SAMPLE_NAME_SIZE+1]) { // find xydiff and read sample names for(unsigned int i=0; i < qcsim->numSamples; i++) { char *sampleName; sampleName = new char[qcsim->sampleNameSize]; float xydTotal = 0.0; // running total of xy difference vector<uint16_t> *intensity_int = new vector<uint16_t>; vector<float> *intensity_float = new vector<float>; if (qcsim->numberFormat == 0) { qcsim->getNextRecord(sampleName, intensity_float); } else { qcsim->getNextRecord(sampleName, intensity_int); } strcpy(sampleNames[i], sampleName); for (unsigned int j=0; j<qcsim->numProbes; j++) { int index = j*qcsim->numChannels; float xyd; if (qcsim->numberFormat == 0) { xyd = intensity_float->at(index+1) - intensity_float->at(index); } else { xyd = intensity_int->at(index+1) - intensity_int->at(index); } xydTotal += xyd; } xydBySample[i] = xydTotal / qcsim->numProbes; } } <|endoftext|>
<commit_before>// Generator builder // This is the device that builds generators. #include <filesystem> // C++17 specific feature. #include <gtk/gtk.h> #include <ifstream> #include <libxml/parser.h> #include <string> #include <vector> namespace fs = std::filesystem // Add element to document. // elementLabel is the label for the element, and // listFile is the name of the list file. void addElement(string elementToAdd, string elementLabel, string listFile) { xmlNodePtr elementLabelNodePtr; xmlNodePtr elementNodePtr; elementLabelNodePtr = xmlNewNode(NULL, BAD_CAST "root"); xmlNodeSetContent(n, BAD_CAST elementToAdd); xmlDocSetRootElement(doc, elementLabelNodePtr); } // Remove element from document. void removeElement(xmlNodePtr elementToRemove) { xmlUnlinkNode(elementToRemove); xmlFreeNode(elementToRemove); } int main(void) { GtkWidget *window; GtkWidget *button; gtk_init(); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(window, "delete-event", G_CALLBACK(delete_event), NULL); g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL); // Build a list of directories. string path = ""; // Path to directory vector<string> fileNames = ""; int i = 0; for (auto & p : fs::directory_iterator(path)) { fileNames[i] = p; i++; } // Display the list of files. // CList // Vertical Scrollbar xmlChar *xmlbuffer; int buffersize; // Create the XML document to store the generator. xmlDocPtr doc; doc = xmlNewDoc(BAD_CAST "1.0"); // Generate the menu for selecting a list file. return(0); } <commit_msg>Delete genbuilder_old2.cpp<commit_after><|endoftext|>
<commit_before>//===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements the SelectionDAG::viewGraph method. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/Function.h" #include "llvm/Support/GraphWriter.h" #include "llvm/ADT/StringExtras.h" #include <fstream> using namespace llvm; namespace llvm { template<> struct DOTGraphTraits<SelectionDAG*> : public DefaultDOTGraphTraits { static std::string getGraphName(const SelectionDAG *G) { return G->getMachineFunction().getFunction()->getName(); } static bool renderGraphFromBottomUp() { return true; } static std::string getNodeLabel(const SDNode *Node, const SelectionDAG *Graph); static std::string getNodeAttributes(const SDNode *N) { return "shape=Mrecord"; } static void addCustomGraphFeatures(SelectionDAG *G, GraphWriter<SelectionDAG*> &GW) { GW.emitSimpleNode(0, "plaintext=circle", "GraphRoot"); GW.emitEdge(0, -1, G->getRoot().Val, -1, ""); } }; } std::string DOTGraphTraits<SelectionDAG*>::getNodeLabel(const SDNode *Node, const SelectionDAG *G) { std::string Op = Node->getOperationName(); for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) { switch (Node->getValueType(i)) { default: Op += ":unknownvt!"; break; case MVT::Other: Op += ":ch"; break; case MVT::i1: Op += ":i1"; break; case MVT::i8: Op += ":i8"; break; case MVT::i16: Op += ":i16"; break; case MVT::i32: Op += ":i32"; break; case MVT::i64: Op += ":i64"; break; case MVT::i128: Op += ":i128"; break; case MVT::f32: Op += ":f32"; break; case MVT::f64: Op += ":f64"; break; case MVT::f80: Op += ":f80"; break; case MVT::f128: Op += ":f128"; break; case MVT::isVoid: Op += ":void"; break; } } if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(Node)) { Op += ": " + utostr(CSDN->getValue()); } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(Node)) { Op += ": " + ftostr(CSDN->getValue()); } else if (const GlobalAddressSDNode *GADN = dyn_cast<GlobalAddressSDNode>(Node)) { Op += ": " + GADN->getGlobal()->getName(); } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(Node)) { Op += " " + itostr(FIDN->getIndex()); } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Node)){ Op += "<" + utostr(CP->getIndex()) + ">"; } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(Node)) { Op = "BB: "; const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock(); if (LBB) Op += LBB->getName(); //Op += " " + (const void*)BBDN->getBasicBlock(); } else if (const RegSDNode *C2V = dyn_cast<RegSDNode>(Node)) { Op += " #" + utostr(C2V->getReg()); } else if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Node)) { Op += "'" + std::string(ES->getSymbol()) + "'"; } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(Node)) { if (M->getValue()) Op += "<" + M->getValue()->getName() + ":" + itostr(M->getOffset()) + ">"; else Op += "<null:" + itostr(M->getOffset()) + ">"; } return Op; } /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG /// rendered using 'dot'. /// void SelectionDAG::viewGraph() { std::string Filename = "/tmp/dag." + getMachineFunction().getFunction()->getName() + ".dot"; std::cerr << "Writing '" << Filename << "'... "; std::ofstream F(Filename.c_str()); if (!F) { std::cerr << " error opening file for writing!\n"; return; } WriteGraph(F, this); F.close(); std::cerr << "\n"; std::cerr << "Running 'dot' program... " << std::flush; if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename + " > /tmp/dag.tempgraph.ps").c_str())) { std::cerr << "Error running dot: 'dot' not in path?\n"; } else { std::cerr << "\n"; system("gv /tmp/dag.tempgraph.ps"); } system(("rm " + Filename + " /tmp/dag.tempgraph.ps").c_str()); } <commit_msg>If the Graphviz program is available, use it to visualize dot graphs.<commit_after>//===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements the SelectionDAG::viewGraph method. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/Function.h" #include "llvm/Support/GraphWriter.h" #include "llvm/ADT/StringExtras.h" #include <fstream> using namespace llvm; namespace llvm { template<> struct DOTGraphTraits<SelectionDAG*> : public DefaultDOTGraphTraits { static std::string getGraphName(const SelectionDAG *G) { return G->getMachineFunction().getFunction()->getName(); } static bool renderGraphFromBottomUp() { return true; } static std::string getNodeLabel(const SDNode *Node, const SelectionDAG *Graph); static std::string getNodeAttributes(const SDNode *N) { return "shape=Mrecord"; } static void addCustomGraphFeatures(SelectionDAG *G, GraphWriter<SelectionDAG*> &GW) { GW.emitSimpleNode(0, "plaintext=circle", "GraphRoot"); GW.emitEdge(0, -1, G->getRoot().Val, -1, ""); } }; } std::string DOTGraphTraits<SelectionDAG*>::getNodeLabel(const SDNode *Node, const SelectionDAG *G) { std::string Op = Node->getOperationName(); for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) { switch (Node->getValueType(i)) { default: Op += ":unknownvt!"; break; case MVT::Other: Op += ":ch"; break; case MVT::i1: Op += ":i1"; break; case MVT::i8: Op += ":i8"; break; case MVT::i16: Op += ":i16"; break; case MVT::i32: Op += ":i32"; break; case MVT::i64: Op += ":i64"; break; case MVT::i128: Op += ":i128"; break; case MVT::f32: Op += ":f32"; break; case MVT::f64: Op += ":f64"; break; case MVT::f80: Op += ":f80"; break; case MVT::f128: Op += ":f128"; break; case MVT::isVoid: Op += ":void"; break; } } if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(Node)) { Op += ": " + utostr(CSDN->getValue()); } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(Node)) { Op += ": " + ftostr(CSDN->getValue()); } else if (const GlobalAddressSDNode *GADN = dyn_cast<GlobalAddressSDNode>(Node)) { Op += ": " + GADN->getGlobal()->getName(); } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(Node)) { Op += " " + itostr(FIDN->getIndex()); } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Node)){ Op += "<" + utostr(CP->getIndex()) + ">"; } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(Node)) { Op = "BB: "; const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock(); if (LBB) Op += LBB->getName(); //Op += " " + (const void*)BBDN->getBasicBlock(); } else if (const RegSDNode *C2V = dyn_cast<RegSDNode>(Node)) { Op += " #" + utostr(C2V->getReg()); } else if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Node)) { Op += "'" + std::string(ES->getSymbol()) + "'"; } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(Node)) { if (M->getValue()) Op += "<" + M->getValue()->getName() + ":" + itostr(M->getOffset()) + ">"; else Op += "<null:" + itostr(M->getOffset()) + ">"; } return Op; } /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG /// rendered using 'dot'. /// void SelectionDAG::viewGraph() { std::string Filename = "/tmp/dag." + getMachineFunction().getFunction()->getName() + ".dot"; std::cerr << "Writing '" << Filename << "'... "; std::ofstream F(Filename.c_str()); if (!F) { std::cerr << " error opening file for writing!\n"; return; } WriteGraph(F, this); F.close(); std::cerr << "\n"; #ifdef HAVE_GRAPHVIZ std::cerr << "Running 'Graphviz' program... " << std::flush; if (system(("Graphviz " + Filename).c_str())) { std::cerr << "Error viewing graph: 'Graphviz' not in path?\n"; } else { return; } #endif std::cerr << "Running 'dot' program... " << std::flush; if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename + " > /tmp/dag.tempgraph.ps").c_str())) { std::cerr << "Error viewing graph: 'dot' not in path?\n"; } else { std::cerr << "\n"; system("gv /tmp/dag.tempgraph.ps"); } system(("rm " + Filename + " /tmp/dag.tempgraph.ps").c_str()); } <|endoftext|>
<commit_before>/* Copyright 2014 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "scriptThread.h" #include <QtCore/QEventLoop> #include <QtCore/QDateTime> #include <QScriptValueIterator> #include <QJsonObject> #include "threading.h" #include <QsLog.h> using namespace trikScriptRunner; ScriptThread::ScriptThread(Threading &threading, const QString &id, QScriptEngine *engine, const QString &script) : mId(id) , mEngine(engine) , mScript(script) , mThreading(threading) { } ScriptThread::~ScriptThread() { } void ScriptThread::run() { QLOG_INFO() << "Started thread" << this; qsrand(QDateTime::currentMSecsSinceEpoch()); mEngine->evaluate(mScript); if (mEngine->hasUncaughtException()) { const auto line = mEngine->uncaughtExceptionLineNumber(); const auto & message = mEngine->uncaughtException().toString(); const auto & backtrace = mEngine->uncaughtExceptionBacktrace().join("\n"); mError = tr("Line %1: %2").arg(QString::number(line), message) + "\nBacktrace"+ backtrace; QLOG_ERROR() << "Uncaught exception with next backtrace" << backtrace; } else if (mThreading.inEventDrivenMode()) { QEventLoop loop; connect(this, SIGNAL(stopRunning()), &loop, SLOT(quit()), Qt::QueuedConnection); loop.exec(); } mEngine->deleteLater(); mThreading.threadFinished(mId); QLOG_INFO() << "Ended evaluation, thread" << this; } void ScriptThread::abort() { mEngine->abortEvaluation(); emit stopRunning(); } QString ScriptThread::id() const { return mId; } QString ScriptThread::error() const { return mError; } bool ScriptThread::isEvaluating() const { return mEngine->isEvaluating(); } /* TODO: Fix design error. This slot is called on wrong thread (probably) */ void ScriptThread::onGetVariables(const QString &propertyName) { if (mEngine != nullptr) { QScriptValueIterator it(mEngine->globalObject().property(propertyName)); QJsonObject json; while (it.hasNext()) { it.next(); json[it.name()] = it.value().toString(); } emit variablesReady(json); } } <commit_msg>Do not add empty backtrace in JS error<commit_after>/* Copyright 2014 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "scriptThread.h" #include <QtCore/QEventLoop> #include <QtCore/QDateTime> #include <QScriptValueIterator> #include <QJsonObject> #include "threading.h" #include <QsLog.h> using namespace trikScriptRunner; ScriptThread::ScriptThread(Threading &threading, const QString &id, QScriptEngine *engine, const QString &script) : mId(id) , mEngine(engine) , mScript(script) , mThreading(threading) { } ScriptThread::~ScriptThread() { } void ScriptThread::run() { QLOG_INFO() << "Started thread" << this; qsrand(QDateTime::currentMSecsSinceEpoch()); mEngine->evaluate(mScript); if (mEngine->hasUncaughtException()) { const auto line = mEngine->uncaughtExceptionLineNumber(); const auto &message = mEngine->uncaughtException().toString(); const auto &backtrace = mEngine->uncaughtExceptionBacktrace(); mError = tr("Line %1: %2").arg(QString::number(line), message); if (!backtrace.isEmpty()) { mError += "\n" + backtrace.join('\n'); } QLOG_ERROR() << "Uncaught exception with next backtrace" << backtrace; } else if (mThreading.inEventDrivenMode()) { QEventLoop loop; connect(this, SIGNAL(stopRunning()), &loop, SLOT(quit()), Qt::QueuedConnection); loop.exec(); } mEngine->deleteLater(); mThreading.threadFinished(mId); QLOG_INFO() << "Ended evaluation, thread" << this; } void ScriptThread::abort() { mEngine->abortEvaluation(); emit stopRunning(); } QString ScriptThread::id() const { return mId; } QString ScriptThread::error() const { return mError; } bool ScriptThread::isEvaluating() const { return mEngine->isEvaluating(); } /* TODO: Fix design error. This slot is called on wrong thread (probably) */ void ScriptThread::onGetVariables(const QString &propertyName) { if (mEngine != nullptr) { QScriptValueIterator it(mEngine->globalObject().property(propertyName)); QJsonObject json; while (it.hasNext()) { it.next(); json[it.name()] = it.value().toString(); } emit variablesReady(json); } } <|endoftext|>
<commit_before>//===--- GuaranteedARCOpts.cpp --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-guaranteed-arc-opts" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SIL/SILVisitor.h" using namespace swift; namespace { struct GuaranteedARCOptsVisitor : SILInstructionVisitor<GuaranteedARCOptsVisitor, bool> { bool visitValueBase(ValueBase *V) { return false; } bool visitDestroyAddrInst(DestroyAddrInst *DAI); bool visitStrongReleaseInst(StrongReleaseInst *SRI); bool visitDestroyValueInst(DestroyValueInst *DVI); bool visitReleaseValueInst(ReleaseValueInst *RVI); }; } // end anonymous namespace static SILBasicBlock::reverse_iterator getPrevReverseIterator(SILInstruction *I) { return std::next(I->getIterator().getReverse()); } bool GuaranteedARCOptsVisitor::visitDestroyAddrInst(DestroyAddrInst *DAI) { SILValue Operand = DAI->getOperand(); for (auto II = getPrevReverseIterator(DAI), IE = DAI->getParent()->rend(); II != IE;) { auto *Inst = &*II; ++II; if (auto *CA = dyn_cast<CopyAddrInst>(Inst)) { if (CA->getSrc() == Operand && !CA->isTakeOfSrc()) { CA->setIsTakeOfSrc(IsTake); DAI->eraseFromParent(); return true; } } // destroy_addrs commonly exist in a block of dealloc_stack's, which don't // affect take-ability. if (isa<DeallocStackInst>(Inst)) continue; // This code doesn't try to prove tricky validity constraints about whether // it is safe to push the destroy_addr past interesting instructions. if (Inst->mayHaveSideEffects()) break; } // If we didn't find a copy_addr to fold this into, emit the destroy_addr. return false; } static bool couldReduceStrongRefcount(SILInstruction *Inst) { // Simple memory accesses cannot reduce refcounts. if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) || isa<RetainValueInst>(Inst) || isa<UnownedRetainInst>(Inst) || isa<UnownedReleaseInst>(Inst) || isa<StrongRetainUnownedInst>(Inst) || isa<StoreWeakInst>(Inst) || isa<StrongRetainInst>(Inst) || isa<AllocStackInst>(Inst) || isa<DeallocStackInst>(Inst)) return false; // Assign and copyaddr of trivial types cannot drop refcounts, and 'inits' // never can either. Nontrivial ones can though, because the overwritten // value drops a retain. We would have to do more alias analysis to be able // to safely ignore one of those. if (auto *AI = dyn_cast<AssignInst>(Inst)) { SILType StoredType = AI->getOperand(0)->getType(); if (StoredType.isTrivial(Inst->getModule()) || StoredType.is<ReferenceStorageType>()) return false; } if (auto *CAI = dyn_cast<CopyAddrInst>(Inst)) { // Initializations can only increase refcounts. if (CAI->isInitializationOfDest()) return false; SILType StoredType = CAI->getOperand(0)->getType().getObjectType(); if (StoredType.isTrivial(Inst->getModule()) || StoredType.is<ReferenceStorageType>()) return false; } // This code doesn't try to prove tricky validity constraints about whether // it is safe to push the release past interesting instructions. return Inst->mayHaveSideEffects(); } bool GuaranteedARCOptsVisitor::visitStrongReleaseInst(StrongReleaseInst *SRI) { SILValue Operand = SRI->getOperand(); // Release on a functionref is a noop. if (isa<FunctionRefInst>(Operand)) { SRI->eraseFromParent(); return true; } // Check to see if the instruction immediately before the insertion point is a // strong_retain of the specified operand. If so, we can zap the pair. for (auto II = getPrevReverseIterator(SRI), IE = SRI->getParent()->rend(); II != IE;) { auto *Inst = &*II; ++II; if (auto *SRA = dyn_cast<StrongRetainInst>(Inst)) { if (SRA->getOperand() == Operand) { SRA->eraseFromParent(); SRI->eraseFromParent(); return true; } // Skip past unrelated retains. continue; } // Scan past simple instructions that cannot reduce strong refcounts. if (couldReduceStrongRefcount(Inst)) break; } // If we didn't find a retain to fold this into, return false. return false; } bool GuaranteedARCOptsVisitor::visitDestroyValueInst(DestroyValueInst *DVI) { SILValue Operand = DVI->getOperand(); for (auto II = getPrevReverseIterator(DVI), IE = DVI->getParent()->rend(); II != IE;) { auto *Inst = &*II; ++II; if (auto *CVI = dyn_cast<CopyValueInst>(Inst)) { if (SILValue(CVI) == Operand || CVI->getOperand() == Operand) { CVI->replaceAllUsesWith(CVI->getOperand()); CVI->eraseFromParent(); DVI->eraseFromParent(); return true; } // Skip past unrelated retains. continue; } // Scan past simple instructions that cannot reduce refcounts. if (couldReduceStrongRefcount(Inst)) break; } return false; } bool GuaranteedARCOptsVisitor::visitReleaseValueInst(ReleaseValueInst *RVI) { SILValue Operand = RVI->getOperand(); for (auto II = getPrevReverseIterator(RVI), IE = RVI->getParent()->rend(); II != IE;) { auto *Inst = &*II; ++II; if (auto *SRA = dyn_cast<RetainValueInst>(Inst)) { if (SRA->getOperand() == Operand) { SRA->eraseFromParent(); RVI->eraseFromParent(); return true; } // Skip past unrelated retains. continue; } // Scan past simple instructions that cannot reduce refcounts. if (couldReduceStrongRefcount(Inst)) break; } // If we didn't find a retain to fold this into, emit the release. return false; } //===----------------------------------------------------------------------===// // Top Level Entrypoint //===----------------------------------------------------------------------===// namespace { struct GuaranteedARCOpts : SILFunctionTransform { void run() override { GuaranteedARCOptsVisitor Visitor; bool MadeChange = false; SILFunction *F = getFunction(); for (auto &BB : *F) { for (auto II = BB.begin(), IE = BB.end(); II != IE;) { SILInstruction *I = &*II; ++II; MadeChange |= Visitor.visit(I); } } if (MadeChange) { invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } } StringRef getName() override { return "Guaranteed ARC Opts"; } }; } // end anonymous namespace SILTransform *swift::createGuaranteedARCOpts() { return new GuaranteedARCOpts(); } <commit_msg>[arc] Add a statistic to guaranteed-arc-opts that prints out the number of instructions removed.<commit_after>//===--- GuaranteedARCOpts.cpp --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-guaranteed-arc-opts" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SIL/SILVisitor.h" #include "llvm/ADT/Statistic.h" using namespace swift; STATISTIC(NumInstsEliminated, "Number of instructions eliminated"); namespace { struct GuaranteedARCOptsVisitor : SILInstructionVisitor<GuaranteedARCOptsVisitor, bool> { bool visitValueBase(ValueBase *V) { return false; } bool visitDestroyAddrInst(DestroyAddrInst *DAI); bool visitStrongReleaseInst(StrongReleaseInst *SRI); bool visitDestroyValueInst(DestroyValueInst *DVI); bool visitReleaseValueInst(ReleaseValueInst *RVI); }; } // end anonymous namespace static SILBasicBlock::reverse_iterator getPrevReverseIterator(SILInstruction *I) { return std::next(I->getIterator().getReverse()); } bool GuaranteedARCOptsVisitor::visitDestroyAddrInst(DestroyAddrInst *DAI) { SILValue Operand = DAI->getOperand(); for (auto II = getPrevReverseIterator(DAI), IE = DAI->getParent()->rend(); II != IE;) { auto *Inst = &*II; ++II; if (auto *CA = dyn_cast<CopyAddrInst>(Inst)) { if (CA->getSrc() == Operand && !CA->isTakeOfSrc()) { CA->setIsTakeOfSrc(IsTake); DAI->eraseFromParent(); NumInstsEliminated += 2; return true; } } // destroy_addrs commonly exist in a block of dealloc_stack's, which don't // affect take-ability. if (isa<DeallocStackInst>(Inst)) continue; // This code doesn't try to prove tricky validity constraints about whether // it is safe to push the destroy_addr past interesting instructions. if (Inst->mayHaveSideEffects()) break; } // If we didn't find a copy_addr to fold this into, emit the destroy_addr. return false; } static bool couldReduceStrongRefcount(SILInstruction *Inst) { // Simple memory accesses cannot reduce refcounts. if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) || isa<RetainValueInst>(Inst) || isa<UnownedRetainInst>(Inst) || isa<UnownedReleaseInst>(Inst) || isa<StrongRetainUnownedInst>(Inst) || isa<StoreWeakInst>(Inst) || isa<StrongRetainInst>(Inst) || isa<AllocStackInst>(Inst) || isa<DeallocStackInst>(Inst)) return false; // Assign and copyaddr of trivial types cannot drop refcounts, and 'inits' // never can either. Nontrivial ones can though, because the overwritten // value drops a retain. We would have to do more alias analysis to be able // to safely ignore one of those. if (auto *AI = dyn_cast<AssignInst>(Inst)) { SILType StoredType = AI->getOperand(0)->getType(); if (StoredType.isTrivial(Inst->getModule()) || StoredType.is<ReferenceStorageType>()) return false; } if (auto *CAI = dyn_cast<CopyAddrInst>(Inst)) { // Initializations can only increase refcounts. if (CAI->isInitializationOfDest()) return false; SILType StoredType = CAI->getOperand(0)->getType().getObjectType(); if (StoredType.isTrivial(Inst->getModule()) || StoredType.is<ReferenceStorageType>()) return false; } // This code doesn't try to prove tricky validity constraints about whether // it is safe to push the release past interesting instructions. return Inst->mayHaveSideEffects(); } bool GuaranteedARCOptsVisitor::visitStrongReleaseInst(StrongReleaseInst *SRI) { SILValue Operand = SRI->getOperand(); // Release on a functionref is a noop. if (isa<FunctionRefInst>(Operand)) { SRI->eraseFromParent(); ++NumInstsEliminated; return true; } // Check to see if the instruction immediately before the insertion point is a // strong_retain of the specified operand. If so, we can zap the pair. for (auto II = getPrevReverseIterator(SRI), IE = SRI->getParent()->rend(); II != IE;) { auto *Inst = &*II; ++II; if (auto *SRA = dyn_cast<StrongRetainInst>(Inst)) { if (SRA->getOperand() == Operand) { SRA->eraseFromParent(); SRI->eraseFromParent(); NumInstsEliminated += 2; return true; } // Skip past unrelated retains. continue; } // Scan past simple instructions that cannot reduce strong refcounts. if (couldReduceStrongRefcount(Inst)) break; } // If we didn't find a retain to fold this into, return false. return false; } bool GuaranteedARCOptsVisitor::visitDestroyValueInst(DestroyValueInst *DVI) { SILValue Operand = DVI->getOperand(); for (auto II = getPrevReverseIterator(DVI), IE = DVI->getParent()->rend(); II != IE;) { auto *Inst = &*II; ++II; if (auto *CVI = dyn_cast<CopyValueInst>(Inst)) { if (SILValue(CVI) == Operand || CVI->getOperand() == Operand) { CVI->replaceAllUsesWith(CVI->getOperand()); CVI->eraseFromParent(); DVI->eraseFromParent(); NumInstsEliminated += 2; return true; } // Skip past unrelated retains. continue; } // Scan past simple instructions that cannot reduce refcounts. if (couldReduceStrongRefcount(Inst)) break; } return false; } bool GuaranteedARCOptsVisitor::visitReleaseValueInst(ReleaseValueInst *RVI) { SILValue Operand = RVI->getOperand(); for (auto II = getPrevReverseIterator(RVI), IE = RVI->getParent()->rend(); II != IE;) { auto *Inst = &*II; ++II; if (auto *SRA = dyn_cast<RetainValueInst>(Inst)) { if (SRA->getOperand() == Operand) { SRA->eraseFromParent(); RVI->eraseFromParent(); NumInstsEliminated += 2; return true; } // Skip past unrelated retains. continue; } // Scan past simple instructions that cannot reduce refcounts. if (couldReduceStrongRefcount(Inst)) break; } // If we didn't find a retain to fold this into, emit the release. return false; } //===----------------------------------------------------------------------===// // Top Level Entrypoint //===----------------------------------------------------------------------===// namespace { struct GuaranteedARCOpts : SILFunctionTransform { void run() override { GuaranteedARCOptsVisitor Visitor; bool MadeChange = false; SILFunction *F = getFunction(); for (auto &BB : *F) { for (auto II = BB.begin(), IE = BB.end(); II != IE;) { SILInstruction *I = &*II; ++II; MadeChange |= Visitor.visit(I); } } if (MadeChange) { invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } } StringRef getName() override { return "Guaranteed ARC Opts"; } }; } // end anonymous namespace SILTransform *swift::createGuaranteedARCOpts() { return new GuaranteedARCOpts(); } <|endoftext|>
<commit_before>#include "KnowledgeConstructionPass.h" KnowledgeConstruction::~KnowledgeConstruction() { delete instances; delete instanceStream; } void KnowledgeConstruction::addToInstanceStream(std::string &instance) { (*instanceStream) << instance << " "; } void KnowledgeConstruction::registerInstance(PointerAddress ptrAdr, std::string &instance) { std::pair<PointerAddress, std::string&> pair (ptrAdr, instance); instances->insert(pair); } void KnowledgeConstruction::addToKnowledgeBase(PointerAddress ptrAddress, std::string &instance) { addToInstanceStream(instance); registerInstance(ptrAddress, instance); } std::string KnowledgeConstruction::route(Value* val, FunctionNamer& namer, char* parent) { if(namer.pointerRegistered((PointerAddress)val)) { return namer.nameFromPointer((PointerAddress)val); } else { if(User* u0 = dyn_cast<User>(val)) { return route(u0, namer, parent); } else if(BasicBlock* bb = dyn_cast<BasicBlock>(val)) { return route(bb, namer, parent); } else if(Argument* arg = dyn_cast<Argument>(val)) { return route(arg, namer, parent); } else if(InlineAsm* iasm = dyn_cast<InlineAsm>(val)) { return route(iasm, namer, parent); } else if(MDNode* mdn = dyn_cast<MDNode>(val)) { return route(mdn, namer, parent); } else if(MDString* mds = dyn_cast<MDString>(val)) { return route(mds, namer, parent); } else { llvm::errs() << "WARNING: Found an unimplemented value " << *val << '\n'; char* gensymBuffer = (char*)calloc(64, sizeof(char)); namer.makeGensymID(gensymBuffer); std::string name(gensymBuffer); free(gensymBuffer); CLIPSValueBuilder vb (name, "LLVMValue", namer); vb.open(); vb.addFields(val, parent); vb.close(); std::string& str = vb.getCompletedString(); addToKnowledgeBase((PointerAddress)val, str); return name; } } } std::string route(Value* val, FunctionNamer& namer) { } char KnowledgeConstruction::ID = 0; static RegisterPass<KnowledgeConstruction> kc("knowledge", "Knowledge constructor", false, false); INITIALIZE_PASS(KnowledgeConstruction, "knowledge", "Knowledge constructor", false, false) //for opt <commit_msg>Completed route functions for MDNode, MDString, Argument, and InlineASM<commit_after>#include "KnowledgeConstructionPass.h" KnowledgeConstruction::~KnowledgeConstruction() { delete instances; delete instanceStream; } void KnowledgeConstruction::addToInstanceStream(std::string &instance) { (*instanceStream) << instance << " "; } void KnowledgeConstruction::registerInstance(PointerAddress ptrAdr, std::string &instance) { std::pair<PointerAddress, std::string&> pair (ptrAdr, instance); instances->insert(pair); } void KnowledgeConstruction::addToKnowledgeBase(PointerAddress ptrAddress, std::string &instance) { addToInstanceStream(instance); registerInstance(ptrAddress, instance); } std::string KnowledgeConstruction::route(Value* val, FunctionNamer& namer, char* parent) { if(namer.pointerRegistered((PointerAddress)val)) { return namer.nameFromPointer((PointerAddress)val); } else { if(User* u0 = dyn_cast<User>(val)) { return route(u0, namer, parent); } else if(BasicBlock* bb = dyn_cast<BasicBlock>(val)) { return route(bb, namer, parent); } else if(Argument* arg = dyn_cast<Argument>(val)) { return route(arg, namer, parent); } else if(InlineAsm* iasm = dyn_cast<InlineAsm>(val)) { return route(iasm, namer, parent); } else if(MDNode* mdn = dyn_cast<MDNode>(val)) { return route(mdn, namer, parent); } else if(MDString* mds = dyn_cast<MDString>(val)) { return route(mds, namer, parent); } else { llvm::errs() << "WARNING: Found an unimplemented value " << *val << '\n'; char* gensymBuffer = (char*)calloc(64, sizeof(char)); namer.makeGensymID(gensymBuffer); std::string name(gensymBuffer); free(gensymBuffer); CLIPSValueBuilder vb (name, "LLVMValue", namer); vb.open(); vb.addFields(val, parent); vb.close(); std::string& str = vb.getCompletedString(); addToKnowledgeBase((PointerAddress)val, str); return name; } } } std::string KnowledgeConstruction::route(Value* val, FunctionNamer& namer) { if(Instruction* inst = dyn_cast<Instruction>(val)) { return route(inst, namer, (char*)inst->getParent()->getName().data()); } else { return route(val, namer, "nil"); } } std::string KnowledgeConstruction::route(User* user, FunctionNamer& namer, char* parent) { } std::string KnowledgeConstruction::route(Constant* cnst, FunctionNamer& namer) { } std::string KnowledgeConstruction::route(Constant* cnst, FunctionNamer& namer, char* parent) { } std::string KnowledgeConstruction::route(Instruction* inst, FunctionNamer& namer, char* parent) { } std::string KnowledgeConstruction::route(Type* t, FunctionNamer& namer) { } std::string KnowledgeConstruction::route(Operator* op, FunctionNamer& namer, char* parent) { } std::string KnowledgeConstruction::route(BasicBlock* bb, FunctionNamer& namer, char* parent, bool constructInstructions) { } std::string KnowledgeConstruction::route(Region* region, FunctionNamer& namer, char* parent) { } std::string KnowledgeConstruction::route(Argument* arg, FunctionNamer& namer, char* parent) { if(namer.pointerRegistered((PointerAddress)arg)) { return namer.nameFromPointer((PointerAddress)arg); } else { char* gensymBuffer = (char*)calloc(64, sizeof(char)); namer.makeGensymID(gensymBuffer); std::string name(gensymBuffer); free(gensymBuffer); CLIPSArgumentBuilder ab(name, namer); ab.open(); ab.addFields(name, parent); ab.clone(); std::string &str = ab.getCompletedString(); addToKnowledgeBase((PointerAddress)arg, str); return name; } } std::string KnowledgeConstruction::route(Loop* loop, FunctionNamer& namer, char* parent) { } std::string KnowledgeConstruction::route(MDString* mds, FunctionNamer& namer, char* parent) { if(namer.pointerRegistered((PointerAddress)mds)) { return namer.nameFromPointer((PointerAddress)mds); } else { char* gensymBuffer = (char*)calloc(64, sizeof(char)); namer.makeGensymID(gensymBuffer); std::string name(gensymBuffer); free(gensymBuffer); CLIPSValueBuilder vb(name, "LLVMMDString", namer); vb.open(); vb.addFields(val, parent); vb.addStringField("String", mds->getString()); vb.close(); std::string &str = vb.getCompletedString(); addToKnowledgeBase((PointerAddress)mds, str); return name; } } std::string KnowledgeConstruction::route(MDNode* mdn, FunctionNamer& namer, char* parent) { if(namer.pointerRegistered((PointerAddress)mdn)) { return namer.nameFromPointer((PointerAddress)mdn); } else { char* gensymBuffer = (char*)calloc(64, sizeof(char)); namer.makeGensymID(gensymBuffer); std::string name(gensymBuffer); free(gensymBuffer); CLIPSValueBuilder vb (name, "LLVMMDNode", namer); vb.open(); vb.addFields(val, parent); if(mdn->isFunctionLocal()) vb.addTrueField("IsFunctionLocal"); const Function* fn = mdn->getFunction(); if(fn != 0) { vb.addField("TargetFunction", fn->getName()); } unsigned total = mdn->getNumOperands(); if(total > 0) { char* cName = (char*)name.c_str(); vb.openField("Operands"); for(unsigned i = 0; i < total; ++i) { vb.appendValue(route(mdn->getOperand(i), namer, cName)); } vb.closeField(); } vb.close(); std::string &str = vb.getCompletedString(); addToKnowledgeBase((PointerAddress)mdn, str); return name; } } std::string KnowledgeConstruction::route(InlineAsm* iasm, FunctionNamer& namer, char* parent) { if(namer.pointerRegistered((PointerAddress)iasm)) { return namer.nameFromPointer((PointerAddress)iasm); } else { char* gensymBuffer = (char*)calloc(64, sizeof(char)); namer.makeGensymID(gensymBuffer); std::string name(gensymBuffer); free(gensymBuffer); CLIPSValueBuilder vb (name, "LLVMInlineAsm", namer); vb.open(); vb.addFields(val, parent); if(iasm->hasSideEffects()) vb.addTrueField("HasSideEffects"); if(iasm->isAlignStack()) vb.addTrueField("IsAlignStack"); const std::string& aStr = iasm->getAsmString(); const std::string& cnStr = iasm->getConstraintString(); vb.addStringField("AsmString", aStr); vb.addStringField("ConstraintString", cnStr); vb.close(); std::string &str = vb.getCompletedString(); addToKnowledgeBase((PointerAddress)iasm, str); return name; } } void KnowledgeConstruction::route(RegionInfo& ri, FunctionNamer& namer, char* parent) { } void KnowledgeConstruction::route(LoopInfo& li, FunctionNamer& namer, char* parent) { } void KnowledgeConstruction::updateFunctionContents(Function& fn, FunctionNamer& namer) { } char KnowledgeConstruction::ID = 0; static RegisterPass<KnowledgeConstruction> kc("knowledge", "Knowledge constructor", false, false); INITIALIZE_PASS(KnowledgeConstruction, "knowledge", "Knowledge constructor", false, false) //for opt <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de> * Changed: $Id$ * * Version: $Revision$ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief Export routines for CPACS configurations. */ #include "CTiglExportIges.h" #include "CCPACSImportExport.h" #include "CCPACSConfiguration.h" #include "CCPACSFuselageSegment.h" #include "CCPACSWingSegment.h" #include "CTiglError.h" #include "CNamedShape.h" #include "tiglcommonfunctions.h" #include "CTiglFusePlane.h" #include "TopoDS_Shape.hxx" #include "TopoDS_Edge.hxx" #include "Standard_CString.hxx" #include "IGESControl_Controller.hxx" #include "IGESControl_Writer.hxx" #include "IGESData_IGESModel.hxx" #include "Interface_Static.hxx" #include "BRepAlgoAPI_Cut.hxx" #include "ShapeAnalysis_FreeBounds.hxx" #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <TopTools_IndexedMapOfShape.hxx> // IGES export #include <TransferBRep_ShapeMapper.hxx> #include <Transfer_FinderProcess.hxx> #include <TransferBRep.hxx> #include <IGESData_IGESEntity.hxx> #ifdef TIGL_USE_XCAF // OCAF #include <TDocStd_Document.hxx> #include <TDF_Label.hxx> #include <TDataStd_Name.hxx> // XCAF, TODO: Get rid of xcaf #include <XCAFApp_Application.hxx> #include <XCAFDoc_DocumentTool.hxx> #include <XCAFDoc_ShapeTool.hxx> #include "IGESCAFControl_Writer.hxx" #endif // TIGL_USE_XCAF #include <map> #include <cassert> namespace { /** * @brief WriteIGESFaceNames takes the names of each face and writes it into the IGES model. */ void WriteIGESFaceNames(Handle_Transfer_FinderProcess FP, const PNamedShape shape) { if (!shape) { return; } TopTools_IndexedMapOfShape faceMap; TopExp::MapShapes(shape->Shape(), TopAbs_FACE, faceMap); for (int iface = 1; iface <= faceMap.Extent(); ++iface) { TopoDS_Face face = TopoDS::Face(faceMap(iface)); std::string name = shape->ShortName(); PNamedShape origin = shape->GetFaceTraits(iface-1).Origin(); if (origin) { name = origin->ShortName(); } // set face name Handle(IGESData_IGESEntity) entity; Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, face ); if ( FP->FindTypedTransient ( mapper, STANDARD_TYPE(IGESData_IGESEntity), entity ) ) { Handle(TCollection_HAsciiString) str = new TCollection_HAsciiString(name.c_str()); entity->SetLabel(str); } } } } //namespace namespace tigl { // Constructor CTiglExportIges::CTiglExportIges(CCPACSConfiguration& config) : myConfig(config) { myStoreType = NAMED_COMPOUNDS; } // Destructor CTiglExportIges::~CTiglExportIges(void) { } void CTiglExportIges::SetTranslationParameters() const { Interface_Static::SetCVal("xstep.cascade.unit", "M"); Interface_Static::SetCVal("write.iges.unit", "M"); /* * BRep entities in IGES are experimental and untested. * They allow to specify things like shells and solids. * It seems, that CATIA does not support these entities. * Hence we stay the compatible way. */ Interface_Static::SetIVal("write.iges.brep.mode", 0); Interface_Static::SetCVal("write.iges.header.author", "TiGL"); Interface_Static::SetCVal("write.iges.header.company", "German Aerospace Center (DLR), SC"); } // Exports the whole configuration as IGES file // All wing- and fuselage segments are exported as single bodys void CTiglExportIges::ExportIGES(const std::string& filename) const { if ( filename.empty()) { LOG(ERROR) << "Error: Empty filename in ExportIGES."; return; } ListPNamedShape shapes; // Export all wings of the configuration for (int w = 1; w <= myConfig.GetWingCount(); w++) { CCPACSWing& wing = myConfig.GetWing(w); for (int i = 1; i <= wing.GetSegmentCount(); i++) { CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i); TopoDS_Shape loft = segment.GetLoft(); PNamedShape shape(new CNamedShape(loft, segment.GetUID().c_str())); shapes.push_back(shape); } } // Export all fuselages of the configuration for (int f = 1; f <= myConfig.GetFuselageCount(); f++) { CCPACSFuselage& fuselage = myConfig.GetFuselage(f); for (int i = 1; i <= fuselage.GetSegmentCount(); i++) { CCPACSFuselageSegment& segment = (tigl::CCPACSFuselageSegment &) fuselage.GetSegment(i); TopoDS_Shape loft = segment.GetLoft(); // Transform loft by fuselage transformation => absolute world coordinates loft = fuselage.GetFuselageTransformation().Transform(loft); PNamedShape shape(new CNamedShape(loft, segment.GetUID().c_str())); shapes.push_back(shape); } } CCPACSFarField& farfield = myConfig.GetFarField(); if (farfield.GetFieldType() != NONE) { PNamedShape shape(new CNamedShape(farfield.GetLoft(), farfield.GetUID().c_str())); shapes.push_back(shape); } // write iges try { ExportShapes(shapes, filename); } catch (CTiglError&) { throw CTiglError("Cannot export airplane in CTiglExportIges", TIGL_ERROR); } } // Exports the whole configuration as one fused part to an IGES file void CTiglExportIges::ExportFusedIGES(const std::string& filename) { if (filename.empty()) { LOG(ERROR) << "Error: Empty filename in ExportFusedIGES."; return; } PTiglFusePlane fuser = myConfig.AircraftFusingAlgo(); fuser->SetResultMode(HALF_PLANE_TRIMMED_FF); assert(fuser); PNamedShape fusedAirplane = fuser->FusedPlane(); PNamedShape farField = fuser->FarField(); if (!fusedAirplane) { throw CTiglError("Error computing fused airplane.", TIGL_NULL_POINTER); } try { ListPNamedShape l; l.push_back(fusedAirplane); l.push_back(farField); // add intersections const ListPNamedShape& ints = fuser->Intersections(); ListPNamedShape::const_iterator it; for (it = ints.begin(); it != ints.end(); ++it) { l.push_back(*it); } ExportShapes(l, filename); } catch (CTiglError&) { throw CTiglError("Cannot export fused Airplane as IGES", TIGL_ERROR); } } // Save a sequence of shapes in IGES Format void CTiglExportIges::ExportShapes(const ListPNamedShape& shapes, const std::string& filename) const { IGESControl_Controller::Init(); if ( filename.empty()) { LOG(ERROR) << "Error: Empty filename in ExportShapes."; return; } ListPNamedShape::const_iterator it; SetTranslationParameters(); #ifdef TIGL_USE_XCAF // create the xde document Handle(XCAFApp_Application) hApp = XCAFApp_Application::GetApplication(); Handle(TDocStd_Document) hDoc; hApp->NewDocument("MDTV-XCAF", hDoc); Handle(XCAFDoc_ShapeTool) myAssembly = XCAFDoc_DocumentTool::ShapeTool(hDoc->Main()); IGESCAFControl_Writer igesWriter; for (it = shapes.begin(); it != shapes.end(); ++it) { InsertShapeToCAF(myAssembly, *it, true); } igesWriter.Model()->ApplyStatic(); // apply set parameters if (igesWriter.Transfer(hDoc) == Standard_False) { throw CTiglError("Cannot export fused airplane as IGES", TIGL_ERROR); } #else IGESControl_Writer igesWriter; igesWriter.Model()->ApplyStatic(); for (it = shapes.begin(); it != shapes.end(); ++it) { PNamedShape pshape = *it; igesWriter.AddShape (pshape->Shape()); } igesWriter.ComputeModel(); #endif // write face entity names for (it = shapes.begin(); it != shapes.end(); ++it) { PNamedShape pshape = *it; WriteIGESFaceNames(igesWriter.TransferProcess(), pshape); } if (igesWriter.Write(const_cast<char*>(filename.c_str())) != Standard_True) { throw CTiglError("Error: Export of shapes to IGES file failed in CCPACSImportExport::SaveIGES", TIGL_ERROR); } } void CTiglExportIges::SetOCAFStoreType(ShapeStoreType type) { myStoreType = type; } } // end namespace tigl <commit_msg>IGES export behaviour now equals STEP export<commit_after>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de> * Changed: $Id$ * * Version: $Revision$ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief Export routines for CPACS configurations. */ #include "CTiglExportIges.h" #include "CCPACSImportExport.h" #include "CCPACSConfiguration.h" #include "CCPACSFuselageSegment.h" #include "CCPACSWingSegment.h" #include "CTiglError.h" #include "CNamedShape.h" #include "tiglcommonfunctions.h" #include "CTiglFusePlane.h" #include "TopoDS_Shape.hxx" #include "TopoDS_Edge.hxx" #include "Standard_CString.hxx" #include "IGESControl_Controller.hxx" #include "IGESControl_Writer.hxx" #include "IGESData_IGESModel.hxx" #include "Interface_Static.hxx" #include "BRepAlgoAPI_Cut.hxx" #include "ShapeAnalysis_FreeBounds.hxx" #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <TopTools_IndexedMapOfShape.hxx> // IGES export #include <TransferBRep_ShapeMapper.hxx> #include <Transfer_FinderProcess.hxx> #include <TransferBRep.hxx> #include <IGESData_IGESEntity.hxx> #ifdef TIGL_USE_XCAF // OCAF #include <TDocStd_Document.hxx> #include <TDF_Label.hxx> #include <TDataStd_Name.hxx> // XCAF, TODO: Get rid of xcaf #include <XCAFApp_Application.hxx> #include <XCAFDoc_DocumentTool.hxx> #include <XCAFDoc_ShapeTool.hxx> #include "IGESCAFControl_Writer.hxx" #endif // TIGL_USE_XCAF #include <map> #include <cassert> namespace { /** * @brief WriteIGESFaceNames takes the names of each face and writes it into the IGES model. */ void WriteIGESFaceNames(Handle_Transfer_FinderProcess FP, const PNamedShape shape) { if (!shape) { return; } TopTools_IndexedMapOfShape faceMap; TopExp::MapShapes(shape->Shape(), TopAbs_FACE, faceMap); for (int iface = 1; iface <= faceMap.Extent(); ++iface) { TopoDS_Face face = TopoDS::Face(faceMap(iface)); std::string faceName = shape->GetFaceTraits(iface-1).Name(); // set face name Handle(IGESData_IGESEntity) entity; Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, face ); if ( FP->FindTypedTransient ( mapper, STANDARD_TYPE(IGESData_IGESEntity), entity ) ) { Handle(TCollection_HAsciiString) str = new TCollection_HAsciiString(faceName.c_str()); entity->SetLabel(str); } } } } //namespace namespace tigl { // Constructor CTiglExportIges::CTiglExportIges(CCPACSConfiguration& config) : myConfig(config) { myStoreType = NAMED_COMPOUNDS; } // Destructor CTiglExportIges::~CTiglExportIges(void) { } void CTiglExportIges::SetTranslationParameters() const { Interface_Static::SetCVal("xstep.cascade.unit", "M"); Interface_Static::SetCVal("write.iges.unit", "M"); /* * BRep entities in IGES are experimental and untested. * They allow to specify things like shells and solids. * It seems, that CATIA does not support these entities. * Hence we stay the compatible way. */ Interface_Static::SetIVal("write.iges.brep.mode", 0); Interface_Static::SetCVal("write.iges.header.author", "TiGL"); Interface_Static::SetCVal("write.iges.header.company", "German Aerospace Center (DLR), SC"); } // Exports the whole configuration as IGES file // All wing- and fuselage segments are exported as single bodys void CTiglExportIges::ExportIGES(const std::string& filename) const { if ( filename.empty()) { LOG(ERROR) << "Error: Empty filename in ExportIGES."; return; } ListPNamedShape shapes; // Export all wings of the configuration for (int w = 1; w <= myConfig.GetWingCount(); w++) { CCPACSWing& wing = myConfig.GetWing(w); for (int i = 1; i <= wing.GetSegmentCount(); i++) { CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i); TopoDS_Shape loft = segment.GetLoft(); PNamedShape shape(new CNamedShape(loft, segment.GetUID().c_str())); shapes.push_back(shape); } } // Export all fuselages of the configuration for (int f = 1; f <= myConfig.GetFuselageCount(); f++) { CCPACSFuselage& fuselage = myConfig.GetFuselage(f); for (int i = 1; i <= fuselage.GetSegmentCount(); i++) { CCPACSFuselageSegment& segment = (tigl::CCPACSFuselageSegment &) fuselage.GetSegment(i); TopoDS_Shape loft = segment.GetLoft(); // Transform loft by fuselage transformation => absolute world coordinates loft = fuselage.GetFuselageTransformation().Transform(loft); PNamedShape shape(new CNamedShape(loft, segment.GetUID().c_str())); shapes.push_back(shape); } } CCPACSFarField& farfield = myConfig.GetFarField(); if (farfield.GetFieldType() != NONE) { PNamedShape shape(new CNamedShape(farfield.GetLoft(), farfield.GetUID().c_str())); shapes.push_back(shape); } // write iges try { ExportShapes(shapes, filename); } catch (CTiglError&) { throw CTiglError("Cannot export airplane in CTiglExportIges", TIGL_ERROR); } } // Exports the whole configuration as one fused part to an IGES file void CTiglExportIges::ExportFusedIGES(const std::string& filename) { if (filename.empty()) { LOG(ERROR) << "Error: Empty filename in ExportFusedIGES."; return; } PTiglFusePlane fuser = myConfig.AircraftFusingAlgo(); fuser->SetResultMode(HALF_PLANE_TRIMMED_FF); assert(fuser); PNamedShape fusedAirplane = fuser->FusedPlane(); PNamedShape farField = fuser->FarField(); if (!fusedAirplane) { throw CTiglError("Error computing fused airplane.", TIGL_NULL_POINTER); } try { ListPNamedShape l; l.push_back(fusedAirplane); l.push_back(farField); // add intersections const ListPNamedShape& ints = fuser->Intersections(); ListPNamedShape::const_iterator it; for (it = ints.begin(); it != ints.end(); ++it) { l.push_back(*it); } ExportShapes(l, filename); } catch (CTiglError&) { throw CTiglError("Cannot export fused Airplane as IGES", TIGL_ERROR); } } // Save a sequence of shapes in IGES Format void CTiglExportIges::ExportShapes(const ListPNamedShape& shapes, const std::string& filename) const { IGESControl_Controller::Init(); if ( filename.empty()) { LOG(ERROR) << "Error: Empty filename in ExportShapes."; return; } ListPNamedShape::const_iterator it; SetTranslationParameters(); #ifdef TIGL_USE_XCAF // create the xde document Handle(XCAFApp_Application) hApp = XCAFApp_Application::GetApplication(); Handle(TDocStd_Document) hDoc; hApp->NewDocument("MDTV-XCAF", hDoc); Handle(XCAFDoc_ShapeTool) myAssembly = XCAFDoc_DocumentTool::ShapeTool(hDoc->Main()); IGESCAFControl_Writer igesWriter; ListPNamedShape list; for (it = shapes.begin(); it != shapes.end(); ++it) { ListPNamedShape templist = GroupFaces(*it, myStoreType); for (ListPNamedShape::iterator it2 = templist.begin(); it2 != templist.end(); ++it2) { list.push_back(*it2); } } for (it = list.begin(); it != list.end(); ++it) { InsertShapeToCAF(myAssembly, *it, true); } igesWriter.Model()->ApplyStatic(); // apply set parameters if (igesWriter.Transfer(hDoc) == Standard_False) { throw CTiglError("Cannot export fused airplane as IGES", TIGL_ERROR); } #else IGESControl_Writer igesWriter; igesWriter.Model()->ApplyStatic(); for (it = shapes.begin(); it != shapes.end(); ++it) { PNamedShape pshape = *it; igesWriter.AddShape (pshape->Shape()); } igesWriter.ComputeModel(); #endif // write face entity names for (it = shapes.begin(); it != shapes.end(); ++it) { PNamedShape pshape = *it; WriteIGESFaceNames(igesWriter.TransferProcess(), pshape); } if (igesWriter.Write(const_cast<char*>(filename.c_str())) != Standard_True) { throw CTiglError("Error: Export of shapes to IGES file failed in CCPACSImportExport::SaveIGES", TIGL_ERROR); } } void CTiglExportIges::SetOCAFStoreType(ShapeStoreType type) { myStoreType = type; } } // end namespace tigl <|endoftext|>
<commit_before>// LICENSE/*{{{*/ /* sxc - Simple Xmpp Client Copyright (C) 2008 Dennis Felsing, Andreas Waidler This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*}}}*/ /* $Id$ */ // INCLUDE/*{{{*/ #include <string> #include <pthread.h> #include <gloox/jid.h> #include <gloox/presence.h> #include <gloox/clientbase.h> #include <gloox/message.h> #include <gloox/disco.h> #include <gloox/error.h> #include <libsxc/Exception/Exception.hxx> #include <Control/Control.hxx> #include <Control/Roster.hxx> #include <generateErrorText.hxx> #include <print.hxx> #ifdef HAVE_CONFIG_H # include <config.hxx> #endif #ifdef DEBUG # include <sstream> #endif /*}}}*/ #include <iostream> namespace Control { Control::Control(/*{{{*/ const gloox::JID &jid, int port, const std::string &name, const std::string &version) : _client(jid, "", port), // Fill in the passphrase later. _roster(_client) // FIXME // _output(this, jid.bare()), // _input(this, jid.bare()) { _client.registerConnectionListener(this); // Up to this point there were two roster managers registered with the // client, but gloox is capable of handling this. _client.disableRoster(); // "console" is not exactly what sxc is, but "pc" is described as a // full-featured GUI. const std::string category = "client"; const std::string type = "console"; # if DEBUG printLog( "Set identity: (category: \"" + category + "\", type: \"" + type + "\", name: \"" + name + "\")."); # endif _client.disco()->setIdentity(category, type, name); # if DEBUG printLog( "Set version: (name: \"" + name + "\", version: \"" + version + "\")."); # endif _client.disco()->setVersion(name, version); }/*}}}*/ Control::~Control()/*{{{*/ { # if DEBUG printLog("Destructing Control::Control"); # endif _client.disconnect(); }/*}}}*/ void Control::setPassphrase(const std::string &pass)/*{{{*/ { # if DEBUG printLog("Set passphrase: \"" + pass + "\"."); # endif _client.setPassword(pass); }/*}}}*/ void Control::setPresence(/*{{{*/ gloox::Presence::PresenceType presence, int priority, const std::string &status) { # if DEBUG/*{{{*/ std::string presenceStr; switch (presence) { case gloox::Presence::Available: presenceStr = "Available"; break; case gloox::Presence::Chat: presenceStr = "Chat"; break; case gloox::Presence::Away: presenceStr = "Away"; break; case gloox::Presence::DND: presenceStr = "DND"; break; case gloox::Presence::XA: presenceStr = "XA"; break; case gloox::Presence::Unavailable: presenceStr = "Unavailable"; break; case gloox::Presence::Probe: presenceStr = "Probe"; break; case gloox::Presence::Error: presenceStr = "Error"; break; case gloox::Presence::Invalid: presenceStr = "Invalid"; break; default: presenceStr = "Unknown"; } std::stringstream text; text << "Set presence: (\"" << presenceStr << "\" (" << presence << "), priority: " << priority << ", message: \"" << status << "\").";; printLog(text.str()); # endif/*}}}*/ _client.setPresence(presence, priority, status); // Don't connect if already connected or connecting. if (gloox::StateDisconnected == _client.state()) { pthread_create(&_thread, NULL, _run, (void*)this); } }/*}}}*/ void Control::setPresence(/*{{{*/ gloox::Presence::PresenceType presence, const std::string &status) { setPresence(presence, _client.priority(), status); }/*}}}*/ void Control::sendMessage(/*{{{*/ const gloox::JID &to, const std::string &body) { gloox::Message message( gloox::Message::Normal, // Not Chat. to, body); _client.send(message); }/*}}}*/ void Control::handleMessage(/*{{{*/ const gloox::Message &msg, gloox::MessageSession *session) { // FIXME //print(session->target()->full() + ": " + msg.body()); }/*}}}*/ void Control::handleError(/*{{{*/ libsxc::Exception::Exception &e, bool isCritical) const { if (isCritical) { printErr(e.getDescription()); exit(e.getType()); } print(e.getDescription()); }/*}}}*/ void Control::print(std::string text) const/*{{{*/ { // FIXME //_output->write(text); }/*}}}*/ Roster &Control::getRoster()/*{{{*/ { return _roster; }/*}}}*/ void Control::onConnect()/*{{{*/ { # if DEBUG printLog("Connection established."); # endif }/*}}}*/ void Control::onDisconnect(gloox::ConnectionError e)/*{{{*/ { std::string text = "Disconnected: " + generateErrorText( e, _client.streamError(), _client.streamErrorText(), _client.authError()); if (!text.empty()) print(text); # if DEBUG printLog(text); # endif //FIXME: Decide whether to reconnect and restart _run or not. }/*}}}*/ bool Control::onTLSConnect(const gloox::CertInfo &info)/*{{{*/ { # if DEBUG printLog("Acknowledge TLS certificate."); # endif return true; }/*}}}*/ void *Control::_run(void *rawThat)/*{{{*/ { # if DEBUG printLog("Start socket receiving thread."); # endif Control *that = (Control *) rawThat; that->_client.connect(); // Blocking. # if DEBUG printLog("End socket receiving thread."); # endif }/*}}}*/ } // Use no tabs at all; four spaces indentation; max. eighty chars per line. // vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker <commit_msg>Fix: Return correctly<commit_after>// LICENSE/*{{{*/ /* sxc - Simple Xmpp Client Copyright (C) 2008 Dennis Felsing, Andreas Waidler This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*}}}*/ /* $Id$ */ // INCLUDE/*{{{*/ #include <string> #include <pthread.h> #include <gloox/jid.h> #include <gloox/presence.h> #include <gloox/clientbase.h> #include <gloox/message.h> #include <gloox/disco.h> #include <gloox/error.h> #include <libsxc/Exception/Exception.hxx> #include <Control/Control.hxx> #include <Control/Roster.hxx> #include <generateErrorText.hxx> #include <print.hxx> #ifdef HAVE_CONFIG_H # include <config.hxx> #endif #ifdef DEBUG # include <sstream> #endif /*}}}*/ #include <iostream> namespace Control { Control::Control(/*{{{*/ const gloox::JID &jid, int port, const std::string &name, const std::string &version) : _client(jid, "", port), // Fill in the passphrase later. _roster(_client) // FIXME // _output(this, jid.bare()), // _input(this, jid.bare()) { _client.registerConnectionListener(this); // Up to this point there were two roster managers registered with the // client, but gloox is capable of handling this. _client.disableRoster(); // "console" is not exactly what sxc is, but "pc" is described as a // full-featured GUI. const std::string category = "client"; const std::string type = "console"; # if DEBUG printLog( "Set identity: (category: \"" + category + "\", type: \"" + type + "\", name: \"" + name + "\")."); # endif _client.disco()->setIdentity(category, type, name); # if DEBUG printLog( "Set version: (name: \"" + name + "\", version: \"" + version + "\")."); # endif _client.disco()->setVersion(name, version); }/*}}}*/ Control::~Control()/*{{{*/ { # if DEBUG printLog("Destructing Control::Control"); # endif _client.disconnect(); }/*}}}*/ void Control::setPassphrase(const std::string &pass)/*{{{*/ { # if DEBUG printLog("Set passphrase: \"" + pass + "\"."); # endif _client.setPassword(pass); }/*}}}*/ void Control::setPresence(/*{{{*/ gloox::Presence::PresenceType presence, int priority, const std::string &status) { # if DEBUG/*{{{*/ std::string presenceStr; switch (presence) { case gloox::Presence::Available: presenceStr = "Available"; break; case gloox::Presence::Chat: presenceStr = "Chat"; break; case gloox::Presence::Away: presenceStr = "Away"; break; case gloox::Presence::DND: presenceStr = "DND"; break; case gloox::Presence::XA: presenceStr = "XA"; break; case gloox::Presence::Unavailable: presenceStr = "Unavailable"; break; case gloox::Presence::Probe: presenceStr = "Probe"; break; case gloox::Presence::Error: presenceStr = "Error"; break; case gloox::Presence::Invalid: presenceStr = "Invalid"; break; default: presenceStr = "Unknown"; } std::stringstream text; text << "Set presence: (\"" << presenceStr << "\" (" << presence << "), priority: " << priority << ", message: \"" << status << "\").";; printLog(text.str()); # endif/*}}}*/ _client.setPresence(presence, priority, status); // Don't connect if already connected or connecting. if (gloox::StateDisconnected == _client.state()) { pthread_create(&_thread, NULL, _run, (void*)this); } }/*}}}*/ void Control::setPresence(/*{{{*/ gloox::Presence::PresenceType presence, const std::string &status) { setPresence(presence, _client.priority(), status); }/*}}}*/ void Control::sendMessage(/*{{{*/ const gloox::JID &to, const std::string &body) { gloox::Message message( gloox::Message::Normal, // Not Chat. to, body); _client.send(message); }/*}}}*/ void Control::handleMessage(/*{{{*/ const gloox::Message &msg, gloox::MessageSession *session) { // FIXME //print(session->target()->full() + ": " + msg.body()); }/*}}}*/ void Control::handleError(/*{{{*/ libsxc::Exception::Exception &e, bool isCritical) const { if (isCritical) { printErr(e.getDescription()); exit(e.getType()); } print(e.getDescription()); }/*}}}*/ void Control::print(std::string text) const/*{{{*/ { // FIXME //_output->write(text); }/*}}}*/ Roster &Control::getRoster()/*{{{*/ { return _roster; }/*}}}*/ void Control::onConnect()/*{{{*/ { # if DEBUG printLog("Connection established."); # endif }/*}}}*/ void Control::onDisconnect(gloox::ConnectionError e)/*{{{*/ { std::string text = "Disconnected: " + generateErrorText( e, _client.streamError(), _client.streamErrorText(), _client.authError()); if (!text.empty()) print(text); # if DEBUG printLog(text); # endif //FIXME: Decide whether to reconnect and restart _run or not. }/*}}}*/ bool Control::onTLSConnect(const gloox::CertInfo &info)/*{{{*/ { # if DEBUG printLog("Acknowledge TLS certificate."); # endif return true; }/*}}}*/ void *Control::_run(void *rawThat)/*{{{*/ { # if DEBUG printLog("Start socket receiving thread."); # endif Control *that = (Control *) rawThat; that->_client.connect(); // Blocking. # if DEBUG printLog("End socket receiving thread."); # endif return (void *) NULL; }/*}}}*/ } // Use no tabs at all; four spaces indentation; max. eighty chars per line. // vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker <|endoftext|>
<commit_before>#include <stdexcept> #include <iostream> #include <signal.h> #include <sys/wait.h> #include <vector> #include <string.h> #include "ExternalIndexer.h" #include "IndexSink.h" namespace { void X(int error) { // Prevent errors from shutting down the child "gracefully". if (error == -1) { std::cerr << "Error creating child process: " << errno << std::endl; exit(1); } } } void ExternalIndexer::index(IndexSink &sink, StringView line) { log_.debug("Writing to child..."); auto bytes = ::write(sendPipe_.writeFd(), line.begin(), line.length()); if (bytes != (ssize_t)line.length()) { log_.error("Failed to write to child process: ", errno); throw std::runtime_error("Unable to write to child process"); } bytes = ::write(sendPipe_.writeFd(), "\n", 1); if (bytes != 1) { log_.error("Failed to write to child process: ", errno); throw std::runtime_error("Unable to write to child process"); } log_.debug("Finished writing"); std::vector<char> buf; for (; ;) { auto readPos = buf.size(); constexpr auto blockSize = 4096u; auto initSize = buf.size(); buf.resize(initSize + blockSize); bytes = ::read(receivePipe_.readFd(), &buf[readPos], blockSize); if (bytes < 0) throw std::runtime_error("Error reading from child process"); if (bytes == 0) throw std::runtime_error("Child process died"); buf.resize(initSize + bytes); if (!buf.empty() && buf.back() == '\n') break; if (memchr(&buf[0], '\n', buf.size())) { auto strBuf = std::string(&buf[0], buf.size()); throw std::runtime_error( "Child process emitted more than one line: '" + strBuf + "'"); } } auto ptr = &buf[0]; auto end = &buf[buf.size() - 1]; while (ptr < end) { auto nextSep = static_cast<char *>(memchr(ptr, separator_, end - ptr)); if (!nextSep) nextSep = end; auto length = nextSep - ptr; if (length) sink.add(StringView(ptr, length), 0); // TODO: offset ptr = nextSep + 1; } } ExternalIndexer::ExternalIndexer(Log &log, const std::string &command, char separator) : log_(log), childPid_(0), separator_(separator) { auto forkResult = fork(); if (forkResult == -1) { log_.error("Unable to fork: ", errno); throw std::runtime_error("Unable to fork"); } else if (forkResult == 0) { runChild(command); // never returns } childPid_ = forkResult; log_.debug("Forked child process ", childPid_); sendPipe_.closeRead(); receivePipe_.closeWrite(); signal(SIGCHLD, SIG_IGN); signal(SIGPIPE, SIG_IGN); } ExternalIndexer::~ExternalIndexer() { if (childPid_ > 0) { log_.debug("Sending child process QUIT"); kill(childPid_, SIGQUIT); int status = 0; log_.debug("Waiting on child"); waitpid(childPid_, &status, 0); log_.debug("Child exited"); } } void ExternalIndexer::runChild(const std::string &command) { // Send and receive are from the point of view of the parent. sendPipe_.closeWrite(); receivePipe_.closeRead(); X(dup2(sendPipe_.readFd(), STDIN_FILENO)); X(dup2(receivePipe_.writeFd(), STDOUT_FILENO)); X(execl("/bin/sh", "/bin/sh", "-c", command.c_str(), nullptr)); } <commit_msg>Use SIGTERM to kill child<commit_after>#include <stdexcept> #include <iostream> #include <signal.h> #include <sys/wait.h> #include <vector> #include <string.h> #include "ExternalIndexer.h" #include "IndexSink.h" namespace { void X(int error) { // Prevent errors from shutting down the child "gracefully". if (error == -1) { std::cerr << "Error creating child process: " << errno << std::endl; exit(1); } } } void ExternalIndexer::index(IndexSink &sink, StringView line) { log_.debug("Writing to child..."); auto bytes = ::write(sendPipe_.writeFd(), line.begin(), line.length()); if (bytes != (ssize_t)line.length()) { log_.error("Failed to write to child process: ", errno); throw std::runtime_error("Unable to write to child process"); } bytes = ::write(sendPipe_.writeFd(), "\n", 1); if (bytes != 1) { log_.error("Failed to write to child process: ", errno); throw std::runtime_error("Unable to write to child process"); } log_.debug("Finished writing"); std::vector<char> buf; for (; ;) { auto readPos = buf.size(); constexpr auto blockSize = 4096u; auto initSize = buf.size(); buf.resize(initSize + blockSize); bytes = ::read(receivePipe_.readFd(), &buf[readPos], blockSize); if (bytes < 0) throw std::runtime_error("Error reading from child process"); if (bytes == 0) throw std::runtime_error("Child process died"); buf.resize(initSize + bytes); if (!buf.empty() && buf.back() == '\n') break; if (memchr(&buf[0], '\n', buf.size())) { auto strBuf = std::string(&buf[0], buf.size()); throw std::runtime_error( "Child process emitted more than one line: '" + strBuf + "'"); } } auto ptr = &buf[0]; auto end = &buf[buf.size() - 1]; while (ptr < end) { auto nextSep = static_cast<char *>(memchr(ptr, separator_, end - ptr)); if (!nextSep) nextSep = end; auto length = nextSep - ptr; if (length) sink.add(StringView(ptr, length), 0); // TODO: offset ptr = nextSep + 1; } } ExternalIndexer::ExternalIndexer(Log &log, const std::string &command, char separator) : log_(log), childPid_(0), separator_(separator) { auto forkResult = fork(); if (forkResult == -1) { log_.error("Unable to fork: ", errno); throw std::runtime_error("Unable to fork"); } else if (forkResult == 0) { runChild(command); // never returns } childPid_ = forkResult; log_.debug("Forked child process ", childPid_); sendPipe_.closeRead(); receivePipe_.closeWrite(); signal(SIGCHLD, SIG_IGN); signal(SIGPIPE, SIG_IGN); } ExternalIndexer::~ExternalIndexer() { if (childPid_ > 0) { log_.debug("Sending child process TERM"); auto result = kill(childPid_, SIGTERM); if (result == -1) { log_.error("Unable to send kill: ", errno); throw std::runtime_error("Unable to kill child"); } int status = 0; log_.debug("Waiting on child"); waitpid(childPid_, &status, 0); log_.debug("Child exited"); } } void ExternalIndexer::runChild(const std::string &command) { // Send and receive are from the point of view of the parent. sendPipe_.closeWrite(); receivePipe_.closeRead(); X(dup2(sendPipe_.readFd(), STDIN_FILENO)); X(dup2(receivePipe_.writeFd(), STDOUT_FILENO)); X(execl("/bin/sh", "/bin/sh", "-c", command.c_str(), nullptr)); } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../library/osrm.hpp" #include "../util/git_sha.hpp" #include "../util/json_renderer.hpp" #include "../util/routed_options.hpp" #include "../util/simple_logger.hpp" #include <osrm/json_container.hpp> #include <osrm/libosrm_config.hpp> #include <osrm/route_parameters.hpp> #include <string> int main(int argc, const char *argv[]) { LogPolicy::GetInstance().Unmute(); try { std::string ip_address; int ip_port, requested_thread_num; bool trial_run = false; libosrm_config lib_config; const unsigned init_result = GenerateServerProgramOptions( argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, lib_config.use_shared_memory, trial_run, lib_config.max_locations_distance_table); if (init_result == INIT_OK_DO_NOT_START_ENGINE) { return 0; } if (init_result == INIT_FAILED) { return 1; } SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION; OSRM routing_machine(lib_config); RouteParameters route_parameters; route_parameters.zoom_level = 18; // no generalization route_parameters.print_instructions = true; // turn by turn instructions route_parameters.alternate_route = true; // get an alternate route, too route_parameters.geometry = true; // retrieve geometry of route route_parameters.compression = true; // polyline encoding route_parameters.check_sum = -1; // see wiki route_parameters.service = "viaroute"; // that's routing route_parameters.output_format = "json"; route_parameters.jsonp_parameter = ""; // set for jsonp wrapping route_parameters.language = ""; // unused atm // route_parameters.hints.push_back(); // see wiki, saves I/O if done properly // start_coordinate route_parameters.coordinates.emplace_back(52.519930 * COORDINATE_PRECISION, 13.438640 * COORDINATE_PRECISION); // target_coordinate route_parameters.coordinates.emplace_back(52.513191 * COORDINATE_PRECISION, 13.415852 * COORDINATE_PRECISION); osrm::json::Object json_result; const int result_code = routing_machine.RunQuery(route_parameters, json_result); SimpleLogger().Write() << "http code: " << result_code; osrm::json::render(SimpleLogger().Write(), json_result); } catch (std::exception &current_exception) { SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what(); return -1; } return 0; } <commit_msg>fix compilation<commit_after>/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../library/osrm.hpp" #include "../util/git_sha.hpp" #include "../util/json_renderer.hpp" #include "../util/routed_options.hpp" #include "../util/simple_logger.hpp" #include <osrm/json_container.hpp> #include <osrm/libosrm_config.hpp> #include <osrm/route_parameters.hpp> #include <string> int main(int argc, const char *argv[]) { LogPolicy::GetInstance().Unmute(); try { std::string ip_address; int ip_port, requested_thread_num, max_locations_map_matching; bool trial_run = false; libosrm_config lib_config; const unsigned init_result = GenerateServerProgramOptions( argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, lib_config.use_shared_memory, trial_run, lib_config.max_locations_distance_table, max_locations_map_matching); if (init_result == INIT_OK_DO_NOT_START_ENGINE) { return 0; } if (init_result == INIT_FAILED) { return 1; } SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION; OSRM routing_machine(lib_config); RouteParameters route_parameters; route_parameters.zoom_level = 18; // no generalization route_parameters.print_instructions = true; // turn by turn instructions route_parameters.alternate_route = true; // get an alternate route, too route_parameters.geometry = true; // retrieve geometry of route route_parameters.compression = true; // polyline encoding route_parameters.check_sum = -1; // see wiki route_parameters.service = "viaroute"; // that's routing route_parameters.output_format = "json"; route_parameters.jsonp_parameter = ""; // set for jsonp wrapping route_parameters.language = ""; // unused atm // route_parameters.hints.push_back(); // see wiki, saves I/O if done properly // start_coordinate route_parameters.coordinates.emplace_back(52.519930 * COORDINATE_PRECISION, 13.438640 * COORDINATE_PRECISION); // target_coordinate route_parameters.coordinates.emplace_back(52.513191 * COORDINATE_PRECISION, 13.415852 * COORDINATE_PRECISION); osrm::json::Object json_result; const int result_code = routing_machine.RunQuery(route_parameters, json_result); SimpleLogger().Write() << "http code: " << result_code; osrm::json::render(SimpleLogger().Write(), json_result); } catch (std::exception &current_exception) { SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what(); return -1; } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "new.hpp" #include "types.hpp" #include "utility.hpp" namespace ox { template<typename T> class Vector { private: std::size_t m_size = 0; std::size_t m_cap = 0; T *m_items = nullptr; public: Vector() noexcept = default; explicit Vector(std::size_t size) noexcept; Vector(const Vector &other) noexcept; Vector(Vector &&other) noexcept; ~Vector() noexcept; Vector &operator=(const Vector &other) noexcept; Vector &operator=(Vector &&other) noexcept; T &operator[](std::size_t i) noexcept; const T &operator[](std::size_t i) const noexcept; T &front() noexcept; const T &front() const noexcept; T &back() noexcept; const T &back() const noexcept; std::size_t size() const noexcept; void resize(std::size_t size) noexcept; T *data(); const T *data() const; bool contains(T) const noexcept; void insert(std::size_t pos, const T &val) noexcept; template<typename... Args> void emplace_back(Args&&... args) noexcept; void push_back(const T &item) noexcept; void pop_back() noexcept; /** * Removes an item from the Vector. * @param pos position of item to remove */ void erase(std::size_t pos) noexcept; /** * Moves the last item in the Vector to position pos and decrements the * size by 1. * @param pos position of item to remove */ void unordered_erase(std::size_t pos) noexcept; private: void expandCap(std::size_t cap) noexcept; }; template<typename T> Vector<T>::Vector(std::size_t size) noexcept { m_size = size; m_cap = m_size; m_items = reinterpret_cast<T*>(new AllocAlias<T>[m_cap]); for (std::size_t i = 0; i < size; i++) { m_items[i] = {}; } } template<typename T> Vector<T>::Vector(const Vector<T> &other) noexcept { m_size = other.m_size; m_cap = other.m_cap; m_items = reinterpret_cast<T*>(new AllocAlias<T>[m_cap]); for (std::size_t i = 0; i < m_size; i++) { m_items[i] = ox::move(other.m_items[i]); } } template<typename T> Vector<T>::Vector(Vector<T> &&other) noexcept { m_size = other.m_size; m_cap = other.m_cap; m_items = other.m_items; other.m_size = 0; other.m_cap = 0; other.m_items = nullptr; } template<typename T> Vector<T>::~Vector() noexcept { if constexpr(ox::is_class<T>()) { for (std::size_t i = 0; i < m_size; i++) { m_items[i].~T(); } } delete[] reinterpret_cast<AllocAlias<T>*>(m_items); m_items = nullptr; } template<typename T> Vector<T> &Vector<T>::operator=(const Vector<T> &other) noexcept { this->~Vector<T>(); m_size = other.m_size; m_cap = other.m_cap; m_items = reinterpret_cast<T*>(new AllocAlias<T>[m_cap]); for (std::size_t i = 0; i < m_size; i++) { m_items[i] = other.m_items[i]; } return *this; } template<typename T> Vector<T> &Vector<T>::operator=(Vector<T> &&other) noexcept { this->~Vector<T>(); m_size = other.m_size; m_cap = other.m_cap; m_items = other.m_items; other.m_size = 0; other.m_cap = 0; other.m_items = nullptr; return *this; } template<typename T> T &Vector<T>::operator[](std::size_t i) noexcept { return m_items[i]; } template<typename T> const T &Vector<T>::operator[](std::size_t i) const noexcept { return m_items[i]; } template<typename T> T &Vector<T>::front() noexcept { return m_items[0]; } template<typename T> const T &Vector<T>::front() const noexcept { return m_items[0]; } template<typename T> T &Vector<T>::back() noexcept { return m_items[m_size - 1]; } template<typename T> const T &Vector<T>::back() const noexcept { return m_items[m_size - 1]; } template<typename T> std::size_t Vector<T>::size() const noexcept { return m_size; } template<typename T> void Vector<T>::resize(std::size_t size) noexcept { if (m_cap < size) { expandCap(size); } for (std::size_t i = m_size; i < size; i++) { m_items[i] = {}; } m_size = size; } template<typename T> T *Vector<T>::data() { return m_items; } template<typename T> const T *Vector<T>::data() const { return m_items; } template<typename T> bool Vector<T>::contains(T v) const noexcept { for (std::size_t i = 0; i < m_size; i++) { if (m_items[i] == v) { return true; } } return false; } template<typename T> void Vector<T>::insert(std::size_t pos, const T &val) noexcept { // TODO: insert should ideally have its own expandCap if (m_size == m_cap) { expandCap(m_cap ? m_cap * 2 : 100); } for (auto i = m_size; i > pos; --i) { m_items[i] = m_items[i - 1]; } m_items[pos] = val; ++m_size; } template<typename T> template<typename... Args> void Vector<T>::emplace_back(Args&&... args) noexcept { if (m_size == m_cap) { expandCap(m_cap ? m_cap * 2 : 100); } new (&m_items[m_size]) T{args...}; ++m_size; } template<typename T> void Vector<T>::push_back(const T &item) noexcept { if (m_size == m_cap) { expandCap(m_cap ? m_cap * 2 : 100); } new (&m_items[m_size]) T(item); ++m_size; } template<typename T> void Vector<T>::pop_back() noexcept { --m_size; } template<typename T> void Vector<T>::erase(std::size_t pos) noexcept { m_size--; for (auto i = pos; i < m_size; i++) { m_items[i] = m_items[i + 1]; } } template<typename T> void Vector<T>::unordered_erase(std::size_t pos) noexcept { m_size--; m_items[pos] = m_items[m_size]; } template<typename T> void Vector<T>::expandCap(std::size_t cap) noexcept { auto oldItems = m_items; m_cap = cap; m_items = reinterpret_cast<T*>(new AllocAlias<T>[m_cap]); if (oldItems) { // move over old items const auto itRange = cap > m_size ? m_size : cap; for (std::size_t i = 0; i < itRange; i++) { m_items[i] = ox::move(oldItems[i]); } for (std::size_t i = itRange; i < m_cap; i++) { new (&m_items[i]) T; } delete[] reinterpret_cast<AllocAlias<T>*>(oldItems); } } } <commit_msg>[ox/std] Remove inappropriate noexcepts and call destructors on erase and resize<commit_after>/* * Copyright 2015 - 2020 gary@drinkingtea.net * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "new.hpp" #include "types.hpp" #include "utility.hpp" namespace ox { template<typename T> class Vector { private: std::size_t m_size = 0; std::size_t m_cap = 0; T *m_items = nullptr; public: Vector() noexcept = default; explicit Vector(std::size_t size); Vector(const Vector &other); Vector(Vector &&other); ~Vector(); Vector &operator=(const Vector &other); Vector &operator=(Vector &&other); T &operator[](std::size_t i) noexcept; const T &operator[](std::size_t i) const noexcept; T &front() noexcept; const T &front() const noexcept; T &back() noexcept; const T &back() const noexcept; std::size_t size() const noexcept; [[nodiscard]] bool empty() const; void clear(); void resize(std::size_t size); T *data() noexcept; const T *data() const noexcept; [[nodiscard]] bool contains(T) const; void insert(std::size_t pos, const T &val); template<typename... Args> void emplace_back(Args&&... args); void push_back(const T &item); void pop_back(); /** * Removes an item from the Vector. * @param pos position of item to remove */ void erase(std::size_t pos); /** * Moves the last item in the Vector to position pos and decrements the * size by 1. * @param pos position of item to remove */ void unordered_erase(std::size_t pos); private: void expandCap(std::size_t cap); }; template<typename T> Vector<T>::Vector(std::size_t size) { m_size = size; m_cap = m_size; m_items = reinterpret_cast<T*>(new AllocAlias<T>[m_cap]); for (std::size_t i = 0; i < size; i++) { m_items[i] = {}; } } template<typename T> Vector<T>::Vector(const Vector<T> &other) { m_size = other.m_size; m_cap = other.m_cap; m_items = reinterpret_cast<T*>(new AllocAlias<T>[m_cap]); for (std::size_t i = 0; i < m_size; i++) { m_items[i] = ox::move(other.m_items[i]); } } template<typename T> Vector<T>::Vector(Vector<T> &&other) { m_size = other.m_size; m_cap = other.m_cap; m_items = other.m_items; other.m_size = 0; other.m_cap = 0; other.m_items = nullptr; } template<typename T> Vector<T>::~Vector() { if constexpr(ox::is_class<T>()) { for (std::size_t i = 0; i < m_size; i++) { m_items[i].~T(); } } delete[] reinterpret_cast<AllocAlias<T>*>(m_items); m_items = nullptr; } template<typename T> Vector<T> &Vector<T>::operator=(const Vector<T> &other) { this->~Vector<T>(); m_size = other.m_size; m_cap = other.m_cap; m_items = reinterpret_cast<T*>(new AllocAlias<T>[m_cap]); for (std::size_t i = 0; i < m_size; i++) { m_items[i] = other.m_items[i]; } return *this; } template<typename T> Vector<T> &Vector<T>::operator=(Vector<T> &&other) { this->~Vector<T>(); m_size = other.m_size; m_cap = other.m_cap; m_items = other.m_items; other.m_size = 0; other.m_cap = 0; other.m_items = nullptr; return *this; } template<typename T> T &Vector<T>::operator[](std::size_t i) noexcept { return m_items[i]; } template<typename T> const T &Vector<T>::operator[](std::size_t i) const noexcept { return m_items[i]; } template<typename T> T &Vector<T>::front() noexcept { return m_items[0]; } template<typename T> const T &Vector<T>::front() const noexcept { return m_items[0]; } template<typename T> T &Vector<T>::back() noexcept { return m_items[m_size - 1]; } template<typename T> const T &Vector<T>::back() const noexcept { return m_items[m_size - 1]; } template<typename T> std::size_t Vector<T>::size() const noexcept { return m_size; } template<typename T> bool Vector<T>::empty() const { return !m_size; } template<typename T> void Vector<T>::clear() { resize(0); } template<typename T> void Vector<T>::resize(std::size_t size) { if (m_cap < size) { expandCap(size); } if (m_size < size) { for (std::size_t i = m_size; i < size; i++) { m_items[i] = {}; } } else { for (std::size_t i = size; i < m_size; i++) { m_items[i].~T(); } } m_size = size; } template<typename T> T *Vector<T>::data() noexcept { return m_items; } template<typename T> const T *Vector<T>::data() const noexcept { return m_items; } template<typename T> bool Vector<T>::contains(T v) const { for (std::size_t i = 0; i < m_size; i++) { if (m_items[i] == v) { return true; } } return false; } template<typename T> void Vector<T>::insert(std::size_t pos, const T &val) { // TODO: insert should ideally have its own expandCap if (m_size == m_cap) { expandCap(m_cap ? m_cap * 2 : 100); } for (auto i = m_size; i > pos; --i) { m_items[i] = ox::move(m_items[i - 1]); } m_items[pos] = val; ++m_size; } template<typename T> template<typename... Args> void Vector<T>::emplace_back(Args&&... args) { if (m_size == m_cap) { expandCap(m_cap ? m_cap * 2 : 100); } new (&m_items[m_size]) T{args...}; ++m_size; } template<typename T> void Vector<T>::push_back(const T &item) { if (m_size == m_cap) { expandCap(m_cap ? m_cap * 2 : 100); } new (&m_items[m_size]) T(item); ++m_size; } template<typename T> void Vector<T>::pop_back() { --m_size; m_items[m_size].~T(); } template<typename T> void Vector<T>::erase(std::size_t pos) { m_size--; for (auto i = pos; i < m_size; i++) { m_items[i] = ox::move(m_items[i + 1]); } } template<typename T> void Vector<T>::unordered_erase(std::size_t pos) { m_size--; m_items[pos] = ox::move(m_items[m_size]); } template<typename T> void Vector<T>::expandCap(std::size_t cap) { auto oldItems = m_items; m_cap = cap; m_items = reinterpret_cast<T*>(new AllocAlias<T>[m_cap]); if (oldItems) { // move over old items const auto itRange = cap > m_size ? m_size : cap; for (std::size_t i = 0; i < itRange; i++) { m_items[i] = ox::move(oldItems[i]); } for (std::size_t i = itRange; i < m_cap; i++) { new (&m_items[i]) T; } delete[] reinterpret_cast<AllocAlias<T>*>(oldItems); } } } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <map> #include "timer.h" #include "crp.h" #include "sampler.h" #include "tdict.h" Dict TD::dict_; std::string TD::empty = ""; std::string TD::space = " "; using namespace std; void ShowTopWords(const map<WordID, int>& counts) { multimap<int, WordID> ms; for (map<WordID,int>::const_iterator it = counts.begin(); it != counts.end(); ++it) ms.insert(make_pair(it->second, it->first)); } int main(int argc, char** argv) { if (argc != 2) { cerr << "Usage: " << argv[0] << " num-classes\n"; return 1; } const int num_classes = atoi(argv[1]); if (num_classes < 2) { cerr << "Must request more than 1 class\n"; return 1; } cerr << "CLASSES: " << num_classes << endl; char* buf = new char[800000]; vector<vector<int> > wji; // w[j][i] - observed word i of doc j vector<vector<int> > zji; // z[j][i] - topic assignment for word i of doc j cerr << "READING DOCUMENTS\n"; while(cin) { cin.getline(buf, 800000); if (buf[0] == 0) continue; wji.push_back(vector<WordID>()); TD::ConvertSentence(buf, &wji.back()); } cerr << "READ " << wji.size() << " DOCUMENTS\n"; MT19937 rng; cerr << "INITIALIZING RANDOM TOPIC ASSIGNMENTS\n"; zji.resize(wji.size()); double beta = 0.01; double alpha = 0.001; vector<CRP<int> > dr(zji.size(), CRP<int>(beta)); // dr[i] describes the probability of using a topic in document i vector<CRP<int> > wr(num_classes, CRP<int>(alpha)); // wr[k] describes the probability of generating a word in topic k int random_topic = rng.next() * num_classes; for (int j = 0; j < zji.size(); ++j) { const size_t num_words = wji[j].size(); vector<int>& zj = zji[j]; const vector<int>& wj = wji[j]; zj.resize(num_words); for (int i = 0; i < num_words; ++i) { if (random_topic == num_classes) { --random_topic; } zj[i] = random_topic; const int word = wj[i]; dr[j].increment(random_topic); wr[random_topic].increment(word); } } cerr << "SAMPLING\n"; vector<map<WordID, int> > t2w(num_classes); const int num_iterations = 1000; const int burnin_size = 800; bool needline = false; Timer timer; SampleSet ss; ss.resize(num_classes); double total_time = 0; for (int iter = 0; iter < num_iterations; ++iter) { if (iter && iter % 10 == 0) { total_time += timer.Elapsed(); timer.Reset(); cerr << '.'; needline=true; prob_t lh = prob_t::One(); for (int j = 0; j < zji.size(); ++j) { const size_t num_words = wji[j].size(); vector<int>& zj = zji[j]; const vector<int>& wj = wji[j]; for (int i = 0; i < num_words; ++i) { const int word = wj[i]; const int cur_topic = zj[i]; lh *= dr[j].prob(cur_topic); lh *= wr[cur_topic].prob(word); if (iter > burnin_size) { ++t2w[cur_topic][word]; } } } if (iter && iter % 200 == 0) { cerr << " [ITER=" << iter << " SEC/SAMPLE=" << (total_time / 200) << " LLH=" << log(lh) << "]\n"; needline=false; total_time=0; } //cerr << "ITERATION " << iter << " LOG LIKELIHOOD: " << log(lh) << endl; } for (int j = 0; j < zji.size(); ++j) { const size_t num_words = wji[j].size(); vector<int>& zj = zji[j]; const vector<int>& wj = wji[j]; for (int i = 0; i < num_words; ++i) { const int word = wj[i]; const int cur_topic = zj[i]; dr[j].decrement(cur_topic); wr[cur_topic].decrement(word); for (int k = 0; k < num_classes; ++k) { ss[k]= dr[j].prob(k) * wr[k].prob(word); } const int new_topic = rng.SelectSample(ss); dr[j].increment(new_topic); wr[new_topic].increment(word); zj[i] = new_topic; } } } if (needline) cerr << endl; for (int j = 0; j < zji.size(); ++j) { const size_t num_words = wji[j].size(); vector<int>& zj = zji[j]; const vector<int>& wj = wji[j]; zj.resize(num_words); for (int i = 0; i < num_words; ++i) { cout << TD::Convert(wj[i]) << '(' << zj[i] << ") "; } cout << endl; } for (int i = 0; i < num_classes; ++i) { ShowTopWords(t2w[i]); } for (map<int,int>::iterator it = t2w[0].begin(); it != t2w[0].end(); ++it) cerr << TD::Convert(it->first) << " " << it->second << endl; cerr << "---------------------------------\n"; for (map<int,int>::iterator it = t2w[1].begin(); it != t2w[1].end(); ++it) cerr << TD::Convert(it->first) << " " << it->second << endl; cerr << "---------------------------------\n"; for (map<int,int>::iterator it = t2w[2].begin(); it != t2w[2].end(); ++it) cerr << TD::Convert(it->first) << " " << it->second << endl; return 0; } <commit_msg>clean up<commit_after>#include <iostream> #include <vector> #include <map> #include "timer.h" #include "crp.h" #include "sampler.h" #include "tdict.h" Dict TD::dict_; std::string TD::empty = ""; std::string TD::space = " "; using namespace std; void ShowTopWords(const map<WordID, int>& counts) { multimap<int, WordID> ms; for (map<WordID,int>::const_iterator it = counts.begin(); it != counts.end(); ++it) ms.insert(make_pair(it->second, it->first)); int cc = 0; for (multimap<int, WordID>::reverse_iterator it = ms.rbegin(); it != ms.rend(); ++it) { cerr << it->first << ':' << TD::Convert(it->second) << " "; ++cc; if (cc==12) break; } cerr << endl; } int main(int argc, char** argv) { if (argc != 3) { cerr << "Usage: " << argv[0] << " num-classes num-samples\n"; return 1; } const int num_classes = atoi(argv[1]); const int num_iterations = atoi(argv[2]); const int burnin_size = num_iterations * 0.666; if (num_classes < 2) { cerr << "Must request more than 1 class\n"; return 1; } if (num_iterations < 5) { cerr << "Must request more than 5 iterations\n"; return 1; } cerr << "CLASSES: " << num_classes << endl; char* buf = new char[800000]; vector<vector<int> > wji; // w[j][i] - observed word i of doc j vector<vector<int> > zji; // z[j][i] - topic assignment for word i of doc j cerr << "READING DOCUMENTS\n"; while(cin) { cin.getline(buf, 800000); if (buf[0] == 0) continue; wji.push_back(vector<WordID>()); TD::ConvertSentence(buf, &wji.back()); } cerr << "READ " << wji.size() << " DOCUMENTS\n"; MT19937 rng; cerr << "INITIALIZING RANDOM TOPIC ASSIGNMENTS\n"; zji.resize(wji.size()); double beta = 0.01; double alpha = 0.001; vector<CRP<int> > dr(zji.size(), CRP<int>(beta)); // dr[i] describes the probability of using a topic in document i vector<CRP<int> > wr(num_classes, CRP<int>(alpha)); // wr[k] describes the probability of generating a word in topic k int random_topic = rng.next() * num_classes; for (int j = 0; j < zji.size(); ++j) { const size_t num_words = wji[j].size(); vector<int>& zj = zji[j]; const vector<int>& wj = wji[j]; zj.resize(num_words); for (int i = 0; i < num_words; ++i) { if (random_topic == num_classes) { --random_topic; } zj[i] = random_topic; const int word = wj[i]; dr[j].increment(random_topic); wr[random_topic].increment(word); } } cerr << "SAMPLING\n"; vector<map<WordID, int> > t2w(num_classes); bool needline = false; Timer timer; SampleSet ss; ss.resize(num_classes); double total_time = 0; for (int iter = 0; iter < num_iterations; ++iter) { if (iter && iter % 10 == 0) { total_time += timer.Elapsed(); timer.Reset(); cerr << '.'; needline=true; prob_t lh = prob_t::One(); for (int j = 0; j < zji.size(); ++j) { const size_t num_words = wji[j].size(); vector<int>& zj = zji[j]; const vector<int>& wj = wji[j]; for (int i = 0; i < num_words; ++i) { const int word = wj[i]; const int cur_topic = zj[i]; lh *= dr[j].prob(cur_topic); lh *= wr[cur_topic].prob(word); if (iter > burnin_size) { ++t2w[cur_topic][word]; } } } if (iter && iter % 200 == 0) { cerr << " [ITER=" << iter << " SEC/SAMPLE=" << (total_time / 200) << " LLH=" << log(lh) << "]\n"; needline=false; total_time=0; } //cerr << "ITERATION " << iter << " LOG LIKELIHOOD: " << log(lh) << endl; } for (int j = 0; j < zji.size(); ++j) { const size_t num_words = wji[j].size(); vector<int>& zj = zji[j]; const vector<int>& wj = wji[j]; for (int i = 0; i < num_words; ++i) { const int word = wj[i]; const int cur_topic = zj[i]; dr[j].decrement(cur_topic); wr[cur_topic].decrement(word); for (int k = 0; k < num_classes; ++k) { ss[k]= dr[j].prob(k) * wr[k].prob(word); } const int new_topic = rng.SelectSample(ss); dr[j].increment(new_topic); wr[new_topic].increment(word); zj[i] = new_topic; } } } if (needline) cerr << endl; #if 0 for (int j = 0; j < zji.size(); ++j) { const size_t num_words = wji[j].size(); vector<int>& zj = zji[j]; const vector<int>& wj = wji[j]; zj.resize(num_words); for (int i = 0; i < num_words; ++i) { cout << TD::Convert(wj[i]) << '(' << zj[i] << ") "; } cout << endl; } #endif for (int i = 0; i < num_classes; ++i) { cerr << "---------------------------------\n"; ShowTopWords(t2w[i]); } return 0; } <|endoftext|>
<commit_before>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * You may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include <string.h> #include <ctime> #include <iostream> #include <string> #include <list> #include "modsecurity/modsecurity.h" #include "modsecurity/rules.h" #include "common/modsecurity_test.h" #include "common/colors.h" #include "regression/regression_test.h" #include "common/modsecurity_test_results.h" #include "regression/custom_debug_log.h" #include "utils/regex.h" using modsecurity_test::CustomDebugLog; using modsecurity_test::ModSecurityTest; using modsecurity_test::ModSecurityTestResults; using modsecurity_test::RegressionTest; using modsecurity_test::RegressionTestResult; using ModSecurity::Utils::regex_search; using ModSecurity::Utils::SMatch; using ModSecurity::Utils::Regex; std::string default_test_path = "test-cases/regression"; void print_help() { std::cout << "Use ./regression-tests /path/to/file" << std::endl; std::cout << std::endl; std::cout << std::endl; } void actions(ModSecurityTestResults<RegressionTest> *r, ModSecurity::Assay *a) { ModSecurity::ModSecurityIntervention it; memset(&it, '\0', sizeof(ModSecurity::ModSecurityIntervention)); it.status = 200; if (a->intervention(&it) == true) { if (it.pause != 0) { // FIXME: } if (it.status != 0) { r->status = it.status; } if (it.url != NULL) { r->location = it.url; } } } void perform_unit_test(std::vector<RegressionTest *> *tests, ModSecurityTestResults<RegressionTestResult> *res, int *count) { for (RegressionTest *t : *tests) { CustomDebugLog *debug_log = new CustomDebugLog(); ModSecurity::ModSecurity *modsec = NULL; ModSecurity::Rules *modsec_rules = NULL; ModSecurity::Assay *modsec_assay = NULL; ModSecurityTestResults<RegressionTest> r; RegressionTestResult *testRes = new RegressionTestResult(); testRes->test = t; r.status = 200; (*count)++; size_t offset = t->filename.find_last_of("/\\"); std::string filename(""); if (offset != std::string::npos) { filename = std::string(t->filename, offset + 1, t->filename.length() - offset - 1); } else { filename = t->filename; } std::cout << std::setw(3) << std::right << std::to_string(*count) << " "; std::cout << std::setw(50) << std::left << filename; std::cout << std::setw(70) << std::left << t->name; modsec = new ModSecurity::ModSecurity(); modsec->setConnectorInformation("ModSecurity-regression v0.0.1-alpha" \ " (ModSecurity regression test utility)"); modsec_rules = new ModSecurity::Rules(debug_log); if (modsec_rules->load(t->rules.c_str(), filename) < 0) { if (t->parser_error.empty() == true) { std::cerr << "parse failed." << std::endl; std::cout << modsec_rules->getParserError() << std::endl; return; } Regex re(t->parser_error); SMatch match; std::string s = modsec_rules->getParserError(); if (regex_search(s, &match, re) && match.size() >= 1) { std::cout << "passed!" << std::endl; return; } else { std::cout << "failed!" << std::endl; std::cout << "Expected a parser error." << std::endl; std::cout << "Expected: " << t->parser_error << std::endl; std::cout << "Produced: " << s << std::endl; return; } } else { if (t->parser_error.empty() == false) { std::cout << "failed!" << std::endl; std::cout << "Expected a parser error." << std::endl; std::cout << "Expected: " << t->parser_error << std::endl; } } modsec_assay = new ModSecurity::Assay(modsec, modsec_rules); modsec_assay->processConnection(t->clientIp.c_str(), t->clientPort, t->serverIp.c_str(), t->serverPort); actions(&r, modsec_assay); if (r.status != 200) { goto end; } modsec_assay->processURI(t->uri.c_str(), t->protocol.c_str(), t->httpVersion.c_str()); actions(&r, modsec_assay); if (r.status != 200) { goto end; } for (std::pair<std::string, std::string> headers : t->request_headers) { modsec_assay->addRequestHeader(headers.first.c_str(), headers.second.c_str()); } modsec_assay->processRequestHeaders(); actions(&r, modsec_assay); if (r.status != 200) { goto end; } modsec_assay->appendRequestBody( (unsigned char *)t->request_body.c_str(), t->request_body.size()); modsec_assay->processRequestBody(); actions(&r, modsec_assay); if (r.status != 200) { goto end; } for (std::pair<std::string, std::string> headers : t->response_headers) { modsec_assay->addResponseHeader(headers.first.c_str(), headers.second.c_str()); } modsec_assay->processResponseHeaders(); actions(&r, modsec_assay); if (r.status != 200) { goto end; } modsec_assay->appendResponseBody( (unsigned char *)t->response_body.c_str(), t->response_body.size()); modsec_assay->processResponseBody(); actions(&r, modsec_assay); if (r.status != 200) { goto end; } end: modsec_assay->processLogging(r.status); CustomDebugLog *d = reinterpret_cast<CustomDebugLog *> (modsec_rules->m_debugLog); if (d != NULL) { if (!d->contains(t->debug_log)) { std::cout << KRED << "failed!" << RESET << std::endl; testRes->reason << "Debug log was not matching the " \ << "expected results." << std::endl; testRes->reason << KWHT << "Expecting: " << RESET \ << t->debug_log + "."; testRes->passed = false; } else if (r.status != t->http_code) { std::cout << KRED << "failed!" << RESET << std::endl; testRes->reason << "HTTP code mismatch. expecting: " + \ std::to_string(t->http_code) + \ " got: " + std::to_string(r.status) + "\n"; testRes->passed = false; } else { std::cout << KGRN << "passed!" << RESET << std::endl; testRes->passed = true; goto after_debug_log; } if (testRes->passed == false) { testRes->reason << std::endl; testRes->reason << KWHT << "Debug log:" << RESET << std::endl; testRes->reason << d->log_messages() << std::endl; } } after_debug_log: if (d != NULL) { r.log_raw_debug_log = d->log_messages(); } delete modsec_assay; delete modsec_rules; delete modsec; /* delete debug_log; */ res->push_back(testRes); } } int main(int argc, char **argv) { ModSecurityTest<RegressionTest> test; ModSecurityTestResults<RegressionTest> results; test.cmd_options(argc, argv); std::cout << test.header(); test.load_tests(); std::cout << std::setw(4) << std::right << "# "; std::cout << std::setw(50) << std::left << "File Name"; std::cout << std::setw(70) << std::left << "Test Name"; std::cout << std::setw(10) << std::left << "Passed?"; std::cout << std::endl; std::cout << std::setw(4) << std::right << "--- "; std::cout << std::setw(50) << std::left << "---------"; std::cout << std::setw(70) << std::left << "---------"; std::cout << std::setw(10) << std::left << "-------"; std::cout << std::endl; int counter = 0; std::list<std::string> keyList; for (std::pair<std::string, std::vector<RegressionTest *> *> a : test) { keyList.push_back(a.first); } keyList.sort(); ModSecurityTestResults<RegressionTestResult> res; for (std::string &a : keyList) { std::vector<RegressionTest *> *tests = test[a]; perform_unit_test(tests, &res, &counter); } std::cout << std::endl; int passed = 0; int failed = 0; for (RegressionTestResult *r : res) { if (r->passed) { passed++; } else { std::cout << KRED << "Test failed." << RESET << KWHT << " From: " \ << RESET << r->test->filename << "." << std::endl; std::cout << KWHT << "Test name: " << RESET << r->test->name << "." << std::endl; std::cout << KWHT << "Reason: " << RESET << std::endl; std::cout << r->reason.str() << std::endl; failed++; } } std::cout << "Ran a total of: " << std::to_string(failed + passed) \ << " regression tests - "; if (failed == 0) { std::cout << KGRN << "All tests passed" << RESET << std::endl; } else { std::cout << KRED << failed << " failed." << RESET << std::endl; } for (std::pair<std::string, std::vector<RegressionTest *> *> a : test) { std::vector<RegressionTest *> *vec = a.second; for (int i = 0; i < vec->size(); i++) { delete vec->at(i); } delete vec; } return 0; } <commit_msg>Cosmetic: Makes the parser error more verbose on the regression tests<commit_after>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * You may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include <string.h> #include <ctime> #include <iostream> #include <string> #include <list> #include "modsecurity/modsecurity.h" #include "modsecurity/rules.h" #include "common/modsecurity_test.h" #include "common/colors.h" #include "regression/regression_test.h" #include "common/modsecurity_test_results.h" #include "regression/custom_debug_log.h" #include "utils/regex.h" using modsecurity_test::CustomDebugLog; using modsecurity_test::ModSecurityTest; using modsecurity_test::ModSecurityTestResults; using modsecurity_test::RegressionTest; using modsecurity_test::RegressionTestResult; using ModSecurity::Utils::regex_search; using ModSecurity::Utils::SMatch; using ModSecurity::Utils::Regex; std::string default_test_path = "test-cases/regression"; void print_help() { std::cout << "Use ./regression-tests /path/to/file" << std::endl; std::cout << std::endl; std::cout << std::endl; } void actions(ModSecurityTestResults<RegressionTest> *r, ModSecurity::Assay *a) { ModSecurity::ModSecurityIntervention it; memset(&it, '\0', sizeof(ModSecurity::ModSecurityIntervention)); it.status = 200; if (a->intervention(&it) == true) { if (it.pause != 0) { // FIXME: } if (it.status != 0) { r->status = it.status; } if (it.url != NULL) { r->location = it.url; } } } void perform_unit_test(std::vector<RegressionTest *> *tests, ModSecurityTestResults<RegressionTestResult> *res, int *count) { for (RegressionTest *t : *tests) { CustomDebugLog *debug_log = new CustomDebugLog(); ModSecurity::ModSecurity *modsec = NULL; ModSecurity::Rules *modsec_rules = NULL; ModSecurity::Assay *modsec_assay = NULL; ModSecurityTestResults<RegressionTest> r; RegressionTestResult *testRes = new RegressionTestResult(); testRes->test = t; r.status = 200; (*count)++; size_t offset = t->filename.find_last_of("/\\"); std::string filename(""); if (offset != std::string::npos) { filename = std::string(t->filename, offset + 1, t->filename.length() - offset - 1); } else { filename = t->filename; } std::cout << std::setw(3) << std::right << std::to_string(*count) << " "; std::cout << std::setw(50) << std::left << filename; std::cout << std::setw(70) << std::left << t->name; modsec = new ModSecurity::ModSecurity(); modsec->setConnectorInformation("ModSecurity-regression v0.0.1-alpha" \ " (ModSecurity regression test utility)"); modsec_rules = new ModSecurity::Rules(debug_log); if (modsec_rules->load(t->rules.c_str(), filename) < 0) { if (t->parser_error.empty() == true) { testRes->reason << KRED << "parse failed." << RESET << std::endl; testRes->reason << modsec_rules->getParserError() << std::endl; testRes->passed = false; return; } Regex re(t->parser_error); SMatch match; std::string s = modsec_rules->getParserError(); if (regex_search(s, &match, re) && match.size() >= 1) { testRes->reason << KGRN << "passed!" << RESET << std::endl; testRes->passed = true; return; } else { testRes->reason << KRED << "failed!" << RESET << std::endl; testRes->reason << KWHT << "Expected a parser error." \ << RESET << std::endl; testRes->reason << KWHT << "Expected: " << RESET \ << t->parser_error << std::endl; testRes->reason << KWHT << "Produced: " << RESET \ << s << std::endl; testRes->passed = false; return; } } else { if (t->parser_error.empty() == false) { std::cout << KRED << "failed!" << std::endl; std::cout << KWHT << "Expected a parser error." \ << RESET << std::endl; std::cout << KWHT << "Expected: " << RESET \ << t->parser_error << std::endl; testRes->passed = false; } } modsec_assay = new ModSecurity::Assay(modsec, modsec_rules); modsec_assay->processConnection(t->clientIp.c_str(), t->clientPort, t->serverIp.c_str(), t->serverPort); actions(&r, modsec_assay); if (r.status != 200) { goto end; } modsec_assay->processURI(t->uri.c_str(), t->protocol.c_str(), t->httpVersion.c_str()); actions(&r, modsec_assay); if (r.status != 200) { goto end; } for (std::pair<std::string, std::string> headers : t->request_headers) { modsec_assay->addRequestHeader(headers.first.c_str(), headers.second.c_str()); } modsec_assay->processRequestHeaders(); actions(&r, modsec_assay); if (r.status != 200) { goto end; } modsec_assay->appendRequestBody( (unsigned char *)t->request_body.c_str(), t->request_body.size()); modsec_assay->processRequestBody(); actions(&r, modsec_assay); if (r.status != 200) { goto end; } for (std::pair<std::string, std::string> headers : t->response_headers) { modsec_assay->addResponseHeader(headers.first.c_str(), headers.second.c_str()); } modsec_assay->processResponseHeaders(); actions(&r, modsec_assay); if (r.status != 200) { goto end; } modsec_assay->appendResponseBody( (unsigned char *)t->response_body.c_str(), t->response_body.size()); modsec_assay->processResponseBody(); actions(&r, modsec_assay); if (r.status != 200) { goto end; } end: modsec_assay->processLogging(r.status); CustomDebugLog *d = reinterpret_cast<CustomDebugLog *> (modsec_rules->m_debugLog); if (d != NULL) { if (!d->contains(t->debug_log)) { std::cout << KRED << "failed!" << RESET << std::endl; testRes->reason << "Debug log was not matching the " \ << "expected results." << std::endl; testRes->reason << KWHT << "Expecting: " << RESET \ << t->debug_log + "."; testRes->passed = false; } else if (r.status != t->http_code) { std::cout << KRED << "failed!" << RESET << std::endl; testRes->reason << "HTTP code mismatch. expecting: " + \ std::to_string(t->http_code) + \ " got: " + std::to_string(r.status) + "\n"; testRes->passed = false; } else { std::cout << KGRN << "passed!" << RESET << std::endl; testRes->passed = true; goto after_debug_log; } if (testRes->passed == false) { testRes->reason << std::endl; testRes->reason << KWHT << "Debug log:" << RESET << std::endl; testRes->reason << d->log_messages() << std::endl; } } after_debug_log: if (d != NULL) { r.log_raw_debug_log = d->log_messages(); } delete modsec_assay; delete modsec_rules; delete modsec; /* delete debug_log; */ res->push_back(testRes); } } int main(int argc, char **argv) { ModSecurityTest<RegressionTest> test; ModSecurityTestResults<RegressionTest> results; test.cmd_options(argc, argv); std::cout << test.header(); test.load_tests(); std::cout << std::setw(4) << std::right << "# "; std::cout << std::setw(50) << std::left << "File Name"; std::cout << std::setw(70) << std::left << "Test Name"; std::cout << std::setw(10) << std::left << "Passed?"; std::cout << std::endl; std::cout << std::setw(4) << std::right << "--- "; std::cout << std::setw(50) << std::left << "---------"; std::cout << std::setw(70) << std::left << "---------"; std::cout << std::setw(10) << std::left << "-------"; std::cout << std::endl; int counter = 0; std::list<std::string> keyList; for (std::pair<std::string, std::vector<RegressionTest *> *> a : test) { keyList.push_back(a.first); } keyList.sort(); ModSecurityTestResults<RegressionTestResult> res; for (std::string &a : keyList) { std::vector<RegressionTest *> *tests = test[a]; perform_unit_test(tests, &res, &counter); } std::cout << std::endl; int passed = 0; int failed = 0; for (RegressionTestResult *r : res) { if (r->passed) { passed++; } else { std::cout << KRED << "Test failed." << RESET << KWHT << " From: " \ << RESET << r->test->filename << "." << std::endl; std::cout << KWHT << "Test name: " << RESET << r->test->name << "." << std::endl; std::cout << KWHT << "Reason: " << RESET << std::endl; std::cout << r->reason.str() << std::endl; failed++; } } std::cout << "Ran a total of: " << std::to_string(failed + passed) \ << " regression tests - "; if (failed == 0) { std::cout << KGRN << "All tests passed" << RESET << std::endl; } else { std::cout << KRED << failed << " failed." << RESET << std::endl; } for (std::pair<std::string, std::vector<RegressionTest *> *> a : test) { std::vector<RegressionTest *> *vec = a.second; for (int i = 0; i < vec->size(); i++) { delete vec->at(i); } delete vec; } return 0; } <|endoftext|>