id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
17,327
spinlock.h
manticoresoftware_manticoresearch/src/std/spinlock.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "thread_annotations.h" #include "unique_lock.h" #include <boost/fiber/detail/spinlock.hpp> namespace sph { // wrapper over boost::fibers::detail::spinlock to provide thread-annotation capabilities // naming convention follows std::mutex, and so, func may be used with std::unique_lock, etc. class CAPABILITY ( "mutex" ) Spinlock_c { boost::fibers::detail::spinlock m_tLock {}; public: Spinlock_c() = default; Spinlock_c ( Spinlock_c const& ) = delete; Spinlock_c& operator= ( Spinlock_c const& ) = delete; void lock() noexcept ACQUIRE() { m_tLock.lock(); } bool try_lock() noexcept TRY_ACQUIRE ( true ) { return m_tLock.try_lock(); } void unlock() noexcept UNLOCK_FUNCTION() { m_tLock.unlock(); } }; using Spinlock_lock = sph::unique_lock<Spinlock_c>; } // namespace sph
1,298
C++
.h
40
30.7
93
0.735365
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,328
hash.h
manticoresoftware_manticoresearch/src/std/hash.h
// // Copyright (c) 2024, Manticore Software LTD (https://manticoresearch.com) // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "generics.h" #define XXH_STATIC_LINKING_ONLY #define XXH_INLINE_ALL #include "xxhash.h" // a wrapper for xxHash FORCE_INLINE uint64_t HashWithSeed ( const void * pInput, size_t tLength, uint64_t uSeed ) { return XXH3_64bits_withSeed ( pInput, tLength, uSeed ); }
663
C++
.h
19
33.631579
90
0.75625
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,329
scoped_comma.h
manticoresoftware_manticoresearch/src/std/scoped_comma.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #pragma once #include "generics.h" #include "stringbuilder.h" class ScopedComma_c: public ISphNoncopyable { public: ScopedComma_c() = default; ScopedComma_c ( StringBuilder_c& tOwner, const char* sDel, const char* sPref = nullptr, const char* sTerm = nullptr, bool bAllowEmpty = true ); ScopedComma_c ( StringBuilder_c& tOwner, const StrBlock_t& dBlock, bool bAllowEmpty = true ); ScopedComma_c ( ScopedComma_c&& rhs ) noexcept { Swap ( rhs ); } ScopedComma_c& operator= ( ScopedComma_c&& rhs ) noexcept { Swap ( rhs ); return *this; } ~ScopedComma_c(); void Swap ( ScopedComma_c& rhs ) noexcept; void Init ( StringBuilder_c& tOwner, const char* sDel, const char* sPref = nullptr, const char* sTerm = nullptr ); StringBuilder_c& Sink() const; private: StringBuilder_c* m_pOwner = nullptr; int m_iLevel = 0; bool m_bAllowEmpty = true; }; #include "scoped_comma_impl.h"
1,375
C++
.h
39
33.461538
144
0.73474
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,330
queue_impl.h
manticoresoftware_manticoresearch/src/std/queue_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include "generics.h" #include <cassert> template<typename T, typename COMP> CSphQueue<T, COMP>::CSphQueue ( int iSize ) { Reset ( iSize ); } template<typename T, typename COMP> CSphQueue<T, COMP>::~CSphQueue() { SafeDeleteArray ( m_pData ); } template<typename T, typename COMP> void CSphQueue<T, COMP>::Reset ( int iSize ) { SafeDeleteArray ( m_pData ); assert ( iSize >= 0 ); m_iSize = iSize; if ( iSize ) m_pData = new T[iSize]; assert ( !iSize || m_pData ); } template<typename T, typename COMP> void CSphQueue<T, COMP>::Clear() { m_iUsed = 0; } /// add entry to the queue template<typename T, typename COMP> bool CSphQueue<T, COMP>::Push ( const T& tEntry ) { assert ( m_pData ); if ( m_iUsed == m_iSize ) { // if it's worse that current min, reject it, else pop off current min if ( COMP::IsLess ( tEntry, m_pData[0] ) ) return false; else Pop(); } // do add m_pData[m_iUsed] = tEntry; int iEntry = m_iUsed++; // shift up if needed, so that worst (lesser) ones float to the top while ( iEntry ) { int iParent = ( iEntry - 1 ) >> 1; if ( !COMP::IsLess ( m_pData[iEntry], m_pData[iParent] ) ) break; // entry is less than parent, should float to the top Swap ( m_pData[iEntry], m_pData[iParent] ); iEntry = iParent; } return true; } /// remove root (ie. top priority) entry template<typename T, typename COMP> void CSphQueue<T, COMP>::Pop() { assert ( m_iUsed && m_pData ); if ( !( --m_iUsed ) ) // empty queue? just return return; // make the last entry my new root m_pData[0] = m_pData[m_iUsed]; // shift down if needed int iEntry = 0; while ( true ) { // select child int iChild = ( iEntry << 1 ) + 1; if ( iChild >= m_iUsed ) break; // select smallest child if ( iChild + 1 < m_iUsed ) if ( COMP::IsLess ( m_pData[iChild + 1], m_pData[iChild] ) ) ++iChild; // if smallest child is less than entry, do float it to the top if ( COMP::IsLess ( m_pData[iChild], m_pData[iEntry] ) ) { Swap ( m_pData[iChild], m_pData[iEntry] ); iEntry = iChild; continue; } break; } } /// get current root template<typename T, typename COMP> inline const T& CSphQueue<T, COMP>::Root() const { assert ( m_iUsed && m_pData ); return m_pData[0]; } template<typename T, typename COMP> inline const T & CSphQueue<T, COMP>::Last() const { assert ( m_iUsed && m_pData ); return m_pData[m_iUsed-1]; }
2,876
C++
.h
110
24.045455
80
0.675528
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,331
strerrorm.h
manticoresoftware_manticoresearch/src/std/strerrorm.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include <cerrno> #include <cstring> // wrapper over strerror inline const char* strerrorm ( int errnum ) { if ( errnum == EMFILE ) return "Too many open files (on linux see /etc/security/limits.conf, 'ulimit -n', max_open_files config option)"; return strerror ( errnum ); }
770
C++
.h
21
35.380952
115
0.742972
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,332
at_scope_exit.h
manticoresoftware_manticoresearch/src/std/at_scope_exit.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "generics.h" #include <utility> /// perform any (function-defined) action on exit from a scope. template<typename ACTION> class AtScopeExit_T { ACTION m_dAction; public: explicit AtScopeExit_T ( ACTION&& tAction ) : m_dAction { std::forward<ACTION> ( tAction ) } {} AtScopeExit_T ( AtScopeExit_T&& rhs ) noexcept : m_dAction { std::move ( rhs.m_dAction ) } {} ~AtScopeExit_T() { m_dAction(); } }; // create action to be performed on-exit-from-scope. // usage example: // someObject * pObj; // need to be freed going out of scope // auto dObjDeleter = AtScopeExit ( [&pObj] { SafeDelete (pObj); } ) // ... template<typename ACTION> AtScopeExit_T<ACTION> AtScopeExit ( ACTION&& action ) { return AtScopeExit_T<ACTION> { std::forward<ACTION> ( action ) }; } #define AT_SCOPE_EXIT( ... ) auto SPH_UID ( tAtExit ) = AtScopeExit ( __VA_ARGS__ ) #define AT_SCOPE_FN( action, exit_action ) action; AT_SCOPE_EXIT ( exit_action ) #define AT_SCOPE( action, exit_action ) AT_SCOPE_FN ( action, [&] { exit_action; } ) #define SCOPED_CHANGE( name, on_enter, on_exit ) AT_SCOPE_FN ( name on_enter, [&name] { name on_exit; } )
1,630
C++
.h
45
34.733333
105
0.708492
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,333
variant_impl.h
manticoresoftware_manticoresearch/src/std/variant_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include "generics.h" #include <cstdlib> /// ctor from C string inline CSphVariant::CSphVariant ( const char* sString, int iTag ) : m_sValue ( sString ) , m_iValue ( sString ? atoi ( sString ) : 0 ) , m_i64Value ( sString ? (int64_t)strtoull ( sString, nullptr, 10 ) : 0 ) , m_fValue ( sString ? (float)atof ( sString ) : 0.0f ) , m_iTag ( iTag ) { } /// copy ctor inline CSphVariant::CSphVariant ( const CSphVariant& rhs ) { if ( rhs.m_pNext ) m_pNext = new CSphVariant ( *rhs.m_pNext ); m_sValue = rhs.m_sValue; m_iValue = rhs.m_iValue; m_i64Value = rhs.m_i64Value; m_fValue = rhs.m_fValue; m_bTag = rhs.m_bTag; m_iTag = rhs.m_iTag; } /// move ctor inline CSphVariant::CSphVariant ( CSphVariant&& rhs ) noexcept : m_pNext ( nullptr ) // otherwise trash in uninitialized m_pNext causes crash in dtr { Swap ( rhs ); } /// default dtor /// WARNING: automatically frees linked items! inline CSphVariant::~CSphVariant() { SafeDelete ( m_pNext ); } /// default copy operator inline CSphVariant& CSphVariant::operator= ( CSphVariant rhs ) { Swap ( rhs ); return *this; } inline void CSphVariant::Swap ( CSphVariant& rhs ) noexcept { ::Swap ( m_pNext, rhs.m_pNext ); ::Swap ( m_sValue, rhs.m_sValue ); ::Swap ( m_iValue, rhs.m_iValue ); ::Swap ( m_i64Value, rhs.m_i64Value ); ::Swap ( m_fValue, rhs.m_fValue ); ::Swap ( m_bTag, rhs.m_bTag ); ::Swap ( m_iTag, rhs.m_iTag ); }
1,881
C++
.h
62
28.741935
86
0.696903
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,334
escaped_builder_impl.h
manticoresoftware_manticoresearch/src/std/escaped_builder_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <cstring> template<typename Q> bool EscapedStringBuilder_T<Q>::AppendEmpty ( const char* sText ) { if ( sText && *sText ) return false; GrowEnough ( 1 ); auto* pCur = end(); *pCur = '\0'; return true; } template<typename Q> void EscapedStringBuilder_T<Q>::AppendEmptyQuotes() { GrowEnough ( 3 ); auto* pCur = end(); pCur[0] = Q::cQuote; pCur[1] = Q::cQuote; pCur[2] = '\0'; m_iUsed += 2; } template<typename Q> bool EscapedStringBuilder_T<Q>::AppendEmptyEscaped ( const char* sText ) { if ( sText && *sText ) return false; AppendEmptyQuotes(); return true; } // dedicated EscBld::eEscape | EscBld::eSkipComma template<typename Q> template<bool BQUOTE> void EscapedStringBuilder_T<Q>::AppendEscapedSkippingCommaT ( const char* sText ) { if constexpr ( BQUOTE ) { if ( AppendEmptyEscaped ( sText ) ) return; } else { if ( !sText || !*sText ) return; } GrowEnough ( BQUOTE ? 7 : 5 ); // 2 quotes, terminator, and possible 4 for long escaping const char* pSrc = sText; auto* pCur = (BYTE*)end(); auto pEnd = (BYTE*)m_szBuffer + m_iSize; if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; for ( ; *pSrc; ++pSrc ) { Q::EscapeChar ( pCur, *pSrc ); if ( pCur > ( pEnd - 8 ) ) // need 1 ending quote, terminator, and m.b. long escaping { m_iUsed = pCur - (BYTE*)m_szBuffer; GrowEnough ( 32 ); pEnd = (BYTE*)m_szBuffer + m_iSize; pCur = (BYTE*)m_szBuffer + m_iUsed; } } if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; *pCur = '\0'; m_iUsed = pCur - (BYTE*)m_szBuffer; } template<typename Q> void EscapedStringBuilder_T<Q>::AppendEscapedSkippingComma ( const char* sText ) { AppendEscapedSkippingCommaT ( sText ); } template<typename Q> void EscapedStringBuilder_T<Q>::AppendEscapedSkippingCommaNoQuotes ( const char* sText ) { AppendEscapedSkippingCommaT<false> ( sText ); } template<typename Q> template<bool BQUOTE> void EscapedStringBuilder_T<Q>::AppendEscapedWithCommaT ( const char* sText ) { auto& sComma = Delim(); if ( sComma.second ) { GrowEnough ( sComma.second ); memcpy ( end(), sComma.first, sComma.second ); m_iUsed += sComma.second; } if constexpr ( BQUOTE ) { if ( AppendEmptyEscaped ( sText ) ) return; } else { if ( !sText || !*sText ) return; } GrowEnough ( BQUOTE ? 7 : 5 ); // 2 quotes and terminator const char* pSrc = sText; auto* pCur = (BYTE*)end(); auto pEnd = (BYTE*)m_szBuffer + m_iSize; if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; for ( ; *pSrc; ++pSrc ) { Q::EscapeChar ( pCur, *pSrc ); if ( pCur > ( pEnd - 8 ) ) // need 1 ending quote, terminator, and m.b. long escaping { m_iUsed = pCur - (BYTE*)m_szBuffer; GrowEnough ( 32 ); pEnd = (BYTE*)m_szBuffer + m_iSize; pCur = (BYTE*)m_szBuffer + m_iUsed; } } if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; *pCur = '\0'; m_iUsed = pCur - (BYTE*)m_szBuffer; } template<typename Q> void EscapedStringBuilder_T<Q>::AppendEscapedWithComma ( const char* sText ) { AppendEscapedWithCommaT ( sText ); } template<typename Q> void EscapedStringBuilder_T<Q>::AppendEscapedWithCommaNoQuotes ( const char* sText ) { AppendEscapedWithCommaT<false> ( sText ); } // dedicated EscBld::eEscape with comma with external len template<typename Q> template<bool BQUOTE> void EscapedStringBuilder_T<Q>::AppendEscapedWithCommaT ( const char* sText, int iLen ) { auto& sComma = Delim(); if ( sComma.second ) { GrowEnough ( sComma.second ); memcpy ( end(), sComma.first, sComma.second ); m_iUsed += sComma.second; } if ( !iLen ) { if constexpr ( BQUOTE ) return AppendEmptyQuotes(); return; } GrowEnough ( BQUOTE ? 7 : 5 ); // 2 quotes, terminator, and possible 4 for long escaping const char* pSrc = sText; auto* pCur = (BYTE*)end(); auto pEnd = (BYTE*)m_szBuffer + m_iSize; if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; for ( ; iLen; ++pSrc, --iLen ) { Q::EscapeChar ( pCur, *pSrc ); if ( pCur > ( pEnd - 8 ) ) // need 1 ending quote, terminator, and m.b. long escaping { m_iUsed = pCur - (BYTE*)m_szBuffer; GrowEnough ( 32 ); pEnd = (BYTE*)m_szBuffer + m_iSize; pCur = (BYTE*)m_szBuffer + m_iUsed; } } if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; *pCur = '\0'; m_iUsed = pCur - (BYTE*)m_szBuffer; } template<typename Q> void EscapedStringBuilder_T<Q>::AppendEscapedWithComma ( const char* sText, int iLength ) { AppendEscapedWithCommaT ( sText, iLength ); } template<typename Q> void EscapedStringBuilder_T<Q>::AppendEscapedWithCommaNoQuotes ( const char* sText, int iLength ) { AppendEscapedWithCommaT<false> ( sText, iLength ); } // dedicated EscBld::eFixupSpace template<typename Q> void EscapedStringBuilder_T<Q>::FixupSpacesAndAppend ( const char* sText ) { if ( AppendEmpty ( sText ) ) return; auto& sComma = Delim(); if ( sComma.second ) { GrowEnough ( sComma.second ); memcpy ( end(), sComma.first, sComma.second ); m_iUsed += sComma.second; } GrowEnough ( 6 ); // terminator const char* pSrc = sText; auto* pCur = (BYTE*)end(); auto pEnd = (BYTE*)m_szBuffer + m_iSize; for ( ; *pSrc; ++pSrc ) { Q::FixupSpace ( pCur, *pSrc ); if ( pCur > ( pEnd - 7 ) ) // need terminator { m_iUsed = pCur - (BYTE*)m_szBuffer; GrowEnough ( 32 ); pEnd = (BYTE*)m_szBuffer + m_iSize; pCur = (BYTE*)m_szBuffer + m_iUsed; } } *pCur = '\0'; m_iUsed = pCur - (BYTE*)m_szBuffer; } // dedicated EscBld::eAll (=EscBld::eFixupSpace | EscBld::eEscape ) template<typename Q> template<bool BQUOTE> void EscapedStringBuilder_T<Q>::FixupSpacedAndAppendEscapedT ( const char* sText ) { auto& sComma = Delim(); if ( sComma.second ) { GrowEnough ( sComma.second ); memcpy ( end(), sComma.first, sComma.second ); m_iUsed += sComma.second; } if constexpr ( BQUOTE ) { if ( AppendEmptyEscaped ( sText ) ) return; } else { if ( !sText || !*sText ) return; } GrowEnough ( BQUOTE ? 7 : 5 ); // 2 quotes, terminator, and possible 4 for long escaping const char* pSrc = sText; auto* pCur = (BYTE*)end(); auto pEnd = (BYTE*)m_szBuffer + m_iSize; if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; for ( ; *pSrc; ++pSrc ) { Q::EscapeCharWithSpaces ( pCur, *pSrc ); if ( pCur > ( pEnd - 8 ) ) // need 1 ending quote, terminator, and m.b. long escaping { m_iUsed = pCur - (BYTE*)m_szBuffer; GrowEnough ( 32 ); pEnd = (BYTE*)m_szBuffer + m_iSize; pCur = (BYTE*)m_szBuffer + m_iUsed; } } if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; *pCur = '\0'; m_iUsed = pCur - (BYTE*)m_szBuffer; } template<typename Q> void EscapedStringBuilder_T<Q>::FixupSpacedAndAppendEscaped ( const char* sText ) { FixupSpacedAndAppendEscapedT ( sText ); } template<typename Q> void EscapedStringBuilder_T<Q>::FixupSpacedAndAppendEscapedNoQuotes ( const char* sText ) { FixupSpacedAndAppendEscapedT<false> ( sText ); } // dedicated EscBld::eAll (=EscBld::eFixupSpace | EscBld::eEscape ) with external len template<typename Q> template<bool BQUOTE> void EscapedStringBuilder_T<Q>::FixupSpacedAndAppendEscapedT ( const char* sText, int iLen ) { assert ( iLen >= 0 ); auto& sComma = Delim(); if ( sComma.second ) { GrowEnough ( sComma.second ); memcpy ( end(), sComma.first, sComma.second ); m_iUsed += sComma.second; } if ( !iLen ) { if constexpr ( BQUOTE ) return AppendEmptyQuotes(); return; } GrowEnough ( BQUOTE ? 7 : 5 ); // 2 quotes, terminator, and possible 4 for long escaping const char* pSrc = sText; auto* pCur = (BYTE*)end(); auto pEnd = (BYTE*)m_szBuffer + m_iSize; if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; for ( ; iLen; ++pSrc, --iLen ) { Q::EscapeCharWithSpaces ( pCur, *pSrc ); if ( pCur > ( pEnd - 8 ) ) // need 1 ending quote, terminator, and m.b. long escaping { m_iUsed = pCur - (BYTE*)m_szBuffer; GrowEnough ( 32 ); pEnd = (BYTE*)m_szBuffer + m_iSize; pCur = (BYTE*)m_szBuffer + m_iUsed; } } if constexpr ( BQUOTE ) *pCur++ = Q::cQuote; *pCur = '\0'; m_iUsed = pCur - (BYTE*)m_szBuffer; } template<typename Q> void EscapedStringBuilder_T<Q>::FixupSpacedAndAppendEscaped ( const char* sText, int iLen ) { FixupSpacedAndAppendEscapedT ( sText, iLen ); } template<typename Q> void EscapedStringBuilder_T<Q>::FixupSpacedAndAppendEscapedNoQuotes ( const char* sText, int iLen ) { FixupSpacedAndAppendEscapedT<false> ( sText, iLen ); } // generic implementation. Used this way in tests. For best performance consider to use specialized versions // (see selector switch inside) directly. template<typename Q> void EscapedStringBuilder_T<Q>::AppendEscaped ( const char* sText, BYTE eWhat, int iLen ) { if ( iLen == -1 ) eWhat |= EscBld::eNoLimit; else eWhat &= ~EscBld::eNoLimit; // shortcuts to dedicated separate cases switch ( eWhat ) { case ( EscBld::eEscape | EscBld::eSkipComma | EscBld::eNoLimit ): AppendEscapedSkippingComma ( sText ); return; case ( EscBld::eEscape | EscBld::eSkipComma | EscBld::eNoLimit | EscBld::eSkipQuotes ): AppendEscapedSkippingCommaNoQuotes ( sText ); return; case ( EscBld::eEscape | EscBld::eNoLimit ): AppendEscapedWithComma ( sText ); return; case ( EscBld::eEscape | EscBld::eNoLimit | EscBld::eSkipQuotes ): AppendEscapedWithCommaNoQuotes ( sText ); return; case ( EscBld::eEscape ): AppendEscapedWithComma ( sText, iLen ); return; case ( EscBld::eEscape | EscBld::eSkipQuotes ): AppendEscapedWithCommaNoQuotes ( sText, iLen ); return; case ( EscBld::eFixupSpace | EscBld::eNoLimit ): case ( EscBld::eFixupSpace | EscBld::eNoLimit | EscBld::eSkipQuotes ): FixupSpacesAndAppend ( sText ); return; case ( EscBld::eAll | EscBld::eNoLimit ): FixupSpacedAndAppendEscaped ( sText ); return; case ( EscBld::eAll | EscBld::eNoLimit | EscBld::eSkipQuotes ): FixupSpacedAndAppendEscapedNoQuotes ( sText ); return; case ( EscBld::eAll ): FixupSpacedAndAppendEscaped ( sText, iLen ); return; case ( EscBld::eAll | EscBld::eSkipQuotes ): FixupSpacedAndAppendEscapedNoQuotes ( sText, iLen ); return; } if ( ( eWhat & EscBld::eEscape ) == 0 && AppendEmpty ( sText ) ) return; // process comma if ( eWhat & EscBld::eSkipComma ) // assert no eEscape here, since it is hold separately already. eWhat -= EscBld::eSkipComma; else { auto sComma = Delim(); if ( sComma.second ) { GrowEnough ( sComma.second ); memcpy ( end(), sComma.first, sComma.second ); m_iUsed += sComma.second; } } if ( ( eWhat & EscBld::eEscape ) && AppendEmptyEscaped ( sText ) ) return; const char* pSrc = sText; int iFinalLen = 0; if ( eWhat & EscBld::eEscape ) { if ( eWhat & EscBld::eNoLimit ) { eWhat &= ~EscBld::eNoLimit; for ( ; *pSrc; ++pSrc ) iFinalLen += Q::EscapingSpace ( *pSrc ); } else { for ( auto iL = 0; iL < iLen; ++pSrc, ++iL ) iFinalLen += Q::EscapingSpace ( *pSrc ); } iLen = (int)( pSrc - sText ); iFinalLen += iLen + 2; // 2 quotes: 1 prefix, 2 postfix. } else if ( eWhat & EscBld::eNoLimit ) { eWhat &= ~EscBld::eNoLimit; iFinalLen = iLen = (int)strlen ( sText ); } else iFinalLen = iLen; GrowEnough ( iFinalLen + 1 ); // + zero terminator auto* pCur = (BYTE*)end(); switch ( eWhat ) { case EscBld::eNone: memcpy ( pCur, sText, iFinalLen ); pCur += iFinalLen; break; case EscBld::eFixupSpace: // EscBld::eNoLimit hold especially for ( ; iLen; --iLen ) Q::FixupSpace ( pCur, *sText++ ); break; case EscBld::eEscape: *pCur++ = Q::cQuote; for ( ; iLen; --iLen ) Q::EscapeChar ( pCur, *sText++ ); *pCur++ = Q::cQuote; break; case EscBld::eAll: default: *pCur++ = Q::cQuote; for ( ; iLen; --iLen ) Q::EscapeCharWithSpaces ( pCur, *sText++ ); *pCur++ = Q::cQuote; } *pCur = '\0'; m_iUsed += iFinalLen; } template<typename Q> EscapedStringBuilder_T<Q>& EscapedStringBuilder_T<Q>::SkipNextComma() { StringBuilder_c::SkipNextComma(); return *this; } template<typename Q> EscapedStringBuilder_T<Q>& EscapedStringBuilder_T<Q>::AppendName ( const char* sName, bool bQuoted ) { StringBuilder_c::AppendName ( sName, bQuoted ); return *this; }
12,500
C++
.h
449
25.516704
108
0.683921
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,335
num_conv.h
manticoresoftware_manticoresearch/src/std/num_conv.h
// // Copyright (c) 2022-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" namespace sph { /// my own converter num to string. template<typename Num> // let compiler deduce whether signed or unsigned... int NtoA ( char* pOutput, Num nVal, int iBase = 10, int iWidth = 0, int iPrec = 0, char cFill = ' ' ); /// my own fixed-point floats. iPrec - num of digits after point. i.e. 100000, 3 -> 100.000 int IFtoA ( char* pOutput, int nVal, int iPrec = 3 ); int IFtoA ( char* pOutput, int64_t nVal, int iPrec = 6 ); } #include "num_conv_impl.h"
975
C++
.h
23
41.173913
102
0.721225
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,336
stringhash.h
manticoresoftware_manticoresearch/src/std/stringhash.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "string.h" #include "orderedhash.h" ///////////////////////////////////////////////////////////////////////////// /// string hash function struct CSphStrHashFunc { static int Hash ( const CSphString& sKey ); }; /// small hash with string keys template<typename T, int LENGTH = 256> using SmallStringHash_T = CSphOrderedHash<T, CSphString, CSphStrHashFunc, LENGTH>; namespace sph { // used to simple add/delete strings and check if a string was added by [] op class StringSet: private SmallStringHash_T<bool> { using BASE = SmallStringHash_T<bool>; public: inline bool Add ( const CSphString& sKey ) { return BASE::Add ( true, sKey ); } inline bool operator[] ( const CSphString& sKey ) const { HashEntry_t* pEntry = FindByKey ( sKey ); return pEntry ? pEntry->second : false; } StringSet ( std::initializer_list<const char *> dVals ); StringSet ( const VecTraits_T<CSphString> & dVals ); StringSet() = default; using BASE::Delete; using BASE::Reset; using BASE::GetLength; using BASE::IsEmpty; using BASE::begin; using BASE::end; using Iterator_c = BASE::Iterator_c; }; }
1,605
C++
.h
51
29.764706
82
0.708171
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,337
openhash.h
manticoresoftware_manticoresearch/src/std/openhash.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" #include <utility> #pragma pack(push,4) template < typename KEY, typename VALUE > class OpenHashEntry_T { public: KEY m_Key; VALUE m_Value; FORCE_INLINE OpenHashEntry_T(); template <typename STATE> FORCE_INLINE bool IsUsed ( const STATE & tState ) const { return m_bUsed; } template <typename STATE> FORCE_INLINE void SetUsed ( const STATE & tState, bool bUsed ) { m_bUsed = bUsed; } private: bool m_bUsed = false; }; #pragma pack(pop) #pragma pack(push,4) template < typename KEY, typename VALUE > class OpenHashVersionEntry_T { public: KEY m_Key; VALUE m_Value; template <typename STATE> FORCE_INLINE bool IsUsed ( const STATE & tState ) const { return m_uVersion==tState.m_uVersion; } template <typename STATE> FORCE_INLINE void SetUsed ( const STATE & tState, bool bUsed ) { m_uVersion = tState.m_uVersion - !bUsed; } private: uint32_t m_uVersion = 0; }; #pragma pack(pop) #pragma pack(push,4) template < typename KEY > class OpenHashSetEntry_T { public: KEY m_Key = (KEY)0; template <typename STATE> FORCE_INLINE bool IsUsed ( const STATE & tState ) const { return m_bUsed; } template <typename STATE> FORCE_INLINE void SetUsed ( const STATE & tState, bool bUsed ) { m_bUsed = bUsed; } private: bool m_bUsed = false; }; #pragma pack(pop) #pragma pack(push,4) template < typename KEY > class OpenHashSetVersionEntry_T { public: KEY m_Key; template <typename STATE> FORCE_INLINE bool IsUsed ( const STATE & tState ) const { return m_uVersion==tState.m_uVersion; } template <typename STATE> FORCE_INLINE void SetUsed ( const STATE & tState, bool bUsed ) { m_uVersion = tState.m_uVersion - !bUsed; } private: uint32_t m_uVersion = 0; }; #pragma pack(pop) struct HashNoState_t { void Swap ( HashNoState_t & rhs ) {} }; struct HashStateVersion_t { uint32_t m_uVersion = 1; void Swap ( HashStateVersion_t & rhs ) { std::swap ( m_uVersion, rhs.m_uVersion ); } }; struct HashFunc_Int64_t; template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> class OpenHashTraits_T : public STATE { using MYTYPE = OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>; public: explicit OpenHashTraits_T ( int64_t iSize=256 ) { Reset(iSize); } OpenHashTraits_T ( const OpenHashTraits_T & rhs ); ~OpenHashTraits_T() { SafeDeleteArray ( m_pHash ); } void Reset ( int64_t iSize ); void Clear(); FORCE_INLINE bool Delete ( KEY k ); /// get number of inserted key-value pairs FORCE_INLINE int64_t GetLength() const { return m_iUsed; } /// get total size (not accounting for load factor) FORCE_INLINE int64_t GetSize() const { return m_iSize; } FORCE_INLINE bool IsFull() const { return m_iUsed==m_iMaxUsed; } FORCE_INLINE int64_t GetLengthBytes() const { return m_iSize*sizeof(ENTRY); } FORCE_INLINE int64_t GetUsedLengthBytes() const { return m_iUsed*sizeof(ENTRY); } static FORCE_INLINE float GetLoadFactor() { return LOAD_FACTOR; } // move contents to another hash (possibly of larger size) void MoveTo ( MYTYPE & rhs ) const; protected: static constexpr float LOAD_FACTOR = 0.95f; int64_t m_iSize {0}; // total hash size int64_t m_iUsed {0}; // how many entries are actually used int64_t m_iMaxUsed {0}; // resize threshold ENTRY * m_pHash {nullptr}; ///< hash entries /// find (and do not touch!) entry by key FORCE_INLINE ENTRY * FindEntry ( KEY k ) const; /// acquire value by key (ie. get existing hashed value, or add a new default value) FORCE_INLINE ENTRY & AcquireEntry ( KEY k ); /// we are overloaded, lets grow 2x and rehash void Grow(); /// get max load, ie. max number of actually used entries at given size FORCE_INLINE int64_t GetMaxLoad ( int64_t iSize ) const { return (int64_t)( iSize*LOAD_FACTOR ); } FORCE_INLINE void DeleteEntry ( ENTRY * pEntry ); void MoveToNewStorage ( MYTYPE & rhs, ENTRY * pNew, int64_t iNewSize ) const; void Swap ( MYTYPE & rhs ) noexcept; }; /// simple open-addressing hash template <typename KEY, typename VALUE, typename HASHFUNC=HashFunc_Int64_t, typename ENTRY=OpenHashEntry_T<KEY,VALUE>, typename STATE=HashNoState_t> class OpenHashTable_T : public OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE> { using BASE = OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>; using MYTYPE = OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>; using BASE::BASE; public: OpenHashTable_T ( const OpenHashTable_T & rhs ); OpenHashTable_T ( OpenHashTable_T && rhs ) noexcept { BASE::Swap(rhs); } OpenHashTable_T & operator = ( OpenHashTable_T && rhs ) noexcept; OpenHashTable_T & operator = ( const OpenHashTable_T & rhs ) noexcept; /// acquire value by key (ie. get existing hashed value, or add a new default value) FORCE_INLINE VALUE & Acquire ( KEY k ) { return BASE::AcquireEntry(k).m_Value; } /// find an existing value by key FORCE_INLINE VALUE * Find ( KEY k ) const; /// find and delete; assumes that key exists FORCE_INLINE VALUE FindAndDelete ( KEY k ); /// add or fail (if key already exists) FORCE_INLINE bool Add ( KEY k, const VALUE & v ); /// find existing value, or add a new value FORCE_INLINE VALUE & FindOrAdd ( KEY k, const VALUE & v ); /// iterate the hash by entry index, starting from 0 /// finds the next alive key-value pair starting from the given index /// returns that pair and updates the index on success /// returns NULL when the hash is over VALUE * Iterate ( int64_t * pIndex, KEY * pKey ) const; // same as above, but without messing of return value/return param std::pair<KEY,VALUE*> Iterate ( int64_t & iIndex ) const; }; template <typename KEY, typename VALUE, typename HASHFUNC=HashFunc_Int64_t, typename ENTRY=OpenHashVersionEntry_T<KEY,VALUE>> class OpenHashTableFastClear_T : public OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,HashStateVersion_t> { using BASE = OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,HashStateVersion_t>; using BASE::BASE; public: FORCE_INLINE void Clear(); }; template <typename KEY, typename HASHFUNC=HashFunc_Int64_t, typename ENTRY=OpenHashSetEntry_T<KEY>, typename STATE=HashNoState_t> class OpenHashSet_T : public OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE> { using BASE = OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>; using BASE::BASE; public: FORCE_INLINE bool Find ( KEY k ) const { return !!BASE::FindEntry(k); } FORCE_INLINE bool Add ( KEY k ); KEY * Iterate ( int64_t & iIndex ) const; }; template <typename KEY, typename HASHFUNC=HashFunc_Int64_t, typename ENTRY=OpenHashSetVersionEntry_T<KEY>> class OpenHashSetFastClear_T : public OpenHashSet_T<KEY,HASHFUNC,ENTRY,HashStateVersion_t> { using BASE = OpenHashSet_T<KEY,HASHFUNC,ENTRY,HashStateVersion_t>; using BASE::BASE; public: FORCE_INLINE void Clear(); }; #include "openhash_impl.h"
7,259
C++
.h
171
40.491228
148
0.734926
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,338
datamove.h
manticoresoftware_manticoresearch/src/std/datamove.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "type_traits.h" #include "ints.h" #include <utility> #include <cstring> namespace sph { ////////////////////////////////////////////////////////////////////////// /// Copy backends for vector /// Each backend provides Copy, Move and CopyOrSwap /// Copy/move vec of a data item-by-item template<typename T, bool C = IS_TRIVIALLY_COPYABLE ( T )> class DataMover_T { public: static void Copy ( T* pNew, const T* pData, int64_t iLength ); static void Move ( T* pNew, T* pData, int64_t iLength ); static void Zero ( T* pData, int64_t iLength ); }; template<typename T> /// Copy/move blob of trivial data using memmove class DataMover_T<T, true> { public: static void Copy ( T* pNew, const T* pData, int64_t iLength ); static void Move ( T* pNew, T* pData, int64_t iLength ); static void Zero ( T* pData, int64_t iLength ); // append raw blob: defined ONLY in POD specialization. static void CopyVoid ( T* pNew, const void* pData, int64_t iLength ); }; /// default vector mover template<typename T> class DefaultCopy_T: public DataMover_T<T> { public: static void CopyOrSwap ( T& pLeft, const T& pRight ); }; /// swap-vector policy (for non-copyable classes) /// use Swap() instead of assignment on resize template<typename T> class SwapCopy_T { public: static void Copy ( T* pNew, T* pData, int64_t iLength ); static void Move ( T* pNew, T* pData, int64_t iLength ); static void CopyOrSwap ( T& dLeft, T& dRight ); static void CopyOrSwap ( T& dLeft, T&& dRight ); }; } // namespace sph #include "datamove_impl.h"
2,033
C++
.h
60
32.416667
80
0.702758
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,339
autoevent.h
manticoresoftware_manticoresearch/src/std/autoevent.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "generics.h" #include <mutex> #include "ints.h" /// fixme! use std::mutex, std::condition_variable // event implementation class EventWrapper_c: public ISphNoncopyable { public: EventWrapper_c(); ~EventWrapper_c(); inline bool Initialized() const { return m_bInitialized; } protected: bool m_bInitialized = false; #if _WIN32 CONDITION_VARIABLE m_tCond; CRITICAL_SECTION m_tMutex; #else pthread_cond_t m_tCond; pthread_mutex_t m_tMutex; #endif }; template<bool bONESHOT = true> class AutoEvent_T: public EventWrapper_c { public: // increase of set (oneshot) event's count and issue an event. void SetEvent(); // decrease or reset (oneshot) event's count. If count empty, go to sleep until new events // returns true if event happened, false if timeout reached or event is not initialized bool WaitEvent ( int iMsec = -1 ); // -1 means 'infinite' private: volatile int m_iSent = 0; }; using CSphAutoEvent = AutoEvent_T<false>; using OneshotEvent_c = AutoEvent_T<>;
1,489
C++
.h
50
28.2
91
0.757003
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,340
buffer.h
manticoresoftware_manticoresearch/src/std/buffer.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "generics.h" #include "vectraits.h" #include "string.h" /// buffer trait that neither own buffer nor clean-up it on destroy template<typename T> class CSphBufferTrait: public ISphNoncopyable, public VecTraits_T<T> { protected: using VecTraits_T<T>::m_pData; using VecTraits_T<T>::m_iCount; public: using VecTraits_T<T>::GetLengthBytes; /// ctor CSphBufferTrait() = default; /// dtor virtual ~CSphBufferTrait(); virtual void Reset() = 0; /// get write address T* GetWritePtr() const { return m_pData; } /// returns read address - same as write, but const pointer const T* GetReadPtr() const { return GetWritePtr(); } void Set ( T* pData, int64_t iCount ); bool MemLock ( CSphString& sWarning ); protected: bool m_bMemLocked = false; void MemUnlock(); }; #include "buffer_impl.h"
1,313
C++
.h
46
26.717391
80
0.743017
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,341
scopedlock.h
manticoresoftware_manticoresearch/src/std/scopedlock.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "thread_annotations.h" #include "generics.h" /// scoped mutex lock /// may adopt, lock and unlock explicitly template<typename MTX> class CAPABILITY ( "mutex" ) SCOPED_CAPABILITY CSphScopedLock: public ISphNoncopyable { public: // Tag type used to distinguish constructors. enum ADOPT_LOCK_E { adopt_lock }; /// adopt already held lock CSphScopedLock ( MTX& tMutex, ADOPT_LOCK_E ) REQUIRES ( tMutex ) ACQUIRE ( tMutex ); /// constructor acquires the lock explicit CSphScopedLock ( MTX& tMutex ) ACQUIRE ( tMutex ); /// unlock on going out of scope ~CSphScopedLock() RELEASE(); /// Explicitly acquire the lock. /// to be used ONLY from the same thread! (call from another is obviously wrong) void Lock() ACQUIRE(); /// Explicitly release the lock. void Unlock() RELEASE(); bool Locked() const { return m_bLocked; } typename MTX::mtx& mutex() RETURN_CAPABILITY ( m_tMutexRef ) { return m_tMutexRef.mutex(); } private: MTX& m_tMutexRef; bool m_bLocked; // whether the mutex is currently locked or unlocked }; #include "scopedlock_impl.h"
1,570
C++
.h
46
32.326087
85
0.744048
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,342
orderedhash.h
manticoresoftware_manticoresearch/src/std/orderedhash.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include <utility> #include <cassert> #include "generics.h" ////////////////////////////////////////////////////////////////////////// /// simple dynamic hash /// implementation: fixed-size bucket + chaining /// keeps the order, so Iterate() return the entries in the order they was inserted /// WARNING: slow copy template<typename T, typename KEY, typename HASHFUNC, int LENGTH> class CSphOrderedHash { public: using KeyValue_t = std::pair<KEY, T>; using KEY_TYPE = KEY; using VAL_TYPE = T; protected: struct HashEntry_t: public KeyValue_t // key, data, owned by the hash { HashEntry_t* m_pNextByHash = nullptr; ///< next entry in hash list HashEntry_t* m_pPrevByOrder = nullptr; ///< prev entry in the insertion order HashEntry_t* m_pNextByOrder = nullptr; ///< next entry in the insertion order }; protected: HashEntry_t* m_dHash[LENGTH]; ///< all the hash entries HashEntry_t* m_pFirstByOrder = nullptr; ///< first entry in the insertion order HashEntry_t* m_pLastByOrder = nullptr; ///< last entry in the insertion order int m_iLength = 0; ///< entries count protected: unsigned int HashPos ( const KEY& tKey ) const; /// find entry by key HashEntry_t* FindByKey ( const KEY& tKey ) const; HashEntry_t* AddImpl ( const KEY& tKey ); public: /// ctor CSphOrderedHash(); /// dtor ~CSphOrderedHash(); /// reset void Reset(); /// add new entry /// returns true on success /// returns false if this key is already hashed bool Add ( T&& tValue, const KEY& tKey ); bool Add ( const T& tValue, const KEY& tKey ); /// add new entry /// returns ref to just inserted or previously existed value T& AddUnique ( const KEY& tKey ); /// delete an entry bool Delete ( const KEY& tKey ); /// check if key exists bool Exists ( const KEY& tKey ) const { return FindByKey ( tKey ) != nullptr; } /// get value pointer by key T* operator() ( const KEY& tKey ) const { HashEntry_t* pEntry = FindByKey ( tKey ); return pEntry ? &pEntry->second : nullptr; } /// get value reference by key, asserting that the key exists in hash T& operator[] ( const KEY& tKey ) const; /// copying ctor CSphOrderedHash ( const CSphOrderedHash& rhs ) : CSphOrderedHash() { for ( const auto& tData : rhs ) Add ( tData.second, tData.first ); } /// moving ctor CSphOrderedHash ( CSphOrderedHash&& rhs ) noexcept : CSphOrderedHash() { Swap ( rhs ); } void Swap ( CSphOrderedHash& rhs ) noexcept; /// copying & moving CSphOrderedHash& operator= ( CSphOrderedHash rhs ) { Swap ( rhs ); return *this; } /// length query int GetLength() const { return m_iLength; } /// emptiness bool IsEmpty() const { return m_iLength == 0; } public: class Iterator_c { HashEntry_t* m_pIterator = nullptr; public: explicit Iterator_c ( HashEntry_t* pIterator = nullptr ) : m_pIterator ( pIterator ) {} KeyValue_t& operator*() { return *m_pIterator; } KeyValue_t* operator->() const { return m_pIterator; }; Iterator_c& operator++() { m_pIterator = m_pIterator->m_pNextByOrder; return *this; } Iterator_c& operator--() { m_pIterator = m_pIterator->m_pPrevByOrder; return *this; } bool operator== ( const Iterator_c& rhs ) const { return m_pIterator == rhs.m_pIterator; } bool operator!= ( const Iterator_c& rhs ) const { return !operator== ( rhs ); } }; // c++11 style iteration Iterator_c begin() const { return Iterator_c { m_pFirstByOrder }; } static Iterator_c end() { return Iterator_c { nullptr }; } }; #include "orderedhash_impl.h"
4,073
C++
.h
144
25.888889
83
0.686889
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,343
comma.h
manticoresoftware_manticoresearch/src/std/comma.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "blobs.h" /// text delimiter /// returns "" first time, then defined delimiter starting from 2-nd call /// NOTE that using >1 call in one chain like out << comma << "foo" << comma << "bar" is NOT defined, /// since order of calling 2 commas here is undefined (so, you may take "foo, bar", but may ", foobar" also). /// Use out << comma << "foo"; out << comma << "bar"; in the case class Comma_c { protected: Str_t m_sComma = dEmptyStr; bool m_bStarted = false; public: // standalone - cast to 'Str_t' when necessary explicit Comma_c ( const char* sDelim = nullptr ); explicit Comma_c ( Str_t sDelim ); Comma_c ( const Comma_c& rhs ) = default; Comma_c ( Comma_c&& rhs ) noexcept = default; Comma_c& operator= ( Comma_c rhs ); void Swap ( Comma_c& rhs ) noexcept; inline bool Started() const { return m_bStarted; } operator Str_t(); }; #include "comma_impl.h"
1,376
C++
.h
35
37.742857
109
0.704955
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,344
type_traits.h
manticoresoftware_manticoresearch/src/std/type_traits.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include <type_traits> // workaround missing "is_trivially_copyable" in g++ < 5.0 #if defined( __GNUG__ ) && ( __GNUC__ < 5 ) && !defined( __clang__ ) #define IS_TRIVIALLY_COPYABLE( T ) __has_trivial_copy ( T ) #define IS_TRIVIALLY_DEFAULT_CONSTRUCTIBLE( T ) std::has_trivial_default_constructor<T>::value #else #define IS_TRIVIALLY_COPYABLE( T ) std::is_trivially_copyable<T>::value #define IS_TRIVIALLY_DEFAULT_CONSTRUCTIBLE( T ) std::is_trivially_default_constructible<T>::value #endif
979
C++
.h
21
45.52381
97
0.735356
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,345
stringbuilder_impl.h
manticoresoftware_manticoresearch/src/std/stringbuilder_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include "num_conv.h" #if __has_include( <charconv>) #include <charconv> #endif inline void StringBuilder_c::AppendRawChunk ( Str_t sText ) // append without any commas { if ( !sText.second ) return; GrowEnough ( sText.second + 1 ); // +1 because we'll put trailing \0 also memcpy ( m_szBuffer + m_iUsed, sText.first, sText.second ); m_iUsed += sText.second; m_szBuffer[m_iUsed] = '\0'; } inline StringBuilder_c& StringBuilder_c::SkipNextComma() { if ( !m_dDelimiters.IsEmpty() ) m_dDelimiters.Last().SkipNext(); return *this; } inline StringBuilder_c& StringBuilder_c::AppendName ( const Str_t& sName, bool bQuoted ) { if ( ::IsEmpty ( sName ) ) return *this; AppendChunk ( sName, bQuoted ? '"' : '\0' ); GrowEnough ( 2 ); m_szBuffer[m_iUsed] = ':'; m_szBuffer[m_iUsed + 1] = '\0'; m_iUsed += 1; return SkipNextComma(); } inline StringBuilder_c& StringBuilder_c::AppendName ( const char* szName, bool bQuoted ) { return AppendName ( FromSz ( szName ), bQuoted ); } inline StringBuilder_c& StringBuilder_c::AppendChunk ( const Str_t& sChunk, char cQuote ) { if ( !sChunk.second ) return *this; auto sComma = Delim(); int iQuote = cQuote != 0; GrowEnough ( sChunk.second + sComma.second + iQuote + iQuote + 1 ); // +1 because we'll put trailing \0 also if ( sComma.second ) memcpy ( m_szBuffer + m_iUsed, sComma.first, sComma.second ); if ( iQuote ) m_szBuffer[m_iUsed + sComma.second] = cQuote; memcpy ( m_szBuffer + m_iUsed + sComma.second + iQuote, sChunk.first, sChunk.second ); m_iUsed += sChunk.second + sComma.second + iQuote + iQuote; if ( iQuote ) m_szBuffer[m_iUsed - 1] = cQuote; m_szBuffer[m_iUsed] = '\0'; return *this; } inline StringBuilder_c& StringBuilder_c::AppendString ( const CSphString& sText, char cQuote ) { return AppendChunk ( FromStr ( sText ), cQuote ); } inline StringBuilder_c& StringBuilder_c::AppendString ( const char* szText, char cQuote ) { return AppendChunk ( FromSz ( szText ), cQuote ); } inline StringBuilder_c& StringBuilder_c::AppendString ( Str_t sText, char cQuote ) { return AppendChunk ( sText, cQuote ); } inline StringBuilder_c& StringBuilder_c::operator+= ( const char* sText ) { if ( !sText || *sText == '\0' ) return *this; return AppendChunk ( { sText, (int)strlen ( sText ) } ); } inline StringBuilder_c& StringBuilder_c::operator<< ( const Str_t& sChunk ) { return AppendChunk ( sChunk ); } inline StringBuilder_c& StringBuilder_c::operator<< ( const VecTraits_T<char>& sText ) { if ( sText.IsEmpty() ) return *this; return AppendChunk ( { sText.begin(), sText.GetLength() } ); } inline StringBuilder_c& StringBuilder_c::operator<< ( int iVal ) { InitAddPrefix(); GrowEnough ( 32 ); #if __has_include( <charconv>) SetPos ( std::to_chars ( end(), AfterEnd(), iVal ).ptr ); #else m_iUsed += sph::NtoA ( end(), iVal ); #endif m_szBuffer[m_iUsed] = '\0'; return *this; } inline StringBuilder_c& StringBuilder_c::operator<< ( long iVal ) { InitAddPrefix(); GrowEnough ( 32 ); #if __has_include( <charconv>) SetPos ( std::to_chars ( end(), AfterEnd(), iVal ).ptr ); #else m_iUsed += sph::NtoA ( end(), iVal ); #endif m_szBuffer[m_iUsed] = '\0'; return *this; } inline StringBuilder_c& StringBuilder_c::operator<< ( long long iVal ) { InitAddPrefix(); GrowEnough ( 32 ); #if __has_include( <charconv>) SetPos ( std::to_chars ( end(), AfterEnd(), iVal ).ptr ); #else m_iUsed += sph::NtoA ( end(), iVal ); #endif m_szBuffer[m_iUsed] = '\0'; return *this; } inline StringBuilder_c& StringBuilder_c::operator<< ( unsigned int uVal ) { InitAddPrefix(); GrowEnough ( 32 ); #if __has_include( <charconv>) SetPos ( std::to_chars ( end(), AfterEnd(), uVal ).ptr ); #else m_iUsed += sph::NtoA ( end(), uVal ); #endif m_szBuffer[m_iUsed] = '\0'; return *this; } inline StringBuilder_c& StringBuilder_c::operator<< ( unsigned long uVal ) { InitAddPrefix(); GrowEnough ( 32 ); #if __has_include( <charconv>) SetPos ( std::to_chars ( end(), AfterEnd(), uVal ).ptr ); #else m_iUsed += sph::NtoA ( end(), uVal ); #endif m_szBuffer[m_iUsed] = '\0'; return *this; } inline StringBuilder_c& StringBuilder_c::operator<< ( unsigned long long uVal ) { InitAddPrefix(); GrowEnough ( 32 ); #if __has_include( <charconv>) SetPos ( std::to_chars ( end(), AfterEnd(), uVal ).ptr ); #else m_iUsed += sph::NtoA ( end(), uVal ); #endif m_szBuffer[m_iUsed] = '\0'; return *this; } template<typename T> StringBuilder_c& StringBuilder_c::operator+= ( const T* pVal ) { InitAddPrefix(); AppendRawChunk ( FROMS ( "0x" ) ); GrowEnough ( sizeof ( void* ) * 2 ); m_iUsed += sph::NtoA ( end(), reinterpret_cast<uintptr_t> ( pVal ), 16, sizeof ( void* ) * 2, 0, '0' ); m_szBuffer[m_iUsed] = '\0'; return *this; } inline StringBuilder_c& StringBuilder_c::operator<< ( bool bVal ) { if ( bVal ) return *this << "true"; return *this << "false"; } inline void StringBuilder_c::Clear() { Rewind(); m_dDelimiters.Reset(); } inline void StringBuilder_c::Rewind() { if ( m_szBuffer ) m_szBuffer[0] = '\0'; m_iUsed = 0; } template<typename INT, int iBase, int iWidth, int iPrec, char cFill> inline void StringBuilder_c::NtoA ( INT uVal ) { InitAddPrefix(); const int MAX_NUMERIC_STR = 22; GrowEnough ( MAX_NUMERIC_STR + 1 ); #if __has_include( <charconv>) if constexpr ( iWidth == 0 && iPrec == 0 && cFill == ' ' ) SetPos ( std::to_chars ( end(), AfterEnd(), uVal, iBase ).ptr ); else m_iUsed += sph::NtoA ( end(), uVal, iBase, iWidth, iPrec, cFill ); #else m_iUsed += sph::NtoA ( end(), uVal, iBase, iWidth, iPrec, cFill ); #endif m_szBuffer[m_iUsed] = '\0'; } template<typename INT, int iPrec> inline void StringBuilder_c::IFtoA ( FixedFrac_T<INT, iPrec> tVal ) { InitAddPrefix(); const int MAX_NUMERIC_STR = 22; GrowEnough ( MAX_NUMERIC_STR + 1 ); int iLen = sph::IFtoA ( end(), tVal.m_tVal, iPrec ); m_iUsed += iLen; m_szBuffer[m_iUsed] = '\0'; } // shrink, if necessary, to be able to fit at least iLen more chars inline void StringBuilder_c::GrowEnough ( int iLen ) { if ( m_iUsed + iLen<m_iSize ) return; Grow ( iLen ); } inline void StringBuilder_c::InitAddPrefix() { if ( !m_szBuffer ) InitBuffer(); assert ( m_iUsed==0 || m_iUsed<m_iSize ); auto sPrefix = Delim(); if ( sPrefix.second ) // prepend delimiter first... { GrowEnough ( sPrefix.second ); memcpy ( m_szBuffer + m_iUsed, sPrefix.first, sPrefix.second ); m_iUsed += sPrefix.second; } } inline const Str_t & StringBuilder_c::Delim () { if ( m_dDelimiters.IsEmpty ()) return dEmptyStr; int iLast = m_dDelimiters.GetLength()-1; std::function<void()> fnApply = [this, &iLast, &fnApply]() { --iLast; if ( iLast>=0 ) AppendRawChunk( m_dDelimiters[iLast].RawComma( fnApply )); }; return m_dDelimiters.Last().RawComma( fnApply ); } inline void StringBuilder_c::LazyComma_c::Swap ( LazyComma_c & rhs ) noexcept { Comma_c::Swap ( rhs ); m_sPrefix.swap ( rhs.m_sPrefix ); m_sSuffix.swap ( rhs.m_sSuffix ); ::Swap ( m_bSkipNext, rhs.m_bSkipNext ); } template<typename... Params> StringBuilder_c& StringBuilder_c::Sprint ( Params&&... tValues ) { (void)std::initializer_list<int> { ( *this << std::forward<Params>(tValues), 0 )... }; return *this; } inline StringBuilder_c& operator<< ( StringBuilder_c& tOut, const CSphNamedInt& tValue ) { tOut.Sprintf ( "%s=%d", tValue.first.cstr(), tValue.second ); return tOut; } inline StringBuilder_c& operator<< ( StringBuilder_c& tOut, timespan_t tVal ) { tOut.Sprintf ( "%t", tVal.m_iVal ); return tOut; } inline StringBuilder_c& operator<< ( StringBuilder_c& tOut, timestamp_t tVal ) { tOut.Sprintf ( "%T", tVal.m_iVal ); return tOut; } template<typename INT, int iPrec> inline StringBuilder_c& operator<< ( StringBuilder_c& tOut, FixedFrac_T<INT, iPrec> tVal ) { tOut.template IFtoA<INT, iPrec>(tVal); return tOut; } template<typename INT, int iBase, int iWidth, int iPrec, char cFill> StringBuilder_c& operator<< ( StringBuilder_c& tOut, FixedNum_T<INT, iBase, iWidth, iPrec, cFill> tVal ) { tOut.template NtoA<INT, iBase, iWidth, iPrec, cFill> ( tVal.m_tVal ); return tOut; }
8,574
C++
.h
289
27.896194
109
0.687439
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,346
deleter.h
manticoresoftware_manticoresearch/src/std/deleter.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once /// Deleter abstraction is used in smart pointer (shared ptr, hazard ptr, etc.) // tags enum class ETYPE { SINGLE, ARRAY }; template<typename PTR, ETYPE> struct Deleter_T { static void Delete ( void* pArg ); }; template<typename PTR> struct Deleter_T<PTR, ETYPE::ARRAY> { static void Delete ( void* pArg ); }; // stateless (i.e. may use pointer to fn) template<typename PTR, typename DELETER> struct StaticDeleter_t { static void Delete ( void * pArg ); }; // statefull (i.e. contains state, implies using of lambda with captures) template<typename PTR, typename DELETER> class CustomDeleter_T { DELETER m_dDeleter; public: CustomDeleter_T () = default; CustomDeleter_T ( DELETER&& dDeleter ) noexcept; void Delete ( void * pArg ); }; #include "deleter_impl.h"
1,264
C++
.h
42
28.738095
80
0.749588
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,348
lrucache_impl.h
manticoresoftware_manticoresearch/src/std/lrucache_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org/ // #include "scopedlock.h" template <typename KEY, typename VALUE, typename HELPER> LRUCache_T<KEY,VALUE,HELPER>::LRUCache_T ( int64_t iCacheSize ) : m_iCacheSize ( iCacheSize ) , m_tHash ( 1024 ) {} template <typename KEY, typename VALUE, typename HELPER> LRUCache_T<KEY,VALUE,HELPER>::~LRUCache_T() { LinkedEntry_t * pEntry = m_pHead; while ( pEntry ) { LinkedEntry_t * pToDelete = pEntry; pEntry = pEntry->m_pNext; Delete(pToDelete); } } template <typename KEY, typename VALUE, typename HELPER> bool LRUCache_T<KEY,VALUE,HELPER>::Find ( KEY tKey, VALUE & tData ) { ScopedMutex_t tLock(m_tLock); LinkedEntry_t ** ppEntry = m_tHash.Find(tKey); if ( !ppEntry ) return false; MoveToHead ( *ppEntry ); (*ppEntry)->m_iRefcount++; tData = (*ppEntry)->m_tValue; return true; } template <typename KEY, typename VALUE, typename HELPER> bool LRUCache_T<KEY,VALUE,HELPER>::Add ( KEY tKey, const VALUE & tData ) { ScopedMutex_t tLock(m_tLock); // if another thread managed to add a similar block while we were uncompressing ours, let it be LinkedEntry_t ** ppEntry = m_tHash.Find(tKey); if ( ppEntry ) return false; DWORD uSize = HELPER::GetSize(tData); DWORD uSpaceNeeded = uSize + sizeof(LinkedEntry_t); if ( !HaveSpaceFor ( uSpaceNeeded ) ) { DWORD MAX_BLOCK_SIZE = m_iCacheSize/64; if ( uSpaceNeeded>MAX_BLOCK_SIZE ) return false; SweepUnused ( uSpaceNeeded ); if ( !HaveSpaceFor ( uSpaceNeeded ) ) return false; } LinkedEntry_t * pEntry = new LinkedEntry_t; *(VALUE*)pEntry = tData; pEntry->m_iRefcount++; pEntry->m_tKey = tKey; pEntry->m_uSize = uSize; Add ( pEntry ); return true; } template <typename KEY, typename VALUE, typename HELPER> void LRUCache_T<KEY,VALUE,HELPER>::Release ( KEY tKey ) { ScopedMutex_t tLock(m_tLock); LinkedEntry_t ** ppEntry = m_tHash.Find(tKey); assert(ppEntry); LinkedEntry_t * pEntry = *ppEntry; pEntry->m_iRefcount--; assert ( pEntry->m_iRefcount>=0 ); } template <typename KEY, typename VALUE, typename HELPER> template <typename COND> void LRUCache_T<KEY,VALUE,HELPER>::Delete ( COND && fnCond ) { ScopedMutex_t tLock(m_tLock); LinkedEntry_t * pEntry = m_pHead; while ( pEntry ) { if ( fnCond ( pEntry->m_tKey) ) { assert ( !pEntry->m_iRefcount ); LinkedEntry_t * pToDelete = pEntry; pEntry = pEntry->m_pNext; Delete(pToDelete); } else pEntry = pEntry->m_pNext; } } template <typename KEY, typename VALUE, typename HELPER> void LRUCache_T<KEY,VALUE,HELPER>::MoveToHead ( LinkedEntry_t * pEntry ) { assert ( pEntry ); if ( pEntry==m_pHead ) return; if ( m_pTail==pEntry ) m_pTail = pEntry->m_pPrev; if ( pEntry->m_pPrev ) pEntry->m_pPrev->m_pNext = pEntry->m_pNext; if ( pEntry->m_pNext ) pEntry->m_pNext->m_pPrev = pEntry->m_pPrev; pEntry->m_pPrev = nullptr; pEntry->m_pNext = m_pHead; m_pHead->m_pPrev = pEntry; m_pHead = pEntry; } template <typename KEY, typename VALUE, typename HELPER> void LRUCache_T<KEY,VALUE,HELPER>::Add ( LinkedEntry_t * pEntry ) { pEntry->m_pNext = m_pHead; if ( m_pHead ) m_pHead->m_pPrev = pEntry; if ( !m_pTail ) m_pTail = pEntry; m_pHead = pEntry; Verify ( m_tHash.Add ( pEntry->m_tKey, pEntry ) ); m_iMemUsed += pEntry->m_uSize + sizeof(LinkedEntry_t); } template <typename KEY, typename VALUE, typename HELPER> void LRUCache_T<KEY,VALUE,HELPER>::Delete ( LinkedEntry_t * pEntry ) { Verify ( m_tHash.Delete ( pEntry->m_tKey ) ); if ( m_pHead == pEntry ) m_pHead = pEntry->m_pNext; if ( m_pTail==pEntry ) m_pTail = pEntry->m_pPrev; if ( pEntry->m_pPrev ) pEntry->m_pPrev->m_pNext = pEntry->m_pNext; if ( pEntry->m_pNext ) pEntry->m_pNext->m_pPrev = pEntry->m_pPrev; m_iMemUsed -= pEntry->m_uSize + sizeof(LinkedEntry_t); assert ( m_iMemUsed>=0 ); HELPER::Reset ( pEntry->m_tValue ); SafeDelete(pEntry); } template <typename KEY, typename VALUE, typename HELPER> void LRUCache_T<KEY,VALUE,HELPER>::SweepUnused ( DWORD uSpaceNeeded ) { // least recently used blocks are the tail LinkedEntry_t * pEntry = m_pTail; while ( pEntry && !HaveSpaceFor ( uSpaceNeeded ) ) { if ( !pEntry->m_iRefcount ) { assert ( !pEntry->m_iRefcount ); LinkedEntry_t * pToDelete = pEntry; pEntry = pEntry->m_pPrev; Delete(pToDelete); } else pEntry = pEntry->m_pPrev; } } template <typename KEY, typename VALUE, typename HELPER> bool LRUCache_T<KEY,VALUE,HELPER>::HaveSpaceFor ( DWORD uSpaceNeeded ) const { return m_iMemUsed+uSpaceNeeded <= m_iCacheSize; }
4,965
C++
.h
165
27.884848
96
0.711405
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,349
rwlock_impl.h
manticoresoftware_manticoresearch/src/std/rwlock_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include "checks.h" #include "ints.h" inline RwLock_t::~RwLock_t () { Verify ( Done() ); #if !_WIN32 SafeDelete ( m_pLock ); SafeDelete ( m_pWritePreferHelper ); #endif } template<class LOCKED> CSphScopedRLock_T<LOCKED>::CSphScopedRLock_T ( LOCKED & tLock ) : m_tLock ( tLock ) { m_tLock.ReadLock(); } template<class LOCKED> CSphScopedRLock_T<LOCKED>::~CSphScopedRLock_T () { m_tLock.Unlock(); } template<class LOCKED> CSphScopedWLock_T<LOCKED>::CSphScopedWLock_T ( LOCKED & tLock ) : m_tLock ( tLock ) { m_tLock.WriteLock(); } template<class LOCKED> CSphScopedWLock_T<LOCKED>::~CSphScopedWLock_T () { m_tLock.Unlock(); } template<class LOCKED> ScopedUnlock_T<LOCKED>::ScopedUnlock_T ( LOCKED &tLock ) : m_pLock ( &tLock ) {} template<class LOCKED> ScopedUnlock_T<LOCKED>::ScopedUnlock_T ( ScopedUnlock_T && tLock ) noexcept : m_pLock ( tLock.m_pLock ) { tLock.m_pLock = nullptr; } template<class LOCKED> ScopedUnlock_T<LOCKED>& ScopedUnlock_T<LOCKED>::operator= ( ScopedUnlock_T<LOCKED> &&rhs ) noexcept { if ( this==&rhs ) return *this; if ( m_pLock ) m_pLock->Unlock(); m_pLock = rhs.m_pLock; rhs.m_pLock = nullptr; return *this; } template<class LOCKED> ScopedUnlock_T<LOCKED>::~ScopedUnlock_T () { if ( m_pLock ) m_pLock->Unlock (); }
1,756
C++
.h
70
23.5
99
0.729179
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,350
deleter_impl.h
manticoresoftware_manticoresearch/src/std/deleter_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <utility> template<typename PTR, ETYPE TP> inline void Deleter_T<PTR, TP>::Delete ( void* pArg ) { if ( pArg ) delete (PTR)pArg; } template<typename PTR> inline void Deleter_T<PTR, ETYPE::ARRAY>::Delete ( void* pArg ) { if ( pArg ) delete[] (PTR)pArg; } template<typename PTR, typename DELETER> inline void StaticDeleter_t<PTR, DELETER>::Delete ( void* pArg ) { if ( pArg ) DELETER() ( PTR ( pArg ) ); } template<typename PTR, typename DELETER> CustomDeleter_T<PTR, DELETER>::CustomDeleter_T ( DELETER&& dDeleter ) noexcept : m_dDeleter { std::forward<DELETER> ( dDeleter ) } {} template<typename PTR, typename DELETER> inline void CustomDeleter_T<PTR, DELETER>::Delete ( void* pArg ) { if ( m_dDeleter ) m_dDeleter ( (PTR)pArg ); }
1,240
C++
.h
40
29.425
80
0.728571
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,351
smalloc_impl.h
manticoresoftware_manticoresearch/src/std/smalloc_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // template<typename T> inline T* sph::CustomStorage_T<T>::Allocate ( int64_t iLimit ) { return sphAllocateSmall ( int ( iLimit * sizeof ( T ) ) ); } #if WITH_SMALLALLOC template<typename T> inline void sph::CustomStorage_T<T>::Deallocate ( T* pData, int64_t iLimit ) { sphDeallocateSmall ( (BYTE*)pData, int ( iLimit * sizeof ( T ) ) ); } #else template<typename T> inline void sph::CustomStorage_T<T>::Deallocate ( T * pData ) { sphDeallocateSmall ( (BYTE*)pData ); } inline BYTE* sphAllocateSmall ( int iBytes ) { return new BYTE[iBytes]; }; inline void sphDeallocateSmall ( const BYTE* pBlob, int ) { delete[] pBlob; }; inline void sphDeallocateSmall ( const BYTE* pBlob ) { delete[] pBlob; }; // how many allocated right now inline size_t sphGetSmallAllocatedSize() { return 0; }; // how many pooled from the sys right now inline size_t sphGetSmallReservedSize() { return 0; }; #endif // WITH_SMALLALLOC
1,401
C++
.h
51
26.078431
80
0.741405
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,352
bitvec_impl.h
manticoresoftware_manticoresearch/src/std/bitvec_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include "bitcount.h" #include <utility> #include <cstring> template<typename T, int STATICBITS> BitVec_T<T, STATICBITS>::BitVec_T ( int iElements ) { Init ( iElements ); } template<typename T, int STATICBITS> BitVec_T<T, STATICBITS>::BitVec_T ( T * pData, int iElements ) { if ( m_pData != m_dStatic ) SafeDeleteArray(m_pData); m_iElements = iElements; m_pData = pData; m_bOwnStorage = false; } template<typename T, int STATICBITS> BitVec_T<T, STATICBITS>::~BitVec_T() { if ( m_pData != m_dStatic && m_bOwnStorage ) SafeDeleteArray ( m_pData ); } template<typename T, int STATICBITS> BitVec_T<T, STATICBITS>::BitVec_T ( const BitVec_T<T, STATICBITS>& rhs ) { m_pData = nullptr; m_iElements = rhs.m_iElements; auto iStorage = CalcStorage(); m_pData = ( m_iElements > STATICBITS ) ? new T[iStorage] : m_dStatic; memcpy ( m_pData, rhs.m_pData, GetSizeBytes() ); } template<typename T, int STATICBITS> void BitVec_T<T, STATICBITS>::Swap ( BitVec_T<T, STATICBITS>& rhs ) noexcept { if ( m_pData == m_dStatic && rhs.m_pData == rhs.m_dStatic ) { // both static - just exchange values for ( auto i = 0; i < STATICSIZE; ++i ) std::swap ( m_dStatic[i], rhs.m_dStatic[i] ); } else if ( m_pData == m_dStatic ) { // me static, rhs dynamic assert ( rhs.m_pData != rhs.m_dStatic ); for ( auto i = 0; i < STATICSIZE; ++i ) rhs.m_dStatic[i] = m_dStatic[i]; m_pData = rhs.m_pData; rhs.m_pData = rhs.m_dStatic; } else if ( rhs.m_pData == rhs.m_dStatic ) { // me dynamic, rhs static assert ( m_pData != m_dStatic ); for ( auto i = 0; i < STATICSIZE; ++i ) m_dStatic[i] = rhs.m_dStatic[i]; rhs.m_pData = m_pData; m_pData = m_dStatic; } else { // both dynamic. No need to copy static at all assert ( rhs.m_pData != rhs.m_dStatic ); assert ( m_pData != m_dStatic ); std::swap ( m_pData, rhs.m_pData ); } std::swap ( m_iElements, rhs.m_iElements ); } template<typename T, int STATICBITS> BitVec_T<T, STATICBITS>::BitVec_T ( BitVec_T<T, STATICBITS>&& rhs ) noexcept { Swap ( rhs ); } template<typename T, int STATICBITS> BitVec_T<T, STATICBITS>& BitVec_T<T, STATICBITS>::operator= ( BitVec_T<T, STATICBITS> rhs ) { Swap ( rhs ); return *this; } template<typename T, int STATICBITS> void BitVec_T<T, STATICBITS>::Init ( int iElements ) { assert ( iElements >= 0 ); if ( m_pData != m_dStatic ) SafeDeleteArray ( m_pData ); m_iElements = iElements; if ( iElements > STATICBITS ) m_pData = new T[CalcStorage()]; else m_pData = m_dStatic; Clear(); } template<typename T, int STATICBITS> void BitVec_T<T, STATICBITS>::Clear() { memset ( m_pData, 0, GetSizeBytes() ); } template<typename T, int STATICBITS> void BitVec_T<T, STATICBITS>::Set() { memset ( m_pData, 0xff, GetSizeBytes() ); } template<typename T, int STATICBITS> bool BitVec_T<T, STATICBITS>::BitGet ( int iIndex ) const noexcept { assert ( m_pData ); assert ( iIndex >= 0 ); assert ( iIndex < m_iElements ); return ( m_pData[iIndex >> SHIFT] & ( 1ULL << ( iIndex & MASK ) ) ) != 0; // NOLINT } template<typename T, int STATICBITS> bool BitVec_T<T, STATICBITS>::BitGetOr ( int iIndex, bool bAlternative ) const noexcept { if ( m_pData && iIndex >= 0 && iIndex < m_iElements ) return ( m_pData[iIndex >> SHIFT] & ( 1ULL << ( iIndex & MASK ) ) ) != 0; // NOLINT return bAlternative; } template<typename T, int STATICBITS> void BitVec_T<T, STATICBITS>::BitSet ( int iIndex ) { assert ( iIndex >= 0 ); assert ( iIndex < m_iElements ); m_pData[iIndex >> SHIFT] |= ( 1ULL << ( iIndex & MASK ) ); // NOLINT } template<typename T, int STATICBITS> void BitVec_T<T, STATICBITS>::BitClear ( int iIndex ) { assert ( iIndex >= 0 ); assert ( iIndex < m_iElements ); m_pData[iIndex >> SHIFT] &= ~( 1ULL << ( iIndex & MASK ) ); // NOLINT } template<typename T, int STATICBITS> const T* BitVec_T<T, STATICBITS>::Begin() const noexcept { return m_pData; } template<typename T, int STATICBITS> T* BitVec_T<T, STATICBITS>::Begin() { return m_pData; } template<typename T, int STATICBITS> int BitVec_T<T, STATICBITS>::GetSizeBytes() const noexcept { return CalcStorage() * sizeof ( T ); } template<typename T, int STATICBITS> int BitVec_T<T, STATICBITS>::GetSize() const noexcept { return m_iElements; } template<typename T, int STATICBITS> bool BitVec_T<T, STATICBITS>::IsEmpty() const noexcept { if ( !m_pData ) return true; return GetSize() == 0; } template<typename T, int STATICBITS> int BitVec_T<T, STATICBITS>::BitCount() const noexcept { int iBitSet = 0; for ( int i = 0; i < CalcStorage(); i++ ) iBitSet += sphBitCount ( m_pData[i] ); return iBitSet; } template<typename T, int STATICBITS> int BitVec_T<T, STATICBITS>::Scan ( int iStart ) const { assert ( iStart < m_iElements ); int iIndex = iStart >> SHIFT; T uMask = ~( ( (T)1 << ( iStart & MASK ) ) - 1 ); if ( m_pData[iIndex] & uMask ) return ( iIndex << SHIFT ) + ScanBit ( iIndex, iStart & MASK ); int iSize = CalcStorage(); iIndex++; while ( iIndex < iSize && !m_pData[iIndex] ) iIndex++; if ( iIndex >= iSize ) return m_iElements; return ( iIndex << SHIFT ) + ScanBit ( iIndex, 0 ); } template<typename T, int STATICBITS> int BitVec_T<T, STATICBITS>::ScanBit ( int iIndex, int iStart ) const { T uData = m_pData[iIndex]; for ( int i = iStart; i < SIZEBITS; i++ ) if ( uData & ( (T)1 << i ) ) return i; return m_iElements; } template<typename T, int STATICBITS> int BitVec_T<T, STATICBITS>::CalcStorage() const noexcept { return ( m_iElements + SIZEBITS - 1 ) / SIZEBITS; } template<typename T, int STATICBITS> void BitVec_T<T, STATICBITS>::Negate() { for ( int i = 0; i < CalcStorage(); i++ ) m_pData[i] = ~m_pData[i]; }
6,153
C++
.h
210
27.452381
91
0.681803
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,353
format.h
manticoresoftware_manticoresearch/src/std/format.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "config.h" #include <limits.h> #include <cstring> #if __has_include(<inttypes.h>) #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRIu64 #define PRIu64 "llu" #endif #ifndef PRIi64 #define PRIi64 "lld" #endif #define UINT64_FMT "%" PRIu64 #define INT64_FMT "%" PRIi64 #ifndef PRIx64 #define PRIx64 "llx" #endif #if __has_include( <charconv>) #include <charconv> #else template<typename T> inline static char* FormatInt ( char sBuf[32], T v ) { if ( sizeof ( T ) == 4 && v == INT_MIN ) return strncpy ( sBuf, "-2147483648", 32 ); if ( sizeof ( T ) == 8 && v == LLONG_MIN ) return strncpy ( sBuf, "-9223372036854775808", 32 ); bool s = ( v < 0 ); if ( s ) v = -v; char* p = sBuf + 31; *p = 0; do { *--p = '0' + char ( v % 10 ); v /= 10; } while ( v ); if ( s ) *--p = '-'; return p; } #endif
1,337
C++
.h
55
22.709091
80
0.674528
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,354
largebuffer.h
manticoresoftware_manticoresearch/src/std/largebuffer.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "buffer.h" ////////////////////////////////////////////////////////////////////////// /// in-memory buffer shared between processes template<typename T, bool SHARED = false> class CSphLargeBuffer: public CSphBufferTrait<T> { public: CSphLargeBuffer() {} ~CSphLargeBuffer() override; /// allocate storage bool Alloc ( int64_t iEntries, CSphString& sError ); /// deallocate storage void Reset() override; }; #include "largebuffer_impl.h"
947
C++
.h
27
33.555556
80
0.698465
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,355
openhash_impl.h
manticoresoftware_manticoresearch/src/std/openhash_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include "ints.h" #include "datamove.h" #include "generics.h" #include "log2.h" #include <cassert> #include <climits> template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::OpenHashTraits_T ( const OpenHashTraits_T & rhs ) { m_iSize = rhs.m_iSize; m_iUsed = rhs.m_iUsed; m_iMaxUsed = rhs.m_iMaxUsed; // as we anyway copy raw data, don't need to call ctrs with this allocation using Entry_Storage = typename std::aligned_storage<sizeof ( ENTRY ), alignof ( ENTRY )>::type; m_pHash = (ENTRY*)new Entry_Storage[m_iSize]; sph::DefaultCopy_T<ENTRY>::CopyVoid ( m_pHash, rhs.m_pHash, m_iSize ); } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> ENTRY * OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::FindEntry ( KEY k ) const { if ( !m_iSize ) return nullptr; int64_t iIndex = HASHFUNC::GetHash(k) & ( m_iSize-1 ); while ( m_pHash[iIndex].IsUsed(*this) ) { ENTRY & tEntry = m_pHash[iIndex]; if ( tEntry.m_Key==k ) return &tEntry; iIndex = ( iIndex+1 ) & ( m_iSize-1 ); } return nullptr; } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> ENTRY & OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::AcquireEntry ( KEY k ) { if ( !m_iSize ) Grow(); DWORD uHash = HASHFUNC::GetHash(k); int64_t iIndex = uHash & ( m_iSize-1 ); while (true) { // found matching key? great, return the value ENTRY * p = m_pHash + iIndex; if ( p->IsUsed(*this) ) { if ( p->m_Key==k ) return *p; } else // no matching keys? add it { // not enough space? grow the hash and force rescan if ( m_iUsed>=m_iMaxUsed ) { Grow(); iIndex = uHash & ( m_iSize-1 ); continue; } // store the newly added key p->m_Key = k; p->SetUsed ( *this, true ); m_iUsed++; return *p; } // no match so far, keep probing iIndex = ( iIndex+1 ) & ( m_iSize-1 ); } } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> void OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::Grow() { int64_t iNewSize = 2*Max(m_iSize,8); assert ( iNewSize<=UINT_MAX ); // sanity check ENTRY * pNew = new ENTRY[iNewSize]; MoveToNewStorage ( *this, pNew, iNewSize ); SafeDeleteArray ( m_pHash ); m_pHash = pNew; m_iSize = iNewSize; m_iMaxUsed = GetMaxLoad ( m_iSize ); } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> void OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::DeleteEntry ( ENTRY * pEntry ) { int64_t iIndex = pEntry-m_pHash; int64_t iNext = iIndex; while ( true ) { iNext = ( iNext+1 ) & ( m_iSize-1 ); ENTRY & tEntry = m_pHash[iNext]; if ( !tEntry.IsUsed(*this) ) break; int64_t iDesired = HASHFUNC::GetHash ( tEntry.m_Key ) & ( m_iSize-1 ); if ( ( iNext>iIndex && ( iDesired<=iIndex || iDesired>iNext ) ) || ( iNext<iIndex && ( iDesired<=iIndex && iDesired>iNext ) ) ) { m_pHash[iIndex] = m_pHash[iNext]; iIndex = iNext; } } m_pHash[iIndex].SetUsed ( *this, false ); m_iUsed--; } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> void OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::MoveToNewStorage ( MYTYPE & rhs, ENTRY * pNew, int64_t iNewSize ) const { for ( int64_t i=0; i<m_iSize; i++ ) if ( m_pHash[i].IsUsed(*this) ) { int64_t j = HASHFUNC::GetHash ( m_pHash[i].m_Key ) & ( iNewSize-1 ); while ( pNew[j].IsUsed(rhs) ) j = ( j+1 ) & ( iNewSize-1 ); pNew[j] = m_pHash[i]; pNew[j].SetUsed ( rhs, true ); } } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> void OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::Swap ( MYTYPE & rhs ) noexcept { STATE::Swap ( (STATE &)rhs ); std::swap ( m_iSize, rhs.m_iSize ); std::swap ( m_iUsed, rhs.m_iUsed ); std::swap ( m_iMaxUsed, rhs.m_iMaxUsed ); std::swap ( m_pHash, rhs.m_pHash ); } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> void OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::MoveTo ( MYTYPE & rhs ) const { assert ( rhs.m_iSize>=m_iSize ); MoveToNewStorage ( rhs, rhs.m_pHash, rhs.m_iSize ); rhs.m_iUsed = m_iUsed; } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> bool OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::Delete ( KEY k ) { ENTRY * pEntry = FindEntry(k); if ( !pEntry ) return false; DeleteEntry(pEntry); return true; } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> void OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::Reset ( int64_t iSize ) { assert ( iSize<=UINT_MAX ); // sanity check SafeDeleteArray ( m_pHash ); if ( iSize<=0 ) { m_iSize = m_iUsed = m_iMaxUsed = 0; return; } iSize = ( 1ULL<<sphLog2 ( iSize-1 ) ); assert ( iSize<=UINT_MAX ); // sanity check m_pHash = new ENTRY[iSize]; m_iSize = iSize; m_iUsed = 0; m_iMaxUsed = GetMaxLoad ( iSize ); } template <typename KEY, typename ENTRY, typename HASHFUNC, typename STATE> void OpenHashTraits_T<KEY,ENTRY,HASHFUNC,STATE>::Clear() { for ( int i=0; i<m_iSize; i++ ) m_pHash[i] = ENTRY(); m_iUsed = 0; } ///////////////////////////////////////////////////////////////////// struct HashFunc_Int64_t { static FORCE_INLINE DWORD GetHash ( int64_t k ) { return ( DWORD(k) * 0x607cbb77UL ) ^ ( k>>32 ); } }; template<typename KEY, typename VALUE> OpenHashEntry_T<KEY,VALUE>::OpenHashEntry_T() = default; template<> inline OpenHashEntry_T<int64_t,int>::OpenHashEntry_T() : m_Key{0}, m_Value{0} {} template<> inline OpenHashEntry_T<int64_t, DWORD>::OpenHashEntry_T() : m_Key{0}, m_Value{0} {} template<> inline OpenHashEntry_T<int64_t,float>::OpenHashEntry_T() : m_Key{0}, m_Value{0.0f} {} template<> inline OpenHashEntry_T<int64_t,int64_t>::OpenHashEntry_T() : m_Key{0}, m_Value{0} {} template<> inline OpenHashEntry_T<int64_t,uint64_t>::OpenHashEntry_T() : m_Key{0}, m_Value{0} {} template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::OpenHashTable_T ( const OpenHashTable_T & rhs ) : BASE(rhs) {} template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE> & OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::operator = ( OpenHashTable_T && rhs ) noexcept { BASE::Swap ( rhs ); return *this; } template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE> & OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::operator = ( const OpenHashTable_T & rhs ) noexcept { OpenHashTable_T tNew(rhs); *this = std::move(tNew); return *this; } template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> VALUE * OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::Find ( KEY k ) const { ENTRY * e = BASE::FindEntry(k); return e ? &e->m_Value : nullptr; } template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> VALUE OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::FindAndDelete ( KEY k ) { ENTRY * pEntry = BASE::FindEntry(k); assert(pEntry); VALUE tRes = pEntry->m_Value; BASE::DeleteEntry(pEntry); return tRes; } template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> bool OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::Add ( KEY k, const VALUE & v ) { int64_t u = BASE::GetLength(); VALUE & x = Acquire(k); if ( u==BASE::GetLength() ) return false; // found an existing value by k, can not add v x = v; return true; } template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> VALUE & OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::FindOrAdd ( KEY k, const VALUE & v ) { int64_t u = BASE::GetLength(); VALUE & x = Acquire(k); if ( u!=BASE::GetLength() ) x = v; // did not find an existing value by k, so add v return x; } template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> VALUE * OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::Iterate ( int64_t * pIndex, KEY * pKey ) const { if ( !pIndex || *pIndex<0 ) return nullptr; for ( int64_t i = *pIndex; i < BASE::m_iSize; ++i ) if ( BASE::m_pHash[i].IsUsed(*this) ) { *pIndex = i+1; if ( pKey ) *pKey = BASE::m_pHash[i].m_Key; return &BASE::m_pHash[i].m_Value; } return nullptr; } template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY, typename STATE> std::pair<KEY,VALUE*> OpenHashTable_T<KEY,VALUE,HASHFUNC,ENTRY,STATE>::Iterate ( int64_t & iIndex ) const { assert ( iIndex>=0 ); for ( int64_t i = iIndex; i<BASE::m_iSize; ++i ) if ( BASE::m_pHash[i].IsUsed(*this) ) { iIndex = i+1; return { BASE::m_pHash[i].m_Key, &BASE::m_pHash[i].m_Value}; } return {0,nullptr}; } ///////////////////////////////////////////////////////////////////// template <typename KEY, typename VALUE, typename HASHFUNC, typename ENTRY> void OpenHashTableFastClear_T<KEY,VALUE,HASHFUNC,ENTRY>::Clear() { BASE::m_uVersion++; BASE::m_iUsed = 0; } ///////////////////////////////////////////////////////////////////// template <typename KEY, typename HASHFUNC, typename ENTRY, typename STATE> bool OpenHashSet_T<KEY,HASHFUNC,ENTRY,STATE>::Add ( KEY k ) { int64_t u = BASE::GetLength(); BASE::AcquireEntry(k); return u!=BASE::GetLength(); } template <typename KEY, typename HASHFUNC, typename ENTRY, typename STATE> KEY * OpenHashSet_T<KEY,HASHFUNC,ENTRY,STATE>::Iterate ( int64_t & iIndex ) const { assert ( iIndex>=0 ); for ( int64_t i = iIndex; i<BASE::m_iSize; i++ ) if ( BASE::m_pHash[i].IsUsed(*this) ) { iIndex = i+1; return &BASE::m_pHash[i].m_Key; } return nullptr; } ///////////////////////////////////////////////////////////////////// template <typename KEY, typename HASHFUNC, typename ENTRY> void OpenHashSetFastClear_T<KEY,HASHFUNC,ENTRY>::Clear() { BASE::m_uVersion++; BASE::m_iUsed = 0; }
10,402
C++
.h
300
32.506667
150
0.68194
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,356
helpers.h
manticoresoftware_manticoresearch/src/std/helpers.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" ///////////////////////////////////////////////////////////////////////////// // HELPERS ///////////////////////////////////////////////////////////////////////////// // make percent honouring fixed-point floats // sprintf ( "%.2D", MakePercent (1.014,10,2) ) will print "10.14" template<typename NUM> int64_t PercentOf ( NUM tVal, NUM tBase, int iFloatDigits = 1 ); #include "helpers_impl.h"
904
C++
.h
21
41.809524
80
0.611617
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,357
binarysearch.h
manticoresoftware_manticoresearch/src/std/binarysearch.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once /// generic binary search template<typename T, typename U, typename PRED> T* sphBinarySearch ( T* pStart, T* pEnd, PRED&& tPred, U tRef ); template<typename T> T* sphBinarySearch ( T* pStart, T* pEnd, T& tRef ); // returns first (leftmost) occurrence of the value // returns -1 if not found template<typename T, typename U, typename PRED> int sphBinarySearchFirst ( T* pValues, int iStart, int iEnd, PRED&& tPred, U tRef ); template<typename T, typename U, typename PRED> T* sphBinarySearchFirst ( T* pStart, T* pEnd, PRED&& tPred, U tRef ); #include "binarysearch_impl.h"
1,067
C++
.h
24
43.208333
84
0.745419
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,358
zip.h
manticoresoftware_manticoresearch/src/std/zip.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" // big-endian (most significant septets first) template<typename T> int sphCalcZippedLen ( T tValue ); // big-endian (most significant septets first) template<typename T, typename WRITER> int ZipValueBE ( WRITER fnPut, T tValue ); // big-endian (most significant septets first) template<typename T> int ZipToPtrBE ( BYTE* pData, T tValue ); // big-endian (most significant septets first) template<typename T, typename READER> std::enable_if_t<sizeof ( T ) == 4, T> UnzipValueBE ( READER&& fnGet ); template<typename T, typename READER> std::enable_if_t<sizeof ( T ) == 8, T> UnzipValueBE ( READER&& fnGet ); // big-endian (most significant septets first) DWORD UnzipIntBE ( const BYTE*& pBuf ); // big-endian (most significant septets first) SphOffset_t UnzipOffsetBE ( const BYTE*& pBuf ); // little-endian (least significant septets first) template<typename T, typename WRITER> int ZipValueLE ( WRITER fnPut, T tValue ); // little-endian (least significant septets first) template<typename T> int ZipToPtrLE ( BYTE* pData, T tValue ); // little-endian (least significant septets first) template<typename T, typename READER> std::enable_if_t<sizeof ( T ) == 4, T> UnzipValueLE ( READER fnGet ); template<typename T, typename READER> std::enable_if_t<sizeof ( T ) == 8, T> UnzipValueLE ( READER fnGet ); // little-endian (least significant septets first) DWORD UnzipIntLE ( const BYTE*& pBuf ); // little-endian (least significant septets first) SphOffset_t UnzipOffsetLE ( const BYTE*& pBuf ); #include "zip_impl.h"
2,039
C++
.h
47
42.042553
80
0.753036
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,359
fixedvector.h
manticoresoftware_manticoresearch/src/std/fixedvector.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "datamove.h" #include "storage.h" #include "generics.h" #include "vectraits.h" #include <type_traits> ////////////////////////////////////////////////////////////////////////// /// dynamically allocated fixed-size vector template<typename T, class POLICY = sph::DefaultCopy_T<T>, class STORE = sph::DefaultStorage_T<T>> class CSphFixedVector: public ISphNoncopyable , public VecTraits_T<T> , protected STORE { protected: using VecTraits_T<T>::m_pData; using VecTraits_T<T>::m_iCount; public: using POLICY_T = POLICY; using STORE_T = STORE; explicit CSphFixedVector ( int64_t iSize ) noexcept; ~CSphFixedVector(); CSphFixedVector ( CSphFixedVector&& rhs ) noexcept; CSphFixedVector& operator= ( CSphFixedVector rhs ) noexcept; void Reset ( int64_t iSize ); // overwrite content with copy of dOrigin void CopyFrom ( const VecTraits_T<T>& dOrigin ); template<typename S = STORE> typename std::enable_if<!S::is_owned, T*>::type LeakData(); /// swap template<typename S = STORE> typename std::enable_if<!S::is_owned>::type SwapData ( CSphFixedVector& rhs ) noexcept; template<typename S = STORE> typename std::enable_if<S::is_constructed && !S::is_owned>::type Set ( T* pData, int64_t iSize ); /// Set whole vec to 0. For trivially copyable memset will be used void ZeroVec(); }; #include "fixedvector_impl.h"
1,841
C++
.h
48
36.541667
98
0.716216
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,360
rwlock.h
manticoresoftware_manticoresearch/src/std/rwlock.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "thread_annotations.h" #include "generics.h" #include "ints.h" #include "mutex.h" /// rwlock implementation class CAPABILITY ( "mutex" ) RwLock_t : public ISphNoncopyable { public: explicit RwLock_t ( bool bPreferWriter = false ); ~RwLock_t (); bool ReadLock () ACQUIRE_SHARED(); bool WriteLock () ACQUIRE(); bool Unlock () UNLOCK_FUNCTION(); // Just for clang negative capabilities. const RwLock_t &operator! () const { return *this; } private: bool m_bInitialized = false; #if _WIN32 HANDLE m_hWriteMutex = 0; HANDLE m_hReadEvent = 0; LONG m_iReaders = 0; #else pthread_rwlock_t * m_pLock; CSphMutex * m_pWritePreferHelper = nullptr; #endif private: bool Init ( bool bPreferWriter = false ); bool Done(); }; /// scoped shared (read) lock template<class LOCKED = RwLock_t> class SCOPED_CAPABILITY CSphScopedRLock_T : ISphNoncopyable { public: /// lock on creation explicit CSphScopedRLock_T ( LOCKED & tLock ) ACQUIRE_SHARED ( tLock ); /// unlock on going out of scope ~CSphScopedRLock_T () RELEASE (); protected: LOCKED & m_tLock; }; /// scoped exclusive (write) lock template<class LOCKED = RwLock_t> class SCOPED_CAPABILITY CSphScopedWLock_T : ISphNoncopyable { public: /// lock on creation explicit CSphScopedWLock_T ( LOCKED & tLock ) ACQUIRE ( tLock ) EXCLUDES ( tLock ); /// unlock on going out of scope ~CSphScopedWLock_T () RELEASE (); protected: LOCKED & m_tLock; }; /// scoped shared (read) fake fake - do nothing, just mute warnings template<class LOCKED = RwLock_t> struct SCOPED_CAPABILITY FakeScopedRLock_T : ISphNoncopyable { explicit FakeScopedRLock_T ( LOCKED & tLock ) ACQUIRE_SHARED ( tLock ) {} ~FakeScopedRLock_T() RELEASE () {} }; /// scoped exclusive (write) fake lock - does nothing, just mute warnings template<class LOCKED = RwLock_t> struct SCOPED_CAPABILITY FakeScopedWLock_T : ISphNoncopyable { explicit FakeScopedWLock_T ( LOCKED & tLock ) ACQUIRE ( tLock ) EXCLUDES ( tLock ) {} ~FakeScopedWLock_T() RELEASE () {} }; /// scoped lock owner - unlock in dtr template<class LOCKED = RwLock_t> class SCOPED_CAPABILITY ScopedUnlock_T : ISphNoncopyable { public: /// lock on creation explicit ScopedUnlock_T ( LOCKED &tLock ) ACQUIRE ( tLock ); ScopedUnlock_T ( ScopedUnlock_T && tLock ) noexcept; ScopedUnlock_T &operator= ( ScopedUnlock_T &&rhs ) noexcept; /// unlock on going out of scope ~ScopedUnlock_T () RELEASE (); protected: LOCKED * m_pLock; }; // shortcuts (original names sometimes looks too long) using ScRL_t = CSphScopedRLock_T<>; using ScWL_t = CSphScopedWLock_T<>; #include "rwlock_impl.h"
3,106
C++
.h
97
30.381443
86
0.740194
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,361
checks.h
manticoresoftware_manticoresearch/src/std/checks.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "attrstub.h" #include <cassert> ///////////////////////////////////////////////////////////////////////////// // COMPILE-TIME CHECKS ///////////////////////////////////////////////////////////////////////////// #define VARIABLE_IS_NOT_USED __attribute__((unused)) #define MAYBE_UNUSED( expr ) do { (void)( expr ); } while ( 0 ) #define STATIC_ASSERT(_cond,_name) typedef char STATIC_ASSERT_FAILED_ ## _name [ (_cond) ? 1 : -1 ] VARIABLE_IS_NOT_USED #define STATIC_SIZE_ASSERT(_type,_size) STATIC_ASSERT ( sizeof(_type)==_size, _type ## _MUST_BE_ ## _size ## _BYTES ) #ifndef __analysis_assume #define __analysis_assume(_arg) #endif /// some function arguments only need to have a name in debug builds #ifndef NDEBUG #define DEBUGARG(_arg) _arg #else #define DEBUGARG(_arg) #endif ///////////////////////////////////////////////////////////////////////////// // DEBUGGING ///////////////////////////////////////////////////////////////////////////// #if _WIN32 #ifndef NDEBUG void sphAssert ( const char * sExpr, const char * sFile, int iLine ); #undef assert #define assert(_expr) (void)( (_expr) || ( sphAssert ( #_expr, __FILE__, __LINE__ ), 0 ) ) #endif // !NDEBUG #endif // _WIN32 // to avoid disappearing of _expr in release builds #ifndef NDEBUG #define Verify(_expr) assert(_expr) #else #define Verify(_expr) _expr #endif #ifndef NDEBUG #define Debug( _expr ) _expr #else #define Debug(_expr) #endif
1,921
C++
.h
51
36.352941
121
0.600324
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,362
generics.h
manticoresoftware_manticoresearch/src/std/generics.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include <utility> // switch off clang-specific warning about non-necessary capturing of constants #ifdef __clang__ _Pragma ( "clang diagnostic ignored \"-Wunused-lambda-capture\"" ) #endif ///////////////////////////////////////////////////////////////////////////// // GENERICS ///////////////////////////////////////////////////////////////////////////// template<typename T> constexpr T Min ( T a, T b ) { return a < b ? a : b; } template<typename T, typename U> constexpr typename std::common_type<T, U>::type Min ( T a, U b ) { using common_type = typename std::common_type<T, U>::type; return static_cast<common_type>(a) < static_cast<common_type>(b) ? a : b; } template<typename T> constexpr T Max ( T a, T b ) { return a < b ? b : a; } template<typename T, typename U> constexpr typename std::common_type<T, U>::type Max ( T a, U b ) { using common_type = typename std::common_type<T, U>::type; return static_cast<common_type>(a) < static_cast<common_type>(b) ? b : a; } inline constexpr int sphRoundUp ( int iValue, int iLimit ) { return ( iValue + iLimit - 1 ) & ~( iLimit - 1 ); } #define SafeDelete( _x ) do { if ( _x ) { delete ( _x ); ( _x ) = nullptr; } } while ( 0 ) #define SafeDeleteArray( _x ) do { if ( _x ) { delete[] ( _x ); ( _x ) = nullptr; } } while ( 0 ) #define SafeReleaseAndZero( _x) do { if ( _x ) { ( _x )->Release(); ( _x ) = nullptr; } } while ( 0 ) #define SafeRelease( _x ) do { if ( _x ) { ( _x )->Release(); } } while ( 0 ) #define SafeAddRef( _x ) do { if ( _x ) { ( _x )->AddRef(); } } while ( 0 ) /// swap template<typename T> inline void Swap ( T& v1, T& v2 ) { T temp = std::move ( v1 ); v1 = std::move ( v2 ); v2 = std::move ( temp ); } /// prevent copy class ISphNoncopyable { public: ISphNoncopyable() = default; ISphNoncopyable ( const ISphNoncopyable& ) = delete; ISphNoncopyable& operator= ( const ISphNoncopyable& ) = delete; }; #define NONCOPYABLE( a ) a(const a&) = delete; a& operator= (const a&) = delete /// prevent move class ISphNonmovable { public: ISphNonmovable() = default; ISphNonmovable ( ISphNonmovable&& ) noexcept = delete; ISphNonmovable& operator= ( ISphNonmovable&& ) noexcept = delete; }; #define NONMOVABLE( a ) a(a&&) = delete; a& operator= (a&&) = delete /// prevent copy and move class ISphNonCopyMovable { public: ISphNonCopyMovable() = default; ISphNonCopyMovable ( const ISphNonCopyMovable& ) = delete; ISphNonCopyMovable ( ISphNonCopyMovable&& ) = delete; ISphNonCopyMovable& operator= ( ISphNonCopyMovable ) = delete; }; #define NONCOPYMOVABLE( a ) a(const a&) = delete; a (a&&) = delete; a& operator= (const a&) = delete; a& operator= (a&&) = delete // implement moving ctr and moving= using swap-and-release #define MOVE_BYSWAP( class_c ) \ class_c ( class_c&& rhs ) noexcept {Swap ( rhs );} \ class_c& operator= ( class_c&& rhs ) noexcept \ { Swap ( rhs ); return *this; } // take all ctr definitions from parent #define FWD_CTOR( type_c, base_c ) \ template<typename... V> \ type_c ( V&&... v ) \ : base_c { std::forward<V> ( v )... } \ { \ } // take all ctr definitions from BASE parent #define FWD_BASECTOR( type_c ) FWD_CTOR ( type_c, BASE ) #if _WIN32 #define DISABLE_CONST_COND_CHECK \ __pragma ( warning ( push ) ) \ __pragma ( warning ( disable:4127 ) ) #define ENABLE_CONST_COND_CHECK \ __pragma ( warning ( pop ) ) #else #define DISABLE_CONST_COND_CHECK #define ENABLE_CONST_COND_CHECK #endif #define if_const(_arg) \ DISABLE_CONST_COND_CHECK \ if ( _arg ) \ ENABLE_CONST_COND_CHECK #ifndef FORCE_INLINE #ifndef NDEBUG #define FORCE_INLINE inline #else #ifdef _MSC_VER #define FORCE_INLINE __forceinline #else #if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ #ifdef __GNUC__ #define FORCE_INLINE inline __attribute__((always_inline)) #else #define FORCE_INLINE inline #endif #else #define FORCE_INLINE #endif #endif #endif #endif #define SPH_INTERNAL_CONCAT2( a, b ) a##b #define SPH_INTERNAL_CONCAT( a, b ) SPH_INTERNAL_CONCAT2 ( a, b ) #define SPH_UID( prefix ) SPH_INTERNAL_CONCAT ( prefix, __LINE__ ) #if _WIN32 #define ALIGNED_UNION_ZERO {0} #else #define ALIGNED_UNION_ZERO {{0}} #endif #define INIT_WITH_0( ... ) std::aligned_union_t<1, __VA_ARGS__ > SPH_UID ( m_init_ ) ALIGNED_UNION_ZERO;
4,943
C++
.h
143
32.601399
129
0.638592
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,363
uniq.h
manticoresoftware_manticoresearch/src/std/uniq.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once template<typename T, typename T_COUNTER, typename COMP> T_COUNTER sphUniq ( T* pData, T_COUNTER iCount, COMP&& tComp ); template<typename T, typename T_COUNTER> T_COUNTER sphUniq ( T* pData, T_COUNTER iCount ); #include "uniq_impl.h"
725
C++
.h
17
41.470588
80
0.753191
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,364
binarysearch_impl.h
manticoresoftware_manticoresearch/src/std/binarysearch_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <assert.h> #include "comp.h" namespace sphstd { /// generic binary search template<typename T, typename U, typename PRED> T* BinarySearch ( T* pStart, T* pEnd, PRED&& tPred, U tRef ) { if ( !pStart || pEnd < pStart ) return nullptr; if ( tPred ( *pStart ) == tRef ) return pStart; if ( tPred ( *pEnd ) == tRef ) return pEnd; while ( pEnd - pStart > 1 ) { if ( tRef < tPred ( *pStart ) || tPred ( *pEnd ) < tRef ) break; assert ( tPred ( *pStart ) < tRef ); assert ( tRef < tPred ( *pEnd ) ); T* pMid = pStart + ( pEnd - pStart ) / 2; if ( tRef == tPred ( *pMid ) ) return pMid; if ( tRef < tPred ( *pMid ) ) pEnd = pMid; else pStart = pMid; } return nullptr; } // returns first (leftmost) occurrence of the value // returns -1 if not found template<typename T, typename U, typename PRED> int BinarySearchFirst ( T* pValues, int iStart, int iEnd, PRED&& tPred, U tRef ) { assert ( iStart <= iEnd ); while ( iEnd - iStart > 1 ) { if ( tRef < tPred ( pValues[iStart] ) || tRef > tPred ( pValues[iEnd] ) ) return -1; int iMid = iStart + ( iEnd - iStart ) / 2; if ( tPred ( pValues[iMid] ) >= tRef ) iEnd = iMid; else iStart = iMid; } return iEnd; } // find the first entry that is greater than tRef template<typename T, typename U, typename PRED> T* BinarySearchFirst ( T* pStart, T* pEnd, PRED&& tPred, U tRef ) { if ( !pStart || pEnd < pStart ) return nullptr; while ( pStart != pEnd ) { T* pMid = pStart + ( pEnd - pStart ) / 2; if ( tRef > tPred ( *pMid ) ) pStart = pMid + 1; else pEnd = pMid; } return pStart; } } // namespace sphstd template<typename T, typename U, typename PRED> T* sphBinarySearch ( T* pStart, T* pEnd, PRED&& tPred, U tRef ) { return sphstd::BinarySearch ( pStart, pEnd, std::forward<PRED> (tPred), tRef ); } template<typename T> T* sphBinarySearch ( T* pStart, T* pEnd, T& tRef ) { return sphstd::BinarySearch ( pStart, pEnd, SphIdentityFunctor_T<T>(), tRef ); } template<typename T, typename U, typename PRED> int sphBinarySearchFirst ( T* pValues, int iStart, int iEnd, PRED&& tPred, U tRef ) { return sphstd::BinarySearchFirst ( pValues, iStart, iEnd, std::forward<PRED> ( tPred ), tRef ); } template<typename T, typename U, typename PRED> T* sphBinarySearchFirst ( T* pStart, T* pEnd, PRED&& tPred, U tRef ) { return sphstd::BinarySearchFirst ( pStart, pEnd, std::forward<PRED> ( tPred ), tRef ); }
2,918
C++
.h
95
28.589474
96
0.673571
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,365
uniq_impl.h
manticoresoftware_manticoresearch/src/std/uniq_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include "comp.h" namespace sphstd { template<typename T, typename T_COUNTER, typename COMP> T_COUNTER Uniq ( T* pData, T_COUNTER iCount, COMP&& tComp ) { if ( !iCount ) return 0; T_COUNTER iSrc = 1, iDst = 1; while ( iSrc < iCount ) { if ( tComp.IsEq ( pData[iDst - 1], pData[iSrc] ) ) iSrc++; else pData[iDst++] = pData[iSrc++]; } return iDst; } } // namespace sphstd template<typename T, typename T_COUNTER, typename COMP> T_COUNTER sphUniq ( T* pData, T_COUNTER iCount, COMP&& tComp ) { return sphstd::Uniq ( pData, iCount, std::forward<COMP> ( tComp ) ); } template<typename T, typename T_COUNTER> T_COUNTER sphUniq ( T* pData, T_COUNTER iCount ) { return sphstd::Uniq ( pData, iCount, SphEqualityFunctor_T<T>() ); }
1,223
C++
.h
39
29.692308
80
0.713073
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,366
string.h
manticoresoftware_manticoresearch/src/std/string.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "attrstub.h" #include "vector.h" #include "blobs.h" bool StrEq ( const char* l, const char* r ); bool StrEqN ( const char* l, const char* r ); bool StrEq ( Str_t l, const char* r ); bool StrEqN ( Str_t l, const char* r ); /// immutable C string proxy struct CSphString { protected: char* m_sValue = nullptr; // Empty ("") string optimization. static char EMPTY[]; private: /// safety gap after the string end; for instance, UTF-8 Russian stemmer /// which treats strings as 16-bit word sequences needs this in some cases. /// note that this zero-filled gap does NOT include trailing C-string zero, /// and does NOT affect strlen() as well. static constexpr int SAFETY_GAP = 4; void SafeFree(); public: CSphString() noexcept = default; // take a note this is not an explicit constructor // so a lot of silent constructing and deleting of strings is possible // Example: // SmallStringHash_T<int> hHash; // ... // hHash.Exists ( "asdf" ); // implicit CSphString construction and deletion here CSphString ( const CSphString& rhs ); CSphString ( CSphString&& rhs ) noexcept { Swap ( rhs ); } ~CSphString() { SafeFree(); } const char* cstr() const { return m_sValue; } const char* scstr() const { return m_sValue ? m_sValue : EMPTY; } inline bool operator== ( const char* t ) const { return StrEq ( t, m_sValue ); } inline bool operator== ( Str_t t ) const { return StrEq ( t, m_sValue ); } inline bool operator== ( const CSphString& t ) const { return operator== ( t.cstr() ); } inline bool operator!= ( const CSphString& t ) const { return !operator== ( t ); } bool operator!= ( const char* t ) const { return !operator== ( t ); } bool operator!= ( Str_t t ) const { return !operator== ( t ); } // compare ignoring case inline bool EqN ( const char* t ) const { return StrEqN ( t, m_sValue ); } inline bool EqN ( const CSphString& t ) const { return EqN ( t.cstr() ); } CSphString ( const char* szString ); // create even if source is null/empty (result will be valid string with valid tail of zeros - for parsers) enum guarded_e { always_create }; CSphString ( const char* szString, guarded_e ); CSphString ( const char* sValue, int iLen ) { SetBinary ( sValue, iLen ); } CSphString ( Str_t sValue ) { SetBinary ( sValue ); } // pass by value - replaces both copy and move assignments. CSphString& operator= ( CSphString rhs ) { Swap ( rhs ); return *this; } CSphString SubString ( int iStart, int iCount ) const; // tries to reuse memory buffer, but calls Length() every time // hope this won't kill performance on a huge strings void SetBinary ( const char* sValue, int iLen ); void SetBinary ( Str_t sValue ) { SetBinary ( sValue.first, sValue.second ); } void Reserve ( int iLen ); const CSphString& SetSprintf ( const char* sTemplate, ... ) __attribute__ ( ( format ( printf, 2, 3 ) ) ); /// format value using provided va_list const CSphString& SetSprintfVa ( const char* sTemplate, va_list ap ); /// \return true if internal char* ptr is null, of value is empty. bool IsEmpty() const; CSphString& ToLower(); CSphString& ToUpper(); void Swap ( CSphString& rhs ); /// \return true if the string begins with sPrefix bool Begins ( const char* sPrefix ) const; /// \return true if the string ends with sSuffix bool Ends ( const char* sSuffix ) const; /// trim leading and trailing spaces CSphString& Trim(); int Length() const; /// \return internal string and releases it from being destroyed in d-tr char* Leak(); /// internal string and releases it from being destroyed in d-tr void LeakToVec ( CSphVector<BYTE>& dVec ); /// take string from outside and 'adopt' it as own child. void Adopt ( char** sValue ); void Adopt ( char*&& sValue ); /// compares using strcmp bool operator<( const CSphString& b ) const; void Unquote(); static int GetGap() { return SAFETY_GAP; } explicit operator ByteBlob_t() const; }; /// string swapper void Swap ( CSphString& v1, CSphString& v2 ); /// directly make formatted string CSphString SphSprintfVa ( const char* sTemplate, va_list ap ); CSphString SphSprintf ( const char* sTemplate, ... ); /// commonly used void ToLower ( Str_t sVal ); using StrVec_t = CSphVector<CSphString>; using StrtVec_t = CSphVector<Str_t>; #include "fixedvector.h" using FixedStrVec_t = CSphFixedVector<CSphString>; using FixedStrtVec_t = CSphFixedVector<Str_t>; #include "string_impl.h"
4,985
C++
.h
156
29.769231
108
0.70986
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,367
string_impl.h
manticoresoftware_manticoresearch/src/std/string_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <cstring> #include <cassert> #include <cstdio> #include <cctype> #include <cstdarg> #include "generics.h" inline bool StrEq ( const char* l, const char* r ) { if ( !l || !r ) return ( ( !r && !l ) || ( !r && !*l ) || ( !l && !*r ) ); return strcmp ( l, r ) == 0; } inline bool StrEqN ( const char* l, const char* r ) { if ( !l || !r ) return ( ( !r && !l ) || ( !r && !*l ) || ( !l && !*r ) ); return strcasecmp ( l, r ) == 0; } inline bool StrEq ( Str_t l, const char * r ) { if ( IsEmpty ( l ) || !r ) return ( ( !r && IsEmpty ( l ) ) || ( IsEmpty ( l ) && !*r ) ); return strncmp ( l.first, r, l.second ) == 0; } inline bool StrEqN ( Str_t l, const char* r ) { if ( IsEmpty ( l ) || !r ) return ( ( !r && IsEmpty ( l ) ) || ( IsEmpty ( l ) && !*r ) ); return strncasecmp ( l.first, r, l.second ) == 0; } inline Str_t FromStr ( const CSphString& sString ) noexcept { return { sString.cstr(), (int)sString.Length() }; } inline void CSphString::SafeFree() { if ( m_sValue != EMPTY ) SafeDeleteArray ( m_sValue ); } // take a note this is not an explicit constructor // so a lot of silent constructing and deleting of strings is possible // Example: // SmallStringHash_T<int> hHash; // ... // hHash.Exists ( "asdf" ); // implicit CSphString construction and deletion here inline CSphString::CSphString ( const CSphString& rhs ) { if ( !rhs.m_sValue ) return; else if ( rhs.m_sValue[0] == '\0' ) { m_sValue = EMPTY; } else { auto iLen = 1 + (int)strlen ( rhs.m_sValue ) + 1; m_sValue = new char[iLen + SAFETY_GAP]; memcpy ( m_sValue, rhs.m_sValue, iLen ); // NOLINT memset ( m_sValue + iLen, 0, SAFETY_GAP ); } } inline CSphString::CSphString ( const char* szString ) // NOLINT { if ( szString ) { if ( szString[0] == '\0' ) { m_sValue = EMPTY; } else { auto iLen = (int)strlen ( szString ); m_sValue = new char[iLen + SAFETY_GAP + 1]; memcpy ( m_sValue, szString, iLen ); // NOLINT memset ( m_sValue + iLen, 0, SAFETY_GAP + 1 ); } } } inline CSphString::CSphString ( const char* szString, guarded_e ) // NOLINT { int iLen = 0; if ( szString && szString[0] != '\0') iLen = (int)strlen ( szString ); m_sValue = new char[iLen + SAFETY_GAP + 1]; if ( iLen ) memcpy ( m_sValue, szString, iLen ); // NOLINT memset ( m_sValue + iLen, 0, SAFETY_GAP + 1 ); } inline CSphString CSphString::SubString ( int iStart, int iCount ) const { #ifndef NDEBUG auto iLen = (int)strlen ( m_sValue ); iCount = Min ( iLen - iStart, iCount ); #endif assert ( iStart >= 0 && iStart <= iLen ); assert ( iCount >= 0 ); assert ( ( iStart + iCount ) <= iLen ); CSphString sRes; sRes.m_sValue = new char[1 + SAFETY_GAP + iCount]; strncpy ( sRes.m_sValue, m_sValue + iStart, iCount ); memset ( sRes.m_sValue + iCount, 0, 1 + SAFETY_GAP ); return sRes; } // tries to reuse memory buffer, but calls Length() every time // hope this won't kill performance on a huge strings inline void CSphString::SetBinary ( const char* sValue, int iLen ) { assert ( iLen >= 0 ); auto iLen_ = size_t ( iLen ); if ( Length() < ( iLen + SAFETY_GAP + 1 ) ) { SafeFree(); if ( !sValue ) m_sValue = EMPTY; else { m_sValue = new char[1 + SAFETY_GAP + iLen]; memcpy ( m_sValue, sValue, iLen_ ); memset ( m_sValue + iLen, 0, 1 + SAFETY_GAP ); } return; } if ( sValue && iLen ) { memcpy ( m_sValue, sValue, iLen_ ); memset ( m_sValue + iLen, 0, 1 + SAFETY_GAP ); } else { SafeFree(); m_sValue = EMPTY; } } inline void CSphString::Reserve ( int iLen ) { SafeFree(); m_sValue = new char[1 + SAFETY_GAP + iLen]; memset ( m_sValue, 0, 1 + SAFETY_GAP + iLen ); } inline const CSphString& CSphString::SetSprintf ( const char* sTemplate, ... ) { char sBuf[1024]; va_list ap; va_start ( ap, sTemplate ); vsnprintf ( sBuf, sizeof ( sBuf ), sTemplate, ap ); va_end ( ap ); ( *this ) = sBuf; return ( *this ); } /// format value using provided va_list inline const CSphString& CSphString::SetSprintfVa ( const char* sTemplate, va_list ap ) { char sBuf[1024]; vsnprintf ( sBuf, sizeof ( sBuf ), sTemplate, ap ); ( *this ) = sBuf; return ( *this ); } /// \return true if internal char* ptr is null, of value is empty. inline bool CSphString::IsEmpty() const { if ( !m_sValue ) return true; return ( ( *m_sValue ) == '\0' ); } inline CSphString& CSphString::ToLower() { if ( m_sValue ) for ( char* s = m_sValue; *s; ++s ) *s = (char)tolower ( *s ); return *this; } inline CSphString& CSphString::ToUpper() { if ( m_sValue ) for ( char* s = m_sValue; *s; s++ ) *s = (char)toupper ( *s ); return *this; } inline void CSphString::Swap ( CSphString& rhs ) { ::Swap ( m_sValue, rhs.m_sValue ); } /// \return true if the string begins with sPrefix inline bool CSphString::Begins ( const char* sPrefix ) const { if ( !m_sValue || !sPrefix ) return false; return strncmp ( m_sValue, sPrefix, strlen ( sPrefix ) ) == 0; } /// \return true if the string ends with sSuffix inline bool CSphString::Ends ( const char* sSuffix ) const { if ( !m_sValue || !sSuffix ) return false; auto iVal = (int)strlen ( m_sValue ); auto iSuffix = (int)strlen ( sSuffix ); if ( iVal < iSuffix ) return false; return strncmp ( m_sValue + iVal - iSuffix, sSuffix, iSuffix ) == 0; } /// trim leading and trailing spaces inline CSphString& CSphString::Trim() { if ( m_sValue ) { const char* sStart = m_sValue; const char* sEnd = m_sValue + strlen ( m_sValue ) - 1; while ( sStart <= sEnd && isspace ( (unsigned char)*sStart ) ) sStart++; while ( sStart <= sEnd && isspace ( (unsigned char)*sEnd ) ) sEnd--; memmove ( m_sValue, sStart, sEnd - sStart + 1 ); m_sValue[sEnd - sStart + 1] = '\0'; } return *this; } inline int CSphString::Length() const { return m_sValue ? (int)strlen ( m_sValue ) : 0; } /// \return internal string and releases it from being destroyed in d-tr inline char* CSphString::Leak() { if ( m_sValue == EMPTY ) { m_sValue = nullptr; auto* pBuf = new char[1]; pBuf[0] = '\0'; return pBuf; } char* pBuf = m_sValue; m_sValue = nullptr; return pBuf; } /// internal string and releases it from being destroyed in d-tr inline void CSphString::LeakToVec ( CSphVector<BYTE>& dVec ) { if ( m_sValue == EMPTY ) { m_sValue = nullptr; auto* pBuf = new char[1]; pBuf[0] = '\0'; dVec.AdoptData ( (BYTE*)pBuf, 0, 1 ); return; } int iLen = Length(); dVec.AdoptData ( (BYTE*)m_sValue, iLen, iLen + 1 + SAFETY_GAP ); m_sValue = nullptr; } /// take string from outside and 'adopt' it as own child. inline void CSphString::Adopt ( char** sValue ) { SafeFree(); m_sValue = *sValue; *sValue = nullptr; } inline void CSphString::Adopt ( char*&& sValue ) { SafeFree(); m_sValue = sValue; sValue = nullptr; } /// compares using strcmp inline bool CSphString::operator<( const CSphString& b ) const { if ( !m_sValue && !b.m_sValue ) return false; if ( !m_sValue || !b.m_sValue ) return !m_sValue; return strcmp ( m_sValue, b.m_sValue ) < 0; } inline void CSphString::Unquote() { int l = Length(); if ( l && m_sValue[0] == '\'' && m_sValue[l - 1] == '\'' ) { memmove ( m_sValue, m_sValue + 1, l - 2 ); m_sValue[l - 2] = '\0'; } } inline CSphString::operator ByteBlob_t() const { return { (const BYTE*)m_sValue, Length() }; } /// string swapper inline void Swap ( CSphString& v1, CSphString& v2 ) { v1.Swap ( v2 ); } /// directly make formatted string inline CSphString SphSprintfVa ( const char* sTemplate, va_list ap ) { CSphString sResult; sResult.SetSprintfVa ( sTemplate, ap ); return sResult; } inline CSphString SphSprintf ( const char* sTemplate, ... ) { CSphString sResult; va_list ap; va_start ( ap, sTemplate ); sResult.SetSprintfVa ( sTemplate, ap ); va_end ( ap ); return sResult; }
8,270
C++
.h
313
24.450479
87
0.647074
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,368
smalloc.h
manticoresoftware_manticoresearch/src/std/smalloc.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "config.h" #include "ints.h" #include "datamove.h" #include "relimit.h" #include "vector.h" /// Allocation for small objects (namely - for movable dynamic attributes). /// internals based on Alexandresku's 'loki' implementation - 'Allocator for small objects' static const int MAX_SMALL_OBJECT_SIZE = 64; BYTE * sphAllocateSmall ( int iBytes ); #if WITH_SMALLALLOC void sphDeallocateSmall ( const BYTE* pBlob, int iBytes ); #else void sphDeallocateSmall ( const BYTE* pBlob ); #endif size_t sphGetSmallAllocatedSize (); // how many allocated right now size_t sphGetSmallReservedSize (); // how many pooled from the sys right now // helper to use in vector as custom allocator namespace sph { template<typename T> class CustomStorage_T { public: using TYPE=T; /// grow enough to hold that much entries. static TYPE * Allocate ( int64_t iLimit ); #if WITH_SMALLALLOC static void Deallocate ( TYPE* pData, int64_t iLimit ); #else static void Deallocate ( TYPE * pData ); #endif static constexpr bool is_sized = (bool)WITH_SMALLALLOC; static constexpr bool is_constructed = true; static constexpr bool is_owned = false; }; } template<typename T> using TightPackedVec_T = sph::Vector_T<T, sph::DefaultCopy_T<T>, sph::TightRelimit, sph::CustomStorage_T<T>>; void sphDeallocatePacked ( BYTE * pBlob ); #include "smalloc_impl.h"
1,851
C++
.h
51
34.647059
109
0.757271
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,369
refptr.h
manticoresoftware_manticoresearch/src/std/refptr.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include <type_traits> #include <utility> #include "generics.h" ////////////////////////////////////////////////////////////////////////// /// automatic pointer wrapper for refcounted objects /// construction from or assignment of a raw pointer takes over (!) the ownership template<typename T> class CSphRefcountedPtr { public: using ORIGTYPE = T; using RAWT = typename std::remove_const<T>::type; using CT = const T; using TYPE = CSphRefcountedPtr<T>; using CTYPE = CSphRefcountedPtr<const T>; using RAWTYPE = CSphRefcountedPtr<RAWT>; public: CSphRefcountedPtr() noexcept = default; ///< default NULL wrapper construction (for vectors) explicit CSphRefcountedPtr ( T* pPtr ) noexcept : m_pPtr ( pPtr ) {} ///< construction from raw pointer, takes over ownership! CSphRefcountedPtr ( std::nullptr_t ) noexcept {}; CSphRefcountedPtr ( const CSphRefcountedPtr& rhs ) noexcept : m_pPtr ( rhs.m_pPtr ) { SafeAddRef ( m_pPtr ); } template<typename DERIVED> explicit CSphRefcountedPtr ( const CSphRefcountedPtr<DERIVED>& rhs ) noexcept : m_pPtr ( rhs.Ptr() ) { SafeAddRef ( m_pPtr ); } CSphRefcountedPtr ( CSphRefcountedPtr&& rhs ) noexcept { Swap ( rhs ); } CSphRefcountedPtr& operator= ( CSphRefcountedPtr rhs ) noexcept { Swap ( rhs ); return *this; } template<typename DERIVED> CSphRefcountedPtr& operator= ( const CSphRefcountedPtr<DERIVED>& rhs ) noexcept { SafeAddRef ( rhs.Ptr() ); SafeRelease ( m_pPtr ); m_pPtr = rhs.Ptr(); return *this; } template<typename DERIVED> CSphRefcountedPtr& operator= ( CSphRefcountedPtr<DERIVED>&& rhs ) noexcept { SafeRelease ( m_pPtr ); m_pPtr = rhs.Leak(); return *this; } void Swap ( CSphRefcountedPtr& rhs ) noexcept { ::Swap ( m_pPtr, rhs.m_pPtr ); } ~CSphRefcountedPtr() noexcept { SafeRelease ( m_pPtr ); } T* operator->() const noexcept { return m_pPtr; } explicit operator bool() const noexcept { return m_pPtr != nullptr; } operator T*() const noexcept { return m_pPtr; } // drop the ownership and reset pointer inline T* Leak() noexcept { return std::exchange ( m_pPtr, nullptr ); } T* Ptr() const noexcept { return m_pPtr; } CT* CPtr() const noexcept { return m_pPtr; } public: /// assignment of a raw pointer, takes over ownership! CSphRefcountedPtr& operator= ( T* pPtr ) noexcept { SafeRelease ( m_pPtr ); m_pPtr = pPtr; return *this; } protected: T* m_pPtr = nullptr; }; template<typename T> using RefCountedRefPtr_T = CSphRefcountedPtr<T>; template<typename T> using cRefCountedRefPtr_T = CSphRefcountedPtr<const T>; template<typename T> inline RefCountedRefPtr_T<T> ConstCastPtr ( cRefCountedRefPtr_T<T> rhs ) { auto* pRaw = const_cast<T*> ( rhs.Ptr() ); if ( pRaw ) pRaw->AddRef(); return RefCountedRefPtr_T<T> { pRaw }; }
3,279
C++
.h
107
28.579439
93
0.712246
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,370
scopedlock_impl.h
manticoresoftware_manticoresearch/src/std/scopedlock_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // template<typename MTX> CSphScopedLock<MTX>::CSphScopedLock ( MTX& tMutex, CSphScopedLock<MTX>::ADOPT_LOCK_E ) : m_tMutexRef ( tMutex ) , m_bLocked ( true ) {} template<typename MTX> CSphScopedLock<MTX>::CSphScopedLock ( MTX& tMutex ) ACQUIRE ( tMutex ) : m_tMutexRef ( tMutex ) , m_bLocked ( true ) { m_tMutexRef.Lock(); m_bLocked = true; } template<typename MTX> CSphScopedLock<MTX>::~CSphScopedLock() RELEASE() { if ( m_bLocked ) m_tMutexRef.Unlock(); } template<typename MTX> void CSphScopedLock<MTX>::Lock() { if ( !m_bLocked ) { m_tMutexRef.Lock(); m_bLocked = true; } } template<typename MTX> void CSphScopedLock<MTX>::Unlock() { if ( m_bLocked ) { m_tMutexRef.Unlock(); m_bLocked = false; } }
1,205
C++
.h
48
23.479167
86
0.726957
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,371
comp.h
manticoresoftware_manticoresearch/src/std/comp.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once /// generic comparator template<typename T> struct SphLess_T { inline static bool IsLess ( const T& a, const T& b ) noexcept { return a < b; } }; /// generic comparator template<typename T> struct SphGreater_T { inline static bool IsLess ( const T& a, const T& b ) noexcept { return b < a; } }; /// generic comparator template<typename T, typename C> struct SphMemberLess_T { const T C::*m_pMember; explicit SphMemberLess_T ( T C::*pMember ); inline bool IsLess ( const C& a, const C& b ) const noexcept; }; template<typename T, typename C> inline SphMemberLess_T<T, C> sphMemberLess ( T C::*pMember ); /// generic comparator initialized by functor template<typename COMP> struct SphLesser { COMP m_fnComp; explicit SphLesser ( COMP&& fnComp ); template<typename T> bool IsLess ( T&& a, T&& b ) const noexcept ( noexcept ( m_fnComp ) ); }; // make template<typename FNCOMP> SphLesser<FNCOMP> Lesser ( FNCOMP&& fnComp ); ////////////////////////////////////////////////////////////////////////// /// member functor, wraps object member access template<typename T, typename CLASS> struct SphMemberFunctor_T { const T CLASS::*m_pMember; explicit SphMemberFunctor_T ( T CLASS::*pMember ); const T& operator() ( const CLASS& arg ) const noexcept; inline bool IsLess ( const CLASS& a, const CLASS& b ) const noexcept; inline bool IsEq ( const CLASS& a, T b ) const noexcept; }; /// handy member functor generator /// this sugar allows you to write like this /// dArr.Sort ( bind ( &CSphType::m_iMember ) ); /// dArr.BinarySearch ( bind ( &CSphType::m_iMember ), iValue ); template<typename T, typename CLASS> inline SphMemberFunctor_T<T, CLASS> bind ( T CLASS::*ptr ) { return SphMemberFunctor_T<T, CLASS> ( ptr ); } /// identity functor template<typename T> struct SphIdentityFunctor_T { inline const T& operator() ( const T& arg ) const { return arg; } }; /// equality functor template<typename T> struct SphEqualityFunctor_T { inline static bool IsEq ( const T& a, const T& b ) { return a == b; } }; /// very popular and so, moved here /// use integer values as hash values (like document IDs, for example) struct IdentityHash_fn { template<typename INT> static inline INT Hash ( INT iValue ) { return iValue; } }; #include "comp_impl.h"
2,762
C++
.h
84
31.416667
80
0.712566
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,372
comp_impl.h
manticoresoftware_manticoresearch/src/std/comp_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // template<typename T, typename C> inline SphMemberLess_T<T, C>::SphMemberLess_T ( T C::*pMember ) : m_pMember ( pMember ) {} template<typename T, typename C> inline bool SphMemberLess_T<T, C>::IsLess ( const C& a, const C& b ) const noexcept { return ( ( &a )->*m_pMember ) < ( ( &b )->*m_pMember ); } template<typename T, typename C> inline SphMemberLess_T<T, C> sphMemberLess ( T C::*pMember ) { return SphMemberLess_T<T, C> ( pMember ); } template<typename COMP> SphLesser<COMP>::SphLesser ( COMP&& fnComp ) : m_fnComp ( std::forward<COMP> ( fnComp ) ) {} template<typename COMP> template<typename T> bool SphLesser<COMP>::IsLess ( T&& a, T&& b ) const noexcept ( noexcept ( m_fnComp ) ) { return m_fnComp ( std::forward<T> ( a ), std::forward<T> ( b ) ); } template<typename FNCOMP> SphLesser<FNCOMP> Lesser ( FNCOMP&& fnComp ) { return SphLesser<FNCOMP> ( std::forward<FNCOMP> ( fnComp ) ); } ////////////////////////////////////////////////////////////////////////// template<typename T, typename CLASS> SphMemberFunctor_T<T,CLASS>::SphMemberFunctor_T ( T CLASS::*pMember ) : m_pMember ( pMember ) {} template<typename T, typename CLASS> const T& SphMemberFunctor_T<T, CLASS>::operator() ( const CLASS& arg ) const noexcept { return ( &arg )->*m_pMember; } template<typename T, typename CLASS> inline bool SphMemberFunctor_T<T, CLASS>::IsLess ( const CLASS& a, const CLASS& b ) const noexcept { return ( &a )->*m_pMember < ( &b )->*m_pMember; } template<typename T, typename CLASS> inline bool SphMemberFunctor_T<T, CLASS>::IsEq ( const CLASS& a, T b ) const noexcept { return ( ( &a )->*m_pMember ) == b; }
2,111
C++
.h
57
35.631579
118
0.682843
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,373
log2_impl.h
manticoresoftware_manticoresearch/src/std/log2_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include "ints.h" #if defined( __GNUC__ ) || defined( __clang__ ) constexpr inline int sphLog2const ( unsigned uValue ) { return (int)sizeof ( uValue ) * 8 - __builtin_clz ( uValue | 1 ); } constexpr inline int sphLog2const ( unsigned long uValue ) { return (int)sizeof ( uValue ) * 8 - __builtin_clzl ( uValue | 1 ); } constexpr inline int sphLog2const ( unsigned long long uValue ) { return (int)sizeof ( uValue ) * 8 - __builtin_clzll ( uValue | 1 ); } inline int sphLog2 ( unsigned uValue ) { return sphLog2const ( uValue ); } inline int sphLog2 ( unsigned long uValue ) { return sphLog2const ( uValue ); } inline int sphLog2 ( unsigned long long uValue ) { return sphLog2const ( uValue ); } inline int GetLeadingZeroBits ( uint32_t uValue ) { assert(uValue); return __builtin_clz ( uValue ); } inline int GetLeadingZeroBits ( uint64_t uValue ) { assert(uValue); return __builtin_clzll ( uValue ); } #else namespace { template<typename UINT> constexpr inline int Log2constUINT ( UINT uValue ) { int iBits = 0; do { uValue >>= 1; ++iBits; } while ( uValue ); return iBits; } } constexpr inline int sphLog2const ( unsigned uValue ) { return Log2constUINT ( uValue ); } constexpr inline int sphLog2const ( unsigned long uValue ) { return Log2constUINT ( uValue ); } constexpr inline int sphLog2const ( unsigned long long uValue ) { return Log2constUINT ( uValue ); } #if _WIN32 #include <intrin.h> // for bsr #pragma intrinsic( _BitScanReverse64 ) #pragma intrinsic( _BitScanReverse ) inline int sphLog2 ( unsigned uValue ) { DWORD uRes; BitScanReverse ( &uRes, uValue | 1 ); return 1 + uRes; } inline int sphLog2 ( unsigned long uValue ) { static_assert ( sizeof ( unsigned ) == sizeof ( unsigned long ), "" ); DWORD uRes; BitScanReverse ( &uRes, uValue | 1 ); return 1 + uRes; } inline int sphLog2 ( unsigned long long uValue ) { DWORD uRes; BitScanReverse64 ( &uRes, uValue | 1 ); return 1 + uRes; } inline int GetLeadingZeroBits ( uint32_t uValue ) { assert(uValue); DWORD uRes; BitScanReverse64 ( &uRes, uValue ); return 31 - uRes; } inline int GetLeadingZeroBits ( uint64_t uValue ) { assert(uValue); DWORD uRes; BitScanReverse64 ( &uRes, uValue ); return 63 - uRes; } #else inline int sphLog2 ( unsigned uValue ) { return sphLog2const ( uValue ); } inline int sphLog2 ( unsigned long uValue ) { return sphLog2const ( uValue ); } inline int sphLog2 ( unsigned long long uValue ) { return sphLog2const ( uValue ); } #endif #endif constexpr inline int sphLog2const ( int iValue ) { return sphLog2const ( static_cast<unsigned> ( iValue ) ); } constexpr inline int sphLog2const ( long iValue ) { return sphLog2const ( static_cast<unsigned long> ( iValue ) ); } constexpr inline int sphLog2const ( long long iValue ) { return sphLog2const ( static_cast<unsigned long long> ( iValue ) ); } inline int sphLog2 ( int iValue ) { return sphLog2 ( static_cast<unsigned> ( iValue ) ); } inline int sphLog2 ( long iValue ) { return sphLog2 ( static_cast<unsigned long> ( iValue ) ); } inline int sphLog2 ( long long iValue ) { return sphLog2 ( static_cast<unsigned long long> ( iValue ) ); }
3,644
C++
.h
149
22.899329
80
0.73158
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,374
relimit_impl.h
manticoresoftware_manticoresearch/src/std/relimit_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <cassert> ////////////////////////////////////////////////////////////////////////// /// Resize backends for vector /// Each backend provides Relimit namespace sph { /// Default relimit: grow 2x int64_t DefaultRelimit::Relimit ( int64_t iLimit, int64_t iNewLimit ) { if ( !iLimit ) iLimit = MAGIC_INITIAL_LIMIT; while ( iLimit < iNewLimit ) { iLimit *= 2; assert ( iLimit > 0 ); } return iLimit; } /// tight-vector policy /// grow only 1.2x on resize (not 2x) starting from a certain threshold int64_t TightRelimit::Relimit ( int64_t iLimit, int64_t iNewLimit ) { if ( !iLimit ) iLimit = MAGIC_INITIAL_LIMIT; while ( iLimit < iNewLimit && iLimit < SLOW_GROW_TRESHOLD ) { iLimit *= 2; assert ( iLimit > 0 ); } while ( iLimit < iNewLimit ) { iLimit = (int)( (float)iLimit * GROW ); assert ( iLimit > 0 ); } return iLimit; } } // namespace sph
1,360
C++
.h
48
26.604167
80
0.67075
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,375
datamove_impl.h
manticoresoftware_manticoresearch/src/std/datamove_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <utility> #include <cstring> #include "datamove.h" namespace sph { template<typename T, bool _> void DataMover_T<T, _>::Copy ( T* pNew, const T* pData, int64_t iLength ) { for ( int i = 0; i < iLength; ++i ) pNew[i] = pData[i]; } template<typename T, bool C> void DataMover_T<T, C>::Move ( T* pNew, T* pData, int64_t iLength ) { for ( int i = 0; i < iLength; ++i ) pNew[i] = std::move ( pData[i] ); } template<typename T, bool _> void DataMover_T<T, _>::Zero ( T* pData, int64_t iLength ) { for ( int i = 0; i < iLength; ++i ) pData[i] = 0; } template<typename T> void DataMover_T<T, true>::Copy ( T* pNew, const T* pData, int64_t iLength ) { if ( iLength ) // m.b. work without this check, but sanitize for paranoids. memmove ( (void*)pNew, (const void*)pData, iLength * sizeof ( T ) ); } template<typename T> void DataMover_T<T, true>::Move ( T* pNew, T* pData, int64_t iLength ) { Copy ( pNew, pData, iLength ); } // append raw blob: defined ONLY in POD specialization. template<typename T> void DataMover_T<T, true>::CopyVoid ( T* pNew, const void* pData, int64_t iLength ) { Copy ( pNew, (T*)const_cast<void*> ( pData ), iLength ); } template<typename T> void DataMover_T<T, true>::Zero ( T* pData, int64_t iLength ) { memset ( (void*)pData, 0, iLength * sizeof ( T ) ); } /// default vector mover template<typename T> void DefaultCopy_T<T>::CopyOrSwap ( T& pLeft, const T& pRight ) { pLeft = pRight; } /// swap-vector policy (for non-copyable classes) /// use Swap() instead of assignment on resize template<typename T> void SwapCopy_T<T>::Copy ( T* pNew, T* pData, int64_t iLength ) { for ( int i = 0; i < iLength; ++i ) Swap ( pNew[i], pData[i] ); } template<typename T> void SwapCopy_T<T>::Move ( T* pNew, T* pData, int64_t iLength ) { for ( int i = 0; i < iLength; ++i ) Swap ( pNew[i], pData[i] ); } template<typename T> void SwapCopy_T<T>::CopyOrSwap ( T& dLeft, T& dRight ) { Swap ( dLeft, dRight ); } template<typename T> void SwapCopy_T<T>::CopyOrSwap ( T& dLeft, T&& dRight ) { dLeft = std::forward<T> (dRight); } } // namespace sph
2,575
C++
.h
86
28.453488
83
0.679077
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,376
iterations.h
manticoresoftware_manticoresearch/src/std/iterations.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once template<typename CONTAINER, typename FILTER> inline bool all_of ( const CONTAINER& dData, FILTER cond ); template<typename CONTAINER, typename FILTER> inline bool any_of ( const CONTAINER& dData, FILTER cond ); template<typename CONTAINER, typename FILTER> inline bool none_of ( const CONTAINER& dData, FILTER cond ); template<typename CONTAINER, typename FILTER> inline int64_t count_of ( const CONTAINER& dData, FILTER cond ); template<typename CONTAINER, typename ACTION> void for_each ( CONTAINER&& dData, ACTION fnAction ); #define ARRAY_FOREACH( _index, _array ) \ for ( int _index = 0; _index < _array.GetLength(); ++_index ) #define ARRAY_FOREACH_COND( _index, _array, _cond ) \ for ( int _index = 0; _index < _array.GetLength() && ( _cond ); ++_index ) #define ARRAY_CONSTFOREACH( _index, _array ) \ for ( int _index = 0, _bound = _array.GetLength(); _index < _bound; ++_index ) #define ARRAY_CONSTFOREACH_COND( _index, _array, _cond ) \ for ( int _index = 0, _bound = _array.GetLength(); _index < _bound && ( _cond ); ++_index ) #include "iterations_impl.h"
1,572
C++
.h
31
49.225806
92
0.722222
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,377
vector.h
manticoresoftware_manticoresearch/src/std/vector.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include <utility> #include "type_traits.h" #include "ints.h" #include "datamove.h" #include "relimit.h" #include "storage.h" #include "vectraits.h" namespace sph { /// generic vector /// uses storage, mover and relimit backends /// (don't even ask why it's not std::vector) template<typename T, class POLICY = DefaultCopy_T<T>, class LIMIT = DefaultRelimit, class STORE = DefaultStorage_T<T>> class Vector_T: public VecTraits_T<T>, protected STORE, LIMIT { template<typename S = STORE> std::enable_if_t< S::is_sized> Deallocate ( typename STORE::TYPE* pData, int64_t ); template<typename S = STORE> std::enable_if_t<!S::is_sized> Deallocate ( typename STORE::TYPE* pData, int64_t ); protected: using BASE = VecTraits_T<T>; using BASE::m_pData; using BASE::m_iCount; using STORE::Allocate; using STORE::Deallocate; public: using BASE::Begin; using BASE::Sort; using BASE::GetLength; // these are for IDE helpers to work using BASE::GetLength64; using BASE::GetLengthBytes; using BASE::Slice; using LIMIT::Relimit; using LIMIT::SANE_SIZE; /// ctor Vector_T() = default; /// ctor with initial size explicit Vector_T ( int64_t iCount ); /// copy ctor Vector_T ( const Vector_T<T>& rhs ); /// move ctr Vector_T ( Vector_T<T>&& rhs ) noexcept; /// dtor ~Vector_T(); /// add entry T& Add(); /// add entry template<typename S = STORE> FORCE_INLINE typename std::enable_if<S::is_constructed>::type Add ( T tValue ); template<typename S = STORE> FORCE_INLINE typename std::enable_if<!S::is_constructed>::type Add ( T tValue ); template<typename S = STORE, class... Args> typename std::enable_if<!S::is_constructed>::type Emplace_back ( Args&&... args ); /// add N more entries, and return a pointer to that buffer T* AddN ( int iCount ); /// add unique entry (ie. do not add if equal to last one) void AddUnique ( const T& tValue ); /// remove several elements by index void Remove ( int iIndex, int iCount = 1 ); /// remove element by index, swapping it with the tail void RemoveFast ( int iIndex ); /// remove element by value (warning, linear O(n) search) bool RemoveValue ( T tValue ); /// remove element by value, asuming vec is sorted/uniq bool RemoveValueFromSorted ( T tValue ); /// pop last value by ref (for constructed storage) template<typename S = STORE> FORCE_INLINE typename std::enable_if<S::is_constructed, T&>::type Pop(); /// pop last value template<typename S = STORE> typename std::enable_if<!S::is_constructed, T>::type Pop(); /// grow enough to hold iNewLimit-iDiscard entries, if needed. /// returns updated index of elem iDiscard. int DiscardAndReserve ( int64_t iDiscard, int64_t iNewLimit ); /// grow enough to hold that much entries, if needed, but do *not* change the length void Reserve ( int64_t iNewLimit ); /// for non-copyable types - work like Reset() + Reserve() /// destroys previous dataset, allocate new one and set size to 0. template<typename S = STORE> typename std::enable_if<!S::is_constructed>::type Reserve_static ( int64_t iNewLimit ); /// ensure we have space for iGap more items (reserve more if necessary) inline void ReserveGap ( int iGap ); /// resize template<typename S = STORE> inline typename std::enable_if<S::is_constructed>::type Resize ( int64_t iNewLength ); /// for non-constructed imply destroy when shrinking, of construct when widening template<typename S = STORE> typename std::enable_if<!S::is_constructed>::type Resize ( int64_t iNewLength ); // doesn't need default c-tr void Shrink ( int64_t iNewLength ); /// reset void Reset(); /// Set whole vec to 0. For trivially copyable memset will be used template<typename S = STORE> typename std::enable_if<S::is_constructed>::type ZeroVec(); /// set the tail [m_iCount..m_iLimit) to zero void ZeroTail(); /// query current reserved size, in elements inline int GetLimit() const; /// query currently allocated RAM, in bytes /// (could be > GetLengthBytes() since uses limit, not size) inline int64_t AllocatedBytes() const; /// filter unique void Uniq ( bool bSort=true ); void MergeSorted ( const Vector_T<T>& dA, const Vector_T<T>& dB ); /// copy + move // if provided lvalue, it will be copied into rhs via copy ctr, then swapped to *this // if provided rvalue, it will just pass to SwapData immediately. Vector_T& operator= ( Vector_T<T> rhs ) noexcept; bool operator== ( const Vector_T<T>& rhs ) noexcept; /// memmove N elements from raw pointer to the end /// works ONLY if T is POD type (i.e. may be simple memmoved) /// otherwize compile error will appear (if so, use typed version below). void Append ( const void* pData, int iN ); /// append another vec to the end /// will use memmove (POD case), or one-by-one copying. template<typename S = STORE> typename std::enable_if<S::is_constructed>::type Append ( const VecTraits_T<T>& rhs ); /// append another vec to the end for non-constructed /// will construct in-place with copy c-tr template<typename S = STORE> typename std::enable_if<!S::is_constructed>::type Append ( const VecTraits_T<T>& rhs ); /// swap template<typename L = LIMIT, typename S = STORE> typename std::enable_if<!S::is_owned>::type SwapData ( Vector_T<T, POLICY, L, STORE>& rhs ) noexcept; /// leak template<typename S = STORE> typename std::enable_if<!S::is_owned, T*>::type LeakData(); /// adopt external buffer /// note that caller must himself then nullify origin pData to avoid double-deletion template<typename S = STORE> typename std::enable_if<!S::is_owned>::type AdoptData ( T* pData, int64_t iLen, int64_t iLimit ); /// insert into a middle (will fail to compile for swap vector) template<typename TT=T> void Insert ( int64_t iIndex, TT&& tValue ); protected: int64_t m_iLimit = 0; ///< entries allocated template<typename S = STORE> typename std::enable_if<S::is_constructed>::type destroy_at ( int64_t, int64_t ) {} template<typename S = STORE> typename std::enable_if<!S::is_constructed>::type destroy_at ( int64_t iIndex, int64_t iCount ); template<typename S = STORE> typename std::enable_if<S::is_constructed>::type construct_at ( int64_t, int64_t ) {} template<typename S = STORE> typename std::enable_if<!S::is_constructed>::type construct_at ( int64_t iIndex, int64_t iCount ); }; } // namespace sph ////////////////////////////////////////////////////////////////////////// /// old well-known vector template<typename T, typename R = sph::DefaultRelimit> using CSphVector = sph::Vector_T<T, sph::DefaultCopy_T<T>, R>; template<typename T, typename R = sph::DefaultRelimit, int STATICSIZE = 4096 / sizeof ( T )> using LazyVector_T = sph::Vector_T<T, sph::DefaultCopy_T<T>, R, sph::LazyStorage_T<T, STATICSIZE>>; /// swap-vector template<typename T> using CSphSwapVector = sph::Vector_T<T, sph::SwapCopy_T<T>>; /// tight-vector template<typename T> using CSphTightVector = CSphVector<T, sph::TightRelimit>; /// raw vector for non-default-constructibles template<typename T> using RawVector_T = sph::Vector_T<T, sph::SwapCopy_T<T>, sph::DefaultRelimit, sph::RawStorage_T<T>>; /// commonly used using IntVec_t = CSphVector<int>; /// vector of byte vectors using BlobVec_t = CSphVector<CSphVector<BYTE>>; #include "vector_impl.h"
7,756
C++
.h
179
41.27933
118
0.717669
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,378
relimit.h
manticoresoftware_manticoresearch/src/std/relimit.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" #include <limits.h> ////////////////////////////////////////////////////////////////////////// /// Resize backends for vector /// Each backend provides Relimit namespace sph { /// Default relimit: grow 2x class DefaultRelimit { public: static constexpr int64_t SANE_SIZE = INT_MAX / 2; static constexpr int MAGIC_INITIAL_LIMIT = 8; static inline int64_t Relimit ( int64_t iLimit, int64_t iNewLimit ); }; /// tight-vector policy /// grow only 1.2x on resize (not 2x) starting from a certain threshold class TightRelimit: public DefaultRelimit { public: static constexpr float GROW = 1.2f; static constexpr int64_t SANE_SIZE = (double)INT_MAX / GROW; // double, since INT_MAX is not convertible to float precisely static constexpr int SLOW_GROW_TRESHOLD = 1024; static inline int64_t Relimit ( int64_t iLimit, int64_t iNewLimit ); }; } // namespace sph #include "relimit_impl.h"
1,398
C++
.h
39
34.461538
124
0.717246
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,379
ints.h
manticoresoftware_manticoresearch/src/std/ints.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "config.h" #include <stdio.h> // for 64-bit types #if __has_include(<cstdint>) #include <cstdint> #endif #if __has_include(<sys/types.h>) #include <sys/types.h> #endif #include "checks.h" #if _WIN32 #include <io.h> #define sphSeek _lseeki64 #define popen _popen #define pclose _pclose using SphOffset_t = int64_t; #else #include <unistd.h> #define sphSeek lseek using SphOffset_t = off_t; #endif ///////////////////////////////////////////////////////////////////////////// // PORTABILITY ///////////////////////////////////////////////////////////////////////////// #if _WIN32 #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #define strcasecmp strcmpi #define strncasecmp _strnicmp #if _MSC_VER < 1900 #define snprintf _snprintf #endif #define strtoll _strtoi64 #define strtoull _strtoui64 #else using DWORD = unsigned int; using WORD = unsigned short; using BYTE = unsigned char; #endif // _WIN32 ///////////////////////////////////////////////////////////////////////////// // 64-BIT INTEGER TYPES AND MACROS ///////////////////////////////////////////////////////////////////////////// #if defined(U64C) || defined(I64C) #error "Internal 64-bit integer macros already defined." #endif // if platform-specific macros were not supplied, use common defaults #ifndef U64C #define U64C(v) v ## ULL #endif #ifndef I64C #define I64C(v) v ## LL #endif #ifndef UINT64_MAX #define UINT64_MAX U64C(0xffffffffffffffff) #endif #ifndef INT64_MIN #define INT64_MIN I64C(0x8000000000000000) #endif #ifndef INT64_MAX #define INT64_MAX I64C(0x7fffffffffffffff) #endif STATIC_SIZE_ASSERT ( uint64_t, 8 ); STATIC_SIZE_ASSERT ( int64_t, 8 ); // conversion macros that suppress %lld format warnings vs printf // problem is, on 64-bit Linux systems with gcc and stdint.h, int64_t is long int // and despite sizeof(long int)==sizeof(long long int)==8, gcc bitches about that // using PRIi64 instead of %lld is of course The Right Way, but ugly like fuck // so lets wrap them args in INT64() instead #define INT64(_v) ((long long int)(_v)) #define UINT64(_v) ((unsigned long long int)(_v))
2,622
C++
.h
83
30.180723
81
0.66468
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,380
vectraits_impl.h
manticoresoftware_manticoresearch/src/std/vectraits_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <utility> #include <cassert> #include <type_traits> #include "thread_annotations.h" #include "checks.h" #include "comp.h" #include "sort.h" #include "binarysearch.h" #include "iterations.h" // this ctr allows to regard any typed blob as VecTraits, and use its benefits. template<typename T> VecTraits_T<T>::VecTraits_T ( T* pData, int64_t iCount ) : m_pData ( pData ) , m_iCount ( iCount ) {} template<typename T> template<typename TT> VecTraits_T<T>::VecTraits_T ( TT* pData, int64_t iCount ) : m_pData ( pData ) , m_iCount ( iCount * sizeof ( TT ) / sizeof ( T ) ) {} template<typename T> template<typename TT, typename INT> VecTraits_T<T>::VecTraits_T ( const std::pair<TT*, INT>& dData ) : m_pData ( (T*)dData.first ) , m_iCount ( dData.second * sizeof ( TT ) / sizeof ( T ) ) {} template<typename T> template<typename TT, typename INT> VecTraits_T<T>::VecTraits_T ( const std::pair<const TT*, INT>& dData ) : m_pData ( (T*)const_cast<TT*> ( dData.first ) ) , m_iCount ( dData.second * sizeof ( TT ) / sizeof ( T ) ) {} template<typename T> VecTraits_T<T> VecTraits_T<T>::Slice ( int64_t iBegin, int64_t iCount ) const { // calculate starting bound if ( iBegin < 0 ) iBegin = 0; else if ( iBegin > m_iCount ) iBegin = m_iCount; iCount = ( iCount < 0 ) ? ( m_iCount - iBegin ) : Min ( iCount, m_iCount - iBegin ); return VecTraits_T ( m_pData + iBegin, iCount ); } /// accessor by forward index template<typename T> T& VecTraits_T<T>::operator[] ( int64_t iIndex ) const { assert ( iIndex >= 0 && iIndex < m_iCount ); return m_pData[iIndex]; } template<typename T> T& VecTraits_T<T>::At ( int64_t iIndex ) const { return this->operator[] ( iIndex ); } /// get first entry ptr template<typename T> T* VecTraits_T<T>::Begin() const { return m_iCount ? m_pData : nullptr; } /// pointer to the item after the last template<typename T> T* VecTraits_T<T>::End() const { return m_pData + m_iCount; } /// make happy C++11 ranged for loops template<typename T> T* VecTraits_T<T>::begin() const { return Begin(); } template<typename T> T* VecTraits_T<T>::end() const { return m_iCount ? m_pData + m_iCount : nullptr; } /// get first entry template<typename T> T& VecTraits_T<T>::First() const { return ( *this )[0]; } /// get last entry template<typename T> T& VecTraits_T<T>::Last() const { return ( *this )[m_iCount - 1]; } /// return idx of the item pointed by pBuf, or -1 template<typename T> int VecTraits_T<T>::Idx ( const T* pBuf ) const { if ( !pBuf ) return -1; if ( pBuf < m_pData || pBuf >= m_pData + m_iCount ) return -1; return int ( pBuf - m_pData ); } /// make possible to pass VecTraits_T<T*> into funcs which need VecTraits_T<const T*> /// fixme! M.b. add check and fire error if T is not a pointer? template<typename T> VecTraits_T<T>::operator VecTraits_T<const typename std::remove_pointer<T>::type*>&() const { return *(VecTraits_T<const typename std::remove_pointer<T>::type*>*)( const_cast<VecTraits_T<T>*> ( this ) ); } template<typename T> template<typename TT> VecTraits_T<T>::operator VecTraits_T<TT>&() const { STATIC_ASSERT ( sizeof ( T ) == sizeof ( TT ), SIZE_OF_DERIVED_NOT_SAME_AS_ORIGIN ); return *(VecTraits_T<TT>*)( const_cast<VecTraits_T<T>*> ( this ) ); } template<typename T> template<typename TT, typename INT> VecTraits_T<T>::operator std::pair<TT*, INT>() const { return { (TT*)m_pData, INT ( m_iCount * sizeof ( T ) / sizeof ( TT ) ) }; } /// check if i'm empty template<typename T> bool VecTraits_T<T>::IsEmpty() const { return ( m_pData == nullptr || m_iCount == 0 ); } /// query current length, in elements template<typename T> int64_t VecTraits_T<T>::GetLength64() const { return m_iCount; } template<typename T> int VecTraits_T<T>::GetLength() const { return (int)m_iCount; } /// get length in bytes template<typename T> size_t VecTraits_T<T>::GetLengthBytes() const { return sizeof ( T ) * (size_t)m_iCount; } /// get length in bytes template<typename T> int64_t VecTraits_T<T>::GetLengthBytes64() const { return m_iCount * sizeof ( T ); } /// default sort template<typename T> void VecTraits_T<T>::Sort ( int iStart, int iEnd ) { Sort ( SphLess_T<T>(), iStart, iEnd ); } /// default reverse sort template<typename T> void VecTraits_T<T>::RSort ( int iStart, int iEnd ) { Sort ( SphGreater_T<T>(), iStart, iEnd ); } /// generic sort template<typename T> template<typename F> void VecTraits_T<T>::Sort ( F&& COMP, int iStart, int iEnd ) NO_THREAD_SAFETY_ANALYSIS { if ( m_iCount < 2 ) return; if ( iStart < 0 ) iStart += m_iCount; if ( iEnd < 0 ) iEnd += m_iCount; assert ( iStart <= iEnd ); sphSort ( m_pData + iStart, iEnd - iStart + 1, std::forward<F> ( COMP ) ); } /// generic binary search /// assumes that the array is sorted in ascending order template<typename T> template<typename U, typename PRED> T* VecTraits_T<T>::BinarySearch ( const PRED& tPred, U tRef ) const NO_THREAD_SAFETY_ANALYSIS { return sphBinarySearch ( m_pData, m_pData + m_iCount - 1, tPred, tRef ); } /// generic binary search /// assumes that the array is sorted in ascending order template<typename T> T* VecTraits_T<T>::BinarySearch ( T tRef ) const { return sphBinarySearch ( m_pData, m_pData + m_iCount - 1, tRef ); } template<typename T> template<typename FILTER> int VecTraits_T<T>::GetFirst ( FILTER&& cond ) const NO_THREAD_SAFETY_ANALYSIS { for ( int i = 0; i < m_iCount; ++i ) if ( cond ( m_pData[i] ) ) return i; return -1; } /// generic 'ARRAY_ALL' template<typename T> template<typename FILTER> bool VecTraits_T<T>::all_of ( FILTER&& cond ) const { return ::all_of ( *this, std::forward<FILTER> ( cond ) ); } /// generic linear search - 'ARRAY_ANY' replace /// see 'Contains()' below for examlpe of usage. template<typename T> template<typename FILTER> bool VecTraits_T<T>::any_of ( FILTER&& cond ) const { return ::any_of ( *this, std::forward<FILTER> ( cond ) ); } template<typename T> template<typename FILTER> bool VecTraits_T<T>::none_of ( FILTER&& cond ) const { return !any_of ( cond ); } template<typename T> template<typename FILTER> int64_t VecTraits_T<T>::count_of ( FILTER&& cond ) const { return ::count_of ( *this, std::forward<FILTER> ( cond ) ); } /// Apply an action to every member /// Apply ( [] (T& item) {...} ); template<typename T> template<typename ACTION> void VecTraits_T<T>::Apply ( ACTION&& Verb ) const { ::for_each ( *this, std::forward<ACTION> ( Verb ) ); } template<typename T> template<typename ACTION> void VecTraits_T<T>::for_each ( ACTION&& tAction ) const { ::for_each ( *this, std::forward<ACTION> ( tAction ) ); } /// generic linear search template<typename T> bool VecTraits_T<T>::Contains ( T tRef ) const NO_THREAD_SAFETY_ANALYSIS { return any_of ( [&] ( const T& v ) { return tRef == v; } ); } /// generic linear search template<typename T> template<typename FUNCTOR, typename U> bool VecTraits_T<T>::Contains ( FUNCTOR&& COMP, U tValue ) NO_THREAD_SAFETY_ANALYSIS { return any_of ( [&] ( const T& v ) { return COMP.IsEq ( v, tValue ); } ); } /// fill with given value template<typename T> void VecTraits_T<T>::Fill ( const T& rhs ) { for ( int i = 0; i < m_iCount; ++i ) m_pData[i] = rhs; } /// fill with sequence (appliable only to integers) template<typename T> void VecTraits_T<T>::FillSeq ( T iStart, T iStep ) { for ( int i = 0; i < m_iCount; ++i, iStart += iStep ) m_pData[i] = iStart; }
7,879
C++
.h
279
26.795699
110
0.692878
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,382
accessor.h
manticoresoftware_manticoresearch/src/std/accessor.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once /// generic accessor template<typename T> struct SphAccessor_T { using MEDIAN_TYPE = T; MEDIAN_TYPE& Key ( T* a ) const; void CopyKey ( MEDIAN_TYPE* pMed, T* pVal ) const; void Swap ( T* a, T* b ) const; T* Add ( T* p, int i ) const; int Sub ( T* b, T* a ) const; }; #include "accessor_impl.h"
792
C++
.h
24
31.583333
80
0.71466
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,383
timers.h
manticoresoftware_manticoresearch/src/std/timers.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" /// microsecond precision timestamp /// current UNIX timestamp in seconds multiplied by 1000000, plus microseconds since the beginning of current second int64_t sphMicroTimer(); /// monotonic microsecond precision timestamp /// value of CLOCK_MONOTONIC source int64_t MonoMicroTimer(); /// return cpu time, in microseconds. CLOCK_THREAD_CPUTIME_ID, or CLOCK_PROCESS_CPUTIME_ID or fall to sphMicroTimer(). /// defined in searchd.cpp since depends from g_bCpuStats int64_t sphProcessCpuTimer(); int64_t sphThreadCpuTimer(); /// returns sphThreadCpuTimer() adjusted to current coro task (coro may jump from thread to thread, so sphThreadCpuTimer() is irrelevant) int64_t sphTaskCpuTimer();
1,199
C++
.h
25
46.72
137
0.780822
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,384
mm.h
manticoresoftware_manticoresearch/src/std/mm.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" enum class Mode_e { NONE, READ, WRITE, RW, }; enum class Share_e { ANON_PRIVATE, ANON_SHARED, SHARED, }; enum class Advise_e { NOFORK, NODUMP, }; void* mmalloc ( size_t uSize, Mode_e = Mode_e::RW, Share_e = Share_e::ANON_PRIVATE ); bool mmapvalid ( const void* pMem ); int mmfree ( void* pMem, size_t uSize ); void mmadvise ( void* pMem, size_t uSize, Advise_e = Advise_e::NODUMP ); bool mmlock ( void* pMem, size_t uSize ); bool mmunlock ( void* pMem, size_t uSize );
989
C++
.h
34
27.676471
85
0.722105
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,385
fixedvector_impl.h
manticoresoftware_manticoresearch/src/std/fixedvector_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <cassert> #include <utility> template<typename T, class POLICY, class STORE> CSphFixedVector<T,POLICY,STORE>::CSphFixedVector ( int64_t iSize ) noexcept { m_iCount = iSize; assert ( iSize >= 0 ); m_pData = ( iSize > 0 ) ? STORE::Allocate ( iSize ) : nullptr; } template<typename T, class POLICY, class STORE> CSphFixedVector<T, POLICY, STORE>::~CSphFixedVector() { STORE::Deallocate ( m_pData ); } template<typename T, class POLICY, class STORE> CSphFixedVector<T, POLICY, STORE>::CSphFixedVector ( CSphFixedVector&& rhs ) noexcept { SwapData ( rhs ); } template<typename T, class POLICY, class STORE> CSphFixedVector<T, POLICY, STORE>& CSphFixedVector<T, POLICY, STORE>::operator= ( CSphFixedVector rhs ) noexcept { SwapData ( rhs ); return *this; } template<typename T, class POLICY, class STORE> void CSphFixedVector<T, POLICY, STORE>::Reset ( int64_t iSize ) { assert ( iSize >= 0 ); if ( iSize == m_iCount ) return; STORE::Deallocate ( m_pData ); m_pData = ( iSize > 0 ) ? STORE::Allocate ( iSize ) : nullptr; m_iCount = iSize; } template<typename T, class POLICY, class STORE> void CSphFixedVector<T, POLICY, STORE>::CopyFrom ( const VecTraits_T<T>& dOrigin ) { Reset ( dOrigin.GetLength() ); POLICY::Copy ( m_pData, dOrigin.begin(), dOrigin.GetLength() ); } template<typename T, class POLICY, class STORE> template<typename S> typename std::enable_if<!S::is_owned, T*>::type CSphFixedVector<T, POLICY, STORE>::LeakData() { T* pData = m_pData; m_pData = nullptr; Reset ( 0 ); return pData; } /// swap template<typename T, class POLICY, class STORE> template<typename S> typename std::enable_if<!S::is_owned>::type CSphFixedVector<T, POLICY, STORE>::SwapData ( CSphFixedVector& rhs ) noexcept { std::swap ( m_pData, rhs.m_pData ); std::swap ( m_iCount, rhs.m_iCount ); } template<typename T, class POLICY, class STORE> template<typename S> typename std::enable_if<S::is_constructed && !S::is_owned>::type CSphFixedVector<T, POLICY, STORE>::Set ( T* pData, int64_t iSize ) { m_pData = pData; m_iCount = iSize; } /// Set whole vec to 0. For trivially copyable memset will be used template<typename T, class POLICY, class STORE> void CSphFixedVector<T, POLICY, STORE>::ZeroVec() { POLICY::Zero ( m_pData, m_iCount ); }
2,742
C++
.h
82
31.987805
131
0.729985
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,386
sort.h
manticoresoftware_manticoresearch/src/std/sort.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once /// generic sort template<typename T, typename U, typename V> void sphSort ( T* pData, int iCount, U&& COMP, V&& ACC ) noexcept; template<typename T, typename U> void sphSort ( T* pData, int iCount, U&& COMP ) noexcept; template<typename T> void sphSort ( T* pData, int iCount ) noexcept; #include "sort_impl.h"
805
C++
.h
20
39
80
0.742308
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,387
log2.h
manticoresoftware_manticoresearch/src/std/log2.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" constexpr int sphLog2const ( unsigned uValue ); constexpr int sphLog2const ( unsigned long uValue ); constexpr int sphLog2const ( unsigned long long uValue ); /// how much bits do we need for given int int sphLog2 ( unsigned uValue ); int sphLog2 ( unsigned long uValue ); int sphLog2 ( unsigned long long uValue ); /// signed ints just casted to unsigned constexpr int sphLog2const ( int iValue ); constexpr int sphLog2const ( long iValue ); constexpr int sphLog2const ( long long iValue ); int sphLog2 ( int iValue ); int sphLog2 ( long iValue ); int sphLog2 ( long long iValue ); int GetLeadingZeroBits ( uint32_t uValue ); int GetLeadingZeroBits ( uint64_t uValue ); #include "log2_impl.h"
1,208
C++
.h
30
39
80
0.762393
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,388
crc32.h
manticoresoftware_manticoresearch/src/std/crc32.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "ints.h" #include "vectraits.h" /// Sphinx CRC32 implementation DWORD sphCRC32 ( const void* pString ); DWORD sphCRC32 ( const void* pString, int iLen, DWORD uPrevCRC=0 ); template<typename T> DWORD sphCRC32 ( VecTraits_T<T> dData, DWORD uPrevCRC=0 ); void CRC32_step ( DWORD& uCRC, BYTE uByte ); DWORD CRC32_next ( DWORD uPrevCRC, BYTE uByte ); DWORD CRC32_start ( BYTE uByte ); #include "crc32_impl.h"
905
C++
.h
22
39.954545
80
0.749716
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,389
fastlog_impl.h
manticoresoftware_manticoresearch/src/std/fastlog_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <cassert> #include <utility> template<typename T> LogMessage_t& LogMessage_t::operator<< ( T&& t ) { m_dLog << std::forward<T> ( t ); return *this; } inline void LocMessage_c::Swap ( LocMessage_c& rhs ) noexcept { std::swap ( m_dLog, rhs.m_dLog ); } inline LocMessage_c::LocMessage_c ( const LocMessage_c& rhs ) { assert ( false && "NRVO failed" ); } template<typename T> LocMessage_c& LocMessage_c::operator<< ( T&& t ) { m_dLog << std::forward<T> ( t ); return *this; } inline LocMessage_c LocMessages_c::GetLoc() { return LocMessage_c ( this ); }
1,048
C++
.h
37
26.945946
80
0.716135
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,390
threadrole.h
manticoresoftware_manticoresearch/src/std/threadrole.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #pragma once #include "thread_annotations.h" /// capability for tracing threads using ThreadRole CAPABILITY ( "role" ) = bool; inline void AcquireRole ( ThreadRole R ) ACQUIRE ( R ) NO_THREAD_SAFETY_ANALYSIS {} inline void ReleaseRole ( ThreadRole R ) RELEASE ( R ) NO_THREAD_SAFETY_ANALYSIS {} class SCOPED_CAPABILITY ScopedRole_c { ThreadRole& m_tRoleRef; public: /// acquire on creation inline explicit ScopedRole_c ( ThreadRole& tRole ) ACQUIRE ( tRole ) : m_tRoleRef ( tRole ) { AcquireRole ( tRole ); } /// release on going out of scope ~ScopedRole_c() RELEASE() { ReleaseRole ( m_tRoleRef ); } };
1,102
C++
.h
35
29.828571
80
0.741265
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,391
fnv64.h
manticoresoftware_manticoresearch/src/std/fnv64.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #ifndef _fnv64_ #define _fnv64_ #include "ints.h" #include "blobs.h" #include "generics.h" constexpr uint64_t SPH_FNV64_SEED = 0xcbf29ce484222325ULL; uint64_t sphFNV64 ( const void * pString ); uint64_t sphFNV64 ( const void * s, int iLen, uint64_t uPrev = SPH_FNV64_SEED ); uint64_t sphFNV64cont ( const void * pString, uint64_t uPrev ); FORCE_INLINE uint64_t sphFNV64 ( uint64_t uVal, uint64_t uPrev = SPH_FNV64_SEED ) { const uint64_t FNV_64_PRIME = 0x100000001b3ULL; const BYTE * p = (const BYTE*)&uVal; uint64_t hval = uPrev; hval ^= (uint64_t)*(p+0); hval *= FNV_64_PRIME; hval ^= (uint64_t)*(p+1); hval *= FNV_64_PRIME; hval ^= (uint64_t)*(p+2); hval *= FNV_64_PRIME; hval ^= (uint64_t)*(p+3); hval *= FNV_64_PRIME; hval ^= (uint64_t)*(p+4); hval *= FNV_64_PRIME; hval ^= (uint64_t)*(p+5); hval *= FNV_64_PRIME; hval ^= (uint64_t)*(p+6); hval *= FNV_64_PRIME; hval ^= (uint64_t)*(p+7); hval *= FNV_64_PRIME; return hval; } inline uint64_t sphFNV64 ( const ByteBlob_t & dBlob ) { return sphFNV64 ( dBlob.first, dBlob.second ); } inline uint64_t sphFNV64cont ( const ByteBlob_t & dBlob, uint64_t uPrev ) { return sphFNV64 ( dBlob.first, dBlob.second, uPrev ); } #endif // _fnv64_
1,688
C++
.h
46
35.086957
131
0.697062
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,392
sort_impl.h
manticoresoftware_manticoresearch/src/std/sort_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <utility> #include "log2.h" #include "accessor.h" #include "comp.h" namespace sphstd { /// heap sort helper template<typename T, typename U, typename V> void SiftDown ( T* pData, int iStart, int iEnd, U&& COMP, V&& ACC ) { while ( true ) { int iChild = iStart * 2 + 1; if ( iChild > iEnd ) return; int iChild1 = iChild + 1; if ( iChild1 <= iEnd && COMP.IsLess ( ACC.Key ( ACC.Add ( pData, iChild ) ), ACC.Key ( ACC.Add ( pData, iChild1 ) ) ) ) iChild = iChild1; if ( COMP.IsLess ( ACC.Key ( ACC.Add ( pData, iChild ) ), ACC.Key ( ACC.Add ( pData, iStart ) ) ) ) return; ACC.Swap ( ACC.Add ( pData, iChild ), ACC.Add ( pData, iStart ) ); iStart = iChild; } } /// heap sort template<typename T, typename U, typename V> void HeapSort ( T* pData, int iCount, U&& COMP, V&& ACC ) { if ( !pData || iCount <= 1 ) return; // build a max-heap, so that the largest element is root for ( int iStart = ( iCount - 2 ) >> 1; iStart >= 0; --iStart ) SiftDown ( pData, iStart, iCount - 1, std::forward<U> ( COMP ), std::forward<V> ( ACC ) ); // now keep popping root into the end of array for ( int iEnd = iCount - 1; iEnd > 0; ) { ACC.Swap ( pData, ACC.Add ( pData, iEnd ) ); SiftDown ( pData, 0, --iEnd, std::forward<U> ( COMP ), std::forward<V> ( ACC ) ); } } /// generic sort template<typename T, typename U, typename V> void Sort ( T* pData, int iCount, U&& COMP, V&& ACC ) { if ( iCount < 2 ) return; typedef T* P; // st0 and st1 are stacks with left and right bounds of array-part. // They allow us to avoid recursion in quicksort implementation. P st0[32], st1[32], a, b, i, j; typename std::remove_reference<V>::type::MEDIAN_TYPE x; int k; const int SMALL_THRESH = 32; int iDepthLimit = sphLog2 ( iCount ); iDepthLimit = ( ( iDepthLimit << 2 ) + iDepthLimit ) >> 1; // x2.5 k = 1; st0[0] = pData; st1[0] = ACC.Add ( pData, iCount - 1 ); while ( k ) { k--; i = a = st0[k]; j = b = st1[k]; // if quicksort fails on this data; switch to heapsort if ( !k ) { if ( !--iDepthLimit ) { HeapSort ( a, ACC.Sub ( b, a ) + 1, std::forward<U> ( COMP ), ACC ); return; } } // for tiny arrays, switch to insertion sort int iLen = ACC.Sub ( b, a ); if ( iLen <= SMALL_THRESH ) { for ( i = ACC.Add ( a, 1 ); i <= b; i = ACC.Add ( i, 1 ) ) { for ( j = i; j > a; ) { P j1 = ACC.Add ( j, -1 ); if ( COMP.IsLess ( ACC.Key ( j1 ), ACC.Key ( j ) ) ) break; ACC.Swap ( j, j1 ); j = j1; } } continue; } // ATTENTION! This copy can lead to memleaks if your CopyKey // copies something which is not freed by objects destructor. ACC.CopyKey ( &x, ACC.Add ( a, iLen / 2 ) ); while ( a < b ) { while ( i <= j ) { while ( COMP.IsLess ( ACC.Key ( i ), x ) ) i = ACC.Add ( i, 1 ); while ( COMP.IsLess ( x, ACC.Key ( j ) ) ) j = ACC.Add ( j, -1 ); if ( i <= j ) { ACC.Swap ( i, j ); i = ACC.Add ( i, 1 ); j = ACC.Add ( j, -1 ); } } // Not so obvious optimization. We put smaller array-parts // to the top of stack. That reduces peak stack size. if ( ACC.Sub ( j, a ) >= ACC.Sub ( b, i ) ) { if ( a < j ) { st0[k] = a; st1[k] = j; k++; } a = i; } else { if ( i < b ) { st0[k] = i; st1[k] = b; k++; } b = j; } } } } } // namespace sphstd template<typename T, typename U, typename V> void sphSort ( T* pData, int iCount, U&& COMP, V&& ACC ) noexcept { sphstd::Sort ( pData, iCount, std::forward<U> ( COMP ), std::forward<V> ( ACC ) ); } template<typename T, typename U> void sphSort ( T* pData, int iCount, U&& COMP ) noexcept { sphSort ( pData, iCount, std::forward<U> ( COMP ), SphAccessor_T<T>() ); } template<typename T> void sphSort ( T* pData, int iCount ) noexcept { sphSort ( pData, iCount, SphLess_T<T>() ); }
4,376
C++
.h
155
25.193548
121
0.594189
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,393
blobs_impl.h
manticoresoftware_manticoresearch/src/std/blobs_impl.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // All rights reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License. You should have // received a copy of the GPL license along with this program; if you // did not, you can find it at http://www.gnu.org // #include <cstring> inline Str_t FromSz ( const char* szString ) noexcept { return { szString, szString ? (int)strlen ( szString ) : 0 }; } template<int prec> inline FixedFrac_T<int, prec> FixedFrac ( int iVal ) { return FixedFrac_T<int, prec> { iVal }; } template<int prec> inline FixedFrac_T<int64_t, prec> FixedFrac ( int64_t iVal ) { return FixedFrac_T<int64_t, prec> { iVal }; } template<int iBase, int iWidth, int iPrec, char cFill> inline FixedNum_T<int64_t, iBase, iWidth, iPrec, cFill> FixedNum ( int64_t iVal ) { return FixedNum_T<int64_t, iBase, iWidth, iPrec, cFill> { iVal }; } template<int iBase, int iWidth, int iPrec, char cFill> inline FixedNum_T<int, iBase, iWidth, iPrec, cFill> FixedNum ( int iVal ) { return FixedNum_T<int, iBase, iWidth, iPrec, cFill> { iVal }; } template<int iWidth> inline FixedNum_T<int64_t, 10, iWidth, 0, '0'> Digits ( int64_t iVal ) { return FixedNum<10, iWidth, 0, '0'> ( iVal ); } template<int iWidth> inline FixedNum_T<int, 10, iWidth, 0, '0'> Digits ( int iVal ) { return FixedNum<10, iWidth, 0, '0'> ( iVal ); }
1,548
C++
.h
43
34.72093
119
0.719813
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,394
helpers_rt.inc
manticoresoftware_manticoresearch/test/helpers_rt.inc
<?php ini_set ( "display_errors", 1 ); ini_set ( "error_reporting", (E_ALL | E_STRICT) & ~E_USER_DEPRECATED ); function escape ( $string ) { $from = array ( '\\', '(',')','|','-','!','@','~','"','&', '/', '^', '$', '=', '<', '\'' ); $to = array ( '\\\\', '\(','\)','\|','\-','\!','\@','\~','\"', '\&', '\/', '\^', '\$', '\=', '\<', '\\\'' ); return str_replace ( $from, $to, $string ); } function populate_rt ( $id_from, $id_to, $commit_step, $con_daemon, $index_name ) { $res = array( 'total'=>0, 'total_found'=>0, 'time'=>0, 'query'=>'', 'tag'=>'', 'error'=>'' ); $con_sql = @mysql_connect ( "localhost", "root", "", true ); if ( !$con_sql ) { $res['error'] = 'failed to connect to MySQL server'; return $res; } if ( !@mysql_select_db ( "lj", $con_sql ) ) { $res['error'] = 'failed to select db'; return $res; } if ( !@mysql_query ( 'SET names utf8', $con_sql ) ) { $res['error'] = 'failed to connect to set utf8'; return $res; } $r = @mysql_query ( "SELECT id, UNCOMPRESS(content) body, title, channel_id idd, ts FROM posting where id>=$id_from AND id<=$id_to;", $con_sql ); if ( !$r ) { $res['error'] = 'faled to fetch'; return $res; } $data = array(); while ( $row = @mysql_fetch_assoc ( $r ) ) { $data[] = array ( 'id'=>$row['id'], 'title'=>$row['title'], 'body'=>$row['body'], 'idd'=>$row['idd'], 'ts'=>$row['ts'] ); } $con_daemon->Query ( "SET autocommit=0" ); $posted = 0; $start = MyMicrotime(); foreach ( $data as $elem ) { $id = $elem['id']; $title = escape ( $elem['title'] ); $body = escape ( $elem['body'] ); $q = "REPLACE INTO $index_name (id, title, body, idd, ts) VALUES ( $id, ' "; $q .= $title; // title $q .= " ', ' "; $q .= $body; // body $q .= " ', "; $q .= $elem['idd']; // idd $q .= ", "; $q .= strtotime($elem['ts']); // ts $q .= " ) "; $r = ( $con_daemon->Query ( $q ) ); if ( stristr ( $r, "NOT CONNECTED" ) || stristr ( $r, "ERROR:" ) ) { $res['error'] = $r . '; query: ' . $q; $res['total_found'] = $posted; return $res; } $posted++; if ( ( $posted % $commit_step )==0 ) $con_daemon->Query ( 'COMMIT' ); } $con_daemon->Query ( 'COMMIT' ); $con_daemon->Query ( "SET autocommit=1" ); $res['time'] = MyMicrotime() - $start; $res['total_found'] = $posted; return $res; } function delete_from_rt ( $ids, $con_daemon, $index_name ) { $res = array( 'total'=>0, 'total_found'=>0, 'time'=>0, 'query'=>'', 'tag'=>'', 'error'=>'' ); $start = MyMicrotime(); foreach ( $ids as $id ) { $q = "DELETE FROM $index_name WHERE id=$id"; $r = ( $con_daemon->Query ( $q ) ); if ( stristr ( $r, "NOT CONNECTED" ) || stristr ( $r, "ERROR:" ) ) { $res['error'] = $r . '; query: ' . $q; $res['total'] = $id; return $res; } } $res['time'] = MyMicrotime() - $start; $res['total_found'] = count($ids); return $res; }
2,987
C++
.inc
92
28.684783
147
0.488462
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,395
helpers.inc
manticoresoftware_manticoresearch/test/helpers.inc
<?php ini_set ( "display_errors", 1 ); ini_set ( "error_reporting", (E_ALL | E_STRICT) & ~E_USER_DEPRECATED ); ini_set ('memory_limit', '256M'); require_once ( $g_locals['api'] ); function MyMicrotime () { $q = @gettimeofday(); return (float)($q["usec"] / 1000000) + $q["sec"]; } function sphFormatTime ( $time ) { if ( $time < 60 ) return sprintf ( '%.0fs', $time ); $time = (int)$time; if ( $time < 3600 ) $u = array ( 'm', 's' ); else { $time = $time / 60; $u = array ( 'h', 'm' ); } return sprintf ( '%d%s:%d%s', $time / 60, $u[0], $time % 60, $u[1] ); } function StrBegins ( $str, $substr ) { return substr($str, 0, strlen($substr)) === $substr; } function mysqli_wr ($q, $conn) { // printf ( "$q\n"); mysqli_report(MYSQLI_REPORT_OFF); return @$conn->query ( $q ); } // return line for text formatting of the table, as +----+---+ function PrintLine($columns) { $str = "+"; foreach ( $columns as $sz ) $str .= str_pad("", $sz+2, '-') . "+"; $str .= "\n"; return $str; } // return formatted line padded by fixed length, like: | foo | bar baz | function PrintDataLine($row, $columns) { $str = "|"; foreach ($row as $key => $value) { if (is_null($value)) $value = 'NULL'; $str .= " " . str_pad ($value, $columns[$key]+1) . "|"; } $str .= "\n"; return $str; } // format $rows dataset as mysql cli does function WriteSphinxqlTable ( $rows ) { $str = ""; $columns=[]; foreach ( $rows[0] as $key=>$s ) $columns[$key] = strlen($key); // collect max lengths foreach ($rows as $row) { foreach ($row as $key => $value) { if (is_null($value)) $value = 'NULL'; $columns[$key] = max($columns[$key], strlen($value)); } } // top line $str .= PrintLine ($columns); // column names $str .= "|"; foreach ( $rows[0] as $key=>$s ) $str .= " " . str_pad ($key, $columns[$key]+1) . "|"; $str .= "\n"; // 2-nd line $str .= PrintLine ($columns); // rowset foreach ($rows as $row) $str .= PrintDataLine ($row, $columns); // tail line $str .= PrintLine ($columns); return $str; } // write single mysql query/result as example function WriteSphinxqlExample ( $log, $result ) { $str = "<!-- request mysql -->\n\n```\n$result[sphinxql];\n```\n\n"; $str .= "<!-- response mysql -->\n\n```\n"; if ( array_key_exists ("total_affected", $result) ) { $str .= "Query OK, $result[total_affected] rows affected (0.00 sec)\n\n"; } else if ( array_key_exists ("error", $result) ) { $str .= "ERROR $result[errno]: $result[error]\n\n"; } else if (array_key_exists ("rows", $result) ) { $str .= WriteSphinxqlTable ($result["rows"]); $str .="$result[total_rows] rows in set (0.00 sec)\n\n"; } else if ( isset($result["total_rows"]) ) { $str .= "$result[total_rows] rows in set (0.00 sec)\n\n"; } $str .= "```\n"; fwrite ( $log, $str); } // writes (append) whole set of examples to provided file. function WriteExamples ( $example_file, $examples ) { if (empty($examples)) return; $log = fopen ( $example_file, "a" ); foreach ( $examples as $name=>$results ) { fwrite ( $log, "\n<!-- example $name -->\n"); foreach ( $results as $result ) { if ( array_key_exists ( "sphinxql", $result ) ) WriteSphinxqlExample ( $log, $result); // else - other types } fwrite ( $log, "<!-- end -->\n"); } fclose ( $log ); } $gl_conn = false; // The wrappers for fresh php without php_mysql. // We use mysqli instead in the code here, // but custom tests still know nothing about it, // so make old-fashion wrappers for them. if ( !function_exists("mysql_query") ) { function mysql_query($query, $conn = NULL) { global $gl_conn; if ($conn == NULL) return $gl_conn->query($query); else return $conn->query($query); } function mysql_connect($host, $user, $password, $newlink) { mysqli_report(MYSQLI_REPORT_OFF); global $gl_conn; $conndetails = explode(":",$host); if ( count($conndetails)==1 ) $gl_conn = new mysqli($host,$user,$password); else { global $g_locals; $dbname = $g_locals["db-name"]; $host = $conndetails[0]; $port = $conndetails[1]; $gl_conn = new mysqli($host, $user, $password, $dbname, (int)$port); } if ($gl_conn->connect_error) return false; return $gl_conn; } function mysql_select_db($db, $conn=NULL) { global $gl_conn; if ( $conn == NULL ) return $gl_conn->select_db($db); else return $conn->select_db($db); } function mysql_close ( $link=NULL ) { if ($link!=NULL) { $link->close(); return; } global $gl_conn; if ($gl_conn!=NULL) $gl_conn->close(); } function mysql_errno ( $link=NULL ) { global $gl_conn; if ($link) return $link->errno; else return $gl_conn->errno; } function mysql_error ( $link=NULL ) { global $gl_conn; if ($link) return $link->error; else return $gl_conn->error; } function mysql_affected_rows($conn = NULL) { if ($conn != NULL) return $conn->affected_rows; global $gl_conn; return $gl_conn->affected_rows; } function mysql_num_rows($res) { return $res->num_rows; } define('MYSQL_ASSOC', MYSQLI_ASSOC); define('MYSQL_NUM', MYSQLI_NUM); define('MYSQL_BOTH', MYSQLI_BOTH); function mysql_fetch_array($res,$restype=MYSQL_BOTH) { if ($res===true) return false; $result = $res->fetch_array($restype); if ($result===NULL) return false; return $result; } function mysql_fetch_assoc($res) { return $res->fetch_assoc(); } function mysql_free_result($res) { if ($res===true) return; $res->free(); } $mysql_simulated = true; } // function_exists ("mysql_query") else { $mysql_simulated = false; } // will use mysql_query from php, or our redefined function legacy_mysql_wr ($q, $conn) { // printf ( "$q\n"); return @mysql_query($q, $conn); } function ConnectDB () { global $g_locals; if ( !function_exists ( "mysqli_connect" ) ) { print ( "ERROR: missing required mysqli_connect(); add php_mysqli.so (.dll on Windows) to your php.ini!\n" ); exit ( 1 ); } mysqli_report(MYSQLI_REPORT_OFF); $conn = new mysqli( $g_locals["db-host"], $g_locals["db-user"], $g_locals["db-password"], $g_locals['db-name'], $g_locals['db-port']); return $conn; } // will use either system mysql, either our wrapper in order to be in sync with client used in custom tests. function LegacyConnectDB () { global $g_locals; $conn = @mysql_connect ( $g_locals["db-host"] . ":" . $g_locals["db-port"], $g_locals["db-user"], $g_locals["db-password"], true ); if ( $conn === false || !@mysql_query ( "CREATE DATABASE IF NOT EXISTS " . $g_locals['db-name'], $conn ) || !@mysql_select_db ( $g_locals['db-name'], $conn ) ) return false; return $conn; } function LegacyCreateDB ( $db_drop, $db_create, $db_insert, $custom_insert, &$error ) { $conn = LegacyConnectDB(); foreach ( $db_drop as $q ) if ( !legacy_mysql_wr ( $q, $conn ) ) { $error = mysqli_error($conn); return false; } foreach ( $db_create as $q ) { if ( stripos ( $q, "create table")!==false ) { if ( stripos ( $q, "engine=")===false ) { $q = trim ( $q, " \t\n\r;" ); $q .= " ENGINE=MEMORY"; } } if ( !legacy_mysql_wr ( $q, $conn ) ) { $error = mysqli_error($conn); return false; } } $oneok = count($db_insert)==0; foreach ( $db_insert as $q ) if ( legacy_mysql_wr ( $q, $conn ) ) $oneok = true; if ( !$oneok ) return false; foreach ( $custom_insert as $code ) { $func = function() use ($code) { eval ("$code"); }; $func(); } return $conn; } function CreateDB ( $db_drop, $db_create, $db_insert, $custom_insert, $skip, &$error ) { if ($skip) return ConnectDB(); // here we split codepaths for old (php5) and new (php7 without php_mysql). // if there is no custom inserts, we just use mysqli. // but if we have them, we need to support mysql syntax since custom inserts use it. // This is done by LegacyConnectDB.After it, it we actually doesn't have mysql (i.e. if we // use wrappers) we just continue to use the connection as mysqli. // but otherwise we have to close mysql conn and reconnect as mysqli to avoid too many changes // of the existing code. global $mysql_simulated; if ( count($custom_insert)>0 ) { $conn = LegacyCreateDB ( $db_drop, $db_create, $db_insert, $custom_insert, $error ); if ( !$mysql_simulated ) { @mysql_close($conn); $conn = ConnectDB(); } return $conn; } $conn = ConnectDB(); foreach ( $db_drop as $q ) if ( !mysqli_wr ( $q, $conn ) ) { $error = mysqli_error($conn); return false; } foreach ( $db_create as $q ) { if ( stripos ( $q, "create table")!==false ) { if ( stripos ( $q, "engine=")===false ) { $q = trim ( $q, " \t\n\r;" ); $q .= " ENGINE=MEMORY"; } } if ( !mysqli_wr ( $q, $conn ) ) { $error = mysqli_error($conn); return false; } } $oneok = count($db_insert)==0; foreach ( $db_insert as $q ) if ( mysqli_wr ( $q, $conn ) ) $oneok = true; if ( !$oneok ) return false; return $conn; } function from_utf8 ( $to, $text ) { if (is_null($to)) return $text; return iconv ('utf-8', $to, $text); } function RunIndexerOnce ( &$error, $params ) { global $g_locals; $path = $g_locals['indexer']; if ( !is_executable($path) ) { $error = "$path: indexer not found"; return 1; } $retval = 0; exec ( "$path --quiet --config ".testdir('config.conf')." $params", $error, $retval ); // Not considering warnings as errors here to avoid possible fails caused by the columnar library init warning $error = join ( "\n", array_filter ( $error, function( $errLine ) { return strpos ( $errLine, "FATAL:" )===0 || strpos ( $errLine, "ERROR:" )===0; } ) ); return ( $retval==0 && !empty($error) ) ? 2 : $retval; } function RunIndexer ( &$error, $params ) { $INDEXING_TRIES = 5; $INDEXING_TICK = 1000000; // msec $tries = 0; for ( $i=0; $i<$INDEXING_TRIES; ++$i ) { $retval = RunIndexerOnce ( $error, $params ); if ( empty($error) || stripos ( $error, "failed to lock")===false ) break; usleep ( $INDEXING_TICK ); ++$tries; } if ( $tries!=0 ) $error = "After $tries tries: $error"; return $retval; } function CheckSearchdLog ( $error_file, &$retval ) { $rawlog = file ( $error_file, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES ); $error = ""; foreach ( $rawlog as $line ) { foreach ( array ( "WARNING:", "ERROR:", "FATAL:" ) as $tag ) { $t = strstr ( $line, $tag ); if ( $t ) { // Adding an explicit check to avoid possible fails caused by the columnar library init warning if ( $tag==="WARNING:" && strpos ( $line, "WARNING: Error initializing columnar storage" )!==false ) continue; // empty binlog is not the actual warning for tests if ( $tag==="WARNING:" && strpos ( $line, "WARNING: binlog: empty binlog" )!==false ) continue; $error .= $t."\n"; if ( $tag!="WARNING:" ) $retval = 1; } } } return $error; } function UseValgrind () { global $g_locals, $VLG; if ( $VLG ) return true; if ( isset ( $g_locals['valgrindsearchd'] ) ) return $g_locals['valgrindsearchd']; else return false; } function ActionRetries () { global $action_retries, $valgrind_action_retries; if (!UseValgrind() ) return $action_retries; return $action_retries + $valgrind_action_retries; } function WaitRetries () { return ActionRetries()*50; } function GetSearchd ( &$searchd, &$error, $full_featured ) { global $g_locals, $VLG; if ( isset ( $g_locals['valgrindoptions'] ) ) $vlgoptions = $g_locals['valgrindoptions']; else $vlgoptions = '--leak-check=full'; if ( $full_featured && UseValgrind() ) { if ( $VLG ) { $vlgvars = explode ( ' ', $VLG ); foreach ( $vlgvars as &$vlgvar ) { if ( substr ( $vlgvar, 0, 10 ) == "--log-file" ) # --log-file=/sphinx/sphinxfrommac/build/Testing/Temporary/MemoryChecker.308.log { $lgfile = explode ('=', $vlgvar)[1]; $vlgvar="--log-fd=9 9>>$lgfile"; break; } } $VLG1 = implode (' ', $vlgvars); $searchd = "$VLG1 "; } else { $searchd = "valgrind $vlgoptions "; if ( file_exists("valgrind.supp" ) ) $searchd .= "--suppressions=" . getcwd() . "/valgrind.supp "; } $searchd .= $g_locals['searchd']; } else { $searchd = $g_locals['searchd']; if ( !is_executable($searchd) ) { $error = "$searchd: searchd not found"; return false; } } return true; } function GetTmDelta() { if ( UseValgrind() ) return 30; return 10; } function StartSearchd ( $config_file, $error_file, $pidfile, &$error, $requirements, $addr=false, $port=false ) { global $g_locals, $windows, $cygwin, $action_wait_timeout, $sd_address, $sd_port; $abs_config_file = testdir($config_file); $abs_error_file = scriptdir($error_file); $win_error_file = testdir($error_file); $abs_pidfile = scriptdir($pidfile); // print ($abs_config_file . "\n"); // print ($abs_error_file . "\n"); // print ($abs_pidfile . "\n"); if (!GetSearchd ($path, $error, true)) return 1; // try to wait a bit here $action_retries = ActionRetries(); $i = 0; while ( !@touch($abs_error_file) && $i < $action_retries ) { usleep ( $action_wait_timeout ); $i++; } if ( !@touch($abs_error_file) ) { $error = "$abs_error_file: unable to create error file"; return 1; } $extra_params = ''; $use_watchdog = isset ($requirements["watchdog"]) && $requirements["watchdog"]; $no_pseudo_sharding = isset ($requirements["no_pseudo_sharding"]) && $requirements["no_pseudo_sharding"]; if ( !$use_watchdog ) $extra_params .= ' --test'; if ( !$no_pseudo_sharding ) $extra_params .= ' --force-pseudo-sharding'; if ( isset ( $g_locals['use_pool'] ) && $g_locals['use_pool'] ) $extra_params .= ' --test-thd-pool'; if ( isset ( $g_locals['extra_searchd_options'] ) ) $extra_params .= ' ' . $g_locals['extra_searchd_options']; $testdir = $g_locals['scriptdir']; $cd = ( $testdir!='' ); if ($cd) { $backdir = getcwd(); chdir($testdir); } $retval = 0; if ( $windows && !$cygwin ) { // using start /min to fire it "in background" // using cmd /c for redirection to work if ( file_exists ( $abs_pidfile ) ) unlink ( $abs_pidfile ); // print ("start /min cmd /c \"$path --config $abs_config_file --pidfile --console $extra_params > $abs_error_file\"\n"); $process = popen ("start /min cmd /c \"$path --config $abs_config_file --pidfile --console $extra_params > $abs_error_file\"", "r" ); pclose ( $process ); } else if ($cygwin) { // using start /min to fire it "in background" // using cmd /c for redirection to work if ( file_exists ( $abs_pidfile ) ) unlink ( $abs_pidfile ); $scmd = "cygstart --hide bash -c \"$path --config $abs_config_file --pidfile --console $extra_params > $abs_error_file\""; print ("cygwin: $scmd\n"); $process = popen ($scmd, "r" ); pclose ( $process ); print ("started\n"); } else { // print ( "$path --config $abs_config_file $extra_params > $abs_error_file\n" ); exec("$path --config $abs_config_file $extra_params", $output, $retval); file_put_contents($abs_error_file, implode("\n", $output)); // print ("started\n"); } if ($cd) chdir($backdir); $action_retries = ActionRetries(); // wait until pid appears for ( $i=0; $i<$action_retries && !file_exists($abs_pidfile); $i++ ) usleep ( $action_wait_timeout ); if ( !file_exists($abs_pidfile) ) { $error = "PID file ($abs_pidfile) was not created"; return 1; } // check for early crash $error = CheckSearchdLog ( $abs_error_file, $retval ); // on windows, searchd starts *fully* async // so lets also wait until pidfile gets real data // (meaning that index precaching is actually done) $STARTUP_TRIES = WaitRetries(); if ( $retval!=1 && $windows ) { $STARTUP_TICK = 50000; // msec // FIXME! add a better check that searchd is still alive than just file_exists for ( $i=0; $i<$STARTUP_TRIES && file_exists($abs_pidfile); $i++ ) { $pid = @file($abs_pidfile); if ( count($pid) ) break; usleep ( $STARTUP_TICK ); } } // lets wait when daemon is ready to accept connections if ( $retval==0 ) { if ( !$addr ) $addr = $sd_address; if ( !$port ) $port = $sd_port; $cl = new SphinxClient; $cl->SetServer ( $addr, $port ); $cl->SetConnectTimeout ( 10 ); $ok = false; $start = MyMicrotime(); for ( $i=0; $i<$STARTUP_TRIES; $i++ ) { if ( $cl->Open() ) { $cl->Close(); $ok = true; break; } usleep ( 500 ); } if ( !$ok ) { $tm = ( MyMicrotime() - $start ); printf ( "\nWARNING: can't connect to daemon on startup for %.3f sec\t\t\t\n", $tm ); } } if ( $retval==0 && !empty($error) ) $retval = 2; // no errors, but there were warnings return $retval; } function StopSearchd ( $config, $pidfile ) { global $action_wait_timeout; $ret = 0; $abs_config = testdir($config); $abs_pidfile = testdir($pidfile); $action_retries = ActionRetries(); if ( file_exists($abs_pidfile) && count(file($abs_pidfile)) ) { GetSearchd ($path, $error, false); $dummy = array(); exec ( "$path --config $abs_config --stopwait", $dummy, $ret ); $i = 0; while ( file_exists ( $abs_pidfile ) && $i < $action_retries ) { usleep ( $action_wait_timeout ); $i++; } // finally kill, since otherwise stacked daemon will ruine following tests if ( file_exists ( $abs_pidfile ) ) KillSearchd($config, $pidfile, 'KILL', true); } return $ret; } function StopWaitSearchd ( $config, $pidfile ) { return StopSearchd ( $config, $pidfile ); } function RestartDaemon ($no_warnings=false) { $stop = StopWaitSearchd ('config.conf', 'searchd.pid'); $status = 'stop=' . ( $stop==0 ? 'ok' : 'error' ) . ', return code=' . $stop; $start = StartSearchd ( 'config.conf', 'error.txt', 'searchd.pid', $error, array() ); if ( $start == 0 || $start == 2 ) { if ($no_warnings) $start = 0; $status .= "; start=ok" . ', return code=' . $start; if ( $start==2 ) $status .= ", error=" . $error; } else { $status .= "; start=failed, return code=" . $start . ", error=" . $error; } return $status; } function KillSearchd ( $config, $pidfile, $signal, $unlinkpid=True ) { global $action_wait_timeout, $windows; $abs_pidfile = testdir($pidfile); if ( file_exists($abs_pidfile) && count(file($abs_pidfile)) ) { $fp = fopen($abs_pidfile,"r"); $pid = fread ( $fp, filesize ( $abs_pidfile ) ); fclose ($fp); if ( $windows ) { if ( $signal=='KILL') exec ("taskkill /F /PID $pid"); else exec("kill -f -s $signal $pid"); } else exec ("kill -s $signal $pid"); if ( $unlinkpid && file_exists ( $abs_pidfile ) ) { usleep ( $action_wait_timeout ); unlink ( $abs_pidfile ); } } } function IsModelGenMode () { global $g_model; return $g_model; } function RandomWords ( $n, $seed ) { srand ( $seed ); $words = []; for ( $k=0; $k<$n; $k++ ) $words[] = substr ( str_shuffle ( 'abcdefghijklmnopqrstuvwxyz' ), 0, 5 ); return join ( " ", $words ); } function RoundFloatValues ( &$values, $roundoff ) { if ( !is_array ( $values ) ) return; foreach ( $values as &$value ) { if ( is_float ( $value ) ) $value = round ( $value, $roundoff ); if ( is_array ( $value ) ) RoundFloatValues ( $value, $roundoff ); } } function RemoveColumnarProperty ( $property ) { $props = explode ( " ", $property ); $key = array_search ( "columnar", $props ); if ( $key !== false ) unset ( $props[$key] ); $key = array_search ( "fast_fetch", $props ); if ( $key !== false ) unset ( $props[$key] ); return implode ( " ", $props ); } if (!function_exists('array_key_first')) { function array_key_first(array $arr) { foreach($arr as $key => $unused) return $key; return NULL; } } function CompareColumns ( $a, $b ) { return strcmp ( array_keys($a)[0], array_keys($b)[0] ); } function JsonRsetFixup ( &$set, $columnar, $keep_json_ctrls ) { if ( isset ( $set["rows"] ) ) { if ( $keep_json_ctrls ) { $json_handler = new SafeJsonHandler(); $rows = $json_handler->Decode ( $set["rows"], 1, 512, JSON_BIGINT_AS_STRING ); } else $rows = json_decode ( $set["rows"], 1, 512, JSON_BIGINT_AS_STRING ); if ( isset ( $rows["hits"] ) && isset ( $rows["hits"]["hits"] ) ) { foreach ( $rows["hits"]["hits"] as &$hit ) { RoundFloatValues ( $hit, 6 ); if ( isset ( $hit["_source"] ) ) ksort ( $hit["_source"] ); } } $set["rows"] = $keep_json_ctrls ? $json_handler->Encode ( $rows ) : json_encode ( $rows ); } if ( isset ( $set["http_endpoint"] ) && ( $set["http_endpoint"]=="sql" || $set["http_endpoint"]=="cli" || $set["http_endpoint"]=="cli_json" ) && isset ( $set["rows"] ) ) { if ( $keep_json_ctrls ) { $json_handler = new SafeJsonHandler(); $rows = $json_handler->Decode ( $set["rows"], 1, 512, JSON_BIGINT_AS_STRING ); } else $rows = json_decode ( $set["rows"], 1, 512, JSON_BIGINT_AS_STRING ); foreach ( $rows as &$row ) { if ( isset ( $row["data"] ) ) { foreach ( $row["data"] as &$entry ) { if ( is_array($entry) && isset ( $entry["Properties"] ) && $columnar ) $entry["Properties"] = RemoveColumnarProperty ( $entry["Properties"] ); } } if ( isset ( $row["columns"] ) ) usort ( $row['columns'], function($a, $b) { return strcmp ( array_key_first($a), array_key_first($b) ); } ); } $set["rows"] = $keep_json_ctrls ? $json_handler->Encode ( $rows ) : json_encode ( $rows ); } } function SqlRsetFixup ( &$set, $columnar ) { if ( !isset ( $set["rows"] ) ) return; foreach ( $set["rows"] as &$row ) { if ( count($row)!=3 ) continue; $keys = array_keys($row); if ( count($keys)!=3 ) return; if ( $keys[0]!='Field' || $keys[1]!='Type' || $keys[2]!='Properties' ) return; if ( $columnar ) $row['Properties'] = RemoveColumnarProperty ( $row['Properties'] ); } } function ChildrenArray ( $node, $name="" ) { $res = array (); if ( !empty($node) && $node->hasChildNodes() ) for ( $i=0; $i<$node->childNodes->length; $i++ ) { $child = $node->childNodes->item ( $i ); if ( $name=="" || strtolower($child->nodeName)==$name ) $res[] = $child; } return $res; } function NextState ( &$iter, &$limits, $ps ) { if ( $ps>count($limits) ) return; ++$iter[$ps]; if ( $iter[$ps]>=$limits[$ps]) { $iter[$ps]=0; NextState ($iter,$limits,$ps+1); } } function AttrArray ( $node, $name="" ) { $res = array (); if ( !empty($node) && $node->hasAttributes() ) for ( $i=0; $i<$node->attributes->length; $i++ ) { $child = $node->attributes->item ( $i ); if ( $name=="" || strtolower($child->nodeName)==$name ) $res[] = $child; } return $res; } function GetfirstAttr ( $node ) { if ( !empty($node) && $node->hasAttributes() ) return $node->attributes->item (0); return NULL; } function GetFirstChild ( $node, $name ) { $children = ChildrenArray ( $node, $name ); return empty($children) ? NULL : $children[0]; } function GetFirstChildValue ( $node, $name, $default="" ) { $child = GetFirstChild ( $node, $name ); return is_null($child) ? $default : $child->nodeValue; } function ArrVal ( $var, $name, $default="" ) { if ( array_key_exists ( $name, $var ) ) return $var[$name]; return $default; } function ArrVals ( $var, $name, $delimiter=" " ) { if ( array_key_exists( $name, $var) ) return explode($delimiter, $var[$name]); else return array(); } function TouchVal ( &$var, $name, $default="" ) { if ( !array_key_exists ( $name, $var ) ) $var[$name] = $default; } function ConnectSpecificQL($agent, $vip=false) { global $agents; $address = $agents[$agent]["address"]; if ( $vip ) $port = $agents[$agent]["sqlport_vip"]; else $port = $agents[$agent]["sqlport"]; // echo "Connecting to agent $address:$port\n"; if ($address == "localhost") $address = "127.0.0.1"; mysqli_report(MYSQLI_REPORT_OFF); return @mysqli_connect ( $address, '', '', '', $port ); } function ConnectQL() { return ConnectSpecificQL(0); } class QLClient { private $_conn = false; function Disconnect() { if ($this->_conn!==false) @mysqli_close($this->_conn); } function Connect() { $this->_conn = ConnectQL(); return $this->_conn!==false; } function Reconnect() { $this->Disconnect(); return $this->Connect(); } function Query($q) { if ($this->_conn===false) return "NOT CONNECTED"; $r = @mysqli_query($this->_conn, $q); if (!$r) return "ERROR: ".mysqli_error($this->_conn); if ( $r===true ) return "OK"; $n = 0; $res = ""; while ($row = mysqli_fetch_row($r)) { $res .= join(" | ", $row) . "\n"; $n++; } $res .= "$n rows"; return $res; } function SetConnection($conn) { $this->_conn = $conn; } } class APIClient extends SphinxClient { function XQuery ( $query, $index="*", $comment="" ) { $res = $this->Query($query, $index, $comment); if ($res===false) return $this->GetLastError(); unset($res["time"]); return $res; } function XUpdateAttributes ( $index, $attrs, $values, $type=SPH_UPDATE_INT, $ignorenonexistent=false ) { $res = $this->UpdateAttributes ( $index, $attrs, $values, $type, $ignorenonexistent ); if ($res===-1) return $this->GetLastError(); return $res; } } function FormatJsonRow ( $j ) { if ( !is_array ( $j ) || !count($j) ) { return "[]\n"; } $str = "[\n"; $row_sep = ""; foreach ( $j as $row ) { $str .= "$row_sep\t"; $str .= json_encode ( $row, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); $row_sep = ",\n"; } $str .= "]"; return $str; } // avoiding json errors in case json being processed contains control characters class SafeJsonHandler { private $replaces = []; function Decode ( $json, $assoc=false, $depth=512, $flags=0 ) { $this->replaces = [ "from" => '%', "to" => [] ]; $matches = []; preg_match_all( '/[[:cntrl:]]/', $json, $matches); if ( !empty( $matches ) ) { $this->replaces["to"] = $matches[0]; // finding a safe replace token $from0 = $this->replaces["from"]; while ( strpos( $json, $this->replaces["from"] ) !== false ) { $this->replaces["from"] .= $from0; } $json = preg_replace( '/[[:cntrl:]]/', $this->replaces["from"], $json ); } return json_decode ( $json, $assoc, $depth, $flags ); } function Encode ( $json_obj, $flags=0, $depth=512 ) { $json = json_encode ( $json_obj, $flags, $depth ); if ( !empty( $this->replaces ) && !empty( $this->replaces["to"] ) ) { $from = $this->replaces["from"]; foreach( $this->replaces["to"] as $to ) { $to_encoded = substr( json_encode($to, $flags, $depth), 1, -1 ); $json = preg_replace( "/$from/", $to_encoded, $json, 1 ); } } return $json; } } function HttpFormatResultSet ( $result, $nquery, $keep_json_ctrls=false ) { $str = ''; $http_endpoint = ''; $http_request = ''; $http_method = ''; $http_code = ''; $rows = array(); $attrs = array(); $matches = array(); $meta = array(); $agent = ''; if ( array_key_exists ( 'http_endpoint', $result ) ) $http_endpoint = $result['http_endpoint']; if ( array_key_exists ( 'http_request', $result ) ) $http_request = $result['http_request']; if ( array_key_exists ( 'http_method', $result ) ) $http_method = $result['http_method']; if ( array_key_exists ( 'http_code', $result ) ) $http_code = $result['http_code']; if ( array_key_exists ( 'rows', $result ) ) { if ( $keep_json_ctrls ) { $json_handler = new SafeJsonHandler(); $rows = $json_handler->Decode ( $result['rows'], 1, 512, JSON_BIGINT_AS_STRING ); } else $rows = json_decode ( $result['rows'], 1, 512, JSON_BIGINT_AS_STRING ); } if ( array_key_exists ("agent", $result ) ) $agent =" (agent-" . $result["agent"] . ")" ; $request = json_encode ( $http_request, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); $request = stripcslashes ( $request ); $str .= "http-$nquery$agent> /$http_endpoint\n"; $str .= "Status: $http_code\n"; $str .= "$http_method ". $request . "\n"; if ( count ( $rows ) ) $str .= ( $keep_json_ctrls ? $json_handler->Encode ( $rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) : json_encode ( $rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) )."\n"; $str .= "\n"; return $str; } function RunCurl ( $curl_desc, &$rows ) { $con = curl_init(); curl_setopt_array ( $con, $curl_desc ); $rows = curl_exec ( $con ); $rows = preg_replace('/"time":\d+(\.\d+)*,/', '"time":0.000,', $rows); $http_code = curl_getinfo ( $con, CURLINFO_HTTP_CODE ); curl_close($con); return $http_code; } function HttpQueryCurl ( $http_method, $http_endpoint, $http_content, $http_query, $use_agent, $use_ssl, $use_gzip, $testdir ) { global $agents; $ssl = $use_ssl ? "https://" : ""; $http_port = $agents[$use_agent]["http_port"]; $curl_desc = array ( CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT=>1, CURLOPT_URL => $ssl . "127.0.0.1:$http_port/" . $http_endpoint ); if ( $http_method=="POST" ) { $curl_desc[CURLOPT_POST] = 1; $curl_desc[CURLOPT_POSTFIELDS] = $http_query; } else if ( $http_method=="PUT" ) { $curl_desc[CURLOPT_CUSTOMREQUEST] = "PUT"; $curl_desc[CURLOPT_POSTFIELDS] = $http_query; } else { $curl_desc[CURLOPT_URL] = $curl_desc[CURLOPT_URL] . '?' . $http_query; } if ( $use_ssl ) { $curl_desc[CURLOPT_SSL_VERIFYPEER] = false; $curl_desc[CURLOPT_SSL_VERIFYHOST] = false; $curl_desc[CURLOPT_SSLVERSION] = CURL_SSLVERSION_DEFAULT; //$curl_desc[CURLOPT_VERBOSE] = true; // !COMMIT } if ( $http_content!==NULL ) $curl_desc[CURLOPT_HTTPHEADER] = array("Content-Type: ".$http_content); if ( $use_gzip && $http_method=="POST" ) { $cfile = file_get_contents( $testdir . "/" . $http_query ); $curl_desc[CURLOPT_ENCODING] = 'gzip'; $curl_desc[CURLOPT_POSTFIELDS] = $cfile; $http_headers = array("Content-Encoding:gzip"); if ( $http_content!==NULL ) $http_headers[] = "Content-Type: ".$http_content; $curl_desc[CURLOPT_HTTPHEADER] = $http_headers; //$curl_desc[CURLOPT_VERBOSE] = 1; //var_dump ( $curl_desc ); } $rows = ""; $http_code = RunCurl( $curl_desc, $rows ); return array ( 'http_endpoint'=>$http_endpoint, 'http_method'=>$http_method, 'http_request'=>$http_query, 'rows'=>$rows, 'http_code'=>$http_code, 'http'=>1 ); } // these two used from custom tests function HttpQueryGet ( $http_endpoint, $http_content, $http_get, $use_agent, $use_ssl ) { $res = HttpQueryCurl ( "GET", $http_endpoint, $http_content, $http_get, $use_agent, $use_ssl, false, '' ); unset ( $res['http'] ); return $res; } function HttpQueryPost ( $http_endpoint, $http_content, $http_get, $use_agent, $use_ssl ) { $res = HttpQueryCurl ( "POST", $http_endpoint, $http_content, $http_get, $use_agent, $use_ssl, false, '' ); unset ( $res['http'] ); return $res; } function GetJsonError() { switch (json_last_error()) { case JSON_ERROR_NONE: return 'no errors'; case JSON_ERROR_DEPTH: return 'maximum stack depth exceeded'; case JSON_ERROR_STATE_MISMATCH: return 'underflow or the modes mismatch'; case JSON_ERROR_CTRL_CHAR: return 'unexpected control character found'; case JSON_ERROR_SYNTAX: return 'syntax error, malformed JSON'; case JSON_ERROR_UTF8: return 'malformed UTF-8 characters, possibly incorrectly encoded'; } return 'unknown error'; } function GetAttrs ($node) { $vals = array (); if (!$node->attributes) return $vals; $len = $node->attributes->length; if ( $len == 0 ) return $vals; foreach( AttrArray( $node ) as $attr ) $vals[$attr->nodeName]=$attr->nodeValue; return $vals; } function ParseRange ( $range ) { if ( !$range ) return false; $values = explode ( ' ', $range ); if ( count($values) != 2 ) { printf ( "ERROR: malformed range attribute: '%s'\n", $range ); return false; } return array ( 'min' => $values[0], 'max' => $values[1] ); } function ParseIndexWeights ( $weights ) { if ( !$weights ) return false; $result = array(); preg_match_all ( '/([^\s]+):(\d+)/', $weights, $matches, PREG_SET_ORDER ); foreach ( $matches as $match ) $result [ $match[1] ] = (int)$match[2]; return $result; } function close_and_null_conn (&$connection) { if ($connection) mysqli_close($connection); $connection = NULL; } function result_must_be_skipped ( $result ) { return ( array_key_exists('skip', $result) && $result['skip']>0 ); } function result_must_not_be_displayed ($result) { if ( array_key_exists ("comment", $result) ) return @$result['hide']==1; return @$result['skip']==1; } class SphinxConfig { private $_name; private $_db_create; private $_db_drop; private $_db_insert; private $_custom_insert; private $_counters; private $_dynamic_entries; private $_queries; private $_vars; private $_sphqueries; private $_query_settings; private $_query_attributes; private $_indexer_runs; private $_custom_test; private $_sd_address; private $_sd_log; private $_sd_port; private $_sd_sphinxql_port; private $_sd_http_port; private $_sd_sphinxql_port_vip; private $_sd_replication_port; private $_sd_pid_file; private $_num_agents; private $_subtest; private $_subtestcount; private $_results; public $_results_model; public $_shadow_results_model; private $_prereqs; private $_config; ///< config DOM node private $_indexdata; ///< data for use "insert into" instead of run indexer private $_connection; ///< mysql connection (since we cound use mysql ans sqphinxql together) private $_testdir; ///< the path to the directory with current test (namely for accessing data without knowing the test name) private $_compat098; private $_skip_indexer; function SetConnection ( $connection ) { $this->_connection = $connection; } function __construct() { global $sd_address, $sd_port, $sd_sphinxql_port, $sd_pid_file, $sd_http_port, $sd_sphinxql_port_vip, $sd_replication_port; $this->_counters = array (); $this->_dynamic_entries = array (); $this->_queries = array (); $this->_vars = array (); $this->_sphqueries = array (); $this->_results = array (); $this->_results_model = array (); $this->_shadow_results_model = array (); $this->_query_attributes = array (); $this->_indexer_runs = array (); $this->_db_create = array (); $this->_db_drop = array (); $this->_db_insert = array (); $this->_custom_insert = array (); $this->_num_agents = 1; $this->_subtest = 0; $this->_subtestcount = 0; $this->_sd_address = $sd_address; $this->_sd_port = $sd_port; $this->_sd_sphinxql_port = $sd_sphinxql_port; $this->_sd_http_port = $sd_http_port; $this->_sd_sphinxql_port_vip= $sd_sphinxql_port_vip; $this->_sd_replication_port = $sd_replication_port; $this->_sd_pid_file = $sd_pid_file; $this->_custom_test = ""; $this->_compat098 = false; $this->_skip_indexer = false; $this->_indexdata = array (); $this->_connection = false; $this->_testdir = ""; } function EnableCompat098 () { $this->_compat098 = true; } function SubtestNo () { return $this->_subtest; } function SubtestCount () { return $this->_subtestcount; } function Name () { return $this->_name; } function DB_Drop () { return $this->_db_drop; } function DB_Create () { return $this->_db_create; } function DB_Insert () { return $this->_db_insert; } function DB_CustomInsert () { return $this->_custom_insert; } function NumAgents () { return $this->_num_agents; } function AddressAPI () { return $this->_sd_address; } function Port () { return $this->_sd_port; } function Requires ( $name ) { return isset($this->_prereqs[$name]); } function IsQueryTest () { return strlen ( $this->_custom_test ) == 0; } function IsNeedDB() { return ! ( empty ( $this->_db_drop ) && empty ( $this->_db_create ) && empty ( $this->_db_insert ) ); } function IsRt() { global $g_locals; if ( !array_key_exists ('rt_mode', $g_locals) ) return false; return $g_locals['rt_mode']; } function IsColumnar() { global $g_locals; if ( !array_key_exists ('columnar_mode', $g_locals) ) return false; return $g_locals['columnar_mode']; } function NeedIndexerEx () { return count ( $this->_indexer_runs ) > 0; } function Results () { return $this->_results; } function GetQuery ( $i ) { return $this->_queries[$i]; } function IsSkipIndexer () { return $this->_skip_indexer; } function ResetResults () { $this->_results = array (); } function SetTestDir ( $dir ) { $this->_testdir = str_replace ( "\\", "/", $dir ); } function GetLocal ( $key ) { global $g_locals; if ( !array_key_exists ( $key, $g_locals ) ) { printf ( "FATAL: unbound local variable '%s' (go add it at ~/.sphinx).\n", $key ); exit ( 1 ); } return $g_locals[$key]; } function CreateNextConfig () { return $this->GenNextCfg ( 0 ); } function SubtestFinished () { $this->_subtest++; } function SubtestFailed () { $this->_subtest++; $failed = array (); array_push ( $failed, "failed" ); if ( IsModelGenMode () ) array_push ( $this->_results_model, $failed ); array_push ( $this->_shadow_results_model, $failed ); } function ModelSubtestFailed () { $failed = array (); array_push ( $failed, "failed" ); return $this->_results_model [$this->SubtestNo ()] == $failed; } function SetAgent ( $agent, $i ) { if ( !is_array ( $agent ) ) return; if ( $i>0 ) $this->_sd_log = "searchd$i.log"; else $this->_sd_log = "searchd.log"; $this->_sd_address = $agent ["address"]; $this->_sd_port = $agent ["port"]; $this->_sd_sphinxql_port = $agent ["sqlport"]; $this->_sd_sphinxql_port_vip = $agent ["sqlport_vip"]; $this->_sd_replication_port = $agent ["replication_port"]; $this->_sd_http_port = $agent["http_port"]; } function SetPIDFile ( $pidfile ) { $this->_sd_pid_file = $pidfile; } function GenNextCfg ( $i ) { if ( count ( $this->_dynamic_entries ) == 0 ) return FALSE; $num_variants = count ( ChildrenArray ( $this->_dynamic_entries[$i], "variant" ) ); if ( $this->_counters [$i] == $num_variants - 1 ) { if ( $i == count ( $this->_dynamic_entries ) - 1 ) return FALSE; else { $this->_counters [$i] = 0; return $this->GenNextCfg ( $i + 1 ); } } else $this->_counters [$i]++; return TRUE; } function WriteCustomTestResults ( $fp ) { $res_fmt = $this->FormatResultSet ( 0, $this->_results ); fwrite ( $fp, $res_fmt ); } function GatherEntities ( $node, &$array ) { foreach ( ChildrenArray($node) as $child ) if ( $child->nodeType == XML_ELEMENT_NODE ) array_push ( $array, $child->nodeValue ); } function GatherNodes ( $node ) { if ( $node->nodeType != XML_TEXT_NODE && $node->nodeType != XML_DOCUMENT_NODE && strtolower ( $node->nodeName ) == "dynamic" ) { $count = count ( $this->_dynamic_entries ); $node->setAttribute ( "count", $count ); array_push ( $this->_dynamic_entries, $node ); array_push ( $this->_counters, 0 ); } for ( $i = 0; !is_null ( $node->childNodes ) && $i < $node->childNodes->length; $i++ ) $this->GatherNodes ( $node->childNodes->item ( $i ) ); } function FormatVar ($nodename, $attrs) { if ( array_key_exists ( 'format', $attrs ) ) return sprintf($attrs['format'], $this->_vars[$nodename]); return $this->_vars[$nodename]; } function GenerateQueryText ( $node ) { global $agents; $result = ""; $attrs = GetAttrs($node); $nodename = strtolower ( $node->nodeName ); switch ( $nodename ) { case "#text": return $node->nodeValue; case "#cdata-section": return $node->nodeValue; case "static": return $node->nodeValue; case "this_test": return $this->_testdir; case "agent0_address": return $agents[0]["address"].":".$agents[0]["port"]; case "agent1_address": return $agents[1]["address"].":".$agents[1]["port"]; case "agent2_address": return $agents[2]["address"].":".$agents[2]["port"]; } if ( array_key_exists ($nodename, $this->_vars) ) return $this->FormatVar($nodename, $attrs); foreach ( ChildrenArray($node) as $child ) $result.= $this->GenerateQueryText ( $child ); return $result; } function GenerateQueryTextWithComments ( $node ) { $results = array(); $result = ''; foreach ( ChildrenArray($node) as $child ) if ( $child->nodeName === '#comment' ) { if ( trim($result)!='' ) $results[]= array ( true, $result ); $results[]= array ( false, $child->nodeValue ) ; $result = ''; } else $result .= $this->GenerateQueryText ( $child ); if ( trim($result)!='' ) $results[]= array ( true, $result ); return $results; } function AddAPIUpdate ($mode, $res) { $res['mode'] = $mode; $json = $res['query'][0]; $upd = json_decode ($json, true); $res['query'] = $upd; $res['type'] = 'apiupdate'; $this->_queries[] = $res; return true; } function AddAPIQuery ($q, $encoding) { $res = GetAttrs ($q); // add query if ( array_key_exists ( "source", $res) ) { $source = $res["source"]; if ( substr ( $source, 0, 6 ) == "local:" ) $source = $this->GetLocal ( substr ( $source, 6 ) ); if ( !is_readable($source) ) { printf ( "FATAL: query source file '%s' not found.\n", $source ); exit ( 1 ); } $queries = file ( $source, FILE_IGNORE_NEW_LINES ); $limit = $this->GetLocal('qlimit'); $res["query"] = $limit ? array_slice( $queries, 0, $limit ) : $queries; } else $res["query"] = array ( from_utf8 ( $encoding, $q->nodeValue ) ); // parse query mode $mode = 0; $mode_s = ArrVal ($res,"mode"); switch ( $mode_s ) { case "": $mode_s = "(default)"; break; case "all": $mode = SPH_MATCH_ALL; break; case "any": $mode = SPH_MATCH_ANY; break; case "phrase": $mode = SPH_MATCH_PHRASE; break; case "extended": $mode = SPH_MATCH_EXTENDED; break; case "extended2": $mode = SPH_MATCH_EXTENDED2; break; case "fullscan": $mode = SPH_MATCH_FULLSCAN; break; case 'update_int': return $this->AddAPIUpdate (SPH_UPDATE_INT, $res ); case 'update_mva': return $this->AddAPIUpdate (SPH_UPDATE_MVA, $res ); case 'update_string': return $this->AddAPIUpdate (SPH_UPDATE_STRING, $res ); case 'update_json': return $this->AddAPIUpdate (SPH_UPDATE_JSON, $res ); default: return "unknown matching mode '" . $mode_s . "'"; } $res["mode"] = $mode; $res["mode_s"] = $mode_s; // parse ranker $ranker = 0; $ranker_s = ArrVal ($res, "ranker"); if ( empty($ranker_s) ) { $ranker_s = "(default)"; } else { $ranker = @constant("SPH_RANK_" . strtoupper($ranker_s)); if ( $ranker===NULL ) return "unknown ranker '" . $ranker_s . "'"; } $res["ranker"] = $ranker; $res["ranker_s"] = $ranker_s; // parse filter // TouchVal ( $res, "filter"); // TouchVal ( $res, "filter_value"); if ( @$res['filter_range']) $res["filter_range"] = ParseRange ($res["filter_range"]); // TouchVal ( $res, "filter_str"); // TouchVal ( $res, "filter_exclude"); // parse sort mode and get clause $sortmode = 0; $sortmode_s = ArrVal ($res,"sortmode"); switch ( $sortmode_s ) { case "": $sortmode_s = "(default)"; break; case "extended": $sortmode = SPH_SORT_EXTENDED; break; case "expr": $sortmode = SPH_SORT_EXPR; break; case "attr_asc": $sortmode = SPH_SORT_ATTR_ASC; break; case "attr_desc": $sortmode = SPH_SORT_ATTR_DESC; break; default: return "unknown sorting mode '" . $sortmode_s . "'"; } $res["sortmode"] = $sortmode; $res["sortmode_s" ] = $sortmode_s; TouchVal ( $res, "sortby"); // groupby $groupfunc = 0; $groupfunc_s = ArrVal ($res,"groupfunc"); switch ( $groupfunc_s ) { case "": $groupfunc = SPH_GROUPBY_ATTR; $groupfunc_s = "attr"; break; case "day": $groupfunc = SPH_GROUPBY_DAY; break; case "week": $groupfunc = SPH_GROUPBY_WEEK; break; case "month": $groupfunc = SPH_GROUPBY_MONTH; break; case "year": $groupfunc = SPH_GROUPBY_YEAR; break; case "attr": $groupfunc = SPH_GROUPBY_ATTR; break; case "attrpair": $groupfunc = SPH_GROUPBY_ATTRPAIR; break; default: return "unknown groupby func '" . $groupfunc_s . "'"; } $res["groupfunc"] = $groupfunc; $res["groupfunc_s"] = $groupfunc_s; // TouchVal ( $res, "groupattr"); TouchVal ($res,"groupsort", "@group desc"); // TouchVal ($res,"groupdistinct"); // TouchVal ($res,"resarray"); TouchVal ($res,"index", "*"); // TouchVal ($res,"select"); if (@$res["index_weights"] ) @$res["index_weights"] = ParseIndexWeights ( $res["index_weights"]); TouchVal ($res,"roundoff"); // TouchVal ($res,"tag"); // TouchVal ($res,"cutoff"); // TouchVal ($res,"limits"); $res['type'] = 'api'; $this->_queries[] = $res; return true; } function AddRepeatComment ($attrs) { $skip = (int)ArrVal ($attrs, "skip", 0); $comment = 'repeat '; foreach ($attrs as $name => $value) $comment .= "$name=\"$value\" "; $this->_queries[] = array( 'query' => trim($comment), 'attrs' => $attrs, 'type' => 'comment', 'hide' => $skip ); } function RepeatedlyAddQuery ($repeat, $addcomment, $cb) { $attrs = GetAttrs($repeat); if ($addcomment) $this->AddRepeatComment($attrs); $delimiter = ArrVal ($attrs, "delimiter", " "); $variants = ArrVals($attrs, "variants", $delimiter); if (!empty($variants)) { // varianted query: <repeat var="foo" variants="a b c> - 3 times repeat with foo=a, foo=b, foo=c $var = ArrVal($attrs, "var", "_"); foreach ($variants as $variant) { $this->_vars[$var] = $variant; foreach ( ChildrenArray ( $repeat ) as $q ) $cb($q); } return; } $count = (int)ArrVal ($attrs, "count", 1); $vars = ArrVals($attrs, "vars", $delimiter); $inits = ArrVals($attrs, "init", $delimiter); $increments = ArrVals($attrs, "inc", $delimiter); // set initial values of vars foreach ($inits as $idx=>$init) $this->_vars[$vars[$idx]] = $init; for ($i=0; $i<$count; ++$i) { foreach ( ChildrenArray ( $repeat ) as $q ) $cb($q); // set next values foreach ($increments as $idx=>$inc) $this->_vars[$vars[$idx]] += $inc; } } function PopulateVar ($var,$cb) { $attrs = GetAttrs($var); $name = ArrVal($attrs, "name" ); $delimiter = ArrVal ($attrs, "delimiter", null); $exists = array_key_exists ( $name, $this->_vars ) && $this->_vars[$name]!==''; $val = trim($cb($var)); if ( !$exists || $delimiter===null ) $this->_vars[$name] = $val; else $this->_vars[$name] .= $delimiter . $val; } function ExposeMetaIndexes ($q, $attrs, $lowername, $metaindexes) { $was_replaced = false; if ( !empty($metaindexes) ) foreach ( $metaindexes as $name=>$indexes ) foreach ($indexes as $index) { $foo = 0; $res = str_replace ( $name, $index, $q, $foo ); if ($foo>0) { $was_replaced = true; $this->_queries[]=array ( "query" => $res, "attrs" => $attrs, "type" => $lowername); } } if (!$was_replaced) // no metaindexes; emit 'as is' { $this->_queries[] = array ( "query" => $q, "attrs" => $attrs, "type" => $lowername); } } function AddQuery ( $q, $encoding, $metaindexes ) { $lowername = strtolower($q->nodeName); $attrs = GetAttrs($q); switch ( $lowername ) { case 'query': if (empty(@$attrs['endpoint'])) // that is API query return $this->AddAPIQuery($q, $encoding); break; case 'sphinxql': break; case 'comment': $this->_queries[] = array ( "query" => from_utf8 ( $encoding, trim($this->GenerateQueryText($q))), "attrs" => $attrs, "type" => 'comment'); return; case '#comment': $this->_queries[] = array ( "query" => from_utf8 ( $encoding, trim($q->nodeValue)), "attrs" => $attrs, "type" => 'comment'); return; case 'repeat': $this->RepeatedlyAddQuery($q, true, function($q) use( $encoding, $metaindexes ) { $this->AddQuery ( $q, $encoding, $metaindexes ); } ); return; case 'var': $this->PopulateVar($q,function($foo) { return $this->GenerateQueryText ($foo); }); return; case 'bulk': // bulk as is { $this->_queries[] = array ( "query" => from_utf8 ( $encoding, $q->nodeValue ), "attrs" => $attrs, "type" => 'query'); return; } default: return; } $query_chunks = $this->GenerateQueryTextWithComments ( $q ); if ( empty ($query_chunks)) $this->_queries[] = array ( "query" => "", "attrs" => $attrs, "type" => $lowername); foreach ($query_chunks as $query_chunk) { if ( !$query_chunk[0] ) // 0-th is bool 'statement/comment' { $this->_queries[] = array ( "query" => from_utf8 ( $encoding, $query_chunk[1]), "attrs" => $attrs, "type" => 'comment'); continue; } $query_texts = preg_split ( "/;\n\s*/", $query_chunk[1], -1, PREG_SPLIT_NO_EMPTY ); foreach ($query_texts as $query_text) $this->ExposeMetaIndexes (from_utf8( $encoding, trim($query_text)), $attrs, $lowername, $metaindexes); } } function AddQueries ( $queries, $encoding, $metaindexes ) { foreach ( ChildrenArray ( $queries ) as $q ) $this->AddQuery ( $q, $encoding, $metaindexes ); } function ExtractQueries ( $node, $encoding, $metaindexes ) { if ( !empty($node) && $node->hasChildNodes() ) for ( $i=0; $i<$node->childNodes->length; $i++ ) { $child = $node->childNodes->item ( $i ); $lowername = strtolower($child->nodeName); if ( $lowername=="sphqueries" || $lowername=="httpqueries") $this->AddQueries ( $child, $encoding, $metaindexes ); } } function AddDbInsertClause ($q, $encoding) { $q = trim ($q); if ($q!='') $this->_db_insert [] = from_utf8 ($encoding, $q); } function AddDbInsertNode( $q, $encoding, &$accum ) { $lowername = strtolower($q->nodeName); switch ( $lowername ) { case 'repeat': $this->RepeatedlyAddQuery($q, false, function($foo) use( $encoding, &$accum ) { $this->AddDbInsertNode ( $foo, $encoding, $accum ); } ); return; case 'db_insert': $this->AddDbInsertClause($accum,$encoding); $accum=''; return; case 'var': $this->PopulateVar($q,function($foo) { return $this->GenerateQueryText ($foo); }); return; default: $accum .= $this->GenerateQueryText ($q); } } function AddDbInsert( $queries, $encoding ) { $accum=""; foreach ( ChildrenArray ( $queries ) as $q ) $this->AddDbInsertNode ( $q, $encoding, $accum ); $this->AddDbInsertClause($accum,$encoding); } function Load ( $config_file ) { // load the file $doc = new DOMDocument ( "1.0" ); if ( !$doc->load ( $config_file ) ) return false; // check for proper root node if ( !$doc->hasChildNodes() ) return false; $xml = $doc->childNodes->item(0); if ( strtolower($xml->nodeName)!="test" ) return false; $custom = GetFirstChild ( $xml, "custom_test" ); if ( $custom ) { $this->_custom_test = $custom->nodeValue; if ( $doc->encoding != 'utf-8' ) $this->_custom_test = from_utf8 ( $doc->encoding, $this->_custom_test ); } // extract indexer run params $indexer_run = GetFirstChild ( $xml, "indexer" ); if ( $indexer_run ) { foreach ( ChildrenArray ( $indexer_run, "run" ) as $run ) $this->_indexer_runs [] = $run->nodeValue; } // extract meta-indexes $metaindexes = array(); foreach ( ChildrenArray ( $xml, "metaindex" ) as $meta ) { $tmp = array(); foreach ( ChildrenArray ( $meta, "index") as $idx ) $tmp[] = from_utf8 ( $doc->encoding, $idx->nodeValue ); $name = GetFirstAttr ( $meta ); $metaindexes[$name->nodeValue] = $tmp; } // extract queries $qs = GetFirstChild ( $xml, "queries" ); if ( $qs ) { // new and cool - everything in <queries>. // <query endpoint=...> - as http, <sphinxql...> - as sphinxql, // rest <query...> - as api. // also <comment...> is suitable here (copied directly into report, doesn't affect result matching) $this->AddQueries ( $qs, $doc->encoding, $metaindexes ); } else { // legacy $qs = array (); $this->GatherEntities ( GetFirstChild ( $xml, "query" ), $qs ); foreach ( $qs as $q ) { $this->_queries[] = array ( "query" => array ( $q ), "mode" => 0, "mode_s" => '(default)', "ranker" => 0, "ranker_s" => '(default)', "index" => '*', "type" => 'api' ); } } // old fashion: sphinxql are in <sphqueries>, http are in <httpqueries> $this->ExtractQueries ( $xml, $doc->encoding, $metaindexes ); // extract my settings $this->_config = GetFirstChild ( $xml, "config" ); $this->GatherNodes ( $this->_config ); $this->GatherEntities ( GetFirstChild ( $xml, "query_attributes" ), $this->_query_attributes ); foreach ( ChildrenArray ( $xml, "db_create" ) as $node ) $this->_db_create []=$node->nodeValue; foreach ( ChildrenArray ( $xml, "db_drop" ) as $node ) $this->_db_drop []=$node->nodeValue; foreach ( ChildrenArray ( $xml, "db_insert" ) as $node ) $this->AddDbInsert ( $node, $doc->encoding ); foreach ( ChildrenArray ( $xml, "custom_insert" ) as $node ) $this->_custom_insert []=$node->nodeValue; $this->_name = GetFirstChildValue ( $xml, "name" ); $this->_query_settings = GetFirstChildValue ( $xml, "query_settings" ); $this->_num_agents = GetFirstChildValue ( $xml, "num_agents", 1 ); $this->_skip_indexer = GetFirstChildValue ( $xml, "skip_indexer", GetFirstChildValue ( $xml, "skip-indexer", false ) ); $this->_prereqs = array(); $prereqs = GetFirstChild ( $xml, "requires", false ); if ( $prereqs ) foreach ( ChildrenArray ( $prereqs ) as $node ) $this->_prereqs [ $node->nodeName ] = 1; // precalc subtests count $this->_subtestcount = 1; foreach ( $this->_dynamic_entries as $entry ) { $variants = count ( ChildrenArray ( $entry, "variant" ) ); $this->_subtestcount *= max ( $variants, 1 ); } return true; } function RunIndexerEx ( &$error ) { foreach ( $this->_indexer_runs as $param ) { $retval = RunIndexer ( $error, $param ); if ( $retval != 0 ) return $retval; } return 0; } function FixupAgentAddress ( $s ) { global $agents; $tr = array( $agents[0]["address"].":".$agents[0]["port"] => "<AGENT0_ADDRESS/>", $agents[1]["address"].":".$agents[1]["port"] => "<AGENT1_ADDRESS/>", $agents[2]["address"].":".$agents[2]["port"] => "<AGENT2_ADDRESS/>" ); return strtr ( $s, $tr ); } function FixupErrorMessage ( $err, $s ) { $s = $this->FixupAgentAddress ( $s ); if ($err!=1064) $s = preg_replace ( '/or \d+ other tokens/', 'or N other tokens', $s ); else $s = preg_replace ( [ '/error when sending data: WSA error 10057/', // windows '/connect and query timed out/', // also windows '/receiving failure .*$/', // linux (errno 111) and mac (errno 64) '/end of file/', // fresh bison from homebrew emits 'end of file' instead of '$end', '/(.* error: no AF_INET address found for:.*, error)(.*)/', '/(.*)(; in \d* retries within [0-9]*[.][0-9]+ sec)/', '/(.*\: file not found\: )(.*)/' ], [ "receiving failure (refused or timedout, substituted)", "receiving failure (refused or timedout, substituted)", "receiving failure (refused or timedout, substituted)", "\$end", "$1: substituted", "$1", "$1 substituted" ], $s ); return $s; } function FixupWarningMessage ( $s ) { if ( strpos ( strtolower ( $s ), 'warning' ) !== false ) $s = $this->FixupAgentAddress ( $s ); return $s; } function PickResult ( $query_result ) { array_push($this->_results, $query_result); if ( !result_must_be_skipped($query_result)) { if (IsModelGenMode()) $this->_results_model[$this->SubtestNo()][] = $query_result; $this->_shadow_results_model[$this->SubtestNo()][] = $query_result; } } function PickResults( $query_results ) { $this->_results = $query_results; if ( IsModelGenMode () ) array_push ( $this->_results_model, $query_results ); array_push ( $this->_shadow_results_model, $query_results ); } function FixupJsonTimeAndFloats ( &$query_result, &$error, $keep_json_ctrls=false ) { if ( !array_key_exists ( 'rows', $query_result ) ) return true; if ( $keep_json_ctrls ) { $json_handler = new SafeJsonHandler(); $decoded_rows = $json_handler->Decode ( $query_result['rows'], null, 512, JSON_BIGINT_AS_STRING ); } else $decoded_rows = json_decode ( $query_result['rows'], null, 512, JSON_BIGINT_AS_STRING ); if ( !$decoded_rows ) { $error = "Unable to decode repsonse json'" . $query_result['rows'] . "': ".GetJsonError(); return false; } if ( is_object($decoded_rows) && property_exists ( $decoded_rows, 'took' ) ) unset ( $decoded_rows->took ); // fixup floats in json if ( isset ( $decoded_rows->hits ) && isset ( $decoded_rows->hits->hits ) ) { foreach ( $decoded_rows->hits->hits as &$hit ) RoundFloatValues ( $hit, 6 ); } $query_result['rows'] = $keep_json_ctrls ? $json_handler->Encode ( $decoded_rows, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) : json_encode ( $decoded_rows, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); return true; } function FixupJsonTotal ( &$query_result, &$error, $keep_json_ctrls=false ) { if ( !array_key_exists ( 'http_endpoint', $query_result ) ) return true; if ( strtolower ($query_result['http_endpoint'] )!='sql' ) return true; if ( !array_key_exists ( 'rows', $query_result ) ) return true; if ( $keep_json_ctrls ) { $json_handler = new SafeJsonHandler(); $decoded_rows = $json_handler->Decode ( $query_result['rows'], null, 512, JSON_BIGINT_AS_STRING ); } else $decoded_rows = json_decode ( $query_result['rows'], null, 512, JSON_BIGINT_AS_STRING ); if ( !$decoded_rows ) { $error = "Unable to decode repsonse json'" . $query_result['rows'] . "': ".GetJsonError(); return false; } if ( !is_object($decoded_rows) || !isset ( $decoded_rows->hits ) ) return true; // fixme! maybe add more intelligent checks instead of just ignoring the 'total'? if ( isset ( $decoded_rows->hits->total_relation ) && $decoded_rows->hits->total_relation=='gte' ) $decoded_rows->hits->total = count ( $decoded_rows->hits->hits ); $query_result['rows'] = $keep_json_ctrls ? $json_handler->Encode ( $decoded_rows, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) : json_encode ( $decoded_rows, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); return true; } function RunQueryHttp ( $query, &$error, &$examples ) { $attrs = $query['attrs']; $http_endpoint=ArrVal ($attrs, "endpoint", NULL); $http_method=ArrVal ($attrs, "method", "POST"); $http_content=ArrVal ($attrs, "content", NULL); $use_agent = ArrVal ($attrs, "d", 0); $use_gzip = ArrVal ($attrs, "gzip", 0); if ( !is_array($query) || !$attrs ) { $error = "HTTP endpoint not specified"; return false; } $query = $query['query']; $http_method = strtoupper($http_method); if ( !($http_method=="POST" || $http_method=="GET" || $http_method=="PUT") ) { $error = "Unknown HTTP method: ".$http_method; return false; } $query_result = HttpQueryCurl ( $http_method, $http_endpoint, $http_content, $query, $use_agent, $this->Requires("https"), $use_gzip, $this->_testdir ); if ( $use_agent>0 ) $query_result['agent'] = $use_agent; $keep_json_ctrls = $this->Requires("keep_json_ctrls"); if ( !$this->FixupJsonTimeAndFloats( $query_result, $error, $keep_json_ctrls ) ) return false; if ( !$this->FixupJsonTotal ( $query_result, $error, $keep_json_ctrls ) ) return false; $this->PickResult ( $query_result ); return true; } function RunQueryApiUpdate ( $query, &$error, &$examples ) { global $sd_address, $sd_port; $cl = new APIClient(); $cl->SetServer ( $sd_address, $sd_port ); $res = $cl->XUpdateAttributes ($query['index'], $query['query']['attrs'], $query['query']['values'], $query['mode'] ); $query_result = array ('updated'=> $res); $this->PickResult ( $query_result ); return true; } function RemovePathsFromExtFiles ( &$query ) { $lower_query = strtolower ( trim ( $query ) ); $create_table = "create table"; $alter_table = "alter table"; if ( StrBegins ( $lower_query, $create_table ) || StrBegins ( $lower_query, $alter_table ) ) { $matches = array(); $preg = preg_match_all ( "/(?:(?:wordforms|stopwords|exceptions|hitless_words|global_idf|jieba_user_dict_path)[ \t]*=[ \t]*)'([^']+)'/", $query, $matches, PREG_OFFSET_CAPTURE ); $result_str = ""; $prev_offset = 0; foreach ( $matches[1] as $entry ) { $paths = explode (' ', $entry[0]); $replacement = ''; foreach ( $paths as $single_path ) { if ( strlen($replacement) ) $replacement .=' '; $replacement .= basename($single_path); } $result_str.= substr ( $query, $prev_offset, $entry[1]-$prev_offset ); $result_str.= $replacement; $prev_offset = $entry[1] + strlen($entry[0]); } $result_str.= substr ( $query, $prev_offset ); $query = $this->FixupAgentAddress($result_str); return true; } return false; } function RemovePathsFromImportTable ( &$query ) { $lower_query = strtolower ( trim ( $query ) ); $import_table = "import table"; if ( StrBegins ( $lower_query, $import_table ) ) { $matches = array(); $preg = preg_match_all ( "/(?:.*)'([^']+)'/", $query, $matches, PREG_OFFSET_CAPTURE ); $result_str = ""; $prev_offset = 0; foreach ( $matches[1] as $entry ) { $result_str.= substr ( $query, $prev_offset, $entry[1]-$prev_offset ); $replacement = basename($entry[0]); $result_str.= $replacement; $prev_offset = $entry[1] + strlen($entry[0]); } $result_str.= substr ( $query, $prev_offset ); $query = $this->FixupAgentAddress($result_str); return true; } return false; } function PostprocessDDL ( &$query ) { if ( $this->RemovePathsFromExtFiles($query) ) return true; if ( $this->RemovePathsFromImportTable($query) ) return true; return false; } function PostprocessQlResult ( $query, &$query_result, &$raw_result, $connection, $no_time, $ignore_rows ) { $raw_result["sphinxql"] = $query; $result = mysqli_wr ($query,$connection); if ($result===true) { if ( $this->PostprocessDDL($query) ) $query_result["sphinxql"] = $query; $query_result["total_affected"] = mysqli_affected_rows($connection); $raw_result["total_affected"] = mysqli_affected_rows($connection); } else if ($result===false) { if ( $this->PostprocessDDL($query) ) $query_result["sphinxql"] = $query; $error = mysqli_errno( $connection ); $query_result["errno"] = $error; $raw_result["errno"] = $error; $raw_result["error"] = mysqli_error( $connection ); $query_result["error"] = $this->FixupErrorMessage ( $error, $raw_result["error"] ); } else { $raw_result["total_rows"] = mysqli_num_rows($result); $query_result["total_rows"] = $raw_result["total_rows"]; while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { $raw_result["rows"][] = $row; if ( $no_time===true && array_key_exists ( 'Variable_name', $row ) && $row['Variable_name']=='time' ) continue; $cont = false; foreach ( $ignore_rows as $ignore_row ) { if ( array_key_exists ( $ignore_row, $row ) ) { $cont = true; break; } } if ($cont) continue; $query_result["rows"][] = $row; } mysqli_free_result($result); if ( isset ( $query_result["rows"] ) ) foreach ( $query_result["rows"] as &$row ) { if ( isset ( $row["Create Table"] ) ) { $create_res = $row["Create Table"]; if ( $this->PostprocessDDL($create_res) ) $row["Create Table"] = $create_res; } } } } function RunQueryQL ( $query, &$error, &$examples, $bench, &$connection, &$old_agent, &$old_vip ) { global $agents, $index_data_path; $attrs = ArrVal ( $query, 'attrs', [] ); $query = trim($query['query']); $query_ref = $query; $sleep_agent=ArrVal ($attrs, "sleep", 0); $use_agent=ArrVal ($attrs, "d", 0); $vip_connection=ArrVal ($attrs, "vip", 0); $system_cmd = ArrVal ($attrs, "system"); $wait_value = ArrVal ($attrs, "wait_value", 0); $cluster_connect = ArrVal ($attrs, "cluster_connect", -1); $cluster_path = ArrVal ($attrs, "cluster_path"); $cluster_name = ArrVal ($attrs, "cluster"); $cluster_status = ArrVal ($attrs, "status"); $example = ArrVal ($attrs, "example"); $skip_result = ArrVal ($attrs, 'skip',false); $ignore_rows = ArrVals ($attrs, 'ignore'); $hide = ArrVals ($attrs, 'hide',false); $params = ArrVal ( $attrs, "params"); // mysql_host - we direct query to host mysql server, NOT to searchd! (that is sometimes need for rotation) $mysql_host = ($use_agent==="mysql"); if ($mysql_host) $use_agent = 0; // $query - array, 0 is data, 1 is attributes, 2 is 'is_http' bool. $agent = $agents[$use_agent]; $daemon = ArrVal ($agent, "daemon", null); if ($cluster_connect>=0) { $cluster = $agents[$cluster_connect]; $address = $cluster["address"] . ":" . $cluster["port"]; $query = str_replace("%addr_connect%", $address, $query); } if ( !empty($cluster_path) ) { $data_path = $agent["data_path"]; $cluster_dir = "$index_data_path/$data_path/$cluster_path"; if ( !file_exists ( $cluster_dir ) ) mkdir ( $cluster_dir ); $query = str_replace ( "%cluster_path%", $cluster_path, $query ); } $query_result = array (); if ( $vip_connection ) $query_result["vip"]=1; if ( $use_agent>0 ) $query_result["agent"]=$use_agent; if ($skip_result) $query_result['skip']=1; if ($hide) $query_result['hide']=1; if ($old_agent!=$use_agent && $system_cmd!='start-agent') { if ($old_agent!=-1) close_and_null_conn($connection); if ($sleep_agent>0) usleep($sleep_agent); if (!($connection = ConnectSpecificQL($use_agent))) return false; $old_agent = $use_agent; } if ($this->Requires('vip') && ( $old_vip!=$vip_connection || $connection===NULL )) { if ( $connection ) close_and_null_conn($connection); // this is needed to test non-vip connections in maintenance mode if (!($connection = ConnectSpecificQL($use_agent,$vip_connection))) { $query_result["sphinxql"]=$query; $query_result["error"] = mysqli_connect_error(); $query_result["errno"] = mysqli_connect_errno(); $this->PickResult($query_result); $connection = NULL; return true; } $old_vip = $vip_connection; } if ( !empty($system_cmd) ) { $status = ''; switch ( $system_cmd ) { case 'restart-daemon': case 'restart-daemon-no-warnings': close_and_null_conn($connection); $status = RestartDaemon($system_cmd=='restart-daemon-no-warnings'); $connection = ConnectSpecificQL($use_agent); break; case 'kill-daemon': close_and_null_conn($connection); KillSearchd($daemon["config"], $daemon["pid"], 'KILL', false); break; case 'start-agent-no-warnings': case 'start-agent': $start = StartSearchd($daemon["config"], $daemon["error"], $daemon["pid"], $error, $daemon["requirements"], $daemon["address"], $daemon["port"]); if ($start == 0 || $start == 2) { if ( $system_cmd==='start-agent-no-warnings' ) $start = 0; $status .= "; start=ok" . ', return code=' . $start; } else { $status .= "; start=failed, return code=" . $start . ", error=" . $error; } close_and_null_conn($connection); $old_agent = -1; break; case 'stop-agent': $stop = StopWaitSearchd($daemon["config"], $daemon["pid"]); $status = 'stop=' . ($stop == 0 ? 'ok' : 'error') . ', return code=' . $stop; close_and_null_conn($connection); $old_agent = -1; break; case 'run-indexer': RunIndexer ( $error, $params ); if ($sleep_agent>0) Sleep ( $sleep_agent); $status = $params . ' ok.'; break; case 'wait-ready': $ql = new QLClient(); $ql->SetConnection($connection); $timeout=GetTmDelta(); $status = $ql->Query("debug wait $cluster_name like 'state' option 'timeout'=$timeout"); break; case 'wait-commit': $ql = new QLClient(); $ql->SetConnection($connection); $timeout=GetTmDelta(); $status = $ql->Query("debug wait $cluster_name status $wait_value like 'state' option 'timeout'=$timeout"); break; default: $status = "unsupported command " . $system_cmd; } $query_result['sphinxql'] = "/* " . $system_cmd . " => " . $status . " */"; $this->PickResult ( $query_result ); return true; } if ($mysql_host) { global $gl_conn; if ( !LegacyConnectDB()) return FALSE; @mysql_query ( $query ); @mysql_close(); $gl_conn = NULL; if ($sleep_agent>0) Sleep ( $sleep_agent); $r = array("sphinxql"=>"/* " . $query . " => ok. */"); $this->PickResult ( $r ); return true; } if ( $query=="RECONNECT" ) { mysqli_close($connection); if (!($connection = ConnectSpecificQL($use_agent))) return false; $r = array("sphinxql"=>$query, "error"=>"reconnected ok!", "errno"=>0); $this->PickResult ( $r ); return true; } $no_time = false; if ( $bench===false && ( stripos ( $query, 'show' )!==false ) && ( stripos ( $query, 'meta' )!==false ) ) $no_time = true; if ( strpos ($query, ";")===FALSE ) // process a single-query line // FIXME! If a query contains ';' it would be false positive for such codepath. { $query_result["sphinxql"]=trim ( $query_ref ); unset ( $query_ref ); $raw_result = []; $this->PostprocessQlResult ( $query, $query_result, $raw_result, $connection, $no_time, $ignore_rows ); $this->PickResult($query_result); if ($example) { $examples[$example][] = $raw_result; } } else { $parts = explode (';',$query); $haserror = true; $erroneousquery = $query; // echo $query; if ( mysqli_multi_query ($connection,$query) ) { $resultset_num = 0; do { if ($result = mysqli_store_result($connection)) { $query_result["total_rows"] = mysqli_num_rows ($result); if (array_key_exists ("rows", $query_result) ) unset ($query_result["rows"]); while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { if ( $no_time===true && array_key_exists ( 'Variable_name', $row ) && $row['Variable_name']=='time' ) continue; if ( array_key_exists ( 'Value', $row ) ) $row['Value'] = $this->FixupWarningMessage ( $row['Value'] ); $query_result["rows"][] = $row; } mysqli_free_result($result); } else { if (mysqli_field_count($connection)) // there were some fields. An error occured. { $query_result["error"] = mysqli_error( $connection ); $query_result["errno"] = mysqli_errno( $connection ); } else $query_result["total_affected"] = mysqli_affected_rows($connection); } if ($resultset_num==0) $query_result["sphinxql"]="$query"; else $query_result["sphinxql"]=($resultset_num<count($parts)?"$parts[$resultset_num] ":"")."/* result ".($resultset_num+1)." of previous multistatement */"; ++$resultset_num; $this->PickResult($query_result); $erroneousquery = ($resultset_num<count($parts)?"$parts[$resultset_num] ":"")."/* result ".($resultset_num+1)." of previous multistatement */"; if (!mysqli_more_results($connection)) { $haserror = false; break; } $query_result = array (); } while (mysqli_next_result($connection)); }; if ($haserror) { $query_result["sphinxql"]=$erroneousquery; $query_result["error"] = mysqli_error( $connection ); $query_result["errno"] = mysqli_errno( $connection ); $this->PickResult($query_result); } } return true; } function ToHide($qinfo) { if ( array_key_exists ( 'hide', $qinfo ) ) return !!$qinfo['hide']; return false; } function GetSearchdRequirements() { $requirements = array(); if ( $this->Requires("no_pseudo_sharding") ) $requirements["no_pseudo_sharding"] = true; if ( $this->Requires("watchdog") ) $requirements["watchdog"] = true; return $requirements; } function RunQuery ( &$error, &$examples, $benchmark = false ) { global $sd_address, $sd_port, $action_retries, $action_wait_timeout, $g_pick_query; $total = $done = 0; if ( $benchmark ) { foreach ( $this->_queries as $qinfo ) $total += count($qinfo['query']); $prefix = $benchmark; $tm = 0; $start = MyMicrotime(); } $compact = $benchmark; $cl = new APIClient; $pconn = $benchmark && method_exists ( $cl, 'Open' ); if ( $pconn ) { $cl = new APIClient; $cl->SetServer ( $sd_address, $sd_port ); $cl->Open (); } $ql_connection=false; $old_agent = -1; $old_vip = -1; $retries = 1; if ( !$benchmark ) $retries = $action_retries; // tricky bit // sometimes, we run some API queries and then some QL queries! // so when picker points to an API query, choose it // but if it points past, adjust the picker $qmin = 0; $qmax = count($this->_queries) - 1; if ( $g_pick_query>0 ) { if ( $g_pick_query<=$qmax ) { $qmin = $g_pick_query-1; $qmax = $g_pick_query-1; } else { $g_pick_query -= count($this->_queries); return true; } } $bOk = true; for ( $n=$qmin; $n<=$qmax; $n++ ) { $qinfo = $this->_queries[$n]; if ($qinfo['type']=='sphinxql') $bOk = $this->RunQueryQL ( $qinfo, $error, $examples, $benchmark, $ql_connection, $old_agent, $old_vip ); elseif ($qinfo['type']=='query') $bOk = $this->RunQueryHttp ( $qinfo, $error, $examples ); elseif ( $qinfo['type']=='comment') { $this->PickResult(array("comment" => trim($qinfo["query"]), 'skip' => 1, 'hide' => $this->ToHide($qinfo) )); $bOk = true; } elseif ($qinfo['type']=='apiupdate') $bOk = $this->RunQueryApiUpdate ( $qinfo, $error, $examples ); if (!$bOk) break; if ($qinfo['type']=='api') foreach ( $qinfo['query'] as $query ) // in bench query might be loaded as big set of strings, so it's array. { if ( $benchmark && MyMicrotime() > $tm ) { $tm = MyMicrotime(); $est = $done ? ( ( $tm - $start ) / $done ) * ( $total - $done ) : 0 ; $qps = $done / ( $tm - $start ); printf ( "\r$prefix %d/%d (est. %s, qps %.1f)", $done, $total, sphFormatTime($est), $qps ); $tm += 1; } $bOk = FALSE; for ( $i=0; $i<$retries && !$bOk; $i++ ) { if ( !$pconn ) { $cl = new APIClient(); $cl->SetServer ( $sd_address, $sd_port ); } else { $cl->ResetFilters (); $cl->ResetGroupBy (); } $results = 0; if ( empty($this->_query_settings) ) { if ( @$qinfo["mode"] ) $cl->SetMatchMode ( $qinfo["mode"] ); if ( @$qinfo["ranker"] ) $cl->SetRankingMode ( $qinfo["ranker"] ); if ( @$qinfo["sortmode"] ) $cl->SetSortMode ( $qinfo["sortmode"], $qinfo["sortby"] ); if ( @$qinfo["groupattr"] ) $cl->SetGroupBy ( $qinfo["groupattr"], $qinfo["groupfunc"], $qinfo["groupsort"] ); if ( @$qinfo["groupdistinct"] ) $cl->SetGroupDistinct ( $qinfo["groupdistinct"] ); if ( @$qinfo["resarray"] ) $cl->SetArrayResult ( true ); if ( @$qinfo["select"] ) $cl->SetSelect ( $qinfo["select"] ); if ( @$qinfo["index"] ) $my_index = $qinfo["index"]; if ( @$qinfo["index_weights"] ) $cl->SetIndexWeights ( $qinfo["index_weights"] ); if ( @$qinfo["cutoff"] ) $cl->SetLimits ( 0, 20, 0, $qinfo["cutoff"] ); if ( @$qinfo["limits"] ) $cl->SetLimits ( 0, (int)$qinfo["limits"] ); if ( @$qinfo["filter"] ) { $name = $qinfo["filter"]; $exclude = false; if ( isset ( $qinfo["filter_exclude"] ) && $qinfo["filter_exclude"]=="1" ) $exclude = true; if ( @$qinfo["filter_value"] ) $cl->SetFilter ( $name, array ( $qinfo["filter_value"] ), $exclude ); elseif ( @$qinfo["filter_range"] ) { $range = $qinfo["filter_range"]; $cl->SetFilterRange ( $name, $range['min'], $range['max'], $exclude ); } elseif ( @$qinfo["filter_str"] ) $cl->SetFilterString ( $name, $qinfo["filter_str"], $exclude ); } $results = $cl->Query ( $query, $my_index, "run".(1+$this->SubtestNo()) ); if ( is_array($results) ) { $results["resarray"] = (int)@$qinfo["resarray"]; $results["roundoff"] = (int)@$qinfo["roundoff"]; // $results["time"] = "0.0001"; } } else { $run_func = function( $client, $query, $index, &$results ) { eval( "$this->_query_settings" ); }; $run_func ( $cl, $query, "*", $results ); } if ( $results ) { // let also work with "array of arrays" result if ( array_key_exists ( "error",$results ) ) { $bOk = TRUE; if ( $compact ) $results = array ( $n, $results['total'], $results['total_found'], $results['time'] ); else $results ["query"] = $query; $this->PickResult ( $results ); } else foreach ( $results as $result ) { $bOk = TRUE; if ( $compact ) $result = array ( $n, $result['total'], $result['total_found'], $result['time'] ); else $result ["query"] = $query; $this->PickResult ( $result ); } } else if ( !$cl->IsConnectError() ) { $bOk = true; $this->PickResult ( array ( "query" => $query, "error" => $cl->GetLastError(), "warning" => "", "total" => 0, "total_found" => 0, "time" => 0 ) ); } else { if ( method_exists ( $cl, 'IsConnectError' ) && $cl->IsConnectError() ) usleep ( $action_wait_timeout ); else if ( $benchmark && $done ) { $this->PickResult ( array ( $n, -1, -1, 0 ) ); $bOk = true; } else break; } } $done++; if ( !$bOk ) { $error = sprintf ( "query %d/%d: %s", $n+1, count($this->_queries), $cl->GetLastError() ); return FALSE; } } } if ( $ql_connection ) mysqli_close ( $ql_connection ); if ( $benchmark ) printf ( " - done in %s\n", sphFormatTime ( MyMicrotime() - $start ) ); if ( $pconn ) $cl->Close (); return $bOk; } function RunCustomTest ( & $error ) { global $sd_address, $sd_port, $action_retries, $action_wait_timeout, $g_locals; $bOk = false; $results = false; for ( $i = 0; $i < $action_retries && !$bOk; $i++ ) { $cl = new APIClient; $cl->SetServer ( $sd_address, $sd_port ); $results = false; $run_func = function( $client, $ql, &$results ) { eval( $this->_custom_test ); }; if ( !LegacyConnectDB()) return FALSE; $GLOBALS["this_test"] = $this->_testdir; $ql = new QLClient(); $run_func ( $cl, $ql, $results ); @mysql_close(); $gl_conn = NULL; if ( $results ) $bOk = TRUE; else usleep ( $action_wait_timeout ); } if ( !$bOk ) { $error = $cl->GetLastError (); return FALSE; } $my_results = array (); $my_results [] = $results; $this->PickResults ( $my_results ); return TRUE; } function FixKeys ( $v ) { if ( is_array($v) ) { $result = array(); foreach ( $v as $key=>$value ) { if ( $key==PHP_INT_MAX || $key==PHP_INT_MIN ) $key = (int)$key; $result[$key] = $this->FixKeys ( $value ); } return $result; } else return $v; } function IsBigNum ( $v ) { return is_int($v) && ( $v>2147483647 || $v<-2147483648 ); } function FixSerialize64 ( $v, & $fixarr ) { if ( is_array($v) ) { foreach ( $v as $key=>$value ) { if ($this->IsBigNum($key)) $fixarr[] = $key; $this->FixSerialize64 ( $value, $fixarr ); } } else if ($this->IsBigNum($v)) $fixarr[] = $v; } // linux and windows line ending breaks model at different boxes function fix_crlf ($contents) { return preg_replace_callback('!s:\d+:"(.*?)";!s', function($m) { return "s:" . strlen($m[1]) . ':"'.$m[1].'";'; }, $contents); } function fix_serialized_bignums ( $bignumbers, $content ) { if ( is_array ($bignumbers) && sizeof($bignumbers)>0) { $findes=[]; $replaces=[]; foreach ($bignumbers as $key) { $findes[]="i:$key"; $replaces[]="s:".strlen($key).":\"$key\""; } $content = str_replace ( $findes, $replaces, $content ); } return $content; } function LoadModel ( $filename ) { if ( ! IsModelGenMode () ) { if ( ! file_exists ( $filename ) ) return -1; $contents = file_get_contents ( $filename ); if ( ! $contents ) return 0; // check for wrapped 'big numbers' model if ( substr( $contents, 0, 24 ) === 'a:2:{s:12:"huge_numbers"' ) { $model32 = unserialize ( $contents ); $fixed_data = $this->fix_crlf($model32["model64"]); // need to patch data only when we need it if (PHP_INT_SIZE<=4) $fixed_data = $this->fix_serialized_bignums (unserialize($model32["huge_numbers"]), $fixed_data ); } else $fixed_data = $this->fix_crlf($contents); $this->_results_model = $this->FixKeys ( unserialize ( $fixed_data ) ); } return 1; } function FixupErrorMessageInResult(&$result) { if ( @is_array($result) && @array_key_exists ( "error", $result ) && $result["error"] ) { $origerror = $result["error"]; $fixup = $this->FixupErrorMessage(1064,$origerror); if ( $fixup!=$origerror ) $result["error"] = $fixup; } } function ImportantResults() { $_results = array(); foreach ( $this->_results as $result ) if ( !result_must_be_skipped ($result) ) $_results[] = $result; return $_results; } function CompareToModel () { return $this->CompareResults ( $this->FixKeys ( $this->ImportantResults () ), $this->_results_model [$this->SubtestNo ()] ); } function CompareResultSetFixup ( &$set, $roundoff, $variants_match, $keep_json_ctrls=false ) { global $g_ignore_weights; if ( !is_array($set) ) return; $this->FixupErrorMessageInResult($set); if ( $roundoff && !@$set["resarray"] ) // FIXME! support resarray too foreach ( $set["attrs"] as $name=>$type ) if ( $type==SPH_ATTR_FLOAT ) { foreach ( $set["matches"] as $id=>$match ) $set["matches"][$id]["attrs"][$name] = sprintf ( "%.{$roundoff}f", $set["matches"][$id]["attrs"][$name] ); } // fixup floats in json via http if ( isset ( $set["http"] ) && $set["http"]==1 ) JsonRsetFixup ( $set, $this->IsColumnar(), $keep_json_ctrls ); else SqlRsetFixup ( $set, $this->IsColumnar() ); // fixup sphinxql trim if ( isset ( $set['sphinxql'] ) ) $set['sphinxql'] = trim ($set['sphinxql']); // fixup http_request trim if ( isset ( $set['http_request'] ) ) $set['http_request'] = trim ($set['http_request']); if ( $g_ignore_weights ) { if ( isset($set["matches"]) ) { if ( @$set["resarray"] ) { for ( $i=0; $i<count($set); $i++ ) unset ( $set["matches"][$i]["weight"] ); } else { foreach ( $set["matches"] as $id=>$match ) unset ( $set["matches"][$id]["weight"] ); } } if ( @$set["words"] ) foreach ( $set["words"] as $word=>$info ) $set["words"][$word] = array ( "hits"=>-1, "docs"=>-1 ); if ( isset($set["sphinxql"]) && isset($set["rows"]) ) { for ( $i=0; $i<count($set["rows"]); $i++ ) unset($set["rows"][$i]["weight()"]); } } //foreach ( preg_split ( "/\\W+/", "time warning status fields resarray roundoff words" ) as $key ) foreach ( ['time', 'warning', 'status', 'fields', 'resarray', 'roundoff'] as $key ) unset ( $set[$key] ); // variants are be used to check mva32/mva64, int/bigint, etc // thus in variants check we fixup the compatible attribute types and only check the data if ( $variants_match && isset ( $set["attrs"] ) ) { foreach ( $set["attrs"] as $k=>$v ) { if ( $v==SPH_ATTR_MULTI64 ) $set["attrs"][$k] = SPH_ATTR_MULTI; if ( $v==SPH_ATTR_BIGINT && $k[0]=="@" ) $set["attrs"][$k] = SPH_ATTR_INTEGER; } } } function CompareResultSets ( $set1, $set2 ) { $roundoff = 0; if ( isset($set1["roundoff"]) ) $roundoff = $set1["roundoff"]; if ( isset($set2["roundoff"]) ) $roundoff = $set2["roundoff"]; $variants_match = $this->Requires("variant_match"); $keep_json_ctrls = $this->Requires("keep_json_ctrls"); $this->CompareResultSetFixup ( $set1, $roundoff, $variants_match, $keep_json_ctrls ); $this->CompareResultSetFixup ( $set2, $roundoff, $variants_match, $keep_json_ctrls ); return $set1===$set2; } function CompareResults ( $query1, $query2 ) { if ( count($query1)!=count($query2) ) return false; for ( $i=0; $i<count($query1); $i++ ) if ( !$this->CompareResultSets ( $query1[$i], $query2[$i] ) ) return false; return true; } /// returns false if everything is okay /// returns error messages if something failed function CheckVariants ( $output_path ) { if ( !$this->Requires("variant_match") ) return false; $total = count ( $this->_results_model ); if ( $total==1 ) return "variant match required, but there are no variants"; else if ( !$this->IsQueryTest() ) return "variant match is not supported with custom tests"; $failed = false; $output = ''; for ( $i=1; $i<$total; $i++ ) { $nqueries = count ( $this->_results_model[0] ); for ( $k=0; $k<$nqueries; $k++ ) if ( !$this->CompareResultSets ( $this->_results_model[0][$k], $this->_results_model[$i][$k] ) ) { $first = $this->FormatResultSet ( $k+1, $this->_results_model[0][$k], array("format_attrs"=>1) ); $current = $this->FormatResultSet ( $k+1, $this->_results_model[$i][$k], array("format_attrs"=>1) ); file_put_contents ( "first", $first ); file_put_contents ( "current", $current ); system ( "diff --unified=3 first current > diff.txt" ); $diff = file_get_contents ( "diff.txt" ); unlink ( "current" ); unlink ( "first" ); unlink ( "diff.txt" ); $output .= $diff . "\n"; $failed = true; } } if ( $failed ) { file_put_contents ( $output_path, $output ); return "variants mismatch; see $output_path for details"; } // all ok, indicated by false ("no error") return false; } function WriteReportHeader ( $fp ) { fprintf ( $fp, "==== Run %d ====\n", $this->SubtestNo () + 1 ); fwrite ( $fp, "Settings:\n" ); $this->WriteDiff ( $fp ); fwrite ( $fp, "\n" ); if ( !empty ( $this->_query_settings ) ) fprintf ( $fp, "Query settings:\n%s\n", $this->_query_settings ); } // At model generation all comments and statements displayed // At testing comments with 'hide', and statements with 'skip' are not displayed. function FormatResultSet ( $nquery, $result, $opts=array() ) { global $sd_skip_indexer; if (@$opts['hide'] && result_must_not_be_displayed ($result)) return ''; if ( array_key_exists ("comment", $result) ) return "/* " . $result["comment"] . " */\n\n"; if ( array_key_exists ("http", $result) ) return HttpFormatResultSet ( $result, $nquery, $this->Requires("keep_json_ctrls") ); if ( array_key_exists ('updated', $result) ) return "/* Updated via SphinxAPI: " . $result['updated'] . " */\n\n"; if ( !$this->IsQueryTest () || !is_array($result) ) return var_export ( $result, true )."\n"; $skipped_result = result_must_be_skipped($result); if ( array_key_exists ("sphinxql", $result) ) { $str = $skipped_result?"sphinxql":"sphinxql-$nquery"; if ( array_key_exists ("vip", $result ) ) $str.=" (vip)"; if ( array_key_exists ("agent", $result ) ) $str.=" (agent-" . $result["agent"] . ")" ; $str.= "> $result[sphinxql];\n"; if ( array_key_exists ("total_affected", $result) ) { $str .= "Query OK, $result[total_affected] rows affected\n"; } else if ( array_key_exists ("error", $result) ) { $str .= "ERROR $result[errno]: $result[error]\n"; } else if (array_key_exists ("rows", $result) ) { foreach ( $result["rows"][0] as $key=>$s ) $str .= "\t$key"; $str .= "\n"; foreach ($result["rows"] as $row) { foreach ($row as $value) { if ( $this->Requires("sphinxql_keep_null") && is_null ( $value ) ) $value = 'NULL'; $str .= "\t$value"; } $str .="\n"; } $str .="$result[total_rows] rows in set\n"; } else if ( isset($result["total_rows"]) ) { $str .= "$result[total_rows] rows in set\n"; } return $str."\n"; } // format header $qinfo = @$this->_queries[$nquery-1]; while ( $nquery>0 && is_array($qinfo) && (!@array_key_exists ( "type", $qinfo) || $qinfo['type'] != 'api' )) { --$nquery; $qinfo = @$this->_queries[$nquery-1]; } $str = ""; if ( $qinfo ) { if ( @array_key_exists ( "index", $qinfo ) && $qinfo ["index"] != '*' ) $str .= "--- Query $nquery (mode=$qinfo[mode_s],ranker=$qinfo[ranker_s],index=$qinfo[index]) ---\n"; else $str .= "--- Query $nquery (mode=$qinfo[mode_s],ranker=$qinfo[ranker_s]) ---\n"; if (@$qinfo["groupattr"]) $str .= "GroupBy: attr: '" . $qinfo["groupattr"] . "' func: '" . $qinfo["groupfunc_s"] . "' sort: '" . $qinfo["groupsort"] . "'\n"; if (@$qinfo["sortmode"] == SPH_SORT_EXPR) $str .= "Sort: expr: " . $qinfo["sortby"] . "\n"; } if ( @$opts["no_time"] ) $str .= @"Query '$result[query]': retrieved $result[total_found] of $result[total] matches.\n"; else $str .= @"Query '$result[query]': retrieved $result[total_found] of $result[total] matches in $result[time] sec.\n"; if ( @array_key_exists ( "error", $result ) && $result["error"] ) $str .= "Error: $result[error]\n"; if ( @array_key_exists ( "warning", $result ) && $result["warning"] ) $str .= "Warning: $result[warning]\n"; $array_result = @$result["resarray"]; // format keywords if ( isset($result["words"]) && is_array($result["words"]) ) { $str .= "Word stats:\n"; foreach ( $result ["words"] as $word => $word_result ) { $hits = $word_result ["hits"]; $docs = $word_result ["docs"]; $str .= "\t'$word' found $hits times in $docs documents\n"; } } // format attribute types if ( @$opts["format_attrs"] ) { $typenames = array ( SPH_ATTR_INTEGER => "int", SPH_ATTR_TIMESTAMP=> "timestamp", SPH_ATTR_ORDINAL => "ordinal", SPH_ATTR_BOOL => "bool", SPH_ATTR_FLOAT => "float", SPH_ATTR_DOUBLE => "double", SPH_ATTR_BIGINT => "bigint", SPH_ATTR_STRING => "string", SPH_ATTR_MULTI => "mva", SPH_ATTR_MULTI64 => "mva" ); // !COMMIT $n = 1; $str .= "Result set attributes:\n"; foreach ( $result["attrs"] as $name=>$type ) { $typename = "type-$type"; if ( $typenames[$type] ) $typename = $typenames[$type]; $str .= "\tattr $n: $typename $name\n"; $n++; } } // check our table for well-known id column names $idcol = ""; if ( $this->IsNeedDB() ) $r = $this->_connection->query ( "DESC test_table" ); else $r = false; if ( $r ) { while ( $row = $r->fetch_assoc() ) { $idcand = strtolower ( $row["Field"] ); if ( in_array ( $idcand, array ( "id", "document_id" ) ) ) { $idcol = $idcand; break; } } } // format matches $str .= "\n"; if ( isset($result["matches"]) && is_array($result["matches"]) ) { $n = 1; $str .= "Matches:"; foreach ( $result ["matches"] as $doc => $docinfo ) { $doc_id = $array_result ? $docinfo["id"] : $doc; $weight = $docinfo["weight"]; $str .= "\n$n. doc_id=$doc_id, weight=$weight"; $n++; // only format specified attrs if requested if ( !empty ( $this->_query_attributes ) ) { foreach ( $this->_query_attributes as $attr ) if ( isset($docinfo ["attrs"][$attr]) ) { $val = $docinfo["attrs"][$attr]; if ( is_array ( $val ) ) $val = join ( " ", $val ); if ( is_string ( $val ) ) $str .= " $attr=\"$val\""; else $str .= " $attr=$val"; } continue; } // format attrs foreach ( $docinfo["attrs"] as $attr=>$val ) { if ( is_array($val) ) $val = join ( ",", $val ); $str .= " $attr=\"$val\""; } } $str .= "\n\n"; } return $str . "\n"; } /// format and write a single result set into log file function WriteQuery ( $fp, $nquery, $result, $hide=false ) { $res_fmt = $this->FormatResultSet ( $nquery, $result,array('hide'=>$hide) ); fwrite ( $fp, $res_fmt ); } /// write all the result sets function WriteResults ( $fp, $hide ) { if ( $this->IsQueryTest () || $this->Requires("http") || $this->Requires("https") ) { $nquery = 1; foreach ( $this->_results as $result ) { $this->WriteQuery($fp, $nquery, $result, $hide); if (!result_must_be_skipped($result)) ++$nquery; } } else $this->WriteCustomTestResults ( $fp ); } /// write difference from the reference result sets function WriteReferenceResultsDiff ( $fp ) { $nquery = 0; if ( !is_array ( $this->_results_model [ $this->SubtestNo() ] ) ) return; fwrite ( $fp, "Run settings:\n" ); $this->WriteDiff ( $fp ); fwrite ( $fp, "\n" ); $_results = $this->ImportantResults (); foreach ( $this->_results_model [ $this->SubtestNo() ] as $ref ) { if (!array_key_exists ($nquery,$_results)) { printf ( "FAILED, model has more results than current test.\n" ); break; } $cur = $_results[$nquery]; $opts = [ "no_time"=>1 ]; unset ( $cur["time"] ); unset ( $ref["time"] ); if ( $this->CompareResultSets ( $ref, $cur ) ) { $nquery++; continue; } if ( isset($cur["attrs"]) || isset($ref["attrs"]) ) if ( @$cur["attrs"]!==@$ref["attrs"] ) $opts["format_attrs"] = 1; $result_f_cur = $this->FormatResultSet ( $nquery+1, $cur, $opts ); $result_f_ref = $this->FormatResultSet ( $nquery+1, $ref, $opts ); file_put_contents ( "current", $result_f_cur ); file_put_contents ( "reference", $result_f_ref ); system ( "diff --unified=3 reference current > diffed.txt" ); $diffed = file_get_contents ( "diffed.txt" ); unlink ( "current" ); unlink ( "reference" ); unlink ( "diffed.txt" ); $nquery++; fwrite ( $fp, "=== query $nquery diff start ===\n" ); fwrite ( $fp, $diffed ); fwrite ( $fp, "=== query $nquery diff end ===\n" ); } $nref = count ( array_keys ( $this->_results_model [ $this->SubtestNo() ] ) ); $nres = count ( array_keys ( $_results ) ); if ( $nres > $nref ) { $delta = $nres - $nref; fwrite ( $fp, "$delta result set(s) missing from model!\n" ); } } function EraseIndexFiles ( $path ) { $dh = glob ( "$path.*" ); foreach ( $dh as $entry ) { if ( is_file ($entry) ) unlink ($entry); } } function WriteConfig ( $filename, $agentid, &$msg, $collectdata = true ) { global $g_locals; $fp = fopen ( $filename, 'w' ); if ( !$fp ) { $msg = "Can't open file $filename for writing"; return FALSE; } $this->Dump ( $this->_config, $fp, false, $agentid ); fclose ( $fp ); $fp = fopen ( $filename, 'r' ); if ( !$fp ) { $msg = "Can't open file $filename for reading"; return FALSE; } $config = fread ( $fp, filesize ( $filename ) ); fclose ( $fp ); // for rt case - extract the schema from the config // and make the new config, making the index as rt instead if ( $this->IsRt() ) { $body = 1; $srcname = 2; $parent = 4; $content = 5; $epilog = 6; $pattern = "/.*?(source\s+(\S*?)(\s*\:\s*(\S*?))?\s*\{(.*?)\n\s*\})(.*?)/s"; preg_match_all ( $pattern, $config, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ); $schemas = array(); $shift = 0; $newconfig = ""; // parse sources foreach ( $matches as $match ) { // split to lines, taking into account multiline variables $lines = explode("\n", str_replace("\\\n", "", $match[$content][0])); $insert_schema = array(); $insert_types = array(); $insert_values = array(); $schema_bits = array(); $sql_attr_multi = array(); $sql_query_pre = array(); $sql_query = ""; $sql_query_range = ""; $sql_file_fields = array(); if ( $match[$parent][0] != "" ) { $insert_types = $schemas[$match[$parent][0]]['types']; $insert_schema = $schemas[$match[$parent][0]]['orders']; $sql_attr_multi = $schemas[$match[$parent][0]]['multi']; $sql_query_pre = $schemas[$match[$parent][0]]['pre']; $sql_query = $schemas[$match[$parent][0]]['query']; $sql_query_range = $schemas[$match[$parent][0]]['range']; } foreach ( $lines as $line ) { // skip comment lines (if any) if ( preg_match ( "/\s*#/" , $line ) > 0 ) continue; // extract config key/value pairs $eq = strpos ( $line,"=" ); if ($eq == 0) continue; $key = strtolower ( trim ( substr($line,0,$eq), " \t" ) ); $value = trim ( substr($line,$eq+1), " \t" ); $lcvalue = strtolower($value); // handle known keys switch ( $key ) { case "type": if ( $value != "mysql" ) { $msg = "non-mysql source (type=$value), skipping..."; return FALSE; } break; case "sql_attr_uint": case "sql_attr_bigint": if (strstr($lcvalue, ":")===false) { $attr = $lcvalue; $bits = ""; } else { $attr = strstr($lcvalue, ":", true); // true == extract the part before needle, ie. attr name $bits = strstr($lcvalue, ":"); } $insert_types[$attr] = "rt_" . substr($key, 4); $schema_bits[$attr] = $bits; break; case "sql_attr_float": $insert_types[$lcvalue] = "rt_attr_float"; break; case "sql_attr_timestamp": $insert_types[$lcvalue] = "rt_attr_timestamp"; break; case "sql_attr_bool": $insert_types[$lcvalue] = "rt_attr_bool"; break; case "sql_attr_json": $insert_types[$lcvalue] = "rt_attr_json"; break; case "sql_attr_string": $insert_types[$lcvalue] = "rt_attr_string"; break; case "sql_field_string": $insert_types[$lcvalue] = "FIELD"; break; case "sql_attr_multi": $sql_attr_multi[] = $value; break; case "sql_query_pre": $sql_query_pre[] = $value; break; case "sql_query": $sql_query = $value; break; case "sql_query_range": $sql_query_range = $value; break; case "sql_file_field": $sql_file_fields[] = $value; break; } } // sql query is not mandatory (e.g. in parent sections) if ( $sql_query ) { // now let's connect to MySQL, run the query, and fetch the values $conn = ConnectDB(); if (mysqli_connect_error()) { $msg = "can't connect or select the database"; return false; } // gotta run pre-queries first! foreach ( $sql_query_pre as $q ) { if ( mysqli_wr ( $q, $conn ) ) continue; $msg = sprintf ( "sql_query_pre failed (query=%s, error=%s)", $q, $conn->error ); $conn->close (); return false; } // copy original query $sql = $sql_query; // apply query range if ( $sql_query_range ) { $res = mysqli_wr ( $sql_query_range, $conn ); if ( !$res ) { $msg = sprintf ( "sql_query failed (query=%s, error=%s)", $sql_query, $conn->error ); $conn->close(); return false; } $range_values = array(); while ( $row = $res->fetch_row() ) $range_values[] = array_values ( $row ); if ( count($range_values)>=1 ) { $sql = str_replace ( '$start', $range_values[0][0], $sql ); $sql = str_replace ( '$end', $range_values[0][1], $sql ); } } // run main query $res = mysqli_wr ( $sql_query, $conn ); if ( !$res ) { $msg = sprintf ( "sql_query failed (query=%s, error=%s)", $sql_query, $conn->error ); $msg = "sql_query can't fetch test data: " . $conn->error; $conn->close (); return false; } // fetch fields $insert_schema = array ( "id" => 0 ); for ( $i=1; $i < $conn->field_count; $i++ ) $insert_schema [ $res->fetch_field_direct ( $i )->name ] = $i; // fetch data while ( $row = $res->fetch_row() ) $insert_values[] = array_values ( $row ); // cleanup $res->close(); // parse mva statements foreach ( $sql_attr_multi as $q ) { $stmt = preg_split ( "/\s*;\s*/", $q, 2 ); $sql_query = count($stmt)>1 ? $stmt[1] : ""; if ( !preg_match ( "/^\s*([^\s]+)\s+([^\s]+)\s+from\s+([^\s]+)/", $stmt[0], $regs) ) { $msg = sprintf ( "invalid mva statement %s\n", $value ); return false; } list ( $dummy, $attr_type, $attr_name, $source_type ) = $regs; $attr_name = strtolower ( $attr_name ); $multi_type = ( $attr_type=="uint" ? "rt_attr_multi" : ( $attr_type=="bigint" ? "rt_attr_multi_64" : "rt_attr_timestamp" ) ); $insert_types[$attr_name] = $multi_type; if ( $source_type=="query" ) { // query mva_pairs $res = mysqli_wr ( $sql_query, $conn ); if ( $res == false ) { $msg = sprintf ( "sql_query failed (query=%s, error=%s)", $sql_query, $conn->error ); $conn->close(); return false; } // fetch mva pairs (id, value), group by id $mva = array(); while ( $row = $res->fetch_row() ) { list ( $id, $value ) = array_values ( $row ); $mva[$id][] = $value; } // cleanup mysqli $res->close(); // add mva attribute to the schema $attr_index = count ( $insert_schema ); $insert_schema[$attr_name] = $attr_index; // insert mva values separated with commas for ( $i=0; $i<count($insert_values); $i++ ) { $id = $insert_values[$i][0]; $insert_values[$i][] = array_key_exists ( $id, $mva ) ? implode ( ',', $mva[$id] ) : ""; } } else if ( $source_type=="field" ) { // get field offset $attr_index = $insert_schema[$attr_name]; // insert mva values for ( $i=0; $i<count($insert_values); $i++ ) { $mva = preg_replace ( "/[a-z\(\)]/i", " ", $insert_values[$i][$attr_index] ); $mva = preg_split ( "/[\s,]+/", $mva, -1, PREG_SPLIT_NO_EMPTY ); $insert_values[$i][$attr_index] = implode ( ',', $mva ); } } } // cleanup $conn->close(); // load files foreach ($sql_file_fields as $ff) { $index = $insert_schema[$ff]; // FIXME? what if it does not exist? for ($i=0; $i<count($insert_values); $i++) { if ( $insert_values[$i][$index]!='' ) $insert_values[$i][$index] = @file_get_contents($insert_values[$i][$index]); // FIXME? handle errors } } } // store $schema = array(); $schema['types'] = $insert_types; $schema['bits'] = $schema_bits; $schema['orders'] = $insert_schema; $schema['multi'] = $sql_attr_multi; $schema['pre'] = $sql_query_pre; $schema['query'] = $sql_query; $schema['range'] = $sql_query_range; $schema['values'] = $insert_values; $schema['sqlport'] = $this->_sd_sphinxql_port; $schema['http_port'] = $this->_sd_http_port; $schemas[$match[$srcname][0]] = $schema; $srclen = $match[$epilog][1] - $match[$body][1]; $config = substr_replace ( $config, "", $match[$body][1]-$shift,$srclen ); $shift += $srclen; } $body = 1; $idxname = 2; $parent = 4; $content = 5; $epilog = 6; $pattern = "/.*?(index\s+(\S*?)(\s*\:\s*(\S*?))?\s*\{(.*?)\n\s*\})(.*?)/s"; preg_match_all ( $pattern, $config, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ); $shift = 0; // parse indexes $indexes = array(); $sources = array(); foreach ( $matches as $match ) { $idx = "index ".$match[$idxname][0]; if ( $match[$parent][0] != "" ) $idx .= " : ".$match[$parent][0]; $idx .= "\n{\n\tdict = keywords\n"; //source could be inherited if ( !strpos ( $match[$content][0],"source" ) ) if ( array_key_exists ( $match[$parent][0], $sources ) ) $match[$content][0] .= "\nsource = ".$sources[$match[$parent][0]]; $lines = explode("\n", str_replace("\\\n", "", $match[$content][0])); $justcopy = false; $rtcopy = false; $attr_names = array(); $idxbody = ""; foreach ($lines as $line) { $eq = strpos ( $line,"=" ); if ($eq == 0) continue; $key = strtolower ( trim ( substr($line,0,$eq), " \t" ) ); $value = trim ( substr($line,$eq+1), " \t" ); switch ( $key ) { case "type": if ($value=="rt") $rtcopy = true; else $justcopy = true; break; case "source"; { $idxbody .= "\ttype\t= rt\n"; if ( $collectdata ) $indexes[$match[$idxname][0]] = $schemas[$value]; foreach ( array_keys( $schemas[$value]['orders'] ) as $key ) if ( $key != "id" && $key != "document_id" ) { if ( array_key_exists ( $key, $schemas[$value]['types'] ) ) { $rt_attr_type = $schemas[$value]['types'][$key]; if ( $rt_attr_type!="rt_attr_json" ) $attr_names[] = $key; if ( $rt_attr_type == "FIELD" ) { $idxbody .= "\trt_field\t= $key\n"; $idxbody .= "\trt_attr_string\t= $key\n"; } else { $idxbody .= "\t".$rt_attr_type."\t= $key"; if (isset($schemas[$value]['bits'][$key])) $idxbody .= $schemas[$value]['bits'][$key]; $idxbody .= "\n"; } } else $idxbody .= "\trt_field\t= $key\n"; } $sources[$match[$idxname][0]] = $value; break; } case "path": $this->EraseIndexFiles($value); // need different index paths at every agent if ( $agentid!=0 ) $value .= "_$agentid"; if ($rtcopy) $justcopy = true; // no break! default: $idxbody .= "\t$key\t= $value\n"; } if ( $justcopy ) // explicitly defined type, don't transform to rt. { $idxbody = $match[$content][0]; break; } } if ( $this->IsColumnar() ) { $attr_names[] = "id"; $columnar_attrs = "\n\tcolumnar_attrs=".implode ( ",", array_unique($attr_names) ); $idxbody.= "$columnar_attrs"; } $idx .= "$idxbody\n}\n"; $srclen = $match[$epilog][1] - $match[$body][1]; $config = substr_replace ($config, $idx, $match[$body][1]-$shift,$srclen ); $shift += $srclen-strlen($idx); } if ( $collectdata ) foreach ($indexes as $key => $value) $this->_indexdata[$key] = $value; $fp = fopen ( $filename, 'w' ); if ( !$fp ) { $msg = "Can't open $filename for writing"; return FALSE; } fwrite ( $fp, $config ); fclose ( $fp ); } else // for rt indexes we need to clean up all index files before the run. { // remove binlog files if any $this->EraseIndexFiles ( 'data/binlog' ); $pattern = "/.*?index\s+\S*?(\s*\:\s*\S*?)?\s*\{(.*?)\}.*?/s"; preg_match_all ( $pattern, $config, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ); // parse indexes $indexes = array(); foreach ( $matches as $match ) { $lines = explode("\n", $match[2][0]); $path = ""; $isrt = false; foreach ($lines as $line) { // skip comment lines (if any) if ( preg_match ( "/\s*#/" , $line ) > 0 ) continue; $eq = strpos ( $line,"=" ); if ($eq == 0) continue; $key = strtolower ( trim ( substr($line,0,$eq), " \t" ) ); $value = trim ( substr($line,$eq+1), " \t" ); switch ( $key ) { case "type": if ($value=="rt") $isrt = true; break; case "path": $path = $value; } if ( $isrt && $path!="" ) { $this->EraseIndexFiles($path); break; } } } } return TRUE; } function InsertIntoIndexer ( &$error ) { global $sd_address, $sd_sphinxql_port, $action_retries, $action_wait_timeout; $address = $sd_address; if ($address == "localhost") $address = "127.0.0.1"; $cn = false; $port = 0; foreach ( $this->_indexdata as $name => $data ) { if ( $port != $data["sqlport"] ) { $port = $data["sqlport"]; $connect_string = "$address:$port"; if ( $cn !== false ) $cn->close(); $cn = new mysqli( $address, "", "", "", $port ); } if ( $cn === false ) return false; $corrected_cols = array(); foreach ( array_keys($data["orders"]) as $key ) $corrected_cols[] = '`'.$key.'`'; $cols = join ( ", ", $corrected_cols ); $prefix = "INSERT INTO $name ($cols) VALUES "; $accum = ""; // mva shouldn't be quoted, e.g. "insert into rt (id,gid,mva) values ('1','2',(1,2))" $is_mva = array(); foreach ( array_keys($data["orders"]) as $key ) $is_mva[] = array_key_exists ( $key, $data["types"] ) && ( $data["types"][$key]=="rt_attr_multi" || $data["types"][$key]=="rt_attr_multi_64" ); foreach ($data['values'] as $row) { $query = ""; $i = 0; foreach ( $row as $column ) { if ( $query!="" ) $query .=","; $s = $cn->real_escape_string($column); $query .= ( array_key_exists ( $i, $is_mva ) && $is_mva[$i] ) ? '('.$s.')' : "'".$s."'"; $i++; } if ( ( strlen ($accum) + strlen ($query) ) > 8192000 ) ///<checkit! { $result = mysqli_wr ( $prefix.$accum, $cn ); if ( $result === false ) { $error = $cn->error; return false; } $accum=""; } if ( $accum != "" ) $accum .=","; $accum .= "($query)"; } // final chunk; if ( $accum !="" ) { $result = mysqli_wr ( $prefix.$accum, $cn ); if ( $result === false ) { $error = $cn->error; return false; } } } if ( $cn ) $cn->close(); return true; } function WriteDiff ( $fp ) { $this->Dump ( $this->_config, $fp, true, "all" ); } function WriteModel ( $filename, $model ) { // that's a legacy hack: we serialize model 'as is', but add a layer of indirection: we write all huge numbers // which are not fit in int32 as array of strings, and then serialize again this array + original serialized // model. So that test on machine with tiny int can first fixup serialized model. if (PHP_INT_SIZE>4) { $allkeys = []; $this->FixSerialize64 ( $model, $allkeys ); $keys = array_unique($allkeys); if ( sizeof($keys)>0 ) { $model32 = ["huge_numbers"=>$this->fix_serialized_bignums ($keys, serialize($keys))]; $model32["model64"] = serialize ( $model ); $result = serialize ($model32); } else $result = serialize ($model); } else $result = serialize ($model); file_put_contents ( $filename, $result ); } function WriteSearchdSettings ( $fp ) { global $sd_log, $sd_split_logs, $sd_query_log, $sd_network_timeout, $sd_max_children, $sd_pid_file; if ( $this->_compat098 ) { fwrite ( $fp, "\taddress = {$this->_sd_address}\n" ); fwrite ( $fp, "\tport = {$this->_sd_port}\n" ); } else { fwrite ( $fp, "\tlisten = {$this->_sd_address}:{$this->_sd_port}\n" ); fwrite ( $fp, "\tlisten = {$this->_sd_address}:{$this->_sd_sphinxql_port}:mysql41\n" ); if ( $this->Requires("http") ) fwrite ( $fp, "\tlisten = {$this->_sd_address}:{$this->_sd_http_port}:http\n" ); if ( $this->Requires("https") ) { $test_root = dirname(__FILE__); fwrite ( $fp, "\tlisten = {$this->_sd_address}:{$this->_sd_http_port}:https\n" ); fwrite ( $fp, "\tssl_key = {$test_root}/ssl_keys/server-key.pem\n" ); fwrite ( $fp, "\tssl_cert = {$test_root}/ssl_keys/server-cert.pem\n" ); } if ( $this->Requires("vip") ) fwrite ( $fp, "\tlisten = {$this->_sd_address}:{$this->_sd_sphinxql_port_vip}:mysql41_vip\n" ); if ( $this->Requires("replication") ) { $replication_port0 = $this->_sd_replication_port; $replication_port1 = $this->_sd_replication_port + 18; fwrite ( $fp, "\tlisten = {$this->_sd_address}:{$replication_port0}-{$replication_port1}:replication\n" ); } } if ( $sd_split_logs ) fwrite ( $fp, "\tlog = {$this->_sd_log}\n" ); else fwrite ( $fp, "\tlog = $sd_log\n" ); fwrite ( $fp, "\tquery_log = $sd_query_log\n" ); fwrite ( $fp, "\tnetwork_timeout= $sd_network_timeout\n" ); fwrite ( $fp, "\tmax_connections = $sd_max_children\n" ); fwrite ( $fp, "\tpid_file = ".$this->_sd_pid_file."\n" ); fwrite ( $fp, "#\tbinlog_path =\n" ); } function WriteSqlSettings ( $fp, $attributes ) { global $g_locals; fwrite ( $fp, "\tsql_host = " . $g_locals['db-host'] . "\n" ); fwrite ( $fp, "\tsql_user = " . $g_locals['db-user'] . "\n" ); fwrite ( $fp, "\tsql_pass = " . $g_locals['db-password'] . "\n" ); fwrite ( $fp, "\tsql_port = " . $g_locals['db-port'] . "\n" ); if (is_null($attributes)) return; $node = $attributes->getNamedItem('sql_db'); fprintf ( $fp, "\tsql_db = %s\n", $node ? $node->nodeValue : $g_locals['db-name'] ); } function WriteOdbcSettings ( $fp, $attributes ) { global $g_locals; // params works for official mysql connector // available at https://dev.mysql.com/downloads/connector/odbc/ // after installing, provide full path to libmyodbc*.so as 'odbc_driver' local. $dsn=array(); $dsn[] = "Driver=" . $g_locals['odbc_driver']; $dsn[] = "Server=" . $g_locals['db-host']; $dsn[] = "Port=" . $g_locals['db-port']; $dsn[] = "UID=" . $g_locals['db-user']; $dsn[] = "PWD=" . $g_locals['db-password']; if (!is_null($attributes)) { $node = $attributes->getNamedItem('sql_db'); if ($node) $dsn[] = "Database=" . $node->nodeValue; else $dsn[] = "Database=" . $g_locals['db-name']; } $dsn = join ( ";", $dsn ); fwrite ( $fp, "odbc_dsn = $dsn" ); } function show_settings ( $nodename ) { global $index_data_path, $agents, $g_locals; switch ($nodename) { case "searchd_settings": $this->WriteSearchdSettings ( STDOUT ); return; case "sql_settings": $this->WriteSqlSettings ( STDOUT, null ); return; case "odbc_settings": $this->WriteOdbcSettings ( STDOUT, null ); return; case "my_address": case "agent0_address": fwrite ( STDOUT, $agents[0]["address"].":".$agents[0]["port"] ); return; case "my_port": fwrite ( STDOUT, $agents[0]["port"]); return; case "agent_address": case "agent1_address": fwrite ( STDOUT, $agents[1]["address"].":".$agents[1]["port"] ); return; case "agent2_address": fwrite ( STDOUT, $agents[2]["address"].":".$agents[2]["port"] ); return; case "test_root": fwrite ( STDOUT, dirname(__FILE__) ); return; case "testdir": { if ( $g_locals['testdir'] == '' ) { fwrite(STDOUT, dirname(__FILE__)."/"); return; } fwrite ( STDOUT, $g_locals['testdir'] ); return; } case "data_path": { fwrite(STDOUT, $index_data_path); return; } } } function Dump ( $node, $fp, $dynamic_only, $agentid ) { global $index_data_path, $agents, $g_locals, $python; $nodename = strtolower ( $node->nodeName ); if ( !$dynamic_only ) switch ( $nodename ) { case "#text": fwrite ( $fp, $node->nodeValue ); return; case "static": fwrite ( $fp, $node->nodeValue ); return; case "searchd_settings": $this->WriteSearchdSettings ( $fp ); return; case "python": fwrite ( $fp, $python ); return; case "sql_settings": $this->WriteSqlSettings ( $fp, $node->attributes ); return; case "odbc_settings": $this->WriteOdbcSettings ( $fp, $node->attributes); return; case "my_address": case "agent0_address": fwrite ( $fp, $agents[0]["address"].":".$agents[0]["port"] ); return; case "my_port": fwrite ( $fp, $agents[0]["port"]); return; case "agent_address": case "agent1_address": fwrite ( $fp, $agents[1]["address"].":".$agents[1]["port"] ); return; case "agent2_address": fwrite ( $fp, $agents[2]["address"].":".$agents[2]["port"] ); return; case "local": fwrite ( $fp, $this->GetLocal ( $node->nodeValue ) ); return; case "test_root": fwrite ( $fp, dirname(__FILE__) ); return; case "this_test": fwrite ( $fp, $this->_testdir ); return; case "testdir": { if ( $g_locals['testdir'] == '' ) { fwrite($fp, dirname(__FILE__)."/"); return; } fwrite ( $fp, $g_locals['testdir'] ); return; } case "data_path": { $subdir = GetfirstAttr($node); if ($subdir==NULL) { fwrite($fp, $index_data_path); return; } $path = "$index_data_path/$subdir->nodeValue"; if ( !file_exists ( $path ) ) mkdir ( $path ); EraseDirContents($path); fwrite($fp, $path); $agents[$agentid]["data_path"] = $subdir->nodeValue; return; } case "agent_id": fwrite($fp, $agentid); return; } if ( $nodename=="dynamic" ) { if ( $node->hasAttribute("count") ) { $count = $node->getAttribute("count"); $variants = ChildrenArray ( $node,"variant" ); $this->Dump ( $variants[$this->_counters[$count]], $fp, $dynamic_only, $agentid ); } } else if ( strpos ( $nodename, "agent" )===0 ) { if ( $agentid==="all" || $nodename=="agent$agentid" ) foreach ( ChildrenArray($node) as $child ) $this->Dump ( $child, $fp, $dynamic_only, $agentid ); } else { foreach ( ChildrenArray($node) as $child ) $this->Dump ( $child, $fp, $dynamic_only, $agentid ); } } } ////////////////////////////////////////////////////////////////////////// function HandleFailure ( $config, $report, $error, &$nfailed ) { $ret = true; if ( !IsModelGenMode() && !$config->ModelSubtestFailed () ) { $nfailed++; $ret = false; fwrite ( $report, "SUBTEST FAILED, UNEXPECTED ERROR:\n" ); } fwrite ( $report, "$error\n" ); $config->SubtestFailed (); return $ret; } function EraseDirContents ( $path, $dir=false ) { $fp = opendir ( $path ); if ( $fp ) { while ( ( $file = readdir ( $fp ) ) !== false ) { if ( $file!="." && $file!=".." && $file!="stub.txt" ) if (!is_dir("$path/$file")) { unlink ( "$path/$file" ); } else if ( $dir ) { EraseDirContents ( "$path/$file", $dir ); rmdir ( "$path/$file" ); } } closedir ( $fp ); } } function CopyDirContents ( $from, $to ) { $ffrom = opendir ( $from ); if ( $ffrom && is_dir ( $to ) ) { while ( ( $file = readdir ( $ffrom ) ) !== false ) { if ( $file != "." && $file != ".." && !is_dir ( $file ) ) copy ( "$from/$file", "$to/$file" ); } closedir ( $ffrom ); } } function CheckConfig ( $config, $path ) { global $g_re2, $g_icu, $g_jieba, $g_odbc, $windows, $g_locals, $mysql_simulated, $g_repli, $g_ssl, $g_columnar_loaded, $g_secondary_loaded, $g_knn_loaded, $g_tzdata_loaded, $g_zlib; if ( $config->Requires("non-windows") && $windows ) { printf ( "SKIPPING %s, %s - use non-Windows system to run this test\n", $path, $config->Name () ); return false; } if ( $config->Requires("windows") && !$windows ) { printf ( "SKIPPING %s, %s - use Windows system to run this test\n", $path, $config->Name () ); return false; } if ( $config->Requires("non-rt") && $config->IsRt() ) { printf ( "SKIPPING %s, %s - explicitly non-RT test skipped in RT mode\n", $path, $config->Name () ); return false; } if ( $config->Requires("non-columnar") && $config->IsColumnar() ) { printf ( "SKIPPING %s, %s - explicitly non-columnar test skipped in columnar mode\n", $path, $config->Name () ); return false; } if ( $config->Requires("non-secondary") && $g_secondary_loaded ) { printf ( "SKIPPING %s, %s - explicitly non-secondary test skipped in secondary mode\n", $path, $config->Name () ); return false; } if ( $config->Requires("re2") && !$g_re2 ) { printf ( "SKIPPING %s, %s - compile with regexp support to run this test\n", $path, $config->Name () ); return false; } if ( $config->Requires("icu") && !$g_icu ) { printf ( "SKIPPING %s, %s - compile with ICU support to run this test\n", $path, $config->Name () ); return false; } if ( $config->Requires("jieba") && !$g_jieba ) { printf ( "SKIPPING %s, %s - compile with Jieba support to run this test\n", $path, $config->Name () ); return false; } if ( $config->Requires("odbc") ) { if (!$g_odbc) { printf ( "SKIPPING %s, %s - compile with ODBC support to run this test\n", $path, $config->Name () ); return false; } if ( !isset($g_locals["odbc_driver"]) ) { printf ( "SKIPPING %s, %s - odbc_driver required, add it to your ~/.sphinx\n", $path, $config->Name () ); return false; } } if ( $config->Requires("columnar") ) { if ( !$g_columnar_loaded ) { printf ( "SKIPPING %s, %s - columnar library not loaded\n", $path, $config->Name () ); return false; } } if ( $config->Requires("php_mysql") && $mysql_simulated ) { printf ( "SKIPPING %s, %s - need php_mysql (not simulated by mysqli) to run this test\n", $path, $config->Name () ); return false; } if ( $config->NeedIndexerEx() && $config->IsRt() ) { printf ( "SKIPPING %s, %s - non-RT test that uses indexer skipped in RT mode\n", $path, $config->Name () ); return false; } if ( $config->Requires("lemmatizer_base") && !isset($g_locals["lemmatizer_base"]) ) { printf ( "SKIPPING %s, %s - lemmatizer_base required, add it to your ~/.sphinx\n", $path, $config->Name () ); return false; } if ( $config->Requires("replication") && !$g_repli ) { printf ( "SKIPPING %s, %s - compile with replication support to run this test\n", $path, $config->Name () ); return false; } if ( $config->Requires("https") && !$g_ssl ) { printf ( "SKIPPING %s, %s - compile with SSL support or add SSL extension to php\n", $path, $config->Name () ); return false; } if ( $config->Requires("secondary") && !$g_secondary_loaded ) { printf ( "SKIPPING %s, %s - secondary library not loaded\n", $path, $config->Name () ); return false; } if ( $config->Requires("knn") && !$g_knn_loaded) { printf ( "SKIPPING %s, %s - knn library not loaded\n", $path, $config->Name () ); return false; } if ( $config->Requires("tzdata") && !$g_tzdata_loaded) { printf ( "SKIPPING %s, %s - timezone data is not available\n", $path, $config->Name () ); return false; } if ( $config->Requires("zlib") && !$g_zlib) { printf ( "SKIPPING %s, %s - zlib is not available\n", $path, $config->Name () ); return false; } return true; } function MarkTest ( $logfile, $test_dir ) { $log = fopen ( $logfile, "a" ); fwrite ( $log, "*** in test $test_dir ***\n"); fclose ( $log ); } function RunTest ( $test_dir, $skipdemo, $usemarks ) { global $index_data_path, $agents, $ss_pid_file, $sd_managed_searchd, $sd_skip_indexer, $windows, $g_locals, $ss_log, $ss_query_log, $g_pick_query; $res_path = scriptdir($test_dir); $model_file = $test_dir."/model.bin"; $conf_dir = $res_path."/Conf"; $config = new SphinxConfig; $lmodel = $config->LoadModel ( $model_file ); $isdemo = false; $error = ""; if ( $lmodel==-1 ) { if ( $skipdemo ) { printf ( "Skipping %s, - this is demo or bugreport (no model.bin file)\n", $test_dir ); return array ( "tests_total"=>0, "tests_failed"=>0, "tests_skipped"=>1 ); } $isdemo = true; } $config->SetTestDir ( getcwd()."/".$test_dir ); if ( !$config->Load ( $test_dir."/test.xml" ) ) return; $prefix = sprintf ( "testing %s, %s...", $test_dir, $config->Name () ); if ( !CheckConfig ( $config, $test_dir ) ) return array ( "tests_total"=>0, "tests_failed"=>0, "tests_skipped"=>1 ); if ( $lmodel==0 ) { printf ( "$prefix FAILED, error loading model\n" ); return; } if ( $config->IsNeedDB() ) { $connection = CreateDB ( $config->DB_Drop(), $config->DB_Create(), $config->DB_Insert(), $config->DB_CustomInsert(), $sd_skip_indexer, $error ); if ( $connection === false ) { printf ( "$prefix FAILED, error creating test DB: " . $error ); return; } $config->SetConnection($connection); } if ( !file_exists ( $conf_dir ) ) mkdir ( $conf_dir ); if ( $config->Requires ( "replication" ) ) EraseDirContents ( testdir ( "data/" ), true ); $report_path = "$res_path/report"; $report_file = "$report_path.txt"; $report = fopen ( $report_file, "w" ); $shadow_model_file = "$report_path.bin"; $example_file = scriptdir("examples.txt"); $examples = []; $nfailed = 0; $error = ""; $log = ""; // subtest failures log $nsubtests = $config->SubtestCount(); // config to pid hash, instances to stop // static is only to workaround PHP braindamage, otherwise $stop gets reset (at least on 5.2.2 under win32) static $stop = array(); $oldlog = ''; $oldquerylog = ''; if ( $isdemo ) { $oldlog = $ss_log; $oldquerylog = $ss_query_log; $ss_log = "$res_path/searchd.log"; $ss_query_log = "$res_path/query.log"; if (file_exists($ss_log)) unlink ($ss_log); if (file_exists($ss_query_log)) unlink ($ss_query_log); } if ( $usemarks ) { MarkTest($ss_log,$test_dir); MarkTest($ss_query_log,$test_dir); } do { // stop them all if ( !$sd_managed_searchd ) foreach ( $stop as $conf=>$pid ) StopSearchd ( $conf, $pid ); $stop = array(); // do the dew $subtest = $config->SubtestNo()+1; print ( "$prefix $subtest/$nsubtests\r" ); $config->WriteReportHeader ( $report ); $config->SetAgent ( $agents [0], 0 ); $msg = ''; if (!$config->WriteConfig ( $conf_dir."/"."config_".$config->SubtestNo ().".conf", "all", $msg, false)) { print ("Interrupted, $msg\n"); continue; } $config->WriteConfig ( scriptdir("config.conf"), "all", $msg, $config->NumAgents () < 2 ); if ( !$sd_skip_indexer ) EraseDirContents ( $index_data_path ); if ( $config->Requires( "pre_copy_ref" ) ) CopyDirContents ( $test_dir . "/refdata/", testdir("data/") ); if ( $config->IsSkipIndexer()===false && $sd_managed_searchd===false && $sd_skip_indexer===false ) { // standard run if ( !$config->IsRt() ) { $indexer_ret = RunIndexer ( $error, "--all" ); if ( $indexer_ret==2 ) { fwrite ( $report, "$error\n" ); } else if ( $indexer_ret!=0 ) { if ( !HandleFailure ( $config, $report, $error, $nfailed ) ) $log .= "\tsubtest $subtest: error running indexer with code $indexer_ret; see $report_file\n"; continue; } } // additional optional runs (eg for merge tests) $indexer_ret = $config->RunIndexerEx ( $error ); if ( $indexer_ret==2 ) { fwrite ( $report, "$error\n" ); } else if ( $indexer_ret!=0 ) { if ( !HandleFailure ( $config, $report, $error, $nfailed ) ) $log .= "\tsubtest $subtest: error running indexer with code $indexer_ret; see $report_file\n"; continue; } } $searchd_error = FALSE; if ( $config->NumAgents () == 1 ) { $agents[0]["daemon"] = array ( "config"=>"config.conf", "error"=>"error.txt", "pid"=>$ss_pid_file, "requirements"=>$config->GetSearchdRequirements(), "address"=>false, "port"=>false ); if ( $sd_managed_searchd ) $searchd_ret = 0; else $searchd_ret = StartSearchd ( "config.conf", "error.txt", $ss_pid_file, $error, $config->GetSearchdRequirements() ); $stop[scriptdir("config.conf")] = $ss_pid_file; if ( $searchd_ret == 1 ) { if ( !HandleFailure ( $config, $report, $error, $nfailed ) ) $log .= "\tsubtest $subtest: error starting searchd; see $report_file\n"; $searchd_error = TRUE; } else if ( $searchd_ret==2 ) { fwrite ( $report, "$error\n" ); } } else for ( $i = $config->NumAgents () - 1; $i >= 0 && !$searchd_error; $i-- ) { static $agent_id = 0; $agent_id++; $config_file = "config_".$agent_id.".conf"; $pid_file = "searchd_".$agent_id.".pid"; $abs_config_file = scriptdir($config_file); $abs_pid_file = scriptdir($pid_file); $stop[$abs_config_file] = $abs_pid_file; $msg = ''; $error_agent = "error_".$agent_id.".txt"; $config->SetAgent ( $agents [$i], $i ); $config->SetPIDFile ( $abs_pid_file ); if ( !$config->WriteConfig ( $abs_config_file, $i, $msg ) ) continue; $agents[$i]["daemon"] = array ( "config"=>$config_file, "error"=>$error_agent, "pid"=>$pid_file, "requirements"=>$config->GetSearchdRequirements(), "address"=>$config->AddressAPI(), "port"=>$config->Port() ); if ( $sd_managed_searchd ) $searchd_ret = 0; else $searchd_ret = StartSearchd ( $config_file, $error_agent, $pid_file, $error, $config->GetSearchdRequirements(), $config->AddressAPI(), $config->Port() ); if ( $searchd_ret == 1 ) { if ( !HandleFailure ( $config, $report, $error, $nfailed ) ) $log .= "\tsubtest $subtest: error starting searchd; see $report_file\n"; $searchd_error = TRUE; } else if ( $searchd_ret==2 ) { fwrite ( $report, "$error\n" ); } } if ( $searchd_error ) continue; // in case of RT index - run "insert into" instead of indexer if ( $config->IsRt () ) $config->InsertIntoIndexer ( $error ); $config->ResetResults(); if ( !$config->IsQueryTest () ) { if (!$config->RunCustomTest($error)) { if (!HandleFailure($config, $report, "$error\n", $nfailed)) $log .= "\tsubtest $subtest: query error: $error\n"; continue; } } $error = ""; if ( !$config->RunQuery ( $error, $examples ) ) { if ( !HandleFailure ( $config, $report, "$error\n", $nfailed ) ) $log .= "\tsubtest $subtest: query error: $error\n"; continue; } WriteExamples ( $example_file, $examples ); $showall = $isdemo || IsModelGenMode(); $allmatch = $showall || $config->CompareToModel(); if ( !$allmatch ) { $log .= "\tsubtest $subtest: query results mismatch; see $report_file\n"; $nfailed++; } if ( $isdemo ) $log .= "\tdemo/bugreport $subtest done; see $report_file\n"; $config->WriteResults ( $report, !$showall ); if ( !$allmatch ) { fwrite ( $report, "SUBTEST FAILED, RESULTS ARE DIFFERENT FROM THE REFERENCE:\n\n" ); $config->WriteReferenceResultsDiff ( $report ); } $config->SubtestFinished (); } while ( $config->CreateNextConfig () ); $config->WriteModel($shadow_model_file, $config->_shadow_results_model); if ( $isdemo ) { $ss_log = $oldlog; $ss_query_log = $oldquerylog; } if ( !$sd_managed_searchd ) foreach ( $stop as $conf=>$pid ) StopSearchd ( $conf, $pid ); $total = $config->SubtestNo()+1; $dump_failed = false; if ( IsModelGenMode () ) { $variant = $config->CheckVariants ( $report_path."_variant.txt" ); if ($variant===false) { $config->WriteModel ( $model_file, $config->_results_model ); printf ( "$prefix done; %d/%d subtests run\n", $config->SubtestNo(), $nsubtests ); } else { printf ( "$prefix done; %d/%d subtests: VARIANT CHECK FAILED: %s\n", $config->SubtestNo(), $nsubtests, $variant ); $nfailed = $total; } } else if ( $nfailed==0 ) printf ( "$prefix done; %d/%d subtests OK\n", $config->SubtestNo(), $nsubtests ); else { printf("$prefix done; %d/%d subtests FAILED:\n%s", $nfailed, $nsubtests, $log); $dump_failed = true; } fclose ( $report ); if ($dump_failed && $g_locals['ctest']) { $textreport = file_get_contents ($report_file); printf ( "\n--------------Test report:------------\n%s\n--------------Done report.------------\n", $textreport ); } // cleanup DB after ourselves if ( !array_key_exists ('no_drop_db', $g_locals) && isset($connection) ) foreach ( $config->DB_Drop() as $q ) mysqli_wr ( $q, $connection ); return array ( "tests_total"=>$total, "tests_failed"=>$nfailed, "tests_skipped"=>0 ); }
138,760
C++
.inc
4,176
27.73228
232
0.559439
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,396
settings.inc
manticoresoftware_manticoresearch/test/settings.inc
<?php $sd_address = "127.0.0.1"; $sd_port = 6712; $sd_sphinxql_port = 6706; $sd_http_port = 6780; $sd_replication_port = 6720; $sd_sphinxql_port_vip = 6709; $sd_log = "searchd.log"; $sd_split_logs = false; // if we want one log per agent, its easier to investigate problems! $sd_query_log = "query.log"; $sd_network_timeout = 5; $sd_max_children = 100; $sd_pid_file = "searchd.pid"; $agent_address = "127.0.0.1"; $agent_port = 6713; $agent_port_sql = 6707; $agent_port_sql_vip = 6710; $agent_port_http = 6781; if ( array_key_exists ( "SPHINXDAEMON", $_ENV ) && $_ENV["SPHINXDAEMON"] ) $sd_address = $_ENV["SPHINXDAEMON"]; else if ( array_key_exists ( "SPHINXDAEMON", $_SERVER ) && $_SERVER["SPHINXDAEMON"] ) $sd_address = $_SERVER["SPHINXDAEMON"]; $agents = array ( array ( "address" => $sd_address, "port" => $sd_port, "sqlport" => $sd_sphinxql_port, "sqlport_vip" => $sd_sphinxql_port_vip, "replication_port" => $sd_replication_port, "http_port" => $sd_http_port ), array ( "address" => $agent_address, "port" => $agent_port, "sqlport" => $agent_port_sql, "sqlport_vip" => $agent_port_sql_vip, "replication_port" => $sd_replication_port+20, "http_port" => $agent_port_http ), array ( "address" => $agent_address, "port" => $agent_port+1, "sqlport" => $agent_port_sql+1, "sqlport_vip" => $agent_port_sql_vip+1, "replication_port" => $sd_replication_port+40, "http_port" => $agent_port_http+1 ) ); $index_data_path = "data"; $g_guesscached = false; $g_model = false; $g_re2 = false; $g_icu = false; $g_jieba = false; $g_odbc = false; $g_columnar_loaded = false; $g_strict = false; $g_skipdemo = false; $g_usemarks = true; // that we mark the output of every test in the searchd.log and query.log $g_strictverbose = false; $g_ssl = false; $g_secondary_loaded = false; $g_knn_loaded = false; $g_tzdata_loaded = false; $g_zlib = false; $windows = isset($_SERVER["WINDIR"]) || isset($_SERVER["windir"]) || isset($_SERVER["HOMEDRIVE"]); $action_retries = 100; $valgrind_action_retries = 200; $action_wait_timeout = 50000; $g_locals = null; $g_site_defaults = array ( 'queries' => 'queries.txt', 'qlimit' => null, 'api' => '../api/sphinxapi.php', 'mode' => 'aggregate', 'skip-searchd' => false, 'force-reindex' => false, 'malloc-scribble' => false, 'db-host' => '127.0.0.1', 'db-user' => 'root', 'db-password' => '', 'db-name' => 'test', 'db-port' => 3306 ); // localsettings could include dev's own parameters // which is not to be commited into the public repo (in opposite to this settings.inc) if ( file_exists ('localsettings.inc') ) require_once ( 'localsettings.inc' ); function GetBanner () { global $g_locals; exec ( $g_locals['indexer'], $output, $result ); if ( count($output) == 0 ) { print "ERROR: failed to run the indexer\n"; exit ( 1 ); } else return $output; } function LoadCachedGuesses () { global $g_locals; $guessfile = $g_locals['scriptdir'].'guess.txt'; if ( file_exists ( $guessfile )) { $text = @file_get_contents ( $guessfile ); eval ( $text ); } } function CacheGuesses () { global $g_locals; global $g_re2, $g_icu, $g_jieba, $g_odbc, $g_repli, $g_ssl, $g_columnar_loaded, $g_secondary_loaded, $g_knn_loaded, $g_tzdata_loaded, $g_zlib; $guessfile = $g_locals['scriptdir'].'guess.txt'; $text = "global \$g_guesscached; \$g_guesscached = true;\n"; if ( $g_re2 ) $text .= "global \$g_re2; \$g_re2 = true;\n"; if ( $g_icu ) $text .= "global \$g_icu; \$g_icu = true;\n"; if ( $g_jieba ) $text .= "global \$g_jieba; \$g_jieba = true;\n"; if ( $g_odbc ) $text .= "global \$g_odbc; \$g_odbc = true;\n"; if ( $g_repli ) $text .= "global \$g_repli; \$g_repli = true;\n"; if ( $g_ssl ) $text .= "global \$g_ssl; \$g_ssl = true;\n"; if ( $g_columnar_loaded ) $text .= "global \$g_columnar_loaded; \$g_columnar_loaded = true;\n"; if ( $g_secondary_loaded ) $text .= "global \$g_secondary_loaded; \$g_secondary_loaded = true;\n"; if ( $g_knn_loaded ) $text .= "global \$g_knn_loaded; \$g_knn_loaded = true;\n"; if ( $g_tzdata_loaded ) $text .= "global \g_tzdata_loaded; \$g_tzdata_loaded = true;\n"; if ( $g_zlib ) $text .= "global \$g_zlib; \$g_zlib = true;\n"; file_put_contents ( $guessfile, $text ); } function testdir ($path) { global $g_locals; if ( !$path || $path=='' ) return $g_locals['testdir']; # linux absolute starts with /, windows have drive letter with :. if ( substr ($path, 0, 1) === '/' || substr ($path, 1, 1) === ':' ) return $path; return $g_locals['testdir'].$path; } function scriptdir ($path) { global $g_locals; if ( !$path || $path=='' ) return $g_locals['scriptdir']; # linux absolute starts with /, windows have drive letter with :. if ( substr ($path, 0, 1) === '/' || substr ($path, 1, 1) === ':' ) return $path; return $g_locals['scriptdir'].$path; } function GuessFeature ($config, $testmsg, $matchmsg = null) { global $g_locals; $arg_quiet = '--quiet'; if (null!==$matchmsg) { $arg_quiet = ''; } exec ( $g_locals['indexer'].' '.$arg_quiet.' --config '.$config.' --all', $output, $result ); if ( count($output) == 0 ) { print "ERROR: failed to run the indexer\n"; exit ( 1 ); } $flag = true; foreach ( $output as $str ) { if ( strstr ( $str, $testmsg ) ) { $flag = false; break; } } if (null!==$matchmsg) { $flag = false; foreach ( $output as $str ) { if ( strstr ( $str, $matchmsg ) ) { $flag = true; break; } } } return $flag; } function GuessRE2 () { global $g_re2; $g_re2 = GuessFeature ('test_re.conf','no regexp support compiled'); } function GuessICU () { global $g_icu; $g_icu = GuessFeature ( 'test_icu.conf','no ICU support compiled'); } function GuessJieba () { global $g_jieba; $g_jieba = GuessFeature ( 'test_jieba.conf','no Jieba support compiled'); } function GuessODBC () { global $g_odbc; $g_odbc = GuessFeature ( 'test_odbc.conf','failed to configure some of the sources'); } function GuessColumnar() { global $g_columnar_loaded; $g_columnar_loaded = GuessFeature ( 'test_columnar.conf','columnar library not loaded'); } function GuessSecondary() { global $g_secondary_loaded; $g_secondary_loaded = GuessFeature ( 'test_columnar.conf','secondary library not loaded', ' (secondary '); } function GuessKNN() { global $g_knn_loaded; $g_knn_loaded = GuessFeature ( 'test_columnar.conf','knn library not loaded', ' (knn '); } function GuessTzData() { global $g_tz_data_loaded; $g_tz_data_loaded = strpos( file_get_contents( testdir("searchd.log"), 'Error initializing time zones' ) ) === false; } function GetVersion () { $banner = GetBanner(); return $banner[0]; } function GuessReplication() { $repli_on = 'DWITH_GALERA=1'; global $g_repli; $banner = GetBanner(); foreach ( $banner as $line ) { if ( strpos ( $line, $repli_on ) !== false ) { $g_repli = true; break; } } } function GuessSSL () { global $g_ssl; if ( !defined('OPENSSL_VERSION_NUMBER') ) { $g_ssl = false; return; } $banner = GetBanner(); foreach ( $banner as $line ) { if ( strpos ( $line, 'DWITH_SSL=1' ) !== false ) { $g_ssl = true; break; } } } function GuessZlib() { global $g_zlib; $zlib_on = 'DWITH_ZLIB=1'; $banner = GetBanner(); foreach ( $banner as $line ) { if ( strpos ( $line, $zlib_on ) !== false ) { $g_zlib = true; break; } } } function PublishLocals ( &$locals, $benchmark ) { global $g_locals, $g_site_defaults, $windows; $sources = array(); if ( @$locals['root'] && !@$locals['bin'] && !@$locals['api'] ) { $locals['bin'] = $locals['root'] . '/src/'; $locals['api'] = $locals['root'] . '/api/sphinxapi.php'; } $text = @file_get_contents ( getenv('HOME') . '/.sphinx' ); if ( !$text ) { if ( $windows ) $path = $benchmark ? '..\\bin\\release\\' : '..\\bin\\debug\\'; else $path = '../src/'; $text = @file_get_contents ( $path . '/.sphinx' ); } if ( $text ) { eval('$init = array ' . $text . ';'); $sources[] = $init; } $sources[] = $g_site_defaults; foreach ( $sources as $source ) { foreach ( $source as $key => $value ) { if ( !array_key_exists ( $key, $locals ) ) $locals[$key] = $value; } } if ( !@$locals['bin'] ) { if ( $windows ) $locals['bin'] = $benchmark ? '..\\bin\\release\\' : '..\\bin\\debug\\'; else $locals['bin'] = '../src/'; } if ( $windows ) { $ext = ".exe"; $pref = $benchmark ? "RelWithDebInfo/" : "Debug/"; } else { $ext = ''; $pref = ''; } foreach ( array ( 'searchd', 'indexer', 'spelldump' ) as $key ) { $KEY = getenv(strtoupper($key)); if ( !array_key_exists ( $key, $locals ) ) $locals[$key] = $KEY ? $KEY : $locals['bin'] . $pref . $key . $ext; } $g_locals = $locals; if ( isset($g_locals["icu_data_dir"])) putenv("ICU_DATA_DIR=$g_locals[icu_data_dir]"); if ( isset($g_locals["jieba_data_dir"])) putenv("JIEBA_DATA_DIR=$g_locals[jieba_data_dir]"); if ( isset($g_locals["full_share_dir"])) putenv("FULL_SHARE_DIR=$g_locals[full_share_dir]"); } ?>
9,269
C++
.inc
318
26.235849
220
0.603737
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,397
test.inc
manticoresoftware_manticoresearch/test/test_028/test.inc
printf ( "testing $test_path, spelldump... " ); $windows = isset($_SERVER["WINDIR"]) || isset($_SERVER["windir"]) || isset($_SERVER["HOMEDRIVE"]); global $locals; $spelldump_path = $locals['spelldump']; $res_path = $locals['testdir'].$test_path; global $g_model; if ( $g_model ) { exec ( "$spelldump_path $test_path/model.dict $test_path/model.aff $test_path/model.spell", $error, $retval ); if ( !file_exists ( "$test_path/model.spell" ) ) return false; printf ( "done; 1/1 subtests OK\n" ); return true; } exec ( "$spelldump_path $test_path/model.dict $test_path/model.aff $res_path/current.spell", $error, $retval ); if ( !file_exists ( "$res_path/current.spell" ) ) return false; $model = file_get_contents ( "$test_path/model.spell" ); $result = file_get_contents ( "$res_path/current.spell" ); $model = str_replace ( "\r\n", "\n", $model ); $result = str_replace ( "\r\n", "\n", $result ); if ( $model != $result ) { if ( $windows ) system ( "diff -u3 $test_path/model.spell $res_path/current.spell > $res_path/report.txt" ); else system ( "diff $test_path/model.spell $res_path/current.spell > $res_path/report.txt" ); printf ( "FAILED\n" ); return false; } unlink ( "$res_path/current.spell" ); printf ( "done; 1/1 subtests OK\n" ); return true;
1,324
C++
.inc
33
37
112
0.643026
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,398
sphinxstemru.inl
manticoresoftware_manticoresearch/src/sphinxstemru.inl
#undef LOC_TABLE_ENTRY #undef LOC_TABLE_INDEX #define LOC_TABLE_ENTRY LOC_PREFIX(stem_table_entry_) #define LOC_TABLE_INDEX LOC_PREFIX(stem_table_index_) struct LOC_TABLE_ENTRY { LOC_CHAR_TYPE suffix[8]; int remove, len; }; struct LOC_TABLE_INDEX { LOC_CHAR_TYPE first; int count; }; // TableStringN, where N is a number of chars #undef TS1 #undef TS2 #undef TS3 #undef TS4 #undef TS5 #define TS1(c1) { RUS::c1 } #define TS2(c1,c2) { RUS::c1, RUS::c2 } #define TS3(c1,c2,c3) { RUS::c1, RUS::c2, RUS::c3 } #define TS4(c1,c2,c3,c4) { RUS::c1, RUS::c2, RUS::c3, RUS::c4 } #define TS5(c1,c2,c3,c4,c5) { RUS::c1, RUS::c2, RUS::c3, RUS::c4, RUS::c5 } static LOC_TABLE_INDEX LOC_PREFIX(ru_adj_i)[] = { { RUS::E, 4 }, { RUS::I, 2 }, { RUS::IY, 4 }, { RUS::M, 7 }, { RUS::O, 2 }, { RUS::U, 2 }, { RUS::H, 2 }, { RUS::YU, 4 }, { RUS::YA, 2 }, }; static LOC_TABLE_ENTRY LOC_PREFIX(ru_adj)[] = { { TS2(E,E), 2, -1 }, { TS2(I,E), 2, -1 }, { TS2(Y,E), 2, -1 }, { TS2(O,E), 2, -1 }, { TS3(I,M,I), 3, -1 }, { TS3(Y,M,I), 3, -1 }, { TS2(E,IY), 2, -1 }, { TS2(I,IY), 2, -1 }, { TS2(Y,IY), 2, -1 }, { TS2(O,IY), 2, -1 }, { TS3(A,E,M), 0, -1 }, { TS3(U,E,M), 0, -1 }, { TS3(YA,E,M), 0, -1 }, { TS2(E,M), 2, -1 }, { TS2(I,M), 2, -1 }, { TS2(Y,M), 2, -1 }, { TS2(O,M), 2, -1 }, { TS3(E,G,O), 3, -1 }, { TS3(O,G,O), 3, -1 }, { TS3(E,M,U), 3, -1 }, { TS3(O,M,U), 3, -1 }, { TS2(I,H), 2, -1 }, { TS2(Y,H), 2, -1 }, { TS2(E,YU), 2, -1 }, { TS2(O,YU), 2, -1 }, { TS2(U,YU), 2, -1 }, { TS2(YU,YU), 2, -1 }, { TS2(A,YA), 2, -1 }, { TS2(YA,YA), 2, -1 } }; static LOC_TABLE_INDEX LOC_PREFIX(ru_part_i)[] = { { RUS::A, 3 }, { RUS::M, 1 }, { RUS::N, 3 }, { RUS::O, 3 }, { RUS::Y, 3 }, { RUS::SH, 4 }, { RUS::SCH, 5 } }; static LOC_TABLE_ENTRY LOC_PREFIX(ru_part)[] = { { TS4(A,N,N,A), 2, -1 }, { TS4(E,N,N,A), 2, -1 }, { TS4(YA,N,N,A), 2, -1 }, { TS3(YA,E,M), 2, -1 }, { TS3(A,N,N), 1, -1 }, { TS3(E,N,N), 1, -1 }, { TS3(YA,N,N), 1, -1 }, { TS4(A,N,N,O), 2, -1 }, { TS4(E,N,N,O), 2, -1 }, { TS4(YA,N,N,O), 2, -1 }, { TS4(A,N,N,Y), 2, -1 }, { TS4(E,N,N,Y), 2, -1 }, { TS4(YA,N,N,Y), 2, -1 }, { TS3(A,V,SH), 2, -1 }, { TS3(I,V,SH), 3, -1 }, { TS3(Y,V,SH), 3, -1 }, { TS3(YA,V,SH), 2, -1 }, { TS3(A,YU,SCH), 2, -1 }, { TS2(A,SCH), 1, -1 }, { TS3(YA,YU,SCH), 2, -1 }, { TS2(YA,SCH), 1, -1 }, { TS3(U,YU,SCH), 3, -1 } }; static LOC_TABLE_INDEX LOC_PREFIX(ru_verb_i)[] = { { RUS::A, 7 }, { RUS::E, 9 }, { RUS::I, 4 }, { RUS::IY, 4 }, { RUS::L, 4 }, { RUS::M, 5 }, { RUS::O, 7 }, { RUS::T, 9 }, { RUS::Y, 3 }, { RUS::MYA, 10 }, { RUS::YU, 4 }, { RUS::YA, 1 } }; static LOC_TABLE_ENTRY LOC_PREFIX(ru_verb)[] = { { TS3(A,L,A), 3, -1 }, { TS3(A,N,A), 3, -1 }, { TS3(YA,L,A), 3, -1 }, { TS3(YA,N,A), 3, -1 }, { TS3(I,L,A), 3, -1 }, { TS3(Y,L,A), 3, -1 }, { TS3(E,N,A), 3, -1 }, { TS4(A,E,T,E), 4, -1 }, { TS4(A,IY,T,E), 4, -1 }, { TS3(MYA,T,E), 3, -1 }, { TS4(U,E,T,E), 4, -1 }, { TS4(YA,E,T,E), 4, -1 }, { TS4(YA,IY,T,E), 4, -1 }, { TS4(E,IY,T,E), 4, -1 }, { TS4(U,IY,T,E), 4, -1 }, { TS3(I,T,E), 3, -1 }, { TS3(A,L,I), 3, -1 }, { TS3(YA,L,I), 3, -1 }, { TS3(I,L,I), 3, -1 }, { TS3(Y,L,I), 3, -1 }, { TS2(A,IY), 2, -1 }, { TS2(YA,IY), 2, -1 }, { TS2(E,IY), 2, -1 }, { TS2(U,IY), 2, -1 }, { TS2(A,L), 2, -1 }, { TS2(YA,L), 2, -1 }, { TS2(I,L), 2, -1 }, { TS2(Y,L), 2, -1 }, { TS3(A,E,M), 3, -1 }, { TS3(YA,E,M), 3, -1 }, { TS3(U,E,M), 3, -1 }, { TS2(I,M), 2, -1 }, { TS2(Y,M), 2, -1 }, { TS3(A,L,O), 3, -1 }, { TS3(A,N,O), 3, -1 }, { TS3(YA,L,O), 3, -1 }, { TS3(YA,N,O), 3, -1 }, { TS3(I,L,O), 3, -1 }, { TS3(Y,L,O), 3, -1 }, { TS3(E,N,O), 3, -1 }, { TS3(A,E,T), 3, -1 }, { TS3(A,YU,T), 3, -1 }, { TS3(YA,E,T), 3, -1 }, { TS3(YA,YU,T), 3, -1 }, { TS2(YA,T), 2, -1 }, { TS3(U,E,T), 3, -1 }, { TS3(U,YU,T), 3, -1 }, { TS2(I,T), 2, -1 }, { TS2(Y,T), 2, -1 }, { TS3(A,N,Y), 3, -1 }, { TS3(YA,N,Y), 3, -1 }, { TS3(E,N,Y), 3, -1 }, { TS4(A,E,SH,MYA), 4, -1 }, { TS4(U,E,SH,MYA), 4, -1 }, { TS4(YA,E,SH,MYA), 4, -1 }, { TS3(A,T,MYA), 3, -1 }, { TS3(E,T,MYA), 3, -1 }, { TS3(I,T,MYA), 3, -1 }, { TS3(U,T,MYA), 3, -1 }, { TS3(Y,T,MYA), 3, -1 }, { TS3(I,SH,MYA), 3, -1 }, { TS3(YA,T,MYA), 3, -1 }, { TS2(A,YU), 2, -1 }, { TS2(U,YU), 2, -1 }, { TS2(YA,YU), 2, -1 }, { TS1(YU), 1, -1 }, { TS2(U,YA), 2, -1 } }; static LOC_TABLE_INDEX LOC_PREFIX(ru_dear_i)[] = { { RUS::K, 3 }, { RUS::A, 2 }, { RUS::V, 2 }, { RUS::E, 2 }, { RUS::I, 4 }, { RUS::IY, 2 }, { RUS::M, 4 }, { RUS::O, 2 }, { RUS::U, 2 }, { RUS::H, 2 }, { RUS::YU, 2 } }; static LOC_TABLE_ENTRY LOC_PREFIX(ru_dear)[] = { { TS3(CH,E,K), 3, -1 }, { TS3(CH,O,K), 3, -1 }, { TS3(N,O,K), 3, -1 }, { TS3(CH,K,A), 3, -1 }, { TS3(N, K,A), 3, -1 }, { TS4(CH,K,O,V), 4, -1 }, { TS4(N, K,O,V), 4, -1 }, { TS3(CH,K,E), 3, -1 }, { TS3(N, K,E), 3, -1 }, { TS3(CH,K,I), 3, -1 }, { TS3(N, K,I), 3, -1 }, { TS5(CH,K,A,M,I), 5, -1 }, { TS5(N, K,A,M,I), 5, -1 }, { TS4(CH,K,O,IY), 4, -1 }, { TS4(N, K,O,IY), 4, -1 }, { TS4(CH,K,A,M), 4, -1 }, { TS4(N, K,A,M), 4, -1 }, { TS4(CH,K,O,M), 4, -1 }, { TS4(N, K,O,M), 4, -1 }, { TS3(CH,K,O), 3, -1 }, { TS3(N, K,O), 3, -1 }, { TS3(CH,K,U), 3, -1 }, { TS3(N, K,U), 3, -1 }, { TS4(CH,K,A,H), 4, -1 }, { TS4(N, K,A,H), 4, -1 }, { TS4(CH,K,O,YU), 4, -1 }, { TS4(N, K,O,YU), 4, -1 } }; static LOC_TABLE_INDEX LOC_PREFIX(ru_noun_i)[] = { { RUS::A, 1 }, { RUS::V, 2 }, { RUS::E, 3 }, { RUS::I, 6 }, { RUS::IY, 4 }, { RUS::M, 5 }, { RUS::O, 1 }, { RUS::U, 1 }, { RUS::H, 3 }, { RUS::Y, 1 }, { RUS::MYA, 1 }, { RUS::YU, 3 }, { RUS::YA, 3 } }; static LOC_TABLE_ENTRY LOC_PREFIX(ru_noun)[] = { { TS1(A), 1, -1 }, { TS2(E,V), 2, -1 }, { TS2(O,V), 2, -1 }, { TS2(I,E), 2, -1 }, { TS2(MYA,E), 2, -1 }, { TS1(E), 1, -1 }, { TS4(I,YA,M,I),4, -1 }, { TS3(YA,M,I), 3, -1 }, { TS3(A,M,I), 3, -1 }, { TS2(E,I), 2, -1 }, { TS2(I,I), 2, -1 }, { TS1(I), 1, -1 }, { TS3(I,E,IY), 3, -1 }, { TS2(E,IY), 2, -1 }, { TS2(O,IY), 2, -1 }, { TS2(I,IY), 2, -1 }, { TS3(I,YA,M), 3, -1 }, { TS2(YA,M), 2, -1 }, { TS3(I,E,M), 3, -1 }, { TS2(A,M), 2, -1 }, { TS2(O,M), 2, -1 }, { TS1(O), 1, -1 }, { TS1(U), 1, -1 }, { TS2(A,H), 2, -1 }, { TS3(I,YA,H), 3, -1 }, { TS2(YA,H), 2, -1 }, { TS1(Y), 1, -1 }, { TS1(MYA), 1, -1 }, { TS2(I,YU), 2, -1 }, { TS2(MYA,YU), 2, -1 }, { TS1(YU), 1, -1 }, { TS2(I,YA), 2, -1 }, { TS2(MYA,YA), 2, -1 }, { TS1(YA), 1, -1 } }; int stem_ru_table_i ( LOC_CHAR_TYPE * word, int len, LOC_TABLE_ENTRY * table, LOC_TABLE_INDEX * itable, int icount ) { int i, j, k, m; LOC_CHAR_TYPE l = word[--len]; for ( i=0, j=0; i<icount; i++ ) { if ( l==itable[i].first ) { m = itable[i].count; i = j-1; while ( m-- ) { i++; j = table[i].len; k = len; if ( j>k ) continue; for ( ; j>=0; k--, j-- ) if ( word[k]!=table[i].suffix[j] ) break; if ( j>=0 ) continue; return table[i].remove; } return 0; } j += itable[i].count; } return 0; } #undef STEM_RU_FUNC #define STEM_RU_FUNC(func,table) \ static int func ( LOC_CHAR_TYPE * word, int len ) \ { \ return stem_ru_table ( word, len, LOC_PREFIX(table), \ sizeof(LOC_PREFIX(table))/sizeof(LOC_TABLE_ENTRY) ); \ } #undef STEM_RU_FUNC_I #define STEM_RU_FUNC_I(table) \ static int LOC_PREFIX(stem_##table##_i) ( LOC_CHAR_TYPE * word, int len ) \ { \ return stem_ru_table_i ( word, len, LOC_PREFIX(table), LOC_PREFIX(table##_i), \ sizeof(LOC_PREFIX(table##_i))/sizeof(LOC_TABLE_INDEX) ); \ } STEM_RU_FUNC_I(ru_adj) STEM_RU_FUNC_I(ru_part) STEM_RU_FUNC_I(ru_dear) STEM_RU_FUNC_I(ru_verb) STEM_RU_FUNC_I(ru_noun) static int LOC_PREFIX(stem_ru_adjectival) ( LOC_CHAR_TYPE * word, int len ) { int i = LOC_PREFIX(stem_ru_adj_i) ( word, len ); if ( i ) i += LOC_PREFIX(stem_ru_part_i) ( word, len-i ); return i; } static int LOC_PREFIX(stem_ru_verb_ov) ( LOC_CHAR_TYPE * word, int len ) { int i = LOC_PREFIX(stem_ru_verb_i) ( word, len ); if ( i && (len>=i+2) && word[len-i-2] == RUS::O && word[len-i-1] == RUS::V ) return i+2; return i; } void LOC_PREFIX(stem_ru_init) () { int i; #undef STEM_RU_INIT_TABLE #define STEM_RU_INIT_TABLE(table) \ for ( i=0; i<int(sizeof(LOC_PREFIX(table))/sizeof(LOC_TABLE_ENTRY)); i++ ) \ LOC_PREFIX(table)[i].len = ((int)strlen((char*)LOC_PREFIX(table)[i].suffix)/sizeof(LOC_CHAR_TYPE))- 1; STEM_RU_INIT_TABLE(ru_adj) STEM_RU_INIT_TABLE(ru_part) STEM_RU_INIT_TABLE(ru_verb) STEM_RU_INIT_TABLE(ru_noun) STEM_RU_INIT_TABLE(ru_dear) } void LOC_PREFIX(stem_ru) ( LOC_CHAR_TYPE * word ) { int r1, r2; int i, len; // IsVowel #undef IV #define IV(c) ( \ c==RUS::A || c==RUS::E || c==RUS::YO || c==RUS::I || c==RUS::O || \ c==RUS::U || c==RUS::Y || c==RUS::EE || c==RUS::YU || c==RUS::YA ) // NotEndOfWord #undef NEOW #define NEOW(_arg) (*((unsigned char*)(_arg)) && *((unsigned char*)(_arg)+1)) while ( NEOW(word) ) if ( IV(*word) ) break; else ++word; if ( NEOW(word) ) ++word; else return; len = 0; while ( NEOW(word+len) ) ++len; r1 = r2 = len; for ( i=-1; i<len-1; ++i ) if ( IV(word[i]) && !IV(word[i+1]) ) { r1 = i+2; break; } for ( i=r1; i<len-1; ++i ) if ( IV(word[i]) && !IV(word[i+1]) ) { r2 = i+2; break; } #define C(p) word[len-p] #define W(p,c) ( C(p)==c ) #define XSUFF2(c2,c1) ( W(1,c1) && W(2,c2) ) #define XSUFF3(c3,c2,c1) ( W(1,c1) && W(2,c2) && W(3,c3) ) #define XSUFF4(c4,c3,c2,c1) ( W(1,c1) && W(2,c2) && W(3,c3) && W(4,c4) ) #define XSUFF5(c5,c4,c3,c2,c1) ( W(1,c1) && W(2,c2) && W(3,c3) && W(4,c4) && W(5,c5) ) #define BRK(_arg) { len -= _arg; break; } #define CHK(_func) { i = LOC_PREFIX(_func) ( word, len ); if ( i ) BRK ( i ); } while (true) { CHK ( stem_ru_dear_i ); if ( C(1)==RUS::V && len>=2 ) { if ( C(2)==RUS::I || C(2)==RUS::Y || C(2)==RUS::YA ) BRK(2); if ( C(2)==RUS::A ) { if ( C(3)==RUS::V && C(4)==RUS::A ) BRK(4); BRK(2); } } if ( len>=3 && XSUFF3 ( RUS::V, RUS::SH, RUS::I ) && ( C(4)==RUS::A || C(4)==RUS::I || C(4)==RUS::Y || C(4)==RUS::YA ) ) BRK(4); if ( len>=5 && XSUFF5 ( RUS::V, RUS::SH, RUS::I, RUS::S, RUS::MYA ) && ( C(6)==RUS::A || C(6)==RUS::I || C(6)==RUS::Y || C(6)==RUS::YA ) ) BRK(6); CHK ( stem_ru_adjectival ); if ( len>=2 && ( XSUFF2 ( RUS::S, RUS::MYA ) || XSUFF2 ( RUS::S, RUS::YA ) ) ) { len -= 2; CHK ( stem_ru_adjectival ); CHK ( stem_ru_verb_ov ); } else { CHK ( stem_ru_verb_ov ); } CHK ( stem_ru_noun_i ); break; } if ( len>0 && ( W(1,RUS::IY) || W(1,RUS::I) ) ) len--; if ( len-r2>=3 && XSUFF3 ( RUS::O, RUS::S, RUS::T ) ) len -= 3; else if ( len-r2>=4 && XSUFF4 ( RUS::O, RUS::S, RUS::T, RUS::MYA ) ) len -= 4; if ( len>=3 && XSUFF3 ( RUS::E, RUS::IY, RUS::SH ) ) len -= 3; else if ( len>=4 && XSUFF4 ( RUS::E, RUS::IY, RUS::SH, RUS::E ) ) len -= 4; if ( len>=2 && XSUFF2 ( RUS::N, RUS::N ) ) len--; if ( len>0 && W(1,RUS::MYA) ) len--; *((unsigned char*)(word+len)) = '\0'; } // undefine externally defined stuff #undef LOC_CHAR_TYPE #undef LOC_PREFIX #undef RUS
11,172
C++
.inl
441
22.988662
116
0.473843
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
17,399
platform_service_interface.cpp
anbox_anbox/android/service/platform_service_interface.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "android/service/platform_service_interface.h" namespace android { BpPlatformService::BpPlatformService(const sp<IBinder> &binder) : BpInterface<IPlatformService>(binder) { } status_t BpPlatformService::boot_finished() { Parcel data, reply; data.writeInterfaceToken(IPlatformService::getInterfaceDescriptor()); return remote()->transact(IPlatformService::BOOT_FINISHED, data, &reply); } status_t BpPlatformService::update_window_state(const Parcel&) { Parcel data, reply; data.writeInterfaceToken(IPlatformService::getInterfaceDescriptor()); return remote()->transact(IPlatformService::UPDATE_WINDOW_STATE, data, &reply); } status_t BpPlatformService::update_application_list(const Parcel&) { Parcel data, reply; data.writeInterfaceToken(IPlatformService::getInterfaceDescriptor()); return remote()->transact(IPlatformService::UPDATE_APPLICATION_LIST, data, &reply); } status_t BpPlatformService::set_clipboard_data(const Parcel&) { Parcel data, reply; data.writeInterfaceToken(IPlatformService::getInterfaceDescriptor()); return remote()->transact(IPlatformService::SET_CLIPBOARD_DATA, data, &reply); } status_t BpPlatformService::get_clipboard_data(const Parcel&, Parcel*) { Parcel data, reply; data.writeInterfaceToken(IPlatformService::getInterfaceDescriptor()); return remote()->transact(IPlatformService::GET_CLIPBOARD_DATA, data, &reply); } IMPLEMENT_META_INTERFACE(PlatformService, "org.anbox.IPlatformService"); status_t BnPlatformService::onTransact(uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case BOOT_FINISHED: CHECK_INTERFACE(IPlatformService, data, reply); return boot_finished(); case UPDATE_WINDOW_STATE: CHECK_INTERFACE(IPlatformService, data, reply); return update_window_state(data); case UPDATE_APPLICATION_LIST: CHECK_INTERFACE(IPlatformService, data, reply); return update_application_list(data); case SET_CLIPBOARD_DATA: CHECK_INTERFACE(IPlatformService, data, reply); return set_clipboard_data(data); case GET_CLIPBOARD_DATA: CHECK_INTERFACE(IPlatformService, data, reply); return get_clipboard_data(data, reply); default: break; } return BBinder::onTransact(code, data, reply, flags); } } // namespace android
3,096
C++
.cpp
71
39.056338
87
0.742952
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,401
activity_manager_interface.cpp
anbox_anbox/android/service/activity_manager_interface.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #define LOG_TAG "Anboxd" #include "android/service/activity_manager_interface.h" namespace android { BpActivityManager::BpActivityManager(const sp<IBinder> &binder) : BpInterface<IActivityManager>(binder) { } status_t BpActivityManager::setFocusedTask(int32_t id) { Parcel data, reply; data.writeInterfaceToken(IActivityManager::getInterfaceDescriptor()); data.writeInt32(id); return remote()->transact(IActivityManager::SET_FOCUSED_TASK, data, &reply); } status_t BpActivityManager::removeTask(int32_t id) { Parcel data, reply; data.writeInterfaceToken(IActivityManager::getInterfaceDescriptor()); data.writeInt32(id); return remote()->transact(IActivityManager::REMOVE_TASK, data, &reply); } status_t BpActivityManager::resizeTask(int32_t id, const anbox::graphics::Rect &rect, int resize_mode) { Parcel data, reply; data.writeInterfaceToken(IActivityManager::getInterfaceDescriptor()); data.writeInt32(id); data.writeInt32(resize_mode); data.writeInt32(rect.left()); data.writeInt32(rect.top()); data.writeInt32(rect.right()); data.writeInt32(rect.bottom()); return remote()->transact(IActivityManager::RESIZE_TASK, data, &reply); } IMPLEMENT_META_INTERFACE(ActivityManager, "android.app.IActivityManager"); } // namespace android
1,961
C++
.cpp
47
39.276596
104
0.772417
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,403
daemon.cpp
anbox_anbox/android/service/daemon.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "android/service/daemon.h" #include "android/service/host_connector.h" #include "android/service/platform_service.h" #include "core/posix/signal.h" #include <memory> #include <cstdlib> #include <binder/IPCThreadState.h> #include <binder/ProcessState.h> #include <binder/IServiceManager.h> namespace anbox { Daemon::Daemon() { } Daemon::~Daemon() { } int Daemon::run() { auto trap = core::posix::trap_signals_for_process({core::posix::Signal::sig_term, core::posix::Signal::sig_int}); trap->signal_raised().connect([trap](const core::posix::Signal&) { trap->stop(); }); auto host_connector = std::make_shared<HostConnector>(); host_connector->start(); android::defaultServiceManager()->addService( android::String16(android::PlatformService::service_name()), new android::PlatformService(host_connector->platform_api_stub())); android::ProcessState::self()->startThreadPool(); trap->run(); android::IPCThreadState::self()->joinThreadPool(); return EXIT_SUCCESS; } } // namespace anbox
1,816
C++
.cpp
47
34.148936
86
0.702564
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,404
main.cpp
anbox_anbox/android/service/main.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "android/service/daemon.h" int main(int, char**) { anbox::Daemon daemon; return daemon.run(); }
789
C++
.cpp
21
35.380952
76
0.748042
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,406
android_api_skeleton.cpp
anbox_anbox/android/service/android_api_skeleton.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #define LOG_TAG "Anboxd" #include "android/service/android_api_skeleton.h" #include "anbox_rpc.pb.h" #include "anbox_bridge.pb.h" #include <core/posix/exec.h> #include <core/posix/child_process.h> #include <binder/IServiceManager.h> #include <string> #include <sstream> namespace { std::map<std::string,std::string> common_env = { {"ANDROID_DATA", "/data"}, {"ANDROID_ROOT", "/system"}, }; } namespace anbox { AndroidApiSkeleton::AndroidApiSkeleton() { } AndroidApiSkeleton::~AndroidApiSkeleton() { } void AndroidApiSkeleton::wait_for_process(core::posix::ChildProcess &process, anbox::protobuf::rpc::Void *response) { const auto result = process.wait_for(core::posix::wait::Flags::untraced); if (result.status != core::posix::wait::Result::Status::exited || result.detail.if_exited.status != core::posix::exit::Status::success) { response->set_error("Failed to execute process"); // FIXME once we add proper error codes/domains we need to add structured error // info to the response here. } } void AndroidApiSkeleton::connect_services() { if (!activity_manager_.get()) { auto am = android::defaultServiceManager()->getService(android::String16("activity")); if (am.get()) activity_manager_ = new android::BpActivityManager(am); } } void AndroidApiSkeleton::launch_application(anbox::protobuf::bridge::LaunchApplication const *request, anbox::protobuf::rpc::Void *response, google::protobuf::Closure *done) { (void) response; auto intent = request->intent(); std::vector<std::string> argv = { "/system/bin/am", "start", }; if (request->has_stack()) { argv.push_back("--stack"); argv.push_back(std::to_string(request->stack())); } if (request->has_launch_bounds()) { argv.push_back("--launch-bounds"); std::stringstream launch_bounds; launch_bounds << request->launch_bounds().left() << " " << request->launch_bounds().top() << " " << request->launch_bounds().right() << " " << request->launch_bounds().bottom(); argv.push_back(launch_bounds.str()); } if (intent.has_action()) { argv.push_back("-a"); argv.push_back(intent.action()); } if (intent.has_uri()) { argv.push_back("-d"); argv.push_back(intent.uri()); } if (intent.has_type()) { argv.push_back("-t"); argv.push_back(intent.type()); } std::string component; if (intent.has_package()) component += intent.package(); if (!component.empty() && intent.has_component()) { component += "/"; component += intent.component(); } if (!component.empty()) argv.push_back(component); ALOGI("Launch am with the following arguments: "); std::string test; for (const auto &a : argv) { test += a; test += " "; } ALOGI("%s", test.c_str()); auto process = core::posix::exec("/system/bin/sh", argv, common_env, core::posix::StandardStream::empty); wait_for_process(process, response); done->Run(); } void AndroidApiSkeleton::set_focused_task(anbox::protobuf::bridge::SetFocusedTask const *request, anbox::protobuf::rpc::Void *response, google::protobuf::Closure *done) { connect_services(); if (activity_manager_.get()) activity_manager_->setFocusedTask(request->id()); else response->set_error("ActivityManager is not available"); done->Run(); } void AndroidApiSkeleton::remove_task(anbox::protobuf::bridge::RemoveTask const *request, anbox::protobuf::rpc::Void *response, google::protobuf::Closure *done) { connect_services(); if (activity_manager_.get()) activity_manager_->removeTask(request->id()); else response->set_error("ActivityManager is not available"); done->Run(); } void AndroidApiSkeleton::resize_task(anbox::protobuf::bridge::ResizeTask const *request, anbox::protobuf::rpc::Void *response, google::protobuf::Closure *done) { connect_services(); if (activity_manager_.get()) { auto r = request->rect(); activity_manager_->resizeTask(request->id(), anbox::graphics::Rect{r.left(), r.top(), r.right(), r.bottom()}, request->resize_mode()); } else { response->set_error("ActivityManager is not available"); } done->Run(); } } // namespace anbox
5,497
C++
.cpp
142
31.091549
109
0.612855
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,408
platform_service.cpp
anbox_anbox/android/service/platform_service.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "android/service/platform_service.h" #include "anbox/rpc/channel.h" #include "anbox_rpc.pb.h" #include "anbox_bridge.pb.h" #define LOG_TAG "Anboxd" #include <cutils/log.h> #include <utils/String8.h> using namespace android; namespace android { PlatformService::PlatformService(const std::shared_ptr<anbox::PlatformApiStub> &platform_api_stub) : platform_api_stub_(platform_api_stub) { } status_t PlatformService::boot_finished() { platform_api_stub_->boot_finished(); return OK; } anbox::PlatformApiStub::WindowStateUpdate::Window PlatformService::unpack_window_state(const Parcel &data) { bool has_surface = data.readByte() != 0; String8 package_name(data.readString16()); auto frame_left = data.readInt32(); auto frame_top = data.readInt32(); auto frame_right = data.readInt32(); auto frame_bottom = data.readInt32(); auto task_id = data.readInt32(); auto stack_id = data.readInt32(); auto rotation_angle = data.readInt32(); return anbox::PlatformApiStub::WindowStateUpdate::Window{ -1, // Display id will be added by the caller has_surface, package_name.string(), {frame_left, frame_top, frame_right, frame_bottom}, task_id, stack_id, }; } status_t PlatformService::update_window_state(const Parcel &data) { anbox::PlatformApiStub::WindowStateUpdate state; const auto num_displays = data.readInt32(); for (auto n = 0; n < num_displays; n++) { const auto display_id = data.readInt32(); const auto num_windows = data.readInt32(); for (auto m = 0; m < num_windows; m++) { auto window = unpack_window_state(data); window.display_id = display_id; state.updated_windows.push_back(window); } } const auto num_removed_windows = data.readInt32(); for (auto n = 0; n < num_removed_windows; n++) { auto window = unpack_window_state(data); state.removed_windows.push_back(window); } platform_api_stub_->update_window_state(state); return OK; } status_t PlatformService::update_application_list(const Parcel &data) { anbox::PlatformApiStub::ApplicationListUpdate update; const auto num_packages = data.readInt32(); for (auto n = 0; n < num_packages; n++) { String8 name(data.readString16()); String8 package_name(data.readString16()); auto p = anbox::PlatformApiStub::ApplicationListUpdate::Application{ name.string(), package_name.string(), }; String8 action(data.readString16()); String8 uri(data.readString16()); String8 type(data.readString16()); String8 component_package(data.readString16()); String8 component_class(data.readString16()); std::vector<std::string> categories; unsigned int num_categories = data.readInt32(); for (int m = 0; m < num_categories; m++) categories.push_back(String8(data.readString16()).string()); p.launch_intent.action = action; p.launch_intent.uri = uri; p.launch_intent.type = type; p.launch_intent.package = component_package; p.launch_intent.component = component_class; p.launch_intent.categories = categories; data.readByteVector(&p.icon); // Send updates with icons separately to not overflow protobuf if (p.icon.size() > 0) { anbox::PlatformApiStub::ApplicationListUpdate with_icon_update; with_icon_update.applications.push_back(p); platform_api_stub_->update_application_list(with_icon_update); } else { update.applications.push_back(p); } } const auto num_removed_packages = data.readInt32(); for (auto n = 0; n < num_removed_packages; n++) { String8 package_name(data.readString16()); update.removed_applications.push_back(package_name.string()); } platform_api_stub_->update_application_list(update); return OK; } status_t PlatformService::set_clipboard_data(const Parcel &data) { if (data.readInt32() == 0) return OK; String8 text(data.readString16()); const auto clip_data = anbox::PlatformApiStub::ClipboardData{text.string()}; platform_api_stub_->set_clipboard_data(clip_data); return OK; } status_t PlatformService::get_clipboard_data(const Parcel &data, Parcel *reply) { (void) data; const auto clip_data = platform_api_stub_->get_clipboard_data(); if (clip_data.text.empty()) { reply->writeInt32(0); return OK; } reply->writeInt32(1); reply->writeString16(String16(clip_data.text.c_str(), clip_data.text.length())); return OK; } } // namespace android
5,415
C++
.cpp
134
34.567164
108
0.67866
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,469
audio_hw.cpp
anbox_anbox/android/audio/audio_hw.cpp
/* * Copyright (C) 2012 The Android Open Source Project * * 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. */ #define LOG_TAG "audio_hw_generic" #define LOG_NDEBUG 0 #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <stdint.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/un.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <cutils/log.h> #include <cutils/str_parms.h> #include <hardware/audio.h> #include <hardware/hardware.h> #include <system/audio.h> #include "anbox/audio/client_info.h" #define AUDIO_DEVICE_NAME "/dev/anbox_audio" #define OUT_SAMPLING_RATE 44100 #define OUT_BUFFER_SIZE 4096 #define OUT_LATENCY_MS 20 #define IN_SAMPLING_RATE 8000 #define IN_BUFFER_SIZE 320 struct generic_audio_device { struct audio_hw_device device; pthread_mutex_t lock; struct audio_stream_out *output; struct audio_stream_in *input; bool mic_mute; }; struct generic_stream_out { struct audio_stream_out stream; struct generic_audio_device *dev; audio_devices_t device; int fd; }; struct generic_stream_in { struct audio_stream_in stream; struct generic_audio_device *dev; audio_devices_t device; int fd; }; static uint32_t out_get_sample_rate(const struct audio_stream *stream) { return OUT_SAMPLING_RATE; } static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate) { return -ENOSYS; } static size_t out_get_buffer_size(const struct audio_stream *stream) { return OUT_BUFFER_SIZE; } static audio_channel_mask_t out_get_channels(const struct audio_stream *stream) { return AUDIO_CHANNEL_OUT_STEREO; } static audio_format_t out_get_format(const struct audio_stream *stream) { return AUDIO_FORMAT_PCM_16_BIT; } static int out_set_format(struct audio_stream *stream, audio_format_t format) { return -ENOSYS; } static int out_standby(struct audio_stream *stream) { return 0; } static int out_dump(const struct audio_stream *stream, int fd) { struct generic_stream_out *out = (struct generic_stream_out *)stream; dprintf(fd, "\tout_dump:\n" "\t\tsample rate: %u\n" "\t\tbuffer size: %u\n" "\t\tchannel mask: %08x\n" "\t\tformat: %d\n" "\t\tdevice: %08x\n" "\t\taudio dev: %p\n\n", out_get_sample_rate(stream), out_get_buffer_size(stream), out_get_channels(stream), out_get_format(stream), out->device, out->dev); return 0; } static int out_set_parameters(struct audio_stream *stream, const char *kvpairs) { struct generic_stream_out *out = (struct generic_stream_out *)stream; struct str_parms *parms; char value[32]; int ret; long val; char *end; parms = str_parms_create_str(kvpairs); ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value)); if (ret >= 0) { errno = 0; val = strtol(value, &end, 10); if (errno == 0 && (end != NULL) && (*end == '\0') && ((int)val == val)) { out->device = (int)val; } else { ret = -EINVAL; } } str_parms_destroy(parms); return ret; } static char *out_get_parameters(const struct audio_stream *stream, const char *keys) { struct generic_stream_out *out = (struct generic_stream_out *)stream; struct str_parms *query = str_parms_create_str(keys); char *str; char value[256]; struct str_parms *reply = str_parms_create(); int ret; ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value)); if (ret >= 0) { str_parms_add_int(reply, AUDIO_PARAMETER_STREAM_ROUTING, out->device); str = strdup(str_parms_to_str(reply)); } else { str = strdup(keys); } str_parms_destroy(query); str_parms_destroy(reply); return str; } static uint32_t out_get_latency(const struct audio_stream_out *stream) { return OUT_LATENCY_MS; } static int out_set_volume(struct audio_stream_out *stream, float left, float right) { return -ENOSYS; } static ssize_t out_write(struct audio_stream_out *stream, const void *buffer, size_t bytes) { struct generic_stream_out *out = (struct generic_stream_out *)stream; struct generic_audio_device *adev = out->dev; pthread_mutex_lock(&adev->lock); if (out->fd >= 0) bytes = write(out->fd, buffer, bytes); pthread_mutex_unlock(&adev->lock); return bytes; } static int out_get_render_position(const struct audio_stream_out *stream, uint32_t *dsp_frames) { return -ENOSYS; } static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect) { return 0; } static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect) { return 0; } static int out_get_next_write_timestamp(const struct audio_stream_out *stream, int64_t *timestamp) { return -ENOSYS; } static uint32_t in_get_sample_rate(const struct audio_stream *stream) { return IN_SAMPLING_RATE; } static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate) { return -ENOSYS; } static size_t in_get_buffer_size(const struct audio_stream *stream) { return IN_BUFFER_SIZE; } static audio_channel_mask_t in_get_channels(const struct audio_stream *stream) { return AUDIO_CHANNEL_IN_MONO; } static audio_format_t in_get_format(const struct audio_stream *stream) { return AUDIO_FORMAT_PCM_16_BIT; } static int in_set_format(struct audio_stream *stream, audio_format_t format) { return -ENOSYS; } static int in_standby(struct audio_stream *stream) { return 0; } static int in_dump(const struct audio_stream *stream, int fd) { struct generic_stream_in *in = (struct generic_stream_in *)stream; dprintf(fd, "\tin_dump:\n" "\t\tsample rate: %u\n" "\t\tbuffer size: %u\n" "\t\tchannel mask: %08x\n" "\t\tformat: %d\n" "\t\tdevice: %08x\n" "\t\taudio dev: %p\n\n", in_get_sample_rate(stream), in_get_buffer_size(stream), in_get_channels(stream), in_get_format(stream), in->device, in->dev); return 0; } static int in_set_parameters(struct audio_stream *stream, const char *kvpairs) { struct generic_stream_in *in = (struct generic_stream_in *)stream; struct str_parms *parms; char value[32]; int ret; long val; char *end; parms = str_parms_create_str(kvpairs); ret = str_parms_get_str(parms, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value)); if (ret >= 0) { errno = 0; val = strtol(value, &end, 10); if ((errno == 0) && (end != NULL) && (*end == '\0') && ((int)val == val)) { in->device = (int)val; } else { ret = -EINVAL; } } str_parms_destroy(parms); return ret; } static char *in_get_parameters(const struct audio_stream *stream, const char *keys) { struct generic_stream_in *in = (struct generic_stream_in *)stream; struct str_parms *query = str_parms_create_str(keys); char *str; char value[256]; struct str_parms *reply = str_parms_create(); int ret; ret = str_parms_get_str(query, AUDIO_PARAMETER_STREAM_ROUTING, value, sizeof(value)); if (ret >= 0) { str_parms_add_int(reply, AUDIO_PARAMETER_STREAM_ROUTING, in->device); str = strdup(str_parms_to_str(reply)); } else { str = strdup(keys); } str_parms_destroy(query); str_parms_destroy(reply); return str; } static int in_set_gain(struct audio_stream_in *stream, float gain) { return 0; } static ssize_t in_read(struct audio_stream_in *stream, void *buffer, size_t bytes) { struct generic_stream_in *in = (struct generic_stream_in *)stream; struct generic_audio_device *adev = in->dev; pthread_mutex_lock(&adev->lock); if (in->fd >= 0) bytes = read(in->fd, buffer, bytes); if (adev->mic_mute && (bytes > 0)) { memset(buffer, 0, bytes); } pthread_mutex_unlock(&adev->lock); return bytes; } static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream) { return 0; } static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect) { return 0; } static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect) { return 0; } static int connect_audio_server(const anbox::audio::ClientInfo::Type &type) { int fd = socket(AF_LOCAL, SOCK_STREAM, 0); if (fd < 0) return -errno; struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, AUDIO_DEVICE_NAME, sizeof(addr.sun_path)); if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { close(fd); return -errno; } // We will send out client type information to the server and the // server will either deny the request by closing the connection // or by sending us the approved client details back. anbox::audio::ClientInfo client_info{type}; if (::write(fd, &client_info, sizeof(client_info)) < 0) { close(fd); return -EIO; } auto bytes_read = ::read(fd, &client_info, sizeof(client_info)); if (bytes_read < 0) { close(fd); return -EIO; } // FIXME once we have real client details we need to check if we // got everything we need or if anything is missing. ALOGE("Successfully connected Anbox audio server"); return fd; } static int adev_open_output_stream(struct audio_hw_device *dev, audio_io_handle_t handle, audio_devices_t devices, audio_output_flags_t flags, struct audio_config *config, struct audio_stream_out **stream_out, const char *address __unused) { struct generic_audio_device *adev = (struct generic_audio_device *)dev; struct generic_stream_out *out; int ret = 0, fd = 0; pthread_mutex_lock(&adev->lock); if (adev->output != NULL) { ret = -ENOSYS; goto error; } fd = connect_audio_server(anbox::audio::ClientInfo::Type::Playback); if (fd < 0) { ret = fd; ALOGE("Failed to connect with Anbox audio servers (err %d)", ret); goto error; } if ((config->format != AUDIO_FORMAT_PCM_16_BIT) || (config->channel_mask != AUDIO_CHANNEL_OUT_STEREO) || (config->sample_rate != OUT_SAMPLING_RATE)) { ALOGE("Error opening output stream format %d, channel_mask %04x, sample_rate %u", config->format, config->channel_mask, config->sample_rate); config->format = AUDIO_FORMAT_PCM_16_BIT; config->channel_mask = AUDIO_CHANNEL_OUT_STEREO; config->sample_rate = OUT_SAMPLING_RATE; ret = -EINVAL; goto error; } out = (struct generic_stream_out *)calloc(1, sizeof(struct generic_stream_out)); out->fd = fd; out->stream.common.get_sample_rate = out_get_sample_rate; out->stream.common.set_sample_rate = out_set_sample_rate; out->stream.common.get_buffer_size = out_get_buffer_size; out->stream.common.get_channels = out_get_channels; out->stream.common.get_format = out_get_format; out->stream.common.set_format = out_set_format; out->stream.common.standby = out_standby; out->stream.common.dump = out_dump; out->stream.common.set_parameters = out_set_parameters; out->stream.common.get_parameters = out_get_parameters; out->stream.common.add_audio_effect = out_add_audio_effect; out->stream.common.remove_audio_effect = out_remove_audio_effect; out->stream.get_latency = out_get_latency; out->stream.set_volume = out_set_volume; out->stream.write = out_write; out->stream.get_render_position = out_get_render_position; out->stream.get_next_write_timestamp = out_get_next_write_timestamp; out->dev = adev; out->device = devices; adev->output = (struct audio_stream_out *)out; *stream_out = &out->stream; error: pthread_mutex_unlock(&adev->lock); return ret; } static void adev_close_output_stream(struct audio_hw_device *dev, struct audio_stream_out *stream) { struct generic_audio_device *adev = (struct generic_audio_device *)dev; pthread_mutex_lock(&adev->lock); if (stream == adev->output) { free(stream); adev->output = NULL; } pthread_mutex_unlock(&adev->lock); } static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs) { return 0; } static char *adev_get_parameters(const struct audio_hw_device *dev, const char *keys) { return strdup(""); } static int adev_init_check(const struct audio_hw_device *dev) { return 0; } static int adev_set_voice_volume(struct audio_hw_device *dev, float volume) { return 0; } static int adev_set_master_volume(struct audio_hw_device *dev, float volume) { return -ENOSYS; } static int adev_get_master_volume(struct audio_hw_device *dev, float *volume) { return -ENOSYS; } static int adev_set_master_mute(struct audio_hw_device *dev, bool muted) { return -ENOSYS; } static int adev_get_master_mute(struct audio_hw_device *dev, bool *muted) { return -ENOSYS; } static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode) { return 0; } static int adev_set_mic_mute(struct audio_hw_device *dev, bool state) { struct generic_audio_device *adev = (struct generic_audio_device *)dev; pthread_mutex_lock(&adev->lock); adev->mic_mute = state; pthread_mutex_unlock(&adev->lock); return 0; } static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state) { struct generic_audio_device *adev = (struct generic_audio_device *)dev; pthread_mutex_lock(&adev->lock); *state = adev->mic_mute; pthread_mutex_unlock(&adev->lock); return 0; } static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev, const struct audio_config *config) { return IN_BUFFER_SIZE; } static int adev_open_input_stream(struct audio_hw_device *dev, audio_io_handle_t handle, audio_devices_t devices, struct audio_config *config, struct audio_stream_in **stream_in, audio_input_flags_t flags __unused, const char *address __unused, audio_source_t source __unused) { struct generic_audio_device *adev = (struct generic_audio_device *)dev; struct generic_stream_in *in; int ret = 0, fd = 0; pthread_mutex_lock(&adev->lock); if (adev->input != NULL) { ret = -ENOSYS; goto error; } if ((config->format != AUDIO_FORMAT_PCM_16_BIT) || (config->channel_mask != AUDIO_CHANNEL_IN_MONO) || (config->sample_rate != IN_SAMPLING_RATE)) { ALOGE("Error opening input stream format %d, channel_mask %04x, sample_rate %u", config->format, config->channel_mask, config->sample_rate); config->format = AUDIO_FORMAT_PCM_16_BIT; config->channel_mask = AUDIO_CHANNEL_IN_MONO; config->sample_rate = IN_SAMPLING_RATE; ret = -EINVAL; goto error; } fd = connect_audio_server(anbox::audio::ClientInfo::Type::Recording); if (fd < 0) { ret = fd; ALOGE("Failed to connect with Anbox audio servers (err %d)", ret); goto error; } in = (struct generic_stream_in *)calloc(1, sizeof(struct generic_stream_in)); in->fd = fd; in->stream.common.get_sample_rate = in_get_sample_rate; in->stream.common.set_sample_rate = in_set_sample_rate; in->stream.common.get_buffer_size = in_get_buffer_size; in->stream.common.get_channels = in_get_channels; in->stream.common.get_format = in_get_format; in->stream.common.set_format = in_set_format; in->stream.common.standby = in_standby; in->stream.common.dump = in_dump; in->stream.common.set_parameters = in_set_parameters; in->stream.common.get_parameters = in_get_parameters; in->stream.common.add_audio_effect = in_add_audio_effect; in->stream.common.remove_audio_effect = in_remove_audio_effect; in->stream.set_gain = in_set_gain; in->stream.read = in_read; in->stream.get_input_frames_lost = in_get_input_frames_lost; in->dev = adev; in->device = devices; adev->input = (struct audio_stream_in *)in; *stream_in = &in->stream; error: pthread_mutex_unlock(&adev->lock); return ret; } static void adev_close_input_stream(struct audio_hw_device *dev, struct audio_stream_in *stream) { struct generic_audio_device *adev = (struct generic_audio_device *)dev; pthread_mutex_lock(&adev->lock); if (stream == adev->input) { free(stream); adev->input = NULL; } pthread_mutex_unlock(&adev->lock); } static int adev_dump(const audio_hw_device_t *dev, int fd) { struct generic_audio_device *adev = (struct generic_audio_device *)dev; const size_t SIZE = 256; char buffer[SIZE]; dprintf(fd, "\nadev_dump:\n" "\tmic_mute: %s\n" "\toutput: %p\n" "\tinput: %p\n\n", adev->mic_mute ? "true" : "false", adev->output, adev->input); if (adev->output != NULL) out_dump((const struct audio_stream *)adev->output, fd); if (adev->input != NULL) in_dump((const struct audio_stream *)adev->input, fd); return 0; } static int adev_close(hw_device_t *dev) { struct generic_audio_device *adev = (struct generic_audio_device *)dev; adev_close_output_stream((struct audio_hw_device *)dev, adev->output); adev_close_input_stream((struct audio_hw_device *)dev, adev->input); free(dev); return 0; } static int adev_open(const hw_module_t *module, const char *name, hw_device_t **device) { struct generic_audio_device *adev; if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) return -EINVAL; adev = (struct generic_audio_device*) calloc(1, sizeof(struct generic_audio_device)); adev->device.common.tag = HARDWARE_DEVICE_TAG; adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0; adev->device.common.module = (struct hw_module_t *)module; adev->device.common.close = adev_close; adev->device.init_check = adev_init_check; adev->device.set_voice_volume = adev_set_voice_volume; adev->device.set_master_volume = adev_set_master_volume; adev->device.get_master_volume = adev_get_master_volume; adev->device.set_master_mute = adev_set_master_mute; adev->device.get_master_mute = adev_get_master_mute; adev->device.set_mode = adev_set_mode; adev->device.set_mic_mute = adev_set_mic_mute; adev->device.get_mic_mute = adev_get_mic_mute; adev->device.set_parameters = adev_set_parameters; adev->device.get_parameters = adev_get_parameters; adev->device.get_input_buffer_size = adev_get_input_buffer_size; adev->device.open_output_stream = adev_open_output_stream; adev->device.close_output_stream = adev_close_output_stream; adev->device.open_input_stream = adev_open_input_stream; adev->device.close_input_stream = adev_close_input_stream; adev->device.dump = adev_dump; *device = &adev->device.common; return 0; } static struct hw_module_methods_t hal_module_methods = { .open = adev_open, }; struct audio_module HAL_MODULE_INFO_SYM = { .common = { .tag = HARDWARE_MODULE_TAG, .module_api_version = AUDIO_MODULE_API_VERSION_0_1, .hal_api_version = HARDWARE_HAL_API_VERSION, .id = AUDIO_HARDWARE_MODULE_ID, .name = "Anbox audio HW HAL", .author = "The Android Open Source Project", .methods = &hal_module_methods, }, };
20,257
C++
.cpp
556
31.476619
95
0.66968
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,470
hwcomposer.cpp
anbox_anbox/android/hwcomposer/hwcomposer.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include <hardware/hardware.h> #include <hardware/hwcomposer.h> #include <map> #include <vector> #include <algorithm> #include <string> #define LOG_NDEBUG 1 #include <cutils/log.h> #include "HostConnection.h" #include "gralloc_cb.h" #define DEFINE_HOST_CONNECTION() \ HostConnection *hostCon = HostConnection::get(); \ renderControl_encoder_context_t *rcEnc = (hostCon ? hostCon->rcEncoder() : NULL) #define DEFINE_AND_VALIDATE_HOST_CONNECTION() \ HostConnection *hostCon = HostConnection::get(); \ if (!hostCon) { \ ALOGE("hwcomposer.anbox: Failed to get host connection\n"); \ return -EIO; \ } \ renderControl_encoder_context_t *rcEnc = hostCon->rcEncoder(); \ if (!rcEnc) { \ ALOGE("hwcomposer.anbox: Failed to get renderControl encoder context\n"); \ return -EIO; \ } struct HwcContext { hwc_composer_device_1_t device; // These 3 variables could be reduced to first_overlay only, however it makes // the conditions in the code more complicated. In order to keep things as // simple as possible, there are 3 major ways to display a frame. // 1. Show only the framebuffer. // 2. Show the framebuffer with some overlays above it. // 3. Show all overlays and hide the framebuffer. // // Since the framebuffer has no alpha channel and is opaque, it can only ever // be the rearmost layer that we end up putting on screen, otherwise it will // cover up all layers behind it, since its display frame is the whole window. // // Without framebuffer_visible, the condition of whether to display the // frambuffer becomes more complex and possibly if (numHwLayers == 0 || // hwLayers[0]->compositionType != HWC_OVERLAY) but that might not be correct. // // The range [first_overlay, first_overlay+num_overlay) is a natural way to // structure the loop and prevents requiring state and iterating through all // the non-OVERLAY layers in hwc_set. bool framebuffer_visible; size_t first_overlay; size_t num_overlays; }; static void dump_layer(hwc_layer_1_t const* l) { ALOGD("\tname='%s', type=%d, flags=%08x, handle=%p, tr=%02x, blend=%04x, {%d,%d,%d,%d}, {%d,%d,%d,%d}", l->name, l->compositionType, l->flags, l->handle, l->transform, l->blending, l->sourceCrop.left, l->sourceCrop.top, l->sourceCrop.right, l->sourceCrop.bottom, l->displayFrame.left, l->displayFrame.top, l->displayFrame.right, l->displayFrame.bottom); } static int hwc_prepare(hwc_composer_device_1_t* dev, size_t numDisplays, hwc_display_contents_1_t** displays) { auto context = reinterpret_cast<HwcContext*>(dev); if (displays == NULL || displays[0] == NULL) return -EINVAL; // Anbox only supports the primary display. if (displays[0]->flags & HWC_GEOMETRY_CHANGED) { const size_t& num_hw_layers = displays[0]->numHwLayers; size_t i = 1; bool visible = (num_hw_layers == 1); // Iterate backwards and skip the first (end) layer, which is the // framebuffer target layer. According to the SurfaceFlinger folks, the // actual location of this layer is up to the HWC implementation to // decide, but is in the well know last slot of the list. This does not // imply that the framebuffer target layer must be topmost. for (; i < num_hw_layers; i++) { hwc_layer_1_t* layer = &displays[0]->hwLayers[num_hw_layers - 1 - i]; #if 0 dump_layer(layer); #endif if (layer->flags & HWC_SKIP_LAYER) { // All layers below and including this one will be drawn into the // framebuffer. Stop marking further layers as HWC_OVERLAY. visible = true; break; } switch (layer->compositionType) { case HWC_OVERLAY: case HWC_FRAMEBUFFER: layer->compositionType = HWC_OVERLAY; break; case HWC_BACKGROUND: break; default: ALOGE("hwcomposor: Invalid compositionType %d", layer->compositionType); break; } } context->first_overlay = num_hw_layers - i; context->num_overlays = i - 1; context->framebuffer_visible = visible; } return 0; } /* * We're using "implicit" synchronization, so make sure we aren't passing any * sync object descriptors around. */ static void check_sync_fds(size_t numDisplays, hwc_display_contents_1_t** displays) { unsigned int i, j; for (i = 0; i < numDisplays; i++) { hwc_display_contents_1_t* list = displays[i]; if (list->retireFenceFd >= 0) { ALOGW("retireFenceFd[%u] was %d", i, list->retireFenceFd); list->retireFenceFd = -1; } for (j = 0; j < list->numHwLayers; j++) { hwc_layer_1_t* layer = &list->hwLayers[j]; if (layer->acquireFenceFd >= 0) { ALOGW("acquireFenceFd[%u][%u] was %d, closing", i, j, layer->acquireFenceFd); close(layer->acquireFenceFd); layer->acquireFenceFd = -1; } if (layer->releaseFenceFd >= 0) { ALOGW("releaseFenceFd[%u][%u] was %d", i, j, layer->releaseFenceFd); layer->releaseFenceFd = -1; } } } } static int hwc_set(hwc_composer_device_1_t* dev, size_t numDisplays, hwc_display_contents_1_t** displays) { auto context = reinterpret_cast<HwcContext*>(dev); if (displays == NULL || displays[0] == NULL) return -EFAULT; DEFINE_AND_VALIDATE_HOST_CONNECTION(); for (size_t i = 0 ; i < displays[0]->numHwLayers ; i++) { const auto layer = &displays[0]->hwLayers[i]; if (layer->flags & HWC_SKIP_LAYER || layer->flags & HWC_IS_CURSOR_LAYER) continue; #if 0 dump_layer(layer); #endif // FIXME this is just dirty ... but layer->handle is a const native_handle_t and canBePosted // can't be called with a const. auto cb = const_cast<cb_handle_t*>(reinterpret_cast<const cb_handle_t*>(layer->handle)); if (!cb_handle_t::validate(cb)) { ALOGE("Buffer handle is invalid\n"); return -EINVAL; } rcEnc->rcPostLayer(rcEnc, layer->name, cb->hostHandle, layer->planeAlpha / 255, layer->sourceCrop.left, layer->sourceCrop.top, layer->sourceCrop.right, layer->sourceCrop.bottom, layer->displayFrame.left, layer->displayFrame.top, layer->displayFrame.right, layer->displayFrame.bottom); hostCon->flush(); } rcEnc->rcPostAllLayersDone(rcEnc); check_sync_fds(numDisplays, displays); return 0; } static int hwc_event_control(hwc_composer_device_1* dev, int disp, int event, int enabled) { return -EFAULT; } static void hwc_register_procs(hwc_composer_device_1* dev, hwc_procs_t const* procs) { } static int hwc_blank(hwc_composer_device_1* dev, int disp, int blank) { return 0; } static int hwc_query(hwc_composer_device_1* dev, int what, int* value) { return 0; } static int hwc_device_close(hw_device_t* dev) { auto context = reinterpret_cast<HwcContext*>(dev); delete context; return 0; } static int hwc_get_display_configs(hwc_composer_device_1* dev, int disp, uint32_t* configs, size_t* numConfigs) { if (disp != 0) { return -EINVAL; } if (*numConfigs > 0) { // Config[0] will be passed in to getDisplayAttributes as the disp // parameter. The ARC display supports only 1 configuration. configs[0] = 0; *numConfigs = 1; } return 0; } static int hwc_get_display_attributes(hwc_composer_device_1* dev, int disp, uint32_t config, const uint32_t* attributes, int32_t* values) { if (disp != 0 || config != 0) { return -EINVAL; } DEFINE_AND_VALIDATE_HOST_CONNECTION(); while (*attributes != HWC_DISPLAY_NO_ATTRIBUTE) { switch (*attributes) { case HWC_DISPLAY_VSYNC_PERIOD: *values = rcEnc->rcGetDisplayVsyncPeriod(rcEnc, disp); break; case HWC_DISPLAY_WIDTH: *values = rcEnc->rcGetDisplayWidth(rcEnc, disp); break; case HWC_DISPLAY_HEIGHT: *values = rcEnc->rcGetDisplayHeight(rcEnc, disp); break; case HWC_DISPLAY_DPI_X: *values = 1000 * rcEnc->rcGetDisplayDpiX(rcEnc, disp); break; case HWC_DISPLAY_DPI_Y: *values = 1000 * rcEnc->rcGetDisplayDpiY(rcEnc, disp); break; default: ALOGE("Unknown attribute value 0x%02x", *attributes); } ++attributes; ++values; } return 0; } static int hwc_device_open(const hw_module_t* module, const char* name, hw_device_t** device) { ALOGD("%s", __PRETTY_FUNCTION__); if (strcmp(name, HWC_HARDWARE_COMPOSER) != 0) return -EINVAL; auto dev = new HwcContext; dev->device.common.tag = HARDWARE_DEVICE_TAG; dev->device.common.version = HWC_DEVICE_API_VERSION_1_0; dev->device.common.module = const_cast<hw_module_t*>(module); dev->device.common.close = hwc_device_close; dev->device.prepare = hwc_prepare; dev->device.set = hwc_set; dev->device.eventControl = hwc_event_control; dev->device.blank = hwc_blank; dev->device.query = hwc_query; dev->device.getDisplayConfigs = hwc_get_display_configs; dev->device.getDisplayAttributes = hwc_get_display_attributes; dev->device.registerProcs = hwc_register_procs; dev->device.dump = nullptr; *device = &dev->device.common; return 0; } static hw_module_methods_t hwc_module_methods = { .open = hwc_device_open }; hwc_module_t HAL_MODULE_INFO_SYM = { .common = { .tag = HARDWARE_MODULE_TAG, .version_major = 1, .version_minor = 0, .id = HWC_HARDWARE_MODULE_ID, .name = "Hardware Composer Module", .author = "Anbox Developers", .methods = &hwc_module_methods, } };
11,264
C++
.cpp
286
31.381119
107
0.614216
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,471
lxc_container_tests.cpp
anbox_anbox/tests/anbox/container/lxc_container_tests.cpp
/* * Copyright (C) 2020 NTT Corporation * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include <memory> #include <sys/types.h> #include "anbox/container/lxc_container.h" #include <gtest/gtest.h> namespace anbox { namespace container { TEST(LxcContainer, IDMap) { auto config = get_id_map(static_cast<uid_t>(1000), static_cast<gid_t>(1000)); EXPECT_EQ(6, config.size()); EXPECT_STREQ("u 0 100000 999", config[0].c_str()); EXPECT_STREQ("g 0 100000 999", config[1].c_str()); EXPECT_STREQ("u 1000 1000 1", config[2].c_str()); EXPECT_STREQ("g 1000 1000 1", config[3].c_str()); // NOTE: host UID 100999 and 101000 are unmapped due to a historical reason // https://github.com/anbox/anbox/issues/1428#issuecomment-615377907 EXPECT_STREQ("u 1001 101001 99000", config[4].c_str()); EXPECT_STREQ("g 1001 101001 99000", config[5].c_str()); config = get_id_map(static_cast<uid_t>(2000), static_cast<gid_t>(2000)); EXPECT_EQ(6, config.size()); EXPECT_STREQ("u 0 100000 999", config[0].c_str()); EXPECT_STREQ("g 0 100000 999", config[1].c_str()); EXPECT_STREQ("u 1000 2000 1", config[2].c_str()); EXPECT_STREQ("g 1000 2000 1", config[3].c_str()); EXPECT_STREQ("u 1001 101001 99000", config[4].c_str()); EXPECT_STREQ("g 1001 101001 99000", config[5].c_str()); } } // namespace container } // namespace anbox
1,888
C++
.cpp
44
41.045455
78
0.718869
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,472
restricted_manager_tests.cpp
anbox_anbox/tests/anbox/application/restricted_manager_tests.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "anbox/application/manager.h" #include <gmock/gmock.h> using namespace ::testing; namespace { class MockManager : public anbox::application::Manager { public: MOCK_METHOD3(launch, void(const anbox::android::Intent&, const anbox::graphics::Rect&, const anbox::wm::Stack::Id&)); MOCK_METHOD0(ready, core::Property<bool>&()); }; } TEST(RestrictedManager, RedirectsLaunchesToRightStack) { auto mgr = std::make_shared<MockManager>(); anbox::application::RestrictedManager restricted_mgr(mgr, anbox::wm::Stack::Id::Freeform); EXPECT_CALL(*mgr, launch(_, _, anbox::wm::Stack::Id::Freeform)) .Times(4); restricted_mgr.launch(anbox::android::Intent{}, anbox::graphics::Rect::Empty, anbox::wm::Stack::Id::Default); restricted_mgr.launch(anbox::android::Intent{}, anbox::graphics::Rect::Empty, anbox::wm::Stack::Id::Fullscreen); restricted_mgr.launch(anbox::android::Intent{}, anbox::graphics::Rect::Empty, anbox::wm::Stack::Id::Invalid); restricted_mgr.launch(anbox::android::Intent{}, anbox::graphics::Rect::Empty, anbox::wm::Stack::Id::Freeform); }
2,007
C++
.cpp
46
36.152174
92
0.650436
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,473
buffered_io_stream_tests.cpp
anbox_anbox/tests/anbox/graphics/buffered_io_stream_tests.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "anbox/graphics/buffered_io_stream.h" #include <chrono> #include <gtest/gtest.h> #include <gmock/gmock.h> using namespace ::testing; namespace { class MockSocketMessenger : public anbox::network::SocketMessenger { public: // anbox::network::SocketMessenger MOCK_CONST_METHOD0(creds, anbox::network::Credentials()); MOCK_CONST_METHOD0(local_port, unsigned short()); MOCK_METHOD0(set_no_delay, void()); MOCK_METHOD0(close, void()); // anbox::network::MessageSender MOCK_METHOD2(send, void(char const*, size_t)); MOCK_METHOD2(send_raw, ssize_t(char const*, size_t)); // anbox::network::MessageReceiver MOCK_METHOD2(async_receive_msg, void(AnboxReadHandler const&, boost::asio::mutable_buffers_1 const&)); MOCK_METHOD1(receive_msg, boost::system::error_code(boost::asio::mutable_buffers_1 const&)); MOCK_METHOD0(available_bytes, size_t()); }; } namespace anbox { namespace graphics { TEST(BufferedIOStream, CommitBufferWritesOutToMessenger) { auto messenger = std::make_shared<MockSocketMessenger>(); BufferedIOStream stream(messenger); const size_t buffer_size{1000}; // We will write out the data we get in two junks of half the size // the original buffer has. EXPECT_CALL(*messenger, send_raw(_, buffer_size)) .Times(1) .WillOnce(Return(buffer_size/2)); EXPECT_CALL(*messenger, send_raw(_, buffer_size/2)) .Times(1) .WillOnce(Return(buffer_size/2)); char *ptr = static_cast<char*>(stream.allocBuffer(buffer_size)); ASSERT_NE(ptr, nullptr); ASSERT_EQ(stream.commitBuffer(buffer_size), buffer_size); // The BufferedIOStream class works internally with a thread to // write out the actual data to the messenger. As it blocks in // its d'tor for the writer thread to quit we can safely expect // that the messenger will see all data it has to. } TEST(BufferedIOStream, WriterContinuesWhenSocketIsBusy) { auto messenger = std::make_shared<MockSocketMessenger>(); BufferedIOStream stream(messenger); const size_t buffer_size{1000}; const size_t first_chunk_size{100}; // The writer will check the error code of the send function // and will retry writing the next chunk when it doesn't get // EAGAIN anymore from the sender. EXPECT_CALL(*messenger, send_raw(_, buffer_size)) .Times(1) .WillOnce(Return(first_chunk_size)); EXPECT_CALL(*messenger, send_raw(_, buffer_size - first_chunk_size)) .Times(2) .WillOnce(DoAll(Invoke([](char const*, size_t) { errno = EAGAIN; }), Return(-EAGAIN))) .WillOnce(Return(buffer_size - first_chunk_size)); char *ptr = static_cast<char*>(stream.allocBuffer(buffer_size)); ASSERT_NE(ptr, nullptr); ASSERT_EQ(stream.commitBuffer(buffer_size), buffer_size); } TEST(BufferedIOStream, ReadWhenEnoughDataAvailable) { auto messenger = std::make_shared<MockSocketMessenger>(); BufferedIOStream stream(messenger); Buffer buffer; buffer.push_back(0x12); buffer.push_back(0x34); stream.post_data(std::move(buffer)); std::uint8_t read_data[1] = {0x0}; size_t size = 1; EXPECT_NE(nullptr, stream.read(read_data, &size)); EXPECT_EQ(1, size); EXPECT_EQ(0x12, read_data[0]); EXPECT_NE(nullptr, stream.read(read_data, &size)); EXPECT_EQ(1, size); EXPECT_EQ(0x34, read_data[0]); } TEST(BufferedIOStream, ReadWithNoDataAvailable) { auto messenger = std::make_shared<MockSocketMessenger>(); BufferedIOStream stream(messenger); bool stopped = false; std::thread producer([&](){ while (!stopped) { if (stream.needs_data()) { Buffer buffer; buffer.push_back(0x12); buffer.push_back(0x34); stream.post_data(std::move(buffer)); } std::this_thread::sleep_for(std::chrono::milliseconds{10}); } }); constexpr size_t size{10}; std::uint8_t read_data[size] = {0x0}; size_t read = 10; EXPECT_NE(nullptr, stream.read(read_data, &read)); EXPECT_EQ(2, read); EXPECT_EQ(0x12, read_data[0]); EXPECT_EQ(0x34, read_data[1]); stopped = true; producer.join(); } } // namespace graphics } // namespace anbox
4,747
C++
.cpp
123
35.268293
104
0.721208
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,474
buffer_queue_tests.cpp
anbox_anbox/tests/anbox/graphics/buffer_queue_tests.cpp
// Copyright (C) 2016 The Android Open Source Project // // 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 "anbox/graphics/buffer_queue.h" #include "anbox/common/message_channel.h" #include "anbox/logger.h" #include <gtest/gtest.h> #include <thread> namespace anbox { namespace graphics { TEST(BufferQueue, Constructor) { BufferQueue queue(16); } TEST(BufferQueue, TryPushLocked) { BufferQueue queue(2); EXPECT_EQ(0, queue.try_push_locked(Buffer("Hello"))); EXPECT_EQ(0, queue.try_push_locked(Buffer("World"))); Buffer buff0("You Shall Not Move"); EXPECT_EQ(-EAGAIN, queue.try_push_locked(std::move(buff0))); EXPECT_FALSE(buff0.empty()) << "Buffer should not be moved on failure!"; } TEST(BufferQueue, TryPushLockedOnClosedQueue) { BufferQueue queue(2); EXPECT_EQ(0, queue.try_push_locked(Buffer("Hello"))); // Closing the queue prevents pushing new items to the queue. queue.close_locked(); EXPECT_EQ(-EIO, queue.try_push_locked(Buffer("World"))); } TEST(BufferQueue, TryPopLocked) { BufferQueue queue(2);; Buffer buffer; EXPECT_EQ(-EAGAIN, queue.try_pop_locked(&buffer)); EXPECT_EQ(0, queue.try_push_locked(Buffer("Hello"))); EXPECT_EQ(0, queue.try_push_locked(Buffer("World"))); EXPECT_EQ(0, queue.try_pop_locked(&buffer)); EXPECT_STREQ("Hello", buffer.data()); EXPECT_EQ(0, queue.try_pop_locked(&buffer)); EXPECT_STREQ("World", buffer.data()); EXPECT_EQ(-EAGAIN, queue.try_pop_locked(&buffer)); EXPECT_STREQ("World", buffer.data()); } TEST(BufferQueue, TryPopLockedOnClosedQueue) { BufferQueue queue(2); Buffer buffer; EXPECT_EQ(-EAGAIN, queue.try_pop_locked(&buffer)); EXPECT_EQ(0, queue.try_push_locked(Buffer("Hello"))); EXPECT_EQ(0, queue.try_push_locked(Buffer("World"))); EXPECT_EQ(0, queue.try_pop_locked(&buffer)); EXPECT_STREQ("Hello", buffer.data()); // Closing the queue doesn't prevent popping existing items, but // will generate -EIO once it is empty. queue.close_locked(); EXPECT_EQ(0, queue.try_pop_locked(&buffer)); EXPECT_STREQ("World", buffer.data()); EXPECT_EQ(-EIO, queue.try_pop_locked(&buffer)); EXPECT_STREQ("World", buffer.data()); } namespace { // A TestThread instance that holds a reference to a queue and can either // push or pull to it, on command from another thread. This uses a // MessageChannel to implement the communication channel between the // command thread and this one. class TestThread final { public: TestThread(std::mutex &lock, BufferQueue &queue) : lock_(lock), queue_(queue) { } bool start() { thread_ = std::thread(&TestThread::thread_main, this); return true; } // Tell the test thread to push |buffer| to the queue. // Call endPush() later to get the command's result. bool start_push(Buffer&& buffer) { input_.send(Request{Cmd::Push, std::move(buffer)}); return true; } int end_push() { Reply reply = {}; output_.receive(&reply); return reply.result; } // Tell the test thread to pop a buffer from the queue. // Call end_pop() to get the command's result, as well as the popped // buffer if it is 0. bool start_pop() { input_.send(Request{Cmd::Pop, Buffer{}}); return true; } // Return the result of a previous start_pop() command. If result is // 0, sets |*buffer| to the result buffer. int end_pop(Buffer* buffer) { Reply reply = {}; output_.receive(&reply); if (reply.result == 0) *buffer = std::move(reply.buffer); return reply.result; } // Tell the test thread to close the queue from its side. void do_close() { input_.send(Request{Cmd::Close, Buffer{}}); } // Tell the test thread to stop after completing its current command. void stop() { input_.send(Request{Cmd::Stop, Buffer{}}); thread_.join(); } private: enum class Cmd { Push, Pop, Close, Stop, }; struct Request { Cmd cmd; Buffer buffer; }; struct Reply { int result; Buffer buffer; }; void thread_main() { while (true) { Request r; input_.receive(&r); if (r.cmd == Cmd::Stop) break; std::unique_lock<std::mutex> l(lock_); Reply reply = {}; bool sendReply = false; switch (r.cmd) { case Cmd::Push: reply.result = queue_.push_locked(std::move(r.buffer), l); sendReply = true; break; case Cmd::Pop: reply.result = queue_.pop_locked(&reply.buffer, l); sendReply = true; break; case Cmd::Close: queue_.close_locked(); break; default: ; } if (sendReply) output_.send(std::move(reply)); } } std::thread thread_; std::mutex &lock_; BufferQueue &queue_; anbox::common::MessageChannel<Request, 4> input_; anbox::common::MessageChannel<Reply, 4> output_; }; } // namespace TEST(BufferQueue, PushLocked) { std::mutex lock; BufferQueue queue(2); TestThread thread(lock, queue); ASSERT_TRUE(thread.start()); ASSERT_TRUE(thread.start_pop()); std::unique_lock<std::mutex> l(lock); EXPECT_EQ(0, queue.push_locked(Buffer("Hello"), l)); EXPECT_EQ(0, queue.push_locked(Buffer("World"), l)); EXPECT_EQ(0, queue.push_locked(Buffer("Foo"), l)); thread.stop(); } TEST(BufferQueue, PushLockedWithClosedQueue) { std::mutex lock; BufferQueue queue(2); TestThread thread(lock, queue); ASSERT_TRUE(thread.start()); { std::unique_lock<std::mutex> l(lock); EXPECT_EQ(0, queue.push_locked(Buffer("Hello"), l)); // Closing the queue prevents pushing new items, but not // pulling from the queue. queue.close_locked(); EXPECT_EQ(-EIO, queue.push_locked(Buffer("World"), l)); } Buffer buffer; ASSERT_TRUE(thread.start_pop()); EXPECT_EQ(0, thread.end_pop(&buffer)); EXPECT_STREQ("Hello", buffer.data()); thread.stop(); } TEST(BufferQueue, PopLocked) { std::mutex lock; BufferQueue queue(2); TestThread thread(lock, queue); ASSERT_TRUE(thread.start()); ASSERT_TRUE(thread.start_push(Buffer("Hello World"))); EXPECT_EQ(0, thread.end_push()); { std::unique_lock<std::mutex> l(lock); Buffer buffer; EXPECT_EQ(0, queue.pop_locked(&buffer, l)); EXPECT_STREQ("Hello World", buffer.data()); } thread.stop(); } TEST(BufferQueue, PopLockedWithClosedQueue) { std::mutex lock; BufferQueue queue(2); TestThread thread(lock, queue); ASSERT_TRUE(thread.start()); ASSERT_TRUE(thread.start_push(Buffer("Hello World"))); EXPECT_EQ(0, thread.end_push()); // Closing the queue shall not prevent pulling items from it. // After that, -EIO shall be returned. thread.do_close(); ASSERT_TRUE(thread.start_push(Buffer("Foo Bar"))); EXPECT_EQ(-EIO, thread.end_push()); { std::unique_lock<std::mutex> l(lock); Buffer buffer; EXPECT_EQ(0, queue.pop_locked(&buffer, l)); EXPECT_STREQ("Hello World", buffer.data()); EXPECT_EQ(-EIO, queue.pop_locked(&buffer, l)); EXPECT_STREQ("Hello World", buffer.data()); } thread.stop(); } } // namespace graphics } // namespace anbox
7,872
C++
.cpp
238
28.151261
76
0.656324
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,475
layer_composer_tests.cpp
anbox_anbox/tests/anbox/graphics/layer_composer_tests.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ // Both includes need to go first as otherwise they can conflict with EGL.h // being included by the following includes. #include <gmock/gmock.h> #include <gtest/gtest.h> #include "anbox/application/database.h" #include "anbox/platform/base_platform.h" #include "anbox/wm/multi_window_manager.h" #include "anbox/wm/window_state.h" #include "anbox/graphics/layer_composer.h" #include "anbox/graphics/multi_window_composer_strategy.h" using namespace ::testing; namespace { class MockRenderer : public anbox::graphics::Renderer { public: MOCK_METHOD3(draw, bool(EGLNativeWindowType, const anbox::graphics::Rect&, const RenderableList&)); }; } namespace anbox { namespace graphics { TEST(LayerComposer, FindsNoSuitableWindowForLayer) { auto renderer = std::make_shared<MockRenderer>(); platform::Configuration config; // The default policy will create a dumb window instance when requested // from the manager. auto platform = platform::create(std::string(), nullptr, config); auto app_db = std::make_shared<application::Database>(); auto wm = std::make_shared<wm::MultiWindowManager>(platform, nullptr, app_db); auto single_window = wm::WindowState{ wm::Display::Id{1}, true, graphics::Rect{0, 0, 1024, 768}, "org.anbox.test.1", wm::Task::Id{1}, wm::Stack::Id::Freeform, }; wm->apply_window_state_update({single_window}, {}); LayerComposer composer(renderer, std::make_shared<MultiWindowComposerStrategy>(wm)); // A single renderable which has a different task id then the window we know // about RenderableList renderables = { {"org.anbox.surface.2", 0, 1.0f, {0, 0, 1024, 768}, {0, 0, 1024, 768}}, }; // The renderer should not be called for a layer which doesn't exist EXPECT_CALL(*renderer, draw(_, _, _)).Times(0); composer.submit_layers(renderables); } TEST(LayerComposer, MapsLayersToWindows) { auto renderer = std::make_shared<MockRenderer>(); platform::Configuration config; // The default policy will create a dumb window instance when requested // from the manager. auto platform = platform::create(std::string(), nullptr, config); auto app_db = std::make_shared<application::Database>(); auto wm = std::make_shared<wm::MultiWindowManager>(platform, nullptr, app_db); auto first_window = wm::WindowState{ wm::Display::Id{1}, true, graphics::Rect{0, 0, 1024, 768}, "org.anbox.foo", wm::Task::Id{1}, wm::Stack::Id::Freeform, }; auto second_window = wm::WindowState{ wm::Display::Id{1}, true, graphics::Rect{300, 400, 1324, 1168}, "org.anbox.bar", wm::Task::Id{2}, wm::Stack::Id::Freeform, }; wm->apply_window_state_update({first_window, second_window}, {}); LayerComposer composer(renderer, std::make_shared<MultiWindowComposerStrategy>(wm)); // A single renderable which has a different task id then the window we know // about RenderableList renderables = { {"org.anbox.surface.1", 0, 1.0f, {0, 0, 1024, 768}, {0, 0, 1024, 768}}, {"org.anbox.surface.2", 1, 1.0f, {0, 0, 1024, 768}, {0, 0, 1024, 768}}, }; RenderableList first_window_renderables{ {"org.anbox.surface.1", 0, 1.0f, {0, 0, 1024, 768}, {0, 0, 1024, 768}}, }; RenderableList second_window_renderables{ {"org.anbox.surface.2", 1, 1.0f, {0, 0, 1024, 768}, {0, 0, 1024, 768}}, }; EXPECT_CALL(*renderer, draw(_, Rect{0, 0, first_window.frame().width(), first_window.frame().height()}, first_window_renderables)) .Times(1) .WillOnce(Return(true)); EXPECT_CALL(*renderer, draw(_, Rect{0, 0, second_window.frame().width(), second_window.frame().height()}, second_window_renderables)) .Times(1) .WillOnce(Return(true)); composer.submit_layers(renderables); } TEST(LayerComposer, WindowPartiallyOffscreen) { auto renderer = std::make_shared<MockRenderer>(); platform::Configuration config; // The default policy will create a dumb window instance when requested // from the manager. auto platform = platform::create(std::string(), nullptr, config); auto app_db = std::make_shared<application::Database>(); auto wm = std::make_shared<wm::MultiWindowManager>(platform, nullptr, app_db); auto window = wm::WindowState{ wm::Display::Id{1}, true, graphics::Rect{-100, -100, 924, 668}, "org.anbox.foo", wm::Task::Id{1}, wm::Stack::Id::Freeform, }; wm->apply_window_state_update({window}, {}); LayerComposer composer(renderer, std::make_shared<MultiWindowComposerStrategy>(wm)); // Window is build out of two layers where one is placed inside the other // but the layer covering the whole window is placed with its top left // origin outside of the visible display area. RenderableList renderables = { {"org.anbox.surface.1", 0, 1.0f, {-100, -100, 924, 668}, {0, 0, 1024, 768}}, {"org.anbox.surface.1", 1, 1.0f, {0, 0, 100, 200}, {0, 0, 100, 200}}, }; RenderableList expected_renderables{ {"org.anbox.surface.1", 0, 1.0f, {0, 0, 1024, 768}, {0, 0, 1024, 768}}, {"org.anbox.surface.1", 1, 1.0f, {100, 100, 200, 300}, {0, 0, 100, 200}}, }; EXPECT_CALL(*renderer, draw(_, Rect{0, 0, window.frame().width(), window.frame().height()}, expected_renderables)) .Times(1) .WillOnce(Return(true)); composer.submit_layers(renderables); } TEST(LayerComposer, PopupShouldNotCauseWindowLayerOffset) { auto renderer = std::make_shared<MockRenderer>(); platform::Configuration config; // The default policy will create a dumb window instance when requested // from the manager. auto platform = platform::create(std::string(), nullptr, config); auto app_db = std::make_shared<application::Database>(); auto wm = std::make_shared<wm::MultiWindowManager>(platform, nullptr, app_db); auto window = wm::WindowState{ wm::Display::Id{1}, true, graphics::Rect{1120, 270, 2144, 1038}, "org.anbox.foo", wm::Task::Id{3}, wm::Stack::Id::Freeform, }; wm->apply_window_state_update({window}, {}); LayerComposer composer(renderer, std::make_shared<MultiWindowComposerStrategy>(wm)); // Having two renderables where the second smaller one overlaps the bigger // one and goes a bit offscreen. This should be still placed correctly and // the small layer should go offscreen as it is supposed to. This typically // happens when a popup window appears which has a shadow attached which goes // out of the window area. In our case this is not possible as the area the // window has available is static. RenderableList renderables = { {"org.anbox.surface.3", 0, 1.0f, {1120,270,2144,1038}, {0, 0, 1024, 768}}, {"org.anbox.surface.3", 1, 1.0f, {1904, 246, 2164, 406}, {0, 0, 260, 160}}, }; RenderableList expected_renderables{ {"org.anbox.surface.3", 0, 1.0f, {0, 0, 1024, 768}, {0, 0, 1024, 768}}, {"org.anbox.surface.3", 1, 1.0f, {784, -24, 1044, 136}, {0, 0, 260, 160}}, }; EXPECT_CALL(*renderer, draw(_, Rect{0, 0, window.frame().width(), window.frame().height()}, expected_renderables)) .Times(1) .WillOnce(Return(true)); composer.submit_layers(renderables); } } // namespace graphics } // namespace anbox
8,283
C++
.cpp
192
37.479167
86
0.659916
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,476
render_control_tests.cpp
anbox_anbox/tests/anbox/graphics/render_control_tests.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include <gtest/gtest.h> #include "anbox/graphics/emugl/DisplayManager.h" extern int rcGetDisplayWidth(uint32_t display_id); extern int rcGetDisplayHeight(uint32_t display_id); TEST(RenderControl, WidthHeightAreCorrectlyAssigned) { anbox::graphics::emugl::DisplayInfo::get()->set_resolution(640, 480); ASSERT_EQ(rcGetDisplayWidth(0), 640); ASSERT_EQ(rcGetDisplayHeight(0), 480); }
1,065
C++
.cpp
25
40.6
76
0.772201
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,477
intent_tests.cpp
anbox_anbox/tests/anbox/android/intent_tests.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "anbox/android/intent.h" #include <gtest/gtest.h> TEST(Intent, IsValid) { anbox::android::Intent intent; ASSERT_FALSE(intent.valid()); intent.component = "foo"; ASSERT_TRUE(intent.valid()); intent.package = "bla"; ASSERT_TRUE(intent.valid()); intent.component = ""; ASSERT_TRUE(intent.valid()); }
999
C++
.cpp
28
33.464286
76
0.741736
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,478
at_parser_tests.cpp
anbox_anbox/tests/anbox/support/at_parser_tests.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "anbox/qemu/at_parser.h" #include <gtest/gtest.h> #include <algorithm> TEST(AtParser, BasicCommands) { anbox::qemu::AtParser parser; std::string command = "ATE0Q0V1\nATE0Q0V1\n"; std::vector<uint8_t> data; std::copy(command.begin(), command.end(), std::back_inserter(data)); int commands_expected = 0; int commands_found = 0; auto assert_at_command = [&](const std::string &expected_command) { commands_expected++; return [&](const std::string &command) { commands_found++; ASSERT_STRCASEEQ(expected_command.c_str(), command.c_str()); }; }; parser.register_command("E0Q0V1", assert_at_command("E0Q0V1")); parser.register_command("E0Q0V1", assert_at_command("E0Q0V1")); parser.process_data(data); ASSERT_EQ(commands_expected, commands_found); }
1,532
C++
.cpp
38
36.157895
76
0.705051
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,479
scope_ptr_tests.cpp
anbox_anbox/tests/anbox/common/scope_ptr_tests.cpp
// Copyright (C) 2016 The Android Open Source Project // // 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 "anbox/common/scope_ptr.h" #include <gtest/gtest.h> #include <type_traits> #include <utility> namespace anbox { namespace common { TEST(ScopedPtr, FuncDelete_conversions) { // This test makes sure the code compiles, it doesn't do any runtime checks. auto lambda = [](int i) { return i; }; FuncDelete<decltype(lambda)> lambdaFd(lambda); // unary + converts a captureless lambda into a raw function pointer FuncDelete<decltype(+lambda)> funcFd1(+lambda); // copy ctor FuncDelete<decltype(+lambda)> funcFd2(funcFd1); // assignment operator funcFd2 = funcFd1; // move operator funcFd2 = std::move(funcFd1); // conversion ctor FuncDelete<decltype(+lambda)> funcFd3(lambdaFd); // conversion move ctor FuncDelete<decltype(+lambda)> funcFd4(std::move(lambdaFd)); // conversion assignment funcFd3 = lambdaFd; // conversion move funcFd3 = std::move(lambdaFd); } TEST(ScopedPtr, makeCustomScopedPtr_fromLambda) { auto freeAsLambda = [](void* ptr) { free(ptr); }; auto ptr1 = makeCustomScopedPtr(malloc(1), freeAsLambda); ScopedPtr<void, FuncDelete<void(*)(void*)>> ptr2 = makeCustomScopedPtr(malloc(1), freeAsLambda); ScopedPtr<void, FuncDelete<void(*)(void*)>> ptr3 = makeCustomScopedPtr(malloc(1), +freeAsLambda); static_assert(!std::is_same<decltype(ptr1), decltype(ptr2)>::value, "Custom ScopedPtr<> from a lambda expression type may not " "be the same as with a function pointer"); } } // namespace common } // namespace anbox
2,208
C++
.cpp
53
37.490566
80
0.710686
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,481
binary_writer_tests.cpp
anbox_anbox/tests/anbox/common/binary_writer_tests.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, 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/>. * */ #include "anbox/common/binary_writer.h" #include <gmock/gmock.h> namespace ac = anbox::common; using namespace ::testing; TEST(BinaryWriter, WriteUint32) { std::vector<std::uint8_t> buffer; buffer.resize(sizeof(std::uint32_t) * 2); ac::BinaryWriter writer(buffer.begin(), buffer.end()); writer.write_uint32(0x10); writer.write_uint32(0x3322); ASSERT_EQ(writer.bytes_written(), 8); ASSERT_THAT(buffer, ElementsAre(0x10, 0x00, 0x00, 0x00, 0x22, 0x33, 0x00, 0x00)); } TEST(BinaryWriter, WriteUint32FailsWithExhaustedError) { std::vector<std::uint8_t> buffer; ac::BinaryWriter writer(buffer.begin(), buffer.end()); EXPECT_THROW(writer.write_uint32(0x11), std::out_of_range); } TEST(BinaryWriter, WriteUint32WithChangedBinaryOrder) { std::vector<std::uint8_t> buffer; buffer.resize(sizeof(std::uint32_t)); ac::BinaryWriter writer(buffer.begin(), buffer.end()); writer.set_byte_order(ac::BinaryWriter::Order::Big); writer.write_uint32(0x11223344); ASSERT_EQ(writer.bytes_written(), 4); ASSERT_THAT(buffer, ElementsAre(0x11, 0x22, 0x33, 0x44)); buffer.clear(); buffer.resize(sizeof(std::uint32_t)); writer = ac::BinaryWriter(buffer.begin(), buffer.end()); writer.set_byte_order(ac::BinaryWriter::Order::Little); writer.write_uint32(0x11223344); ASSERT_EQ(writer.bytes_written(), 4); ASSERT_THAT(buffer, ElementsAre(0x44, 0x33, 0x22, 0x11)); } TEST(BinaryWriter, WriteUint16) { std::vector<std::uint8_t> buffer; buffer.resize(sizeof(std::uint16_t) * 2); ac::BinaryWriter writer(buffer.begin(), buffer.end()); writer.write_uint16(0x10); writer.write_uint16(0x3322); ASSERT_EQ(writer.bytes_written(), 4); ASSERT_THAT(buffer, ElementsAre(0x10, 0x00, 0x22, 0x33)); } TEST(BinaryWriter, WriteUint16FailsWithExhaustedError) { std::vector<std::uint8_t> buffer; ac::BinaryWriter writer(buffer.begin(), buffer.end()); EXPECT_THROW(writer.write_uint16(0x11), std::out_of_range); } TEST(BinaryWriter, WriteUint16WithChangedBinaryOrder) { std::vector<std::uint8_t> buffer; buffer.resize(sizeof(std::uint16_t)); ac::BinaryWriter writer(buffer.begin(), buffer.end()); writer.set_byte_order(ac::BinaryWriter::Order::Big); writer.write_uint16(0x1122); ASSERT_EQ(writer.bytes_written(), 2); ASSERT_THAT(buffer, ElementsAre(0x11, 0x22)); buffer.clear(); buffer.resize(sizeof(std::uint16_t)); writer = ac::BinaryWriter(buffer.begin(), buffer.end()); writer.set_byte_order(ac::BinaryWriter::Order::Little); writer.write_uint16(0x1122); ASSERT_EQ(writer.bytes_written(), 2); ASSERT_THAT(buffer, ElementsAre(0x22, 0x11)); } TEST(BinaryWriter, WriteString) { std::vector<std::uint8_t> buffer; buffer.resize(sizeof(std::uint8_t) * 4); ac::BinaryWriter writer(buffer.begin(), buffer.end()); writer.write_string("test", 4); ASSERT_EQ(writer.bytes_written(), 4); ASSERT_THAT(buffer, ElementsAre(0x74, 0x65, 0x73, 0x74)); } TEST(BinaryWriter, WriteStringWithSize) { std::vector<std::uint8_t> buffer; buffer.resize(sizeof(std::uint8_t) * 6); ac::BinaryWriter writer(buffer.begin(), buffer.end()); writer.set_byte_order(ac::BinaryWriter::Order::Big); writer.write_string_with_size("test"); ASSERT_EQ(writer.bytes_written(), 6); ASSERT_THAT(buffer, ElementsAre(0x00, 0x04, 0x74, 0x65, 0x73, 0x74)); }
3,991
C++
.cpp
97
38.391753
83
0.737633
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,482
small_vector_tests.cpp
anbox_anbox/tests/anbox/common/small_vector_tests.cpp
// Copyright 2016 The Android Open Source Project // // This software is licensed under the terms of the GNU General Public // License version 2, as published by the Free Software Foundation, and // may be copied, distributed, and modified under those terms. // // 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. #include "anbox/common/small_vector.h" #include "anbox/common/scope_ptr.h" #include "anbox/testing/gtest_utils.h" #include <gtest/gtest.h> #include <string> namespace anbox { namespace common { TEST(SmallVector, basic) { SmallFixedVector<char, 10> sv; EXPECT_EQ(sv.size(), 0); EXPECT_TRUE(sv.empty()); EXPECT_EQ(10, sv.capacity()); EXPECT_FALSE(sv.isAllocated()); const int values[] = {1, 2, 3}; sv = SmallFixedVector<char, 10>(values, values + 3); EXPECT_EQ(3, sv.size()); EXPECT_FALSE(sv.empty()); EXPECT_EQ(10, sv.capacity()); EXPECT_FALSE(sv.isAllocated()); EXPECT_TRUE(anbox::testing::RangesMatch(values, sv)); sv.clear(); EXPECT_EQ(0, sv.size()); EXPECT_TRUE(sv.empty()); const char str[] = "this is a long string for insertion"; sv = SmallFixedVector<char, 10>(str); EXPECT_EQ(sizeof(str), sv.size()); EXPECT_GT(sv.capacity(), 10); EXPECT_TRUE(sv.isAllocated()); EXPECT_TRUE(anbox::testing::RangesMatch(str, sv)); // make sure explicit loops over indices and iterators work for (size_t i = 0; i != sv.size(); ++i) { EXPECT_EQ(str[i], sv[i]); } const char* c = str; for (auto i : sv) { EXPECT_EQ(*c++, i); } c = str; for (auto it = sv.begin(); it != sv.end(); ++it, ++c) { EXPECT_EQ(*c, *it); } c = str; for (auto it = sv.data(); it != sv.data() + sv.size(); ++it, ++c) { EXPECT_EQ(*c, *it); } } TEST(SmallVector, ctor) { { SmallFixedVector<int, 1> sv; EXPECT_EQ(sv.size(), 0); } { const int values[] = {1, 2, 3}; SmallFixedVector<int, 10> sv(values, values + 3); EXPECT_TRUE(anbox::testing::RangesMatch(values, sv)); } { const int values[] = {1, 2, 3}; SmallFixedVector<int, 10> sv(values); EXPECT_TRUE(anbox::testing::RangesMatch(values, sv)); } { const int values[] = {1, 2, 3}; SmallFixedVector<int, 10> sv(values); EXPECT_TRUE(anbox::testing::RangesMatch(values, sv)); } { const int values[] = {1, 2, 3}; SmallFixedVector<int, 10> sv = {1, 2, 3}; EXPECT_TRUE(anbox::testing::RangesMatch(values, sv)); } { const int values[] = {1, 2, 3}; SmallFixedVector<int, 10> sv1(values); SmallFixedVector<int, 10> sv2(sv1); EXPECT_TRUE(anbox::testing::RangesMatch(values, sv1)); EXPECT_TRUE(anbox::testing::RangesMatch(sv2, sv1)); SmallFixedVector<int, 10> sv3(std::move(sv1)); EXPECT_TRUE(anbox::testing::RangesMatch(sv3, values)); // don't check |sv1| - it is not required to be empty. } } TEST(SmallVector, dtor) { // Count all destructor calls for the elements and make sure they're called // enough times. int destructedTimes = 0; auto deleter = [](int* p) { ++(*p); }; auto item1 = makeCustomScopedPtr(&destructedTimes, deleter); auto item2 = makeCustomScopedPtr(&destructedTimes, deleter); auto item3 = makeCustomScopedPtr(&destructedTimes, deleter); { SmallFixedVector<decltype(item1), 1> sv; sv.emplace_back(std::move(item1)); sv.emplace_back(std::move(item2)); // this one is already empty, so it won't add to |destructedTimes|. sv.emplace_back(std::move(item2)); sv.emplace_back(std::move(item3)); } EXPECT_EQ(3, destructedTimes); } TEST(SmallVector, modifiers) { SmallFixedVector<unsigned, 5> sv; EXPECT_EQ(0, sv.size()); EXPECT_EQ(5, sv.capacity()); sv.reserve(4); EXPECT_EQ(0, sv.size()); EXPECT_EQ(5, sv.capacity()); EXPECT_FALSE(sv.isAllocated()); sv.reserve(6); EXPECT_EQ(0, sv.size()); EXPECT_EQ(6, sv.capacity()); EXPECT_TRUE(sv.isAllocated()); sv.resize(3); EXPECT_EQ(3, sv.size()); EXPECT_EQ(6, sv.capacity()); EXPECT_TRUE(sv.isAllocated()); sv.resize(10); EXPECT_EQ(10, sv.size()); EXPECT_GE(sv.capacity(), 10); EXPECT_TRUE(sv.isAllocated()); sv.push_back(1); EXPECT_EQ(11, sv.size()); EXPECT_GE(sv.capacity(), 11); sv.emplace_back(2); EXPECT_EQ(12, sv.size()); EXPECT_GE(sv.capacity(), 12); sv.clear(); EXPECT_EQ(0, sv.size()); EXPECT_GE(sv.capacity(), 12); // resize_noinit() doesn't really have anything specific we can test // compared to resize() sv.resize_noinit(1); EXPECT_EQ(1, sv.size()); EXPECT_GE(sv.capacity(), 12); sv.resize_noinit(100); EXPECT_EQ(100, sv.size()); EXPECT_GE(sv.capacity(), 100); SmallFixedVector<std::string, 5> strings = {"a", "b", "c"}; strings.emplace_back("d"); strings.push_back("e"); EXPECT_EQ(5, strings.size()); EXPECT_EQ(5, strings.capacity()); EXPECT_FALSE(strings.isAllocated()); strings.push_back(std::string("e")); EXPECT_EQ(6, strings.size()); EXPECT_GE(strings.capacity(), 6); EXPECT_TRUE(strings.isAllocated()); } TEST(SmallVector, useThroughInterface) { SmallFixedVector<int, 10> sfv = {1, 2, 3}; SmallVector<int>& sv = sfv; EXPECT_TRUE(anbox::testing::RangesMatch(sv, sfv)); EXPECT_EQ(sv.isAllocated(), sfv.isAllocated()); sv.reserve(20); EXPECT_TRUE(sv.isAllocated()); EXPECT_EQ(sv.isAllocated(), sfv.isAllocated()); // now make sure that deleting through base class cleans up the memory { int destructedTimes = 0; auto deleter = [](int* p) { ++(*p); }; auto item1 = makeCustomScopedPtr(&destructedTimes, deleter); auto item2 = makeCustomScopedPtr(&destructedTimes, deleter); SmallVector<decltype(item1)>* sv = new SmallFixedVector<decltype(item1), 1>(); sv->push_back(std::move(item1)); sv->emplace_back(std::move(item2)); delete sv; EXPECT_EQ(2, destructedTimes); } } } // namespace common } // namespace anbox
6,418
C++
.cpp
182
29.730769
79
0.627037
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,483
message_channel_tests.cpp
anbox_anbox/tests/anbox/common/message_channel_tests.cpp
// Copyright 2014 The Android Open Source Project // // 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 "anbox/common/message_channel.h" #include <gtest/gtest.h> #include <string> #include <thread> namespace anbox { namespace common { TEST(MessageChannel, SingleThreadWithInt) { MessageChannel<int, 3U> channel; channel.send(1); channel.send(2); channel.send(3); int ret; channel.receive(&ret); EXPECT_EQ(1, ret); channel.receive(&ret); EXPECT_EQ(2, ret); channel.receive(&ret); EXPECT_EQ(3, ret); } TEST(MessageChannel, SingleThreadWithStdString) { MessageChannel<std::string, 5U> channel; channel.send(std::string("foo")); channel.send(std::string("bar")); channel.send(std::string("zoo")); std::string str; channel.receive(&str); EXPECT_STREQ("foo", str.c_str()); channel.receive(&str); EXPECT_STREQ("bar", str.c_str()); channel.receive(&str); EXPECT_STREQ("zoo", str.c_str()); } TEST(MessageChannel, TwoThreadsPingPong) { struct PingPongState { MessageChannel<std::string, 3U> in; MessageChannel<std::string, 3U> out; }; PingPongState state; std::thread thread([&](){ for (;;) { std::string str; state.in.receive(&str); state.out.send(str); if (str == "quit") break; } return 0; }); std::string str; const size_t kCount = 100; for (size_t n = 0; n < kCount; ++n) { state.in.send(std::string("foo")); state.in.send(std::string("bar")); state.in.send(std::string("zoo")); state.out.receive(&str); EXPECT_STREQ("foo", str.c_str()); state.out.receive(&str); EXPECT_STREQ("bar", str.c_str()); state.out.receive(&str); EXPECT_STREQ("zoo", str.c_str()); } state.in.send(std::string("quit")); state.out.receive(&str); EXPECT_STREQ("quit", str.c_str()); thread.join(); } } // namespace common } // namespace anbox
2,547
C++
.cpp
81
26.382716
75
0.641256
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,485
xdg_test.cpp
anbox_anbox/external/xdg/xdg_test.cpp
// Copyright (C) 2015 Thomas Voß <thomas.voss.bochum@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 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 Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <xdg.h> #include <boost/test/unit_test.hpp> #include <cstdlib> #include <iostream> BOOST_AUTO_TEST_CASE(XdgDataHomeThrowsForRelativeDirectoryFromEnv) { ::setenv("XDG_DATA_HOME", "tmp", 1); BOOST_CHECK_THROW(xdg::BaseDirSpecification::create()->data().home(), std::runtime_error); BOOST_CHECK_THROW(xdg::data().home(), std::runtime_error); } BOOST_AUTO_TEST_CASE(XdgDataHomeReturnsDefaultValueForEmptyEnv) { ::setenv("HOME", "/tmp", 1); ::setenv("XDG_DATA_HOME", "", 1); BOOST_CHECK_EQUAL("/tmp/.local/share", xdg::BaseDirSpecification::create()->data().home()); BOOST_CHECK_EQUAL("/tmp/.local/share", xdg::data().home()); } BOOST_AUTO_TEST_CASE(XdgDataDirsCorrectlyTokenizesEnv) { ::setenv("XDG_DATA_DIRS", "/tmp:/tmp", 1); BOOST_CHECK(2 == xdg::BaseDirSpecification::create()->data().dirs().size()); BOOST_CHECK(2 == xdg::data().dirs().size()); } BOOST_AUTO_TEST_CASE(XdgDataDirsThrowsForRelativeDirectoryFromEnv) { ::setenv("XDG_DATA_DIRS", "/tmp:tmp", 1); BOOST_CHECK_THROW(xdg::BaseDirSpecification::create()->data().dirs(), std::runtime_error); BOOST_CHECK_THROW(xdg::data().dirs(), std::runtime_error); } BOOST_AUTO_TEST_CASE(XdgDataDirsReturnsDefaultValueForEmptyEnv) { ::setenv("XDG_DATA_DIRS", "", 1); auto dirs = xdg::data().dirs(); BOOST_CHECK_EQUAL("/usr/local/share", dirs[0]); BOOST_CHECK_EQUAL("/usr/share", dirs[1]); dirs = xdg::BaseDirSpecification::create()->data().dirs(); BOOST_CHECK_EQUAL("/usr/local/share", dirs[0]); BOOST_CHECK_EQUAL("/usr/share", dirs[1]); } BOOST_AUTO_TEST_CASE(XdgConfigHomeThrowsForRelativeDirectoryFromEnv) { ::setenv("XDG_CONFIG_HOME", "tmp", 1); BOOST_CHECK_THROW(xdg::BaseDirSpecification::create()->config().home(), std::runtime_error); BOOST_CHECK_THROW(xdg::config().home(), std::runtime_error); } BOOST_AUTO_TEST_CASE(XdgConfigHomeReturnsDefaultValueForEmptyEnv) { ::setenv("HOME", "/tmp", 1); ::setenv("XDG_CONFIG_HOME", "", 1); BOOST_CHECK_EQUAL("/tmp/.config", xdg::BaseDirSpecification::create()->config().home()); BOOST_CHECK_EQUAL("/tmp/.config", xdg::config().home()); } BOOST_AUTO_TEST_CASE(XdgConfigDirsCorrectlyTokenizesEnv) { ::setenv("XDG_CONFIG_DIRS", "/tmp:/tmp", 1); BOOST_CHECK(2 == xdg::BaseDirSpecification::create()->config().dirs().size()); BOOST_CHECK(2 == xdg::config().dirs().size()); } BOOST_AUTO_TEST_CASE(XdgConfigDirsThrowsForRelativeDirectoryFromEnv) { ::setenv("XDG_CONFIG_DIRS", "/tmp:tmp", 1); BOOST_CHECK_THROW(xdg::BaseDirSpecification::create()->config().dirs(), std::runtime_error); BOOST_CHECK_THROW(xdg::config().dirs(), std::runtime_error); } BOOST_AUTO_TEST_CASE(XdgConfigDirsReturnsDefaultValueForEmptyEnv) { ::setenv("XDG_CONFIG_DIRS", "", 1); auto dirs = xdg::config().dirs(); BOOST_CHECK_EQUAL("/etc/xdg", dirs[0]); dirs = xdg::BaseDirSpecification::create()->config().dirs(); BOOST_CHECK_EQUAL("/etc/xdg", dirs[0]); } BOOST_AUTO_TEST_CASE(XdgCacheHomeThrowsForRelativeDirectoryFromEnv) { ::setenv("XDG_CACHE_HOME", "tmp", 1); BOOST_CHECK_THROW(xdg::BaseDirSpecification::create()->cache().home(), std::runtime_error); BOOST_CHECK_THROW(xdg::cache().home(), std::runtime_error); } BOOST_AUTO_TEST_CASE(XdgCacheHomeReturnsDefaultValueForEmptyEnv) { ::setenv("HOME", "/tmp", 1); ::setenv("XDG_CACHE_HOME", "", 1); BOOST_CHECK_EQUAL("/tmp/.cache", xdg::BaseDirSpecification::create()->cache().home()); BOOST_CHECK_EQUAL("/tmp/.cache", xdg::cache().home()); } BOOST_AUTO_TEST_CASE(XdgRuntimeDirThrowsForRelativeDirectoryFromEnv) { ::setenv("XDG_RUNTIME_DIR", "tmp", 1); BOOST_CHECK_THROW(xdg::BaseDirSpecification::create()->runtime().dir(), std::runtime_error); BOOST_CHECK_THROW(xdg::runtime().dir(), std::runtime_error); } BOOST_AUTO_TEST_CASE(XdgRuntimeDirThrowsForEmptyEnv) { ::setenv("XDG_RUNTIME_DIR", "", 1); BOOST_CHECK_THROW(xdg::BaseDirSpecification::create()->runtime().dir(), std::runtime_error); BOOST_CHECK_THROW(xdg::runtime().dir(), std::runtime_error); }
4,825
C++
.cpp
111
40.459459
96
0.70394
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,486
logging.cpp
anbox_anbox/external/android-emugl/shared/emugl/common/logging.cpp
/* * Copyright (C) 2016 The Android Open Source Project * * 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 "emugl/common/logging.h" void default_logger(const emugl::LogLevel &level, const char* fmt, ...) { } logger_t emugl_logger = default_logger; logger_t emugl_cxt_logger = default_logger; void set_emugl_logger(logger_t f) { if (!f) { emugl_logger = default_logger; } else { emugl_logger = f; } } void set_emugl_cxt_logger(logger_t f) { if (!f) { emugl_cxt_logger = default_logger; } else { emugl_cxt_logger = f; } }
1,084
C++
.cpp
33
30
75
0.714149
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,492
condition_variable_unittest.cpp
anbox_anbox/external/android-emugl/shared/emugl/common/condition_variable_unittest.cpp
// Copyright (C) 2014 The Android Open Source Project // // 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 "emugl/common/condition_variable.h" #include "emugl/common/mutex.h" #include <gtest/gtest.h> namespace emugl { TEST(ConditionVariable, init) { ConditionVariable cond; } } // namespace emugl
818
C++
.cpp
21
37.47619
75
0.769912
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,499
crash_reporter.cpp
anbox_anbox/external/android-emugl/shared/emugl/common/crash_reporter.cpp
/* * Copyright (C) 2016 The Android Open Source Project * * 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 "crash_reporter.h" #include <cstdlib> void default_crash_reporter(const emugl::LogLevel &level, const char* format, ...) { abort(); } logger_t emugl_crash_reporter = default_crash_reporter; void set_emugl_crash_reporter(logger_t crash_reporter) { if (crash_reporter) { emugl_crash_reporter = crash_reporter; } else { emugl_crash_reporter = default_crash_reporter; } }
1,015
C++
.cpp
28
33.928571
84
0.750509
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,510
test_shared_library.cpp
anbox_anbox/external/android-emugl/shared/emugl/common/testing/test_shared_library.cpp
// Copyright (C) 2014 The Android Open Source Project // // 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. // This source file must be compiled into a simple shared library which // will be used by shared_library_unittest.cpp to verify that the // emugl::SharedLibrary class works properly. extern "C" int foo_function(void) { return 42; }
848
C++
.cpp
19
43.263158
75
0.767554
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,513
Parser_unittest.cpp
anbox_anbox/external/android-emugl/host/tools/emugen/Parser_unittest.cpp
/* * Copyright 2014 The Android Open Source Project * * 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 "Parser.h" #include <gtest/gtest.h> #define ARRAYLEN(x) (sizeof(x) / sizeof(x[0])) TEST(ParserTest, normalizeTypeDeclaration) { static const struct { const char* expected; const char* input; } kData[] = { { "char", "char" }, { "const unsigned int", " const unsigned\tint\n" }, { "char* const**", "char *const* *" }, }; const size_t kDataSize = ARRAYLEN(kData); for (size_t n = 0; n < kDataSize; ++n) { std::string result; std::string text = "When parsing '"; text += kData[n].input; text += "'"; result = normalizeTypeDeclaration(kData[n].input); EXPECT_STREQ(kData[n].expected, result.c_str()) << text; } } TEST(ParserTest, parseTypeDeclaration) { static const struct { const char* input; bool expected; const char* expectedType; const char* expectedError; } kData[] = { { "const", false, NULL, "Missing type name" }, { "const const", false, NULL, "Missing type name" }, { "foo", true, "foo", NULL }, { "void", true, "void", NULL }, { "const foo", true, "const foo", NULL }, { "foo *", true, "foo*", NULL }, { "char foo", true, "char foo", NULL }, { "\tunsigned \t int\n", true, "unsigned int", NULL }, { "const * char", false, NULL, "Unexpected '*' before type name" }, { "const char * ", true, "const char*", NULL }, { "const void*const * *", true, "const void* const**", NULL }, }; const size_t kDataSize = ARRAYLEN(kData); for (size_t n = 0; n < kDataSize; ++n) { std::string varname, vartype, error; std::string text = "When parsing '"; text += kData[n].input; text += "'"; EXPECT_EQ(kData[n].expected, parseTypeDeclaration(kData[n].input, &vartype, &error)) << text; if (kData[n].expected) { EXPECT_STREQ(kData[n].expectedType, vartype.c_str()) << text; } else { EXPECT_STREQ(kData[n].expectedError, error.c_str()) << text; } } } TEST(ParserTest, parseParameterDeclaration) { static const struct { const char* input; bool expected; const char* expectedType; const char* expectedVariable; const char* expectedError; } kData[] = { { "foo", false, NULL, NULL, "Missing variable name" }, { "const", false, NULL, NULL, "Missing type name" }, { "const foo", false, NULL, NULL, "Missing variable name" }, { "const const", false, NULL, NULL, "Missing type name" }, { "char foo", true, "char", "foo", NULL }, { "unsigned int\t bar\n", true, "unsigned int", "bar", NULL }, { "const * char foo", false, NULL, NULL, "Unexpected '*' before type name" }, { "const char * foo", true, "const char*", "foo", NULL }, { "const void*const *data", true, "const void* const*", "data", NULL }, { "char foo const", false, NULL, NULL, "Extra 'const' after variable name" }, { "int bar*", false, NULL, NULL, "Extra '*' after variable name" }, }; const size_t kDataSize = ARRAYLEN(kData); for (size_t n = 0; n < kDataSize; ++n) { std::string varname, vartype, error; std::string text = "When parsing '"; text += kData[n].input; text += "'"; EXPECT_EQ(kData[n].expected, parseParameterDeclaration(kData[n].input, &vartype, &varname, &error)) << text; if (kData[n].expected) { EXPECT_STREQ(kData[n].expectedType, vartype.c_str()) << text; EXPECT_STREQ(kData[n].expectedVariable, varname.c_str()) << text; } else { EXPECT_STREQ(kData[n].expectedError, error.c_str()) << text; } } }
4,623
C++
.cpp
112
32.6875
85
0.558294
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,518
Parser.cpp
anbox_anbox/external/android-emugl/host/tools/emugen/Parser.cpp
/* * Copyright 2014 The Android Open Source Project * * 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 "Parser.h" #include <vector> #define WHITESPACE " \t\n" // Parse the |input| string as a list of type-specific tokens. // This tokenizes the input, using whitespace as separators and '*' as // a single token too. On success, return true and sets |*out| to the // list of tokens. On failure, return false. // // Example: 'const char**foo' -> ['const', 'char', '*', '*', 'foo'] // static bool parseTypeTokens(const std::string& input, std::vector<std::string>* out, std::string* error) { out->clear(); size_t pos = 0U; // Parse all tokens in the input, treat '*' as a single token. // I.e. for (;;) { // skip leading whitespace. pos = input.find_first_not_of(WHITESPACE, pos); if (pos == std::string::npos) { break; // end of parse. } // If this is a star, ensure it follows a type name. // otherwise treat it as part of the final type. if (input[pos] == '*') { out->push_back(std::string("*")); pos += 1U; continue; } // find end of type/token. size_t end = input.find_first_of(WHITESPACE "*", pos); if (end == std::string::npos) { end = input.size(); } std::string str = input.substr(pos, end - pos); if (str.size() == 0) { // Sanity check: should not happen. if (error != NULL) { *error = "Unexpected empty token !?"; } return false; } out->push_back(str); pos = end; } if (error != NULL) { // Sanity check: require non-empty input if (out->empty()) { *error = "Empty parameter declaration!"; return false; } // Sanity check: There must be base type name before any '*' for (size_t n = 0; n < out->size(); ++n) { std::string& token = (*out)[n]; if (token == "*") { *error = "Unexpected '*' before type name"; return false; } else if (token != "const") { break; } } } return true; } // Given |tokens|, an input vector of strings, join the first |count| items // into a normalized type string, and return it. static std::string buildTypeString(const std::vector<std::string>& tokens, size_t count) { std::string result; for (size_t n = 0; n < count; ++n) { const std::string& token = tokens[n]; if (n > 0 && token != "*") { result.append(" "); } result.append(token); } return result; } std::string normalizeTypeDeclaration(const std::string& input) { std::vector<std::string> tokens; if (!parseTypeTokens(input, &tokens, NULL)) { return ""; } return buildTypeString(tokens, tokens.size()); } bool parseTypeDeclaration(const std::string& input, std::string* typeName, std::string* error) { // The type name can be made of several tokens, e.g. 'unsigned int' // use an array to store them, and a count variable. Each item can be // one of '*', 'const' or a type name component (e.g. 'struct', 'unsigned') std::vector<std::string> tokens; if (!parseTypeTokens(input, &tokens, error)) { return false; } // Sanity check, there must be a least one non-special tokens. size_t nonSpecialCount = 0; for (size_t n = 0; n < tokens.size(); ++n) { if (tokens[n] != "*" && tokens[n] != "const") { nonSpecialCount++; } } if (nonSpecialCount == 0) { *error = "Missing type name"; return false; } // Build the type name from all tokens before it. *typeName = buildTypeString(tokens, tokens.size()); return true; } bool parseParameterDeclaration(const std::string& param, std::string* typeName, std::string* variableName, std::string* error) { std::vector<std::string> tokens; if (!parseTypeTokens(param, &tokens, error)) { return false; } // Sanity check, there must be a least two non-special tokens. size_t nonSpecialCount = 0; for (size_t n = 0; n < tokens.size(); ++n) { if (tokens[n] != "*" && tokens[n] != "const") { nonSpecialCount++; } } if (nonSpecialCount == 0) { *error = "Missing type name"; return false; } if (nonSpecialCount == 1) { *error = "Missing variable name"; return false; } // Sanity check: variable name must not be followed by 'const' or '*' const std::string& lastToken = tokens[tokens.size() - 1U]; if (lastToken == "*") { *error = "Extra '*' after variable name"; return false; } if (lastToken == "const") { *error = "Extra 'const' after variable name"; return false; } // Extract the variable name as the last token. if (variableName) { *variableName = lastToken; } // Build the type name from all tokens before it. *typeName = buildTypeString(tokens, tokens.size() - 1U); return true; }
5,928
C++
.cpp
167
27.790419
79
0.567021
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,521
foo_dec.cpp
anbox_anbox/external/android-emugl/host/tools/emugen/tests/t.001/expected/decoder/foo_dec.cpp
// Generated Code - DO NOT EDIT !! // generated by 'emugen' #include <string.h> #include "foo_opcodes.h" #include "foo_dec.h" #include "ProtocolUtils.h" #include "ChecksumCalculatorThreadInfo.h" #include <stdio.h> typedef unsigned int tsize_t; // Target "size_t", which is 32-bit for now. It may or may not be the same as host's size_t when emugen is compiled. #ifdef OPENGL_DEBUG_PRINTOUT # define DEBUG(...) do { if (emugl_cxt_logger) { emugl_cxt_logger(__VA_ARGS__); } } while(0) #else # define DEBUG(...) ((void)0) #endif #ifdef CHECK_GLERROR # define SET_LASTCALL(name) sprintf(lastCall, #name) #else # define SET_LASTCALL(name) ((void)0) #endif using namespace emugl; size_t foo_decoder_context_t::decode(void *buf, size_t len, IOStream *stream) { size_t pos = 0; if (len < 8) return pos; unsigned char *ptr = (unsigned char *)buf; bool unknownOpcode = false; #ifdef CHECK_GL_ERROR char lastCall[256] = {0}; #endif while ((len - pos >= 8) && !unknownOpcode) { uint32_t opcode = *(uint32_t *)ptr; size_t packetLen = *(uint32_t *)(ptr + 4); if (len - pos < packetLen) return pos; bool useChecksum = ChecksumCalculatorThreadInfo::getVersion() > 0; size_t checksumSize = 0; if (useChecksum) { checksumSize = ChecksumCalculatorThreadInfo::checksumByteSize(); } switch(opcode) { case OP_fooAlphaFunc: { FooInt var_func = Unpack<FooInt,uint32_t>(ptr + 8); FooFloat var_ref = Unpack<FooFloat,uint32_t>(ptr + 8 + 4); if (useChecksum) { ChecksumCalculatorThreadInfo::validOrDie(ptr, 8 + 4 + 4, ptr + 8 + 4 + 4, checksumSize, "8 + 4 + 4::decode, OP_foo_decoder_context_t: GL checksumCalculator failure\n"); } DEBUG("foo(%p): fooAlphaFunc(%d %f )\n", stream,var_func, var_ref); this->fooAlphaFunc(var_func, var_ref); SET_LASTCALL("fooAlphaFunc"); break; } case OP_fooIsBuffer: { uint32_t size_stuff __attribute__((unused)) = Unpack<uint32_t,uint32_t>(ptr + 8); InputBuffer inptr_stuff(ptr + 8 + 4, size_stuff); if (useChecksum) { ChecksumCalculatorThreadInfo::validOrDie(ptr, 8 + 4 + size_stuff, ptr + 8 + 4 + size_stuff, checksumSize, "8 + 4 + size_stuff::decode, OP_foo_decoder_context_t: GL checksumCalculator failure\n"); } size_t totalTmpSize = sizeof(FooBoolean); totalTmpSize += checksumSize; unsigned char *tmpBuf = stream->alloc(totalTmpSize); DEBUG("foo(%p): fooIsBuffer(%p(%u) )\n", stream,(void*)(inptr_stuff.get()), size_stuff); *(FooBoolean *)(&tmpBuf[0]) = this->fooIsBuffer((void*)(inptr_stuff.get())); if (useChecksum) { ChecksumCalculatorThreadInfo::writeChecksum(&tmpBuf[0], totalTmpSize - checksumSize, &tmpBuf[totalTmpSize - checksumSize], checksumSize); } stream->flush(); SET_LASTCALL("fooIsBuffer"); break; } case OP_fooUnsupported: { uint32_t size_params __attribute__((unused)) = Unpack<uint32_t,uint32_t>(ptr + 8); InputBuffer inptr_params(ptr + 8 + 4, size_params); if (useChecksum) { ChecksumCalculatorThreadInfo::validOrDie(ptr, 8 + 4 + size_params, ptr + 8 + 4 + size_params, checksumSize, "8 + 4 + size_params::decode, OP_foo_decoder_context_t: GL checksumCalculator failure\n"); } DEBUG("foo(%p): fooUnsupported(%p(%u) )\n", stream,(void*)(inptr_params.get()), size_params); this->fooUnsupported((void*)(inptr_params.get())); SET_LASTCALL("fooUnsupported"); break; } case OP_fooDoEncoderFlush: { FooInt var_param = Unpack<FooInt,uint32_t>(ptr + 8); if (useChecksum) { ChecksumCalculatorThreadInfo::validOrDie(ptr, 8 + 4, ptr + 8 + 4, checksumSize, "8 + 4::decode, OP_foo_decoder_context_t: GL checksumCalculator failure\n"); } DEBUG("foo(%p): fooDoEncoderFlush(%d )\n", stream,var_param); this->fooDoEncoderFlush(var_param); SET_LASTCALL("fooDoEncoderFlush"); break; } case OP_fooTakeConstVoidPtrConstPtr: { uint32_t size_param __attribute__((unused)) = Unpack<uint32_t,uint32_t>(ptr + 8); InputBuffer inptr_param(ptr + 8 + 4, size_param); if (useChecksum) { ChecksumCalculatorThreadInfo::validOrDie(ptr, 8 + 4 + size_param, ptr + 8 + 4 + size_param, checksumSize, "8 + 4 + size_param::decode, OP_foo_decoder_context_t: GL checksumCalculator failure\n"); } DEBUG("foo(%p): fooTakeConstVoidPtrConstPtr(%p(%u) )\n", stream,(const void* const*)(inptr_param.get()), size_param); this->fooTakeConstVoidPtrConstPtr((const void* const*)(inptr_param.get())); SET_LASTCALL("fooTakeConstVoidPtrConstPtr"); break; } default: unknownOpcode = true; } //switch if (!unknownOpcode) { pos += packetLen; ptr += packetLen; } } // while return pos; }
4,678
C++
.cpp
115
37
146
0.683617
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,526
foo_enc.cpp
anbox_anbox/external/android-emugl/host/tools/emugen/tests/t.001/expected/encoder/foo_enc.cpp
// Generated Code - DO NOT EDIT !! // generated by 'emugen' #include <memory> #include <string.h> #include "foo_opcodes.h" #include "foo_enc.h" #include <stdio.h> namespace { void enc_unsupported() { ALOGE("Function is unsupported\n"); } void fooAlphaFunc_enc(void *self , FooInt func, FooFloat ref) { foo_encoder_context_t *ctx = (foo_encoder_context_t *)self; IOStream *stream = ctx->m_stream; ChecksumCalculator *checksumCalculator = ctx->m_checksumCalculator; bool useChecksum = checksumCalculator->getVersion() > 0; unsigned char *ptr; unsigned char *buf; const size_t sizeWithoutChecksum = 8 + 4 + 4; const size_t checksumSize = checksumCalculator->checksumByteSize(); const size_t totalSize = sizeWithoutChecksum + checksumSize; buf = stream->alloc(totalSize); ptr = buf; int tmp = OP_fooAlphaFunc;memcpy(ptr, &tmp, 4); ptr += 4; memcpy(ptr, &totalSize, 4); ptr += 4; memcpy(ptr, &func, 4); ptr += 4; memcpy(ptr, &ref, 4); ptr += 4; if (useChecksum) checksumCalculator->addBuffer(buf, ptr-buf); if (useChecksum) checksumCalculator->writeChecksum(ptr, checksumSize); ptr += checksumSize; } FooBoolean fooIsBuffer_enc(void *self , void* stuff) { foo_encoder_context_t *ctx = (foo_encoder_context_t *)self; IOStream *stream = ctx->m_stream; ChecksumCalculator *checksumCalculator = ctx->m_checksumCalculator; bool useChecksum = checksumCalculator->getVersion() > 0; const unsigned int __size_stuff = (4 * sizeof(float)); unsigned char *ptr; unsigned char *buf; const size_t sizeWithoutChecksum = 8 + __size_stuff + 1*4; const size_t checksumSize = checksumCalculator->checksumByteSize(); const size_t totalSize = sizeWithoutChecksum + checksumSize; buf = stream->alloc(totalSize); ptr = buf; int tmp = OP_fooIsBuffer;memcpy(ptr, &tmp, 4); ptr += 4; memcpy(ptr, &totalSize, 4); ptr += 4; *(unsigned int *)(ptr) = __size_stuff; ptr += 4; memcpy(ptr, stuff, __size_stuff);ptr += __size_stuff; if (useChecksum) checksumCalculator->addBuffer(buf, ptr-buf); if (useChecksum) checksumCalculator->writeChecksum(ptr, checksumSize); ptr += checksumSize; FooBoolean retval; stream->readback(&retval, 1); if (useChecksum) checksumCalculator->addBuffer(&retval, 1); if (useChecksum) { std::unique_ptr<unsigned char[]> checksumBuf(new unsigned char[checksumSize]); stream->readback(checksumBuf.get(), checksumSize); if (!checksumCalculator->validate(checksumBuf.get(), checksumSize)) { ALOGE("fooIsBuffer: GL communication error, please report this issue to b.android.com.\n"); abort(); } } return retval; } void fooDoEncoderFlush_enc(void *self , FooInt param) { foo_encoder_context_t *ctx = (foo_encoder_context_t *)self; IOStream *stream = ctx->m_stream; ChecksumCalculator *checksumCalculator = ctx->m_checksumCalculator; bool useChecksum = checksumCalculator->getVersion() > 0; unsigned char *ptr; unsigned char *buf; const size_t sizeWithoutChecksum = 8 + 4; const size_t checksumSize = checksumCalculator->checksumByteSize(); const size_t totalSize = sizeWithoutChecksum + checksumSize; buf = stream->alloc(totalSize); ptr = buf; int tmp = OP_fooDoEncoderFlush;memcpy(ptr, &tmp, 4); ptr += 4; memcpy(ptr, &totalSize, 4); ptr += 4; memcpy(ptr, &param, 4); ptr += 4; if (useChecksum) checksumCalculator->addBuffer(buf, ptr-buf); if (useChecksum) checksumCalculator->writeChecksum(ptr, checksumSize); ptr += checksumSize; stream->flush(); } void fooTakeConstVoidPtrConstPtr_enc(void *self , const void* const* param) { foo_encoder_context_t *ctx = (foo_encoder_context_t *)self; IOStream *stream = ctx->m_stream; ChecksumCalculator *checksumCalculator = ctx->m_checksumCalculator; bool useChecksum = checksumCalculator->getVersion() > 0; const unsigned int __size_param = ; unsigned char *ptr; unsigned char *buf; const size_t sizeWithoutChecksum = 8 + __size_param + 1*4; const size_t checksumSize = checksumCalculator->checksumByteSize(); const size_t totalSize = sizeWithoutChecksum + checksumSize; buf = stream->alloc(totalSize); ptr = buf; int tmp = OP_fooTakeConstVoidPtrConstPtr;memcpy(ptr, &tmp, 4); ptr += 4; memcpy(ptr, &totalSize, 4); ptr += 4; *(unsigned int *)(ptr) = __size_param; ptr += 4; memcpy(ptr, param, __size_param);ptr += __size_param; if (useChecksum) checksumCalculator->addBuffer(buf, ptr-buf); if (useChecksum) checksumCalculator->writeChecksum(ptr, checksumSize); ptr += checksumSize; } } // namespace foo_encoder_context_t::foo_encoder_context_t(IOStream *stream, ChecksumCalculator *checksumCalculator) { m_stream = stream; m_checksumCalculator = checksumCalculator; this->fooAlphaFunc = &fooAlphaFunc_enc; this->fooIsBuffer = &fooIsBuffer_enc; this->fooUnsupported = (fooUnsupported_client_proc_t) &enc_unsupported; this->fooDoEncoderFlush = &fooDoEncoderFlush_enc; this->fooTakeConstVoidPtrConstPtr = &fooTakeConstVoidPtrConstPtr_enc; }
4,926
C++
.cpp
117
39.760684
102
0.742929
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,532
standard_stream.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/standard_stream.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * 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, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/standard_stream.h> namespace core { namespace posix { StandardStream operator|(StandardStream l, StandardStream r) { return static_cast<StandardStream>(static_cast<std::uint8_t>(l) | static_cast<std::uint8_t>(r)); } StandardStream operator&(StandardStream l, StandardStream r) { return static_cast<StandardStream>(static_cast<std::uint8_t>(l) & static_cast<std::uint8_t>(r)); } } }
1,122
C++
.cpp
32
33.15625
100
0.760369
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false