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,021
portrange.cpp
manticoresoftware_manticoresearch/src/replication/portrange.cpp
// // 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 "sphinxstd.h" #include "portrange.h" #include "searchdaemon.h" #if _WIN32 // Win-specific headers and calls #include <io.h> #else // UNIX-specific headers and calls #include <netinet/in.h> #endif struct PortsRange_t { int m_iPort = 0; int m_iCount = 0; }; static bool IsInetAddrFree ( DWORD uAddr, int iPort ) { static struct sockaddr_in iaddr; memset ( &iaddr, 0, sizeof ( iaddr ) ); iaddr.sin_family = AF_INET; iaddr.sin_addr.s_addr = uAddr; iaddr.sin_port = htons ( (short)iPort ); int iSock = socket ( AF_INET, SOCK_STREAM, 0 ); if ( iSock == -1 ) { sphWarning ( "failed to create TCP socket: %s", sphSockError() ); return false; } int iRes = bind ( iSock, (struct sockaddr*)&iaddr, sizeof ( iaddr ) ); SafeCloseSocket ( iSock ); return ( iRes == 0 ); } // manage ports pairs for clusters set as Galera replication listener ports range class FreePortList_c : public FreePortList_i { private: CSphMutex m_tLock; CSphVector<int> m_dFree GUARDED_BY ( m_tLock ); CSphTightVector <PortsRange_t> m_dPorts GUARDED_BY ( m_tLock ); DWORD m_uAddr = 0; public: // set range of ports there is could generate ports pairs void AddRange ( const PortsRange_t & tPorts ) { assert ( tPorts.m_iPort && tPorts.m_iCount && (tPorts.m_iCount % 2)==0 ); ScopedMutex_t tLock ( m_tLock ); m_dPorts.Add ( tPorts ); } void AddAddr ( const CSphString& sAddr ) { m_uAddr = sphGetAddress ( sAddr.cstr(), false, false ); } private: // get next available range of ports for Galera listener // first reuse ports pair that was recently released // or pair from range set int Get () { int iPortMin = -1; ScopedMutex_t tLock ( m_tLock ); while ( m_dPorts.GetLength() || m_dFree.GetLength() ) { if ( !m_dFree.IsEmpty ()) { iPortMin = m_dFree.Pop (); } else if ( m_dPorts.GetLength ()) { assert ( m_dPorts.Last ().m_iCount>=2 ); PortsRange_t & tPorts = m_dPorts.Last (); iPortMin = tPorts.m_iPort; tPorts.m_iPort += 2; tPorts.m_iCount -= 2; if ( !tPorts.m_iCount ) m_dPorts.Pop (); } if ( IsInetAddrFree ( m_uAddr, iPortMin ) && IsInetAddrFree ( m_uAddr, iPortMin + 1 ) ) break; iPortMin = -1; } return iPortMin; } public: ScopedPort_c AcquirePort () override { return ScopedPort_c ( Get(), this ); } // free ports pair and add it to free list void Free ( int iPort ) override { ScopedMutex_t tLock ( m_tLock ); m_dFree.Add ( iPort ); } ~FreePortList_c() override {} }; // ports pairs manager static FreePortList_c g_tReplicationPorts; ScopedPort_c::ScopedPort_c ( int iPort, FreePortList_i * pPortList ) : m_iPort ( iPort ) , m_pPortsList ( pPortList ) { assert ( m_pPortsList ); } ScopedPort_c::~ScopedPort_c () { if ( m_iPort!=-1 ) { m_pPortsList->Free ( m_iPort ); m_iPort = -1; } } ScopedPort_c PortRange::AcquirePort () { return g_tReplicationPorts.AcquirePort(); } void PortRange::AddPortsRange ( int iPort, int iCount ) { PortsRange_t tPorts; tPorts.m_iPort = iPort; tPorts.m_iCount = iCount; if ((tPorts.m_iCount % 2)!=0 ) --tPorts.m_iCount; g_tReplicationPorts.AddRange ( tPorts ); } void PortRange::AddAddr ( const CSphString& sAddr ) { g_tReplicationPorts.AddAddr( sAddr ); } FreePortList_i * PortRange::Create ( const CSphString & sAddr, int iPort, int iCount ) { FreePortList_c * pPortList = new FreePortList_c(); if ( !sAddr.IsEmpty() ) pPortList->AddAddr ( sAddr ); PortsRange_t tPorts; tPorts.m_iPort = iPort; tPorts.m_iCount = iCount; pPortList->AddRange ( tPorts ); return pPortList; }
4,030
C++
.cpp
147
25.217687
90
0.698392
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,022
api_command_cluster.cpp
manticoresoftware_manticoresearch/src/replication/api_command_cluster.cpp
// // Copyright (c) 2019-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 "api_command_cluster.h" #include "configuration.h" #include "digest_sha1.h" #include "common.h" #include "searchdha.h" #include "cluster_commands.h" void operator<< ( ISphOutputBuffer& tOut, const ClusterRequest_t& tReq ) { tOut.SendString ( tReq.m_sCluster.cstr() ); } StringBuilder_c& operator<< ( StringBuilder_c& tOut, const ClusterRequest_t& tReq ) { tOut << "cluster:" << tReq.m_sCluster; return tOut; } void operator>> ( InputBuffer_c& tIn, ClusterRequest_t& tReq ) { tReq.m_sCluster = tIn.GetString(); } void operator<< ( ISphOutputBuffer& tOut, const StrVec_t& dStrings ) { tOut.SendInt ( dStrings.GetLength() ); for ( const auto& sVal : dStrings ) tOut.SendString ( sVal.cstr() ); } StringBuilder_c& operator<< ( StringBuilder_c& tOut, const StrVec_t& dStrings ) { tOut << "strings (" << dStrings.GetLength() << "):"; int iStrings = Min ( 10, dStrings.GetLength() ); for ( int i=0; i<iStrings; ++i ) tOut << dStrings[i]; if ( iStrings > dStrings.GetLength() ) tOut << "...rest" << dStrings.GetLength() - iStrings; return tOut; } void operator>> ( InputBuffer_c& tIn, StrVec_t& dStrings ) { dStrings.Resize ( tIn.GetInt() ); for ( auto& sVal : dStrings ) sVal = tIn.GetString(); } AgentConn_t* CreateAgentBase ( const AgentDesc_t& tDesc, int64_t iTimeoutMs ) { auto* pAgent = new AgentConn_t; pAgent->m_tDesc.CloneFrom ( tDesc ); pAgent->SetNoLimitReplySize(); pAgent->m_tDesc.m_pDash = new HostDashboard_t; pAgent->m_iMyConnectTimeoutMs = ReplicationTimeoutConnect(); pAgent->m_iMyQueryTimeoutMs = iTimeoutMs; return pAgent; } // wrapper of PerformRemoteTasks bool PerformRemoteTasksWrap ( VectorAgentConn_t & dNodes, RequestBuilder_i & tReq, ReplyParser_i & tReply, bool bRetry ) { if ( dNodes.IsEmpty() ) return true; int iQueryRetry = ( bRetry ? ReplicationRetryCount() : -1 ); int iQueryDelay = ( bRetry ? ReplicationRetryDelay() : -1 ); int iNodes = dNodes.GetLength(); int iFinished = PerformRemoteTasks ( dNodes, &tReq, &tReply, iQueryRetry, iQueryDelay ); bool bOk = ( iFinished==iNodes ); if ( !bOk || TlsMsg::HasErr() ) sphLogDebugRpl ( "%d(%d) nodes finished well, tls msg: %s", iFinished, iNodes, TlsMsg::szError() ); if ( bOk && TlsMsg::HasErr() ) TlsMsg::ResetErr(); for ( const AgentConn_t * pAgent : dNodes ) { if ( !pAgent->m_sFailure.IsEmpty() ) { sphWarning ( "'%s:%d': %s", pAgent->m_tDesc.m_sAddr.cstr(), pAgent->m_tDesc.m_iPort, pAgent->m_sFailure.cstr() ); if ( !bOk ) TlsMsg::Err().Appendf ( "'%s:%d': %s", pAgent->m_tDesc.m_sAddr.cstr(), pAgent->m_tDesc.m_iPort, pAgent->m_sFailure.cstr() ); } } return ( bOk && !TlsMsg::HasErr() ); } // handler of all remote commands via API parsed at daemon as SEARCHD_COMMAND_CLUSTER void HandleAPICommandCluster ( ISphOutputBuffer & tOut, WORD uCommandVer, InputBuffer_c & tBuf, const char * szClient ) { auto eClusterCmd = (E_CLUSTER)tBuf.GetWord(); // GET_NODE_VER should skip version check and provide both VER_COMMAND_CLUSTER and VER_COMMAND_REPLICATE if ( eClusterCmd!=E_CLUSTER::GET_NODE_VER && !CheckCommandVersion ( uCommandVer, VER_COMMAND_CLUSTER, tOut ) ) return; if ( eClusterCmd!=E_CLUSTER::FILE_SEND ) sphLogDebugRpl ( "remote cluster command %d(%s), client %s", (int) eClusterCmd, szClusterCmd (eClusterCmd), szClient ); CSphString sCluster; TlsMsg::ResetErr(); switch (eClusterCmd) { case E_CLUSTER::DELETE_: ReceiveClusterDelete ( tOut, tBuf, sCluster ); break; case E_CLUSTER::FILE_RESERVE: ReceiveClusterFileReserve ( tOut, tBuf, sCluster ); break; case E_CLUSTER::FILE_SEND: ReceiveClusterFileSend ( tOut, tBuf ); break; case E_CLUSTER::INDEX_ADD_LOCAL: ReceiveClusterIndexAddLocal ( tOut, tBuf, sCluster ); break; case E_CLUSTER::SYNCED: ReceiveClusterSynced ( tOut, tBuf, sCluster ); break; case E_CLUSTER::GET_NODES: ReceiveClusterGetNodes ( tOut, tBuf, sCluster ); break; case E_CLUSTER::UPDATE_NODES: ReceiveClusterUpdateNodes ( tOut, tBuf, sCluster ); break; case E_CLUSTER::INDEX_ADD_DIST: ReceiveDistIndex ( tOut, tBuf, sCluster ); break; case E_CLUSTER::GET_NODE_STATE: ReceiveClusterGetState ( tOut, tBuf, sCluster ); break; case E_CLUSTER::GET_NODE_VER: ReceiveClusterGetVer ( tOut ); break; default: TlsMsg::Err ( "INTERNAL ERROR: unhandled command %d", (int) eClusterCmd ); break; } if ( !TlsMsg::HasErr() ) return; assert ( eClusterCmd != E_CLUSTER::FILE_SEND ); auto szError = TlsMsg::szError(); sphLogDebugRpl ( "remote cluster '%s' command %s(%d), client %s - %s", sCluster.scstr(), szClusterCmd ( eClusterCmd ), (int)eClusterCmd, szClient, szError ); auto tReply = APIHeader ( tOut, SEARCHD_ERROR ); tOut.SendString ( SphSprintf ( "[%s] %s", szIncomingIP(), szError ).cstr() ); ReportClusterError ( sCluster, szError, szClient, eClusterCmd ); } // 200 msec is ok as we do not need to any missed nodes in cluster node list constexpr int g_iAnyNodesTimeoutMs = 200; constexpr int g_iNodeRetryWaitMs = 500; static int g_iReplConnectTimeoutMs = 0; static int g_iReplQueryTimeoutMs = 0; static int g_iReplRetryCount = 0; static int g_iReplRetryDelayMs = 0; void ReplicationSetTimeouts ( int iConnectTimeoutMs, int iQueryTimeoutMs, int iRetryCount, int iRetryDelayMs ) { g_iReplConnectTimeoutMs = iConnectTimeoutMs; g_iReplQueryTimeoutMs = iQueryTimeoutMs; g_iReplRetryCount = iRetryCount; g_iReplRetryDelayMs = iRetryDelayMs; } int64_t ReplicationTimeoutQuery ( int64_t iTimeout ) { // need default of 2 minutes in msec for replication requests as they are mostly long-running int64_t iTmAtLeast2Min = Max ( g_iReplQueryTimeoutMs, 120 * 1000 ); // should be 2 minutes or timeout if it is longer return Max ( iTmAtLeast2Min, Min ( iTimeout, INT_MAX ) ); } int ReplicationTimeoutConnect () { return g_iReplConnectTimeoutMs; } int ReplicationRetryCount () { return g_iReplRetryCount; } int ReplicationRetryDelay () { return g_iReplRetryDelayMs; } int ReplicationTimeoutAnyNode () { return g_iAnyNodesTimeoutMs; } int ReplicationFileRetryCount () { return Max ( g_iReplRetryCount, 3 ); // should be at least 3 try on file send failure } int ReplicationFileRetryDelay () { return Max ( g_iReplRetryDelayMs, g_iNodeRetryWaitMs ); }
6,712
C++
.cpp
187
33.84492
158
0.733529
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,023
helper.cpp
manticoresoftware_manticoresearch/src/schema/helper.cpp
// // 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 "helper.h" #include "attribute.h" void CSphSchemaHelper::InsertAttr ( CSphVector<CSphColumnInfo> & dAttrs, CSphVector<int> & dUsed, int iPos, const CSphColumnInfo & tCol, bool bDynamic ) { assert ( 0 <= iPos && iPos <= dAttrs.GetLength() ); assert ( tCol.m_eAttrType != SPH_ATTR_NONE ); if ( tCol.m_eAttrType == SPH_ATTR_NONE ) return; dAttrs.Insert ( iPos, tCol ); CSphAttrLocator & tLoc = dAttrs[iPos].m_tLocator; int iBits = ROWITEM_BITS; if ( tLoc.m_iBitCount > 0 ) iBits = tLoc.m_iBitCount; if ( tCol.m_eAttrType == SPH_ATTR_BOOL ) iBits = 1; if ( tCol.m_eAttrType == SPH_ATTR_BIGINT || tCol.m_eAttrType == SPH_ATTR_UINT64 || tCol.m_eAttrType == SPH_ATTR_JSON_FIELD || tCol.m_eAttrType==SPH_ATTR_DOUBLE ) iBits = 64; if ( tCol.IsDataPtr() ) { assert ( bDynamic ); iBits = ROWITEMPTR_BITS; m_dDataPtrAttrs.Add ( dUsed.GetLength() ); } tLoc.m_iBitCount = iBits; tLoc.m_bDynamic = bDynamic; if ( tCol.IsColumnar() ) { // can't have an attribute that is stored in columnar and common storage at the same time // FIXME: maybe add extra flags here? tLoc.m_iBitOffset = 0; } else if ( sphIsBlobAttr ( tCol ) ) { bool bColumnarID = !dAttrs.IsEmpty() && dAttrs[0].m_sName == sphGetDocidName() && dAttrs[0].IsColumnar(); tLoc.m_iBitCount = 0; tLoc.m_iBitOffset = 0; int iBlobAttrId = 0; for ( auto& i : dAttrs ) if ( sphIsBlobAttr ( i ) ) i.m_tLocator.m_iBlobAttrId = iBlobAttrId++; for ( auto& i : dAttrs ) if ( sphIsBlobAttr ( i ) ) { i.m_tLocator.m_nBlobAttrs = iBlobAttrId; i.m_tLocator.m_iBlobRowOffset = bColumnarID ? 0 : 1; } } else if ( iBits >= ROWITEM_BITS ) { tLoc.m_iBitOffset = dUsed.GetLength() * ROWITEM_BITS; int iItems = ( iBits + ROWITEM_BITS - 1 ) / ROWITEM_BITS; for ( int i = 0; i < iItems; i++ ) dUsed.Add ( ROWITEM_BITS ); } else { int iItem; for ( iItem = 0; iItem < dUsed.GetLength(); iItem++ ) if ( dUsed[iItem] + iBits <= ROWITEM_BITS ) break; if ( iItem == dUsed.GetLength() ) dUsed.Add ( 0 ); tLoc.m_iBitOffset = iItem * ROWITEM_BITS + dUsed[iItem]; dUsed[iItem] += iBits; } } void CSphSchemaHelper::Swap ( CSphSchemaHelper& rhs ) noexcept { rhs.m_dDataPtrAttrs.SwapData ( m_dDataPtrAttrs ); rhs.m_dDynamicUsed.SwapData ( m_dDynamicUsed ); } void CSphSchemaHelper::ResetSchemaHelper() { m_dDataPtrAttrs.Reset(); m_dDynamicUsed.Reset(); } void CSphSchemaHelper::CloneMatch ( CSphMatch& tDst, const CSphMatch& rhs ) const { if ( m_dDataPtrAttrs.GetLength() ) CloneMatchSpecial ( tDst, rhs, m_dDataPtrAttrs ); else tDst.Combine ( rhs, GetDynamicSize() ); } void CSphSchemaHelper::FreeDataPtrs ( CSphMatch& tMatch ) const { if ( m_dDataPtrAttrs.IsEmpty() ) return; FreeDataSpecial ( tMatch, m_dDataPtrAttrs ); } void CSphSchemaHelper::CopyPtrs ( CSphMatch& tDst, const CSphMatch& rhs ) const { // notes on PACKEDFACTORS // not immediately obvious: this is not needed while pushing matches to sorters; factors are held in an outer hash table // but it is necessary to copy factors when combining results from several indexes via a sorter because at this moment matches are the owners of factor data CopyPtrsSpecial ( tDst, rhs, m_dDataPtrAttrs ); } CSphVector<int> CSphSchemaHelper::SubsetPtrs ( CSphVector<int>& dDiscarded ) const { CSphVector<int> dFiltered; dDiscarded.Uniq(); for ( int iPtr : m_dDataPtrAttrs ) if ( !dDiscarded.BinarySearch ( iPtr ) ) dFiltered.Add ( iPtr ); dFiltered.Uniq(); return dFiltered; } // declared in sphinxstd.h void sphDeallocatePacked ( BYTE* pBlob ) { if ( !pBlob ) return; #if WITH_SMALLALLOC const BYTE * pFoo = pBlob; sphDeallocateSmall ( pBlob, sphCalcPackedLength ( UnzipIntBE ( pFoo ) ) ); #else sphDeallocateSmall ( pBlob ); #endif } void CSphSchemaHelper::MovePtrsSpecial ( CSphMatch& tDst, CSphMatch& tSrc, const VecTraits_T<int>& dSpecials ) { auto pSrc = tSrc.m_pDynamic; assert ( pSrc || dSpecials.IsEmpty() ); for ( auto i : dSpecials ) { memcpy ( tDst.m_pDynamic + i, pSrc + i, sizeof ( BYTE* ) ); *(BYTE**)( pSrc + i ) = nullptr; } }
4,561
C++
.cpp
135
31.511111
162
0.707993
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,024
columninfo.cpp
manticoresoftware_manticoresearch/src/schema/columninfo.cpp
// // 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 "columninfo.h" #include "sphinxint.h" #include "attribute.h" #include "indexing_sources/source_stats.h" #include "match.h" CSphColumnInfo::CSphColumnInfo ( const char* sName, ESphAttr eType ) : m_sName ( sName ) , m_eAttrType ( eType ) { sphColumnToLowercase ( const_cast<char*> ( m_sName.cstr() ) ); } bool CSphColumnInfo::operator== ( const CSphColumnInfo & rhs ) const { return m_sName == rhs.m_sName && m_eAttrType == rhs.m_eAttrType && m_tLocator.m_iBitCount == rhs.m_tLocator.m_iBitCount && m_tLocator.m_iBitOffset == rhs.m_tLocator.m_iBitOffset && m_tLocator.m_bDynamic == rhs.m_tLocator.m_bDynamic; } bool CSphColumnInfo::IsDataPtr() const { return sphIsDataPtrAttr ( m_eAttrType ); } bool CSphColumnInfo::IsColumnar() const { return m_uAttrFlags & ATTR_COLUMNAR; } bool CSphColumnInfo::HasStringHashes() const { return m_uAttrFlags & ATTR_COLUMNAR_HASHES; } bool CSphColumnInfo::IsColumnarExpr() const { return m_pExpr.Ptr() && m_pExpr->IsColumnar(); } bool CSphColumnInfo::IsStoredExpr() const { return m_pExpr.Ptr() && m_pExpr->IsStored(); } bool CSphColumnInfo::IsIndexedKNN() const { return m_uAttrFlags & ATTR_INDEXED_KNN; } bool CSphColumnInfo::IsJoined() const { return m_uAttrFlags & ATTR_JOINED; } bool CSphColumnInfo::IsIndexedSI() const { return m_uAttrFlags & ATTR_INDEXED_SI; } CSphString sphDumpAttr ( const CSphColumnInfo & tAttr ) { CSphString sRes; sRes.SetSprintf ( "%s %s:%d@%d", sphTypeName ( tAttr.m_eAttrType ), tAttr.m_sName.cstr(), tAttr.m_tLocator.m_iBitCount, tAttr.m_tLocator.m_iBitOffset ); return sRes; }
2,074
C++
.cpp
68
28.823529
153
0.749874
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,025
rset.cpp
manticoresoftware_manticoresearch/src/schema/rset.cpp
// // 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 "rset.h" inline int CSphRsetSchema::ActualLen() const { if ( m_pIndexSchema ) return m_pIndexSchema->GetAttrsCount() - m_dRemoved.GetLength(); return 0; } void CSphRsetSchema::ResetRsetSchema() { CSphSchemaHelper::ResetSchemaHelper(); m_pIndexSchema = nullptr; m_dExtraAttrs.Reset(); } void CSphRsetSchema::AddAttr ( const CSphColumnInfo& tCol, bool bDynamic ) { assert ( bDynamic ); InsertAttr ( m_dExtraAttrs, m_dDynamicUsed, m_dExtraAttrs.GetLength(), tCol, true ); } const char* CSphRsetSchema::GetName() const { return m_pIndexSchema ? m_pIndexSchema->GetName() : nullptr; } int CSphRsetSchema::GetRowSize() const { // we copy over dynamic map in case index schema has dynamic attributes // (that happens in case of inline attributes, or RAM segments in RT indexes) // so there is no need to add GetDynamicSize() here return GetDynamicSize() + ( m_pIndexSchema ? m_pIndexSchema->GetStaticSize() : 0 ); } int CSphRsetSchema::GetStaticSize() const { // result set schemas additions are always dynamic return m_pIndexSchema ? m_pIndexSchema->GetStaticSize() : 0; } int CSphRsetSchema::GetAttrsCount() const { return m_dExtraAttrs.GetLength() + ActualLen(); } int CSphRsetSchema::GetFieldsCount() const { return m_pIndexSchema ? m_pIndexSchema->GetFieldsCount() : 0; } int CSphRsetSchema::GetAttrIndex ( const char* sName ) const { ARRAY_FOREACH ( i, m_dExtraAttrs ) if ( m_dExtraAttrs[i].m_sName == sName ) return i + ActualLen(); if ( !m_pIndexSchema ) return -1; int iRes = m_pIndexSchema->GetAttrIndex ( sName ); if ( iRes >= 0 ) { if ( m_dRemoved.BinarySearch ( iRes ) ) return -1; int iSub = 0; ARRAY_FOREACH_COND ( i, m_dRemoved, iRes >= m_dRemoved[i] ) iSub++; return iRes - iSub; } return -1; } int CSphRsetSchema::GetAttrIndexOriginal ( const char * szName ) const { return m_pIndexSchema->GetAttrIndex ( szName ); } int CSphRsetSchema::GetFieldIndex ( const char * szName ) const { if ( !m_pIndexSchema ) return -1; return m_pIndexSchema->GetFieldIndex ( szName ); } const CSphColumnInfo & CSphRsetSchema::GetField ( int iIndex ) const { assert ( m_pIndexSchema ); return m_pIndexSchema->GetField ( iIndex ); } const CSphColumnInfo * CSphRsetSchema::GetField ( const char * szName ) const { assert ( m_pIndexSchema ); return m_pIndexSchema->GetField(szName); } const CSphVector<CSphColumnInfo>& CSphRsetSchema::GetFields() const { assert ( m_pIndexSchema ); return m_pIndexSchema->GetFields(); } const CSphColumnInfo& CSphRsetSchema::GetAttr ( int iIndex ) const { if ( !m_pIndexSchema ) return m_dExtraAttrs[iIndex]; if ( iIndex < ActualLen() ) { ARRAY_FOREACH_COND ( i, m_dRemoved, iIndex >= m_dRemoved[i] ) ++iIndex; return m_pIndexSchema->GetAttr ( iIndex ); } return m_dExtraAttrs[iIndex - ActualLen()]; } const CSphColumnInfo* CSphRsetSchema::GetAttr ( const char* sName ) const { for ( auto& tExtraAttr : m_dExtraAttrs ) if ( tExtraAttr.m_sName == sName ) return &tExtraAttr; if ( m_pIndexSchema ) return m_pIndexSchema->GetAttr ( sName ); return nullptr; } int CSphRsetSchema::GetAttrId_FirstFieldLen() const { // we assume that field_lens are in the base schema return m_pIndexSchema->GetAttrId_FirstFieldLen(); } int CSphRsetSchema::GetAttrId_LastFieldLen() const { // we assume that field_lens are in the base schema return m_pIndexSchema->GetAttrId_LastFieldLen(); } CSphRsetSchema& CSphRsetSchema::operator= ( const ISphSchema& rhs ) { rhs.AssignTo ( *this ); return *this; } CSphRsetSchema& CSphRsetSchema::operator= ( const CSphSchema& rhs ) { ResetRsetSchema(); m_pIndexSchema = &rhs; // copy over dynamic rowitems map // so that the new attributes we might add would not overlap m_dDynamicUsed = rhs.m_dDynamicUsed; // copy data ptr map. we might want to add proper access via virtual funcs later m_dDataPtrAttrs = rhs.m_dDataPtrAttrs; return *this; } void CSphRsetSchema::Swap ( CSphRsetSchema& rhs ) noexcept { CSphSchemaHelper::Swap ( rhs ); ::Swap ( m_pIndexSchema, rhs.m_pIndexSchema ); ::Swap ( m_dExtraAttrs, rhs.m_dExtraAttrs ); ::Swap ( m_dRemoved, rhs.m_dRemoved ); } CSphRsetSchema::CSphRsetSchema ( const CSphRsetSchema& rhs ) : CSphSchemaHelper ( rhs ) { m_pIndexSchema = rhs.m_pIndexSchema; m_dExtraAttrs = rhs.m_dExtraAttrs; m_dRemoved = rhs.m_dRemoved; } void CSphRsetSchema::RemoveStaticAttr ( int iAttr ) { assert ( m_pIndexSchema ); assert ( iAttr >= 0 ); assert ( iAttr < ActualLen() ); // map from rset indexes (adjusted for removal) to index schema indexes (the original ones) ARRAY_FOREACH_COND ( i, m_dRemoved, iAttr >= m_dRemoved[i] ) iAttr++; m_dRemoved.Add ( iAttr ); m_dRemoved.Uniq(); } bool CSphRsetSchema::IsRemovedAttr ( int iAttr ) const { return ( m_dRemoved.BinarySearch ( iAttr ) ); } void CSphRsetSchema::SwapAttrs ( CSphVector<CSphColumnInfo>& dAttrs ) { #ifndef NDEBUG // ensure that every incoming column has a matching original column // only check locators and attribute types, because at this stage, // names that are used in dAttrs are already overwritten by the aliases // (example: SELECT col1 a, col2 b, count(*) c FROM test) // // FIXME? maybe also lockdown the schema from further swaps, adds etc from here? for ( auto& dAttr : dAttrs ) { auto fComparer = [&dAttr] ( const CSphColumnInfo& dInfo ) { return dInfo.m_tLocator == dAttr.m_tLocator && dInfo.m_eAttrType == dAttr.m_eAttrType; }; bool bFound1 = m_pIndexSchema ? m_pIndexSchema->m_dAttrs.any_of ( fComparer ) : false; bool bFound2 = m_dExtraAttrs.any_of ( fComparer ); assert ( bFound1 || bFound2 ); } #endif m_dExtraAttrs.SwapData ( dAttrs ); m_pIndexSchema = nullptr; } ISphSchema* CSphRsetSchema::CloneMe() const { auto pClone = new CSphRsetSchema; AssignTo ( *pClone ); ARRAY_FOREACH ( i, m_dExtraAttrs ) if ( m_dExtraAttrs[i].m_pExpr ) pClone->m_dExtraAttrs[i].m_pExpr = SafeClone ( m_dExtraAttrs[i].m_pExpr ); return pClone; }
6,467
C++
.cpp
205
29.507317
92
0.740281
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,026
schema.cpp
manticoresoftware_manticoresearch/src/schema/schema.cpp
// // 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 "schema.h" #include "attribute.h" #include "rset.h" #include "match.h" #include "indexsettings.h" CSphSchema::CSphSchema ( CSphString sName ) : m_sName ( std::move ( sName ) ) { memset ( m_dBuckets, 0xFF, sizeof ( m_dBuckets ) ); } CSphSchema::CSphSchema ( const CSphSchema& rhs ) { m_dDataPtrAttrs = rhs.m_dDataPtrAttrs; m_iFirstFieldLenAttr = rhs.m_iFirstFieldLenAttr; m_iLastFieldLenAttr = rhs.m_iLastFieldLenAttr; m_iRowSize = rhs.m_iRowSize; m_sName = rhs.m_sName; m_dFields = rhs.m_dFields; m_dAttrs = rhs.m_dAttrs; m_dStaticUsed = rhs.m_dStaticUsed; m_dDynamicUsed = rhs.m_dDynamicUsed; memcpy ( m_dBuckets, rhs.m_dBuckets, sizeof ( m_dBuckets ) ); } CSphSchema::CSphSchema ( CSphSchema&& rhs ) noexcept : CSphSchema ( nullptr ) { Swap ( rhs ); } void CSphSchema::Swap ( CSphSchema& rhs ) noexcept { ::Swap ( m_dDataPtrAttrs, rhs.m_dDataPtrAttrs ); ::Swap ( m_iFirstFieldLenAttr, rhs.m_iFirstFieldLenAttr ); ::Swap ( m_iLastFieldLenAttr, rhs.m_iLastFieldLenAttr ); ::Swap ( m_iRowSize, rhs.m_iRowSize ); ::Swap ( m_sName, rhs.m_sName ); ::Swap ( m_dFields, rhs.m_dFields ); ::Swap ( m_dAttrs, rhs.m_dAttrs ); ::Swap ( m_dStaticUsed, rhs.m_dStaticUsed ); ::Swap ( m_dDynamicUsed, rhs.m_dDynamicUsed ); std::swap ( m_dBuckets, rhs.m_dBuckets ); } CSphSchema& CSphSchema::operator= ( const ISphSchema& rhs ) { Reset(); m_sName = rhs.GetName(); for ( int i = 0; i < rhs.GetAttrsCount(); ++i ) { const CSphColumnInfo& tAttr = rhs.GetAttr ( i ); if ( tAttr.m_tLocator.m_bDynamic ) AddAttr ( tAttr, true ); else // static attr, keep previous storage m_dAttrs.Add ( tAttr ); } for ( int i = 0; i < rhs.GetFieldsCount(); ++i ) AddField ( rhs.GetField ( i ) ); RebuildHash(); return *this; } CSphSchema& CSphSchema::operator= ( CSphSchema rhs ) { Swap ( rhs ); return *this; } const char* CSphSchema::GetName() const { return m_sName.cstr(); } bool CSphSchema::CompareTo ( const CSphSchema& rhs, CSphString& sError, bool bFullComparison, bool bIndexLoadCheck ) const { // check attr count if ( GetAttrsCount() != rhs.GetAttrsCount() ) { sError.SetSprintf ( "attribute count mismatch (me=%s, in=%s, myattrs=%d, inattrs=%d)", m_sName.cstr(), rhs.m_sName.cstr(), GetAttrsCount(), rhs.GetAttrsCount() ); return false; } // check attrs ARRAY_FOREACH ( i, m_dAttrs ) { const CSphColumnInfo& tAttr1 = rhs.m_dAttrs[i]; const CSphColumnInfo& tAttr2 = m_dAttrs[i]; bool bMismatch; if ( bFullComparison ) bMismatch = !( tAttr1 == tAttr2 ); else { ESphAttr eAttr1 = tAttr1.m_eAttrType; ESphAttr eAttr2 = tAttr2.m_eAttrType; bMismatch = tAttr1.m_sName != tAttr2.m_sName || eAttr1 != eAttr2 || tAttr1.m_eWordpart != tAttr2.m_eWordpart || tAttr1.m_tLocator.m_iBitCount != tAttr2.m_tLocator.m_iBitCount || tAttr1.m_tLocator.m_iBitOffset != tAttr2.m_tLocator.m_iBitOffset; } if ( bMismatch ) { sError.SetSprintf ( "attribute mismatch (me=%s, in=%s, idx=%d, myattr=%s, inattr=%s)", m_sName.cstr(), rhs.m_sName.cstr(), i, sphDumpAttr ( m_dAttrs[i] ).cstr(), sphDumpAttr ( rhs.m_dAttrs[i] ).cstr() ); return false; } } // check field count if ( rhs.m_dFields.GetLength() != m_dFields.GetLength() ) { sError.SetSprintf ( "fulltext fields count mismatch (me=%s, in=%s, myfields=%d, infields=%d)", m_sName.cstr(), rhs.m_sName.cstr(), m_dFields.GetLength(), rhs.m_dFields.GetLength() ); return false; } // check fulltext field names ARRAY_FOREACH ( i, rhs.m_dFields ) { if ( rhs.m_dFields[i].m_sName != m_dFields[i].m_sName ) { sError.SetSprintf ( "fulltext field mismatch (me=%s, myfield=%s, idx=%d, in=%s, infield=%s)", m_sName.cstr(), rhs.m_sName.cstr(), i, m_dFields[i].m_sName.cstr(), rhs.m_dFields[i].m_sName.cstr() ); return false; } DWORD uFlags1 = rhs.m_dFields[i].m_uFieldFlags; DWORD uFlags2 = m_dFields[i].m_uFieldFlags; // stored fields became the default at some point in time // some disk chunks have them and some don't // this doesn't affect functionality but it does affect checks on index load if ( bIndexLoadCheck ) { uFlags1 &= ~CSphColumnInfo::FIELD_STORED; uFlags2 &= ~CSphColumnInfo::FIELD_STORED; } if ( uFlags1!=uFlags2 ) { sError.SetSprintf ( "fulltext field flag mismatch (me=%s, myfield=%s, idx=%d, in=%s, infield=%s)", m_sName.cstr(), rhs.m_sName.cstr(), i, m_dFields[i].m_sName.cstr(), rhs.m_dFields[i].m_sName.cstr() ); return false; } } return true; } int CSphSchema::GetFieldIndex ( const char* sName ) const { if ( !sName ) return -1; ARRAY_FOREACH ( i, m_dFields ) if ( strcasecmp ( m_dFields[i].m_sName.cstr(), sName ) == 0 ) return i; return -1; } const CSphColumnInfo* CSphSchema::GetField ( const char* szName ) const { int iField = GetFieldIndex ( szName ); if ( iField == -1 ) return nullptr; return &m_dFields[iField]; } int CSphSchema::GetAttrIndex ( const char* sName ) const { if ( !sName ) return -1; if ( m_dAttrs.GetLength() >= HASH_THRESH ) { DWORD uCrc = sphCRC32 ( sName ); DWORD uPos = m_dBuckets[uCrc % BUCKET_COUNT]; while ( uPos != 0xffff && m_dAttrs[uPos].m_sName != sName ) uPos = m_dAttrs[uPos].m_uNext; return (short)uPos; // 0xffff == -1 is our "end of list" marker } ARRAY_FOREACH ( i, m_dAttrs ) if ( m_dAttrs[i].m_sName == sName ) return i; return -1; } const CSphColumnInfo* CSphSchema::GetAttr ( const char* sName ) const { int iIndex = GetAttrIndex ( sName ); if ( iIndex >= 0 ) return &m_dAttrs[iIndex]; return NULL; } void CSphSchema::Reset() { CSphSchemaHelper::ResetSchemaHelper(); m_dFields.Reset(); m_dAttrs.Reset(); memset ( m_dBuckets, 0xFF, sizeof ( m_dBuckets ) ); m_dStaticUsed.Reset(); m_iRowSize = 0; } void CSphSchema::InsertAttr ( int iPos, const CSphColumnInfo& tCol, bool bDynamic ) { // it's redundant in case of AddAttr if ( iPos != m_dAttrs.GetLength() ) UpdateHash ( iPos - 1, 1 ); CSphSchemaHelper::InsertAttr ( m_dAttrs, bDynamic ? m_dDynamicUsed : m_dStaticUsed, iPos, tCol, bDynamic ); // update field length locators if ( tCol.m_eAttrType == SPH_ATTR_TOKENCOUNT ) { m_iFirstFieldLenAttr = m_iFirstFieldLenAttr == -1 ? iPos : Min ( m_iFirstFieldLenAttr, iPos ); m_iLastFieldLenAttr = Max ( m_iLastFieldLenAttr, iPos ); } // do hash add if ( m_dAttrs.GetLength() == HASH_THRESH ) RebuildHash(); else if ( m_dAttrs.GetLength() > HASH_THRESH ) { WORD& uPos = GetBucketPos ( m_dAttrs[iPos].m_sName.cstr() ); m_dAttrs[iPos].m_uNext = uPos; uPos = (WORD)iPos; } m_iRowSize = GetRowSize(); } void CSphSchema::RemoveAttr ( const char* szAttr, bool bDynamic ) { int iIndex = GetAttrIndex ( szAttr ); if ( iIndex < 0 ) return; if ( bDynamic ) m_dDynamicUsed.Reset(); else m_dStaticUsed.Reset(); CSphSchemaHelper::ResetSchemaHelper(); m_iFirstFieldLenAttr = -1; m_iLastFieldLenAttr = -1; CSphVector<CSphColumnInfo> dBackup; dBackup.Reserve ( m_dAttrs.GetLength() ); dBackup.SwapData ( m_dAttrs ); ARRAY_FOREACH ( i, dBackup ) if ( i != iIndex ) AddAttr ( dBackup[i], bDynamic ); } void CSphSchema::AddAttr ( const CSphColumnInfo& tCol, bool bDynamic ) { InsertAttr ( m_dAttrs.GetLength(), tCol, bDynamic ); } void CSphSchema::AddField ( const char* szFieldName ) { CSphColumnInfo& tField = m_dFields.Add(); tField.m_sName = szFieldName; } void CSphSchema::AddField ( const CSphColumnInfo& tField ) { m_dFields.Add ( tField ); } void CSphSchema::RemoveField ( const char* szFieldName ) { auto iIdx = GetFieldIndex ( szFieldName ); RemoveField ( iIdx ); } void CSphSchema::RemoveField ( int iIdx ) { if ( iIdx >= 0 ) m_dFields.Remove ( iIdx ); } int CSphSchema::GetAttrId_FirstFieldLen() const { return m_iFirstFieldLenAttr; } int CSphSchema::GetAttrId_LastFieldLen() const { return m_iLastFieldLenAttr; } bool CSphSchema::IsReserved ( const char* szToken ) { static const char * dReserved[] = { "AND", "AS", "BY", "COLUMNARSCAN", "DISTINCT", "DIV", "DOCIDINDEX", "EXPLAIN", "FACET", "FALSE", "FORCE", "FROM", "IGNORE", "IN", "INDEXES", "INNER", "IS", "JOIN", "KNN", "LEFT", "LIMIT", "MOD", "NOT", "NO_COLUMNARSCAN", "NO_DOCIDINDEX", "NO_SECONDARYINDEX", "NULL", "OFFSET", "ON", "OR", "ORDER", "RELOAD", "SECONDARYINDEX", "SELECT", "SYSFILTERS", "TRUE", NULL }; const char** p = dReserved; while ( *p ) if ( strcasecmp ( szToken, *p++ ) == 0 ) return true; return false; } WORD& CSphSchema::GetBucketPos ( const char* sName ) { DWORD uCrc = sphCRC32 ( sName ); return m_dBuckets[uCrc % BUCKET_COUNT]; } void CSphSchema::RebuildHash() { if ( m_dAttrs.GetLength() < HASH_THRESH ) return; memset ( m_dBuckets, 0xFF, sizeof ( m_dBuckets ) ); ARRAY_FOREACH ( i, m_dAttrs ) { WORD& uPos = GetBucketPos ( m_dAttrs[i].m_sName.cstr() ); m_dAttrs[i].m_uNext = uPos; uPos = WORD ( i ); } } void CSphSchema::RebuildLocators() { CSphVector<CSphColumnInfo> dBackup = m_dAttrs; m_dDynamicUsed.Reset(); m_dStaticUsed.Reset(); CSphSchemaHelper::ResetSchemaHelper(); m_dAttrs.Reset(); m_iFirstFieldLenAttr = -1; m_iLastFieldLenAttr = -1; for ( auto& i : dBackup ) AddAttr ( i, i.m_tLocator.m_bDynamic ); } void CSphSchema::UpdateHash ( int iStartIndex, int iAddVal ) { if ( m_dAttrs.GetLength() < HASH_THRESH ) return; for ( auto& dAttr : m_dAttrs ) { WORD& uPos = dAttr.m_uNext; if ( uPos != 0xffff && uPos > iStartIndex ) uPos = (WORD)( uPos + iAddVal ); } for ( WORD& uPos : m_dBuckets ) if ( uPos != 0xffff && uPos > iStartIndex ) uPos = (WORD)( uPos + iAddVal ); } void CSphSchema::AssignTo ( CSphRsetSchema& lhs ) const { lhs = *this; } void CSphSchema::CloneWholeMatch ( CSphMatch& tDst, const CSphMatch& rhs ) const { FreeDataPtrs ( tDst ); tDst.Combine ( rhs, GetRowSize() ); CopyPtrs ( tDst, rhs ); } void CSphSchema::SetFieldWordpart ( int iField, ESphWordpart eWordpart ) { m_dFields[iField].m_eWordpart = eWordpart; } void CSphSchema::SwapAttrs ( CSphVector<CSphColumnInfo>& dAttrs ) { m_dAttrs.SwapData ( dAttrs ); RebuildHash(); m_iRowSize = GetRowSize(); } ISphSchema* CSphSchema::CloneMe() const { return new CSphSchema ( *this ); } bool CSphSchema::HasBlobAttrs() const { return m_dAttrs.any_of ( [] ( const CSphColumnInfo& i ) { return sphIsBlobAttr ( i ); } ); } int CSphSchema::GetCachedRowSize() const { return m_iRowSize; } void CSphSchema::SetupColumnarFlags ( const CSphSourceSettings & tSettings, StrVec_t * pWarnings ) { bool bAllColumnar = false; bool bAllRowwise = false; bool bAllNoHashes = false; SmallStringHash_T<int> hColumnar, hRowwise, hNoHashes; for ( const auto & i : tSettings.m_dColumnarAttrs ) { bAllColumnar |= i=="*"; hColumnar.Add ( 0, i ); } for ( const auto & i : tSettings.m_dRowwiseAttrs ) { bAllRowwise |= i=="*"; hRowwise.Add ( 0, i ); } for ( const auto & i : tSettings.m_dColumnarStringsNoHash ) { bAllNoHashes |= i=="*"; hNoHashes.Add ( 0, i ); } bool bHaveColumnar = false; for ( auto& tAttr : m_dAttrs ) { if ( ( hColumnar.Exists ( tAttr.m_sName ) && hRowwise.Exists ( tAttr.m_sName ) ) || ( bAllColumnar && bAllRowwise ) ) { if ( pWarnings ) { CSphString sWarning; sWarning.SetSprintf ( "both columnar and rowwise storages specified for '%s'; using rowwise", tAttr.m_sName.cstr() ); pWarnings->Add ( sWarning ); } } if ( sphIsInternalAttr ( tAttr ) ) tAttr.m_eEngine = AttrEngine_e::ROWWISE; else { tAttr.m_eEngine = AttrEngine_e::DEFAULT; if ( bAllColumnar || hColumnar.Exists ( tAttr.m_sName ) ) tAttr.m_eEngine = AttrEngine_e::COLUMNAR; if ( bAllRowwise || hRowwise.Exists ( tAttr.m_sName ) ) tAttr.m_eEngine = AttrEngine_e::ROWWISE; } AttrEngine_e eIndexEngine = CombineEngines ( GetDefaultAttrEngine(), tSettings.m_eEngine ); AttrEngine_e eEngine = CombineEngines ( eIndexEngine, tAttr.m_eEngine ); if ( eEngine != AttrEngine_e::COLUMNAR ) continue; if ( tAttr.m_eAttrType==SPH_ATTR_JSON ) { if ( pWarnings ) { CSphString sWarning; sWarning.SetSprintf ( "columnar storage does not support json type ('%s' attribute specified as columnar)", tAttr.m_sName.cstr() ); pWarnings->Add ( sWarning ); } tAttr.m_uAttrFlags &= ~CSphColumnInfo::ATTR_COLUMNAR; continue; } tAttr.m_uAttrFlags |= CSphColumnInfo::ATTR_COLUMNAR; // set strings to have pre-generated hashes by default if ( tAttr.m_eAttrType==SPH_ATTR_STRING && !( bAllNoHashes || hNoHashes.Exists ( tAttr.m_sName ) ) ) tAttr.m_uAttrFlags |= CSphColumnInfo::ATTR_COLUMNAR_HASHES; bHaveColumnar = true; } // if all blob attrs turned columnar, there's no point in keeping the blob locator bool bHaveBlobs = m_dAttrs.any_of ( [] ( const CSphColumnInfo& tAttr ) { return sphIsBlobAttr ( tAttr ); } ); const CSphColumnInfo* pBlobLocator = GetAttr ( sphGetBlobLocatorName() ); if ( !bHaveBlobs && pBlobLocator ) RemoveAttr ( sphGetBlobLocatorName(), pBlobLocator->m_tLocator.m_bDynamic ); if ( bHaveColumnar ) RebuildLocators(); // remove columnar attrs from row storage } void CSphSchema::SetupKNNFlags ( const CSphSourceSettings & tSettings ) { SmallStringHash_T<int> hKNN; ARRAY_FOREACH ( i, tSettings.m_dKNN ) hKNN.Add ( i, tSettings.m_dKNN[i].m_sName ); for ( auto & tAttr : m_dAttrs ) { if ( !hKNN.Exists ( tAttr.m_sName ) ) continue; int iId = hKNN[tAttr.m_sName]; tAttr.m_tKNN = tSettings.m_dKNN[iId]; } } void CSphSchema::SetupSIFlags ( const CSphSourceSettings & tSettings, StrVec_t * pWarnings ) { SmallStringHash_T<int> hJsonSI; for ( const auto & i : tSettings.m_dJsonSIAttrs ) hJsonSI.Add ( 0, i ); for ( auto & tAttr : m_dAttrs ) { if ( !hJsonSI.Exists ( tAttr.m_sName ) ) continue; if ( tAttr.m_eAttrType!=SPH_ATTR_JSON ) { if ( pWarnings ) { CSphString sWarning; sWarning.SetSprintf ( "unable to create json SI on non-json attribute '%s'", tAttr.m_sName.cstr() ); pWarnings->Add ( sWarning ); } } else tAttr.m_uAttrFlags |= CSphColumnInfo::ATTR_INDEXED_SI; } } void CSphSchema::SetupFlags ( const CSphSourceSettings & tSettings, bool bPQ, StrVec_t * pWarnings ) { bool bAllFieldsStored = false; for ( const auto & i : tSettings.m_dStoredFields ) bAllFieldsStored |= i=="*"; for ( auto & tSchemaField : m_dFields ) { bool bFieldStored = bAllFieldsStored; for ( const auto & sStored : tSettings.m_dStoredFields ) if ( !bFieldStored && tSchemaField.m_sName == sStored ) { bFieldStored = true; break; } if ( bFieldStored ) tSchemaField.m_uFieldFlags |= CSphColumnInfo::FIELD_STORED; for ( const auto & sStoredOnly : tSettings.m_dStoredOnlyFields ) if ( tSchemaField.m_sName == sStoredOnly ) tSchemaField.m_uFieldFlags = CSphColumnInfo::FIELD_STORED; } if ( !bPQ ) { SetupColumnarFlags ( tSettings, pWarnings ); SetupKNNFlags(tSettings); SetupSIFlags ( tSettings, pWarnings ); } bool bAllNonStored = false; SmallStringHash_T<int> hColumnarNonStored; for ( const auto & i : tSettings.m_dColumnarNonStoredAttrs ) { bAllNonStored |= i=="*"; hColumnarNonStored.Add ( 0, i ); } int iNumColumnar = 0; for ( auto & i : m_dAttrs ) if ( i.IsColumnar() && !( bAllNonStored || hColumnarNonStored.Exists ( i.m_sName ) ) ) iNumColumnar++; if ( iNumColumnar>1 || ( iNumColumnar>0 && ( bAllNonStored || hColumnarNonStored.GetLength() ) ) ) { for ( auto & i : m_dAttrs ) if ( i.IsColumnar() && !hColumnarNonStored.Exists ( i.m_sName ) ) i.m_uAttrFlags |= CSphColumnInfo::ATTR_STORED; } } bool CSphSchema::HasStoredFields() const { return m_dFields.any_of ( [] ( const CSphColumnInfo& tField ) { return tField.m_uFieldFlags & CSphColumnInfo::FIELD_STORED; } ); } bool CSphSchema::HasStoredAttrs() const { return m_dAttrs.any_of ( []( const CSphColumnInfo & tAttr ){ return tAttr.m_uAttrFlags & CSphColumnInfo::ATTR_STORED; } ); } bool CSphSchema::HasColumnarAttrs() const { return m_dAttrs.any_of ( [] ( const CSphColumnInfo& tAttr ) { return tAttr.IsColumnar(); } ); } bool CSphSchema::HasNonColumnarAttrs() const { return m_dAttrs.any_of ( [] ( const CSphColumnInfo& tAttr ) { return !tAttr.IsColumnar(); } ); } bool CSphSchema::HasKNNAttrs() const { return m_dAttrs.any_of ( [] ( const CSphColumnInfo& tAttr ) { return tAttr.IsIndexedKNN(); } ); } bool CSphSchema::HasJsonSIAttrs() const { return m_dAttrs.any_of ( [] ( const CSphColumnInfo& tAttr ) { return tAttr.IsIndexedSI(); } ); } bool CSphSchema::IsFieldStored ( int iField ) const { return !!( m_dFields[iField].m_uFieldFlags & CSphColumnInfo::FIELD_STORED ); } bool CSphSchema::IsAttrStored ( int iAttr ) const { return !!( m_dAttrs[iAttr].m_uAttrFlags & CSphColumnInfo::ATTR_STORED ); } /////////////////////////////////////////////////////////////////////////////// void sphFixupLocator ( CSphAttrLocator & tLocator, const ISphSchema * pOldSchema, const ISphSchema * pNewSchema ) { // first time schema setup? if ( !pOldSchema ) return; if ( tLocator.m_iBlobAttrId==-1 && tLocator.m_iBitCount==-1 ) return; assert ( pNewSchema ); for ( int i = 0; i < pOldSchema->GetAttrsCount(); i++ ) { const CSphColumnInfo & tAttr = pOldSchema->GetAttr(i); if ( tLocator==tAttr.m_tLocator ) { const CSphColumnInfo * pAttrInNewSchema = pNewSchema->GetAttr ( tAttr.m_sName.cstr() ); if ( pAttrInNewSchema ) { tLocator = pAttrInNewSchema->m_tLocator; return; } } } }
17,954
C++
.cpp
576
28.571181
246
0.691343
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,027
indexlink.cpp
manticoresoftware_manticoresearch/src/detail/indexlink.cpp
// // Copyright (c) 2023-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 "indexlink.h" #include "fileutils.h" #include "fileio.h" // uncomment if need to store absolute (real) new path. String sNewPath should be passed by value for it //#define STORE_ABSOLUTE 1 bool WriteLinkFile ( const CSphString& sBase, const CSphString& sNewPath, CSphString& sError ) { sError = ""; auto sLink = SphSprintf ( "%s.link", sBase.cstr() ); // if sNewPath points to base - .link file is not necessary, and we will delete it, if exists. if ( RealPath ( sBase ) == RealPath ( sNewPath ) && sphIsReadable ( sLink ) ) { auto iRes = ::unlink ( sLink.cstr() ); if (!iRes) return true; sError = strerrorm ( errno ); return false; } CSphWriter tWriter; if ( !tWriter.OpenFile ( sLink, sError ) ) return false; #if defined( STORE_ABSOLUTE ) && STORE_ABSOLUTE auto sStorePath = RealPath ( sNewPath ); #else const auto& sStorePath = sNewPath; #endif tWriter.PutBytes ( sStorePath.cstr(), sStorePath.Length() ); tWriter.CloseFile(); return !tWriter.IsError(); } CSphString RedirectToRealPath ( CSphString sBase ) { auto sLinkFile = SphSprintf ( "%s.link", sBase.cstr() ); if ( !sphIsReadable ( sLinkFile ) ) return sBase; CSphAutofile rdFile; CSphString sError; auto iFileSize = sphGetFileSize ( sLinkFile ); if ( iFileSize < 0 ) return sBase; CSphAutofile tFile; if ( tFile.Open ( sLinkFile, SPH_O_READ, sError ) < 0 ) return sBase; CSphFixedVector<char> dBytes { iFileSize }; auto iRead = (int64_t)sphReadThrottled ( tFile.GetFD(), dBytes.begin(), iFileSize ); if ( iRead != iFileSize ) return sBase; sBase.SetBinary ( dBytes.begin(), iFileSize ); return sBase; }
2,108
C++
.cpp
61
32.590164
104
0.725307
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,028
appendf.cpp
manticoresoftware_manticoresearch/src/gbenches/appendf.cpp
// // 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 "std/stringbuilder.h" #include "std/string.h" #include <benchmark/benchmark.h> static void builder_Appendf ( benchmark::State& st ) { auto NUM_TRIES = st.range ( 0 ); StringBuilder_c sRes; for ( auto _ : st ) for ( int i = 0; i < NUM_TRIES; ++i ) sRes.Appendf ( "%d ", i ); st.SetLabel ( "Use Appendf to builder" ); } static void builder_Sprintf ( benchmark::State& st ) { auto NUM_TRIES = st.range ( 0 ); StringBuilder_c sRes; for ( auto _ : st ) for ( int i = 0; i < NUM_TRIES; ++i ) sRes.Sprintf ( "%d ", i ); st.SetLabel("Use sprintf to builder"); } static void string_Sprintf ( benchmark::State& st ) { auto NUM_TRIES = st.range ( 0 ); CSphString sRes; sRes.SetSprintf ( "%s", "0" ); for ( auto _ : st ) for ( int i = 0; i < NUM_TRIES; ++i ) sRes.SetSprintf ( "%s %d ", sRes.cstr(), i ); st.SetLabel ( "Use SetSprintf to string" ); } BENCHMARK ( builder_Appendf )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK ( builder_Sprintf )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK ( string_Sprintf )->RangeMultiplier ( 10 )->Range ( 10, 1000 );
1,581
C++
.cpp
45
33.377778
80
0.675163
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,029
popcount.cpp
manticoresoftware_manticoresearch/src/gbenches/popcount.cpp
// // 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 <benchmark/benchmark.h> #include "sphinxstd.h" inline int BitCountDW1 ( DWORD n ) { // MIT HACKMEM count // works for 32-bit numbers only // fix last line for 64-bit numbers DWORD tmp; tmp = n - ( ( n >> 1 ) & 033333333333 ) - ( ( n >> 2 ) & 011111111111 ); return ( ( tmp + ( tmp >> 3 ) ) & 030707070707 ) % 63; } inline int BitCountDW2 ( DWORD n ) { // MIT HACKMEM count without division unsigned long tmp = ( n >> 1 ) & 0x77777777UL; n -= tmp; tmp = ( tmp >> 1 ) & 0x77777777UL; n -= tmp; tmp = ( tmp >> 1 ) & 0x77777777UL; n -= tmp; n = ( n + ( n >> 4 ) ) & 0x0F0F0F0FUL; n = n * 0x01010101UL; return n >> 24; } inline int BitCountU641 ( uint64_t n ) { // MIT HACKMEM count without division unsigned long tmp = ( n >> 1 ) & 0x7777777777777777UL; n -= tmp; tmp = ( tmp >> 1 ) & 0x7777777777777777UL; n -= tmp; tmp = ( tmp >> 1 ) & 0x7777777777777777UL; n -= tmp; n = ( n + ( n >> 4 ) ) & 0x0F0F0F0F0F0F0F0FUL; n = n * 0x0101010101010101UL; return n >> 56; } class bench_popcount : public benchmark::Fixture { public: void SetUp ( const ::benchmark::State & state ) override { sphSrand(0); dValues.Resize ( 128+8 ); for ( auto & c: dValues ) c = ( (uint64_t)sphRand() << 32 ) | sphRand(); i = 0; NRUNS = state.range ( 0 ); } CSphVector<uint64_t> dValues; int i; int64_t NRUNS = 0; }; BENCHMARK_DEFINE_F( bench_popcount, artificial_no_division ) ( benchmark::State & st ) { for ( auto _ : st ) { for ( auto j = 0; j < NRUNS; ++j ) { benchmark::DoNotOptimize ( BitCountDW2 ( dValues[++i] ) ); if ( i > 127 ) i = 0; } } st.SetBytesProcessed ( st.iterations() * NRUNS * sizeof ( DWORD ) ); st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetLabel ("DWORD BitCountDW2"); } BENCHMARK_DEFINE_F ( bench_popcount, artificial_with_division ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( auto j = 0; j < NRUNS; ++j ) { benchmark::DoNotOptimize ( BitCountDW1 ( dValues[++i] ) ); if ( i > 127 ) i = 0; } } st.SetBytesProcessed ( st.iterations() * NRUNS * sizeof ( DWORD ) ); st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetLabel ( "DWORD BitCountDW1" ); } BENCHMARK_DEFINE_F ( bench_popcount, artificial_long_no_division ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( auto j = 0; j < NRUNS; ++j ) { benchmark::DoNotOptimize ( BitCountU641 ( dValues[++i] ) ); if ( i > 127 ) i = 0; } } st.SetBytesProcessed ( st.iterations() * NRUNS * sizeof ( uint64_t ) ); st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetLabel ( "uint64_t BitCountU641" ); } BENCHMARK_DEFINE_F ( bench_popcount, intrinsic_dword ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( auto j = 0; j < NRUNS; ++j ) { benchmark::DoNotOptimize ( sphBitCount ( (DWORD)dValues[++i] ) ); if ( i > 127 ) i = 0; } } st.SetBytesProcessed ( st.iterations() * NRUNS * sizeof ( DWORD ) ); st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetLabel ( "DWORD sphBitCount" ); } BENCHMARK_DEFINE_F ( bench_popcount, intrinsic_uint64 ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( auto j = 0; j < NRUNS; ++j ) { benchmark::DoNotOptimize ( sphBitCount ( dValues[++i] ) ); if ( i > 127 ) i = 0; } } st.SetBytesProcessed ( st.iterations() * NRUNS * sizeof ( uint64_t ) ); st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetLabel ( "uint64_t sphBitCount" ); } BENCHMARK_DEFINE_F ( bench_popcount, artificial_byte ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( auto j = 0; j < NRUNS; ++j ) { benchmark::DoNotOptimize ( sphBitCount ( (BYTE)dValues[++i] ) ); if ( i > 127 ) i = 0; } } st.SetBytesProcessed ( st.iterations() * NRUNS ); st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetLabel ( "BYTE sphBitCount" ); } BENCHMARK_REGISTER_F ( bench_popcount, artificial_no_division )->Range ( 1, 4096 ); BENCHMARK_REGISTER_F ( bench_popcount, artificial_with_division )->Range ( 1, 4096 ); BENCHMARK_REGISTER_F ( bench_popcount, artificial_long_no_division )->Range ( 1, 4096 ); BENCHMARK_REGISTER_F ( bench_popcount, intrinsic_dword )->Range ( 1, 4096 ); BENCHMARK_REGISTER_F ( bench_popcount, intrinsic_uint64 )->Range ( 1, 4096 ); BENCHMARK_REGISTER_F ( bench_popcount, artificial_byte )->Range ( 1, 4096 ); namespace { template<typename UINT> constexpr inline int Log2constUINT ( UINT uValue ) { int iBits = 0; do { uValue >>= 1; ++iBits; } while ( uValue ); return iBits; } template<typename T> inline int CalcZippedLenViaLog2 ( T tValue ) { return (sphLog2(tValue)+6)/7; // gives no branching, but stalled-cycles-frontend because of 'bsr' instruction. It works faster standalone, but slower in ZipValue } } static void BM_zippedlen64 ( benchmark::State& st ) { uint64_t uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( sphCalcZippedLen ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } static void BM_zippedlen32 ( benchmark::State& st ) { DWORD uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( sphCalcZippedLen ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } static void BM_zippedlen16 ( benchmark::State& st ) { WORD uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( sphCalcZippedLen ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } BENCHMARK ( BM_zippedlen64 )->DenseRange ( 0, 64, 4 ); BENCHMARK ( BM_zippedlen32 )->DenseRange ( 0, 32, 4 ); BENCHMARK ( BM_zippedlen16 )->DenseRange ( 0, 16, 4 ); static void BM_zippedlenlog2_64 ( benchmark::State& st ) { uint64_t uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( CalcZippedLenViaLog2 ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } static void BM_zippedlenlog2_32 ( benchmark::State& st ) { DWORD uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( CalcZippedLenViaLog2 ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } static void BM_zippedlenlog2_16 ( benchmark::State& st ) { WORD uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( CalcZippedLenViaLog2 ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } BENCHMARK ( BM_zippedlenlog2_64 )->DenseRange ( 0, 64, 4 ); BENCHMARK ( BM_zippedlenlog2_32 )->DenseRange ( 0, 32, 4 ); BENCHMARK ( BM_zippedlenlog2_16 )->DenseRange ( 0, 16, 4 ); static void BM_log2seq64 ( benchmark::State& st ) { uint64_t uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( Log2constUINT ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } static void BM_log2seq32 ( benchmark::State& st ) { DWORD uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( Log2constUINT ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } BENCHMARK ( BM_log2seq64 )->DenseRange ( 0, 64, 4 ); BENCHMARK ( BM_log2seq32 )->DenseRange ( 0, 32, 4 ); static void BM_log2int64 ( benchmark::State& st ) { uint64_t uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( sphLog2 ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } static void BM_log2int32 ( benchmark::State& st ) { DWORD uValue = 1 << st.range ( 0 ); for ( auto _ : st ) benchmark::DoNotOptimize ( sphLog2 ( uValue ) ); st.SetItemsProcessed ( st.iterations() ); } BENCHMARK ( BM_log2int64 )->DenseRange ( 0, 64, 4 ); BENCHMARK ( BM_log2int32 )->DenseRange ( 0, 32, 4 ); #define SPH_VARINT_DECODE( _type, _getexpr ) \ DWORD b = _getexpr; \ _type res = 0; \ while ( b & 0x80 ) \ { \ res = ( res << 7 ) + ( b & 0x7f ); \ b = _getexpr; \ } \ res = ( res << 7 ) + b; \ return res; class heavy { public: virtual int GetByte(); BYTE* m_pBuff; ///< the buffer int m_iBuffPos = 0; int m_iBuffUsed = 0; bool m_bError; CSphString m_sError; virtual void UpdateCache() = 0; inline DWORD UnzipValueBEDWORD_reference() { return UnzipValueBE_reference<DWORD> ( [this]() mutable { return GetByte(); } ); }; inline DWORD UnzipValueBEDWORD() { return UnzipValueBE<DWORD> ( [this]() mutable { return GetByte(); } ); }; inline DWORD UnzipValueBEDWORD_macro() { SPH_VARINT_DECODE ( DWORD, GetByte() ); }; }; class zipunzip: public benchmark::Fixture, public heavy { public: void SetUp ( const ::benchmark::State& state ) override { auto NSEPTETS = state.range ( 0 ); uint64_t uMask = NSEPTETS > 9 ? 0xFFFFFFFFFFFFFFFFULL : ( ( 1ULL << NSEPTETS * 7 ) - 1ULL ); auto NRUNS = state.range ( 1 ); dValues.Resize ( NRUNS ); dBufBE.Reserve ( NRUNS * 10 ); dBufBE.Resize ( 0 ); dBufLE.Reserve ( NRUNS * 10 ); dBufLE.Resize ( 0 ); dBufBE64.Reserve ( NRUNS * 10 ); dBufBE64.Resize ( 0 ); dBufLE64.Reserve ( NRUNS * 10 ); dBufLE64.Resize ( 0 ); sphSrand ( 0 ); for ( auto& c : dValues ) { uint64_t uVal = sphRand(); uVal = ( uVal << 32 ) | sphRand(); uVal &= uMask; c = uVal; ZipValueBE ( [this] ( BYTE b ) mutable { dBufBE.Add ( b ); }, uVal & 0xFFFFFFFF ); ZipValueLE ( [this] ( BYTE b ) mutable { dBufLE.Add ( b ); }, uVal & 0xFFFFFFFF ); ZipValueBE ( [this] ( BYTE b ) mutable { dBufBE64.Add ( b ); }, uVal ); ZipValueLE ( [this] ( BYTE b ) mutable { dBufLE64.Add ( b ); }, uVal ); } iRes = 0; // printf ( "SetUp with mask: %d, %p. %d %d %d %d\n", (int)NSEPTETS, (void*)uMask, // dBufBE.GetLength(), dBufLE.GetLength(), dBufBE64.GetLength(), dBufLE64.GetLength()); } CSphVector<uint64_t> dValues; CSphVector<BYTE> dBufBE; CSphVector<BYTE> dBufLE; CSphVector<BYTE> dBufBE64; CSphVector<BYTE> dBufLE64; volatile int iRes = 0; void UpdateCache() override; }; // metrics from real run searchd with index - mostly 1 byte, sometimes 2 (about 12%) and few cases when 3. Never 4 and 5 // for offsets - same way, mostly 1 byte, and about 0.1% when 4. Never 2, 3, 5+ // | unzip32_hist | 1132420000, 136150000, 50000, 0, 0 | // | unzip64_hist | 7140000, 0, 0, 10000, 0, 0, 0, 0, 0, 0 | class realunzip: public benchmark::Fixture, public heavy { public: static constexpr int iProfile = 113242 + 13615 + 5; static constexpr int iSize = 113242 * 1 + 13615 * 2 + 5 * 3; void SetUp ( const ::benchmark::State& state ) override { auto NRUNS = state.range ( 0 ); dValues.Resize ( NRUNS*iProfile ); dBufBE.Reserve ( NRUNS * iSize ); dBufBE.Resize ( 0 ); sphSrand ( 0 ); uint64_t uMask = ( 1ULL << 1 * 7 ) - 1ULL; for ( int i=0; i<113242*NRUNS; ++i ) { uint64_t uVal = sphRand(); uVal = ( uVal << 32 ) | sphRand(); uVal &= uMask; dValues[i] = uVal; ZipValueBE ( [this] ( BYTE b ) mutable { dBufBE.Add ( b ); }, uVal & 0xFFFFFFFF ); } uMask = ( 1ULL << 2 * 7 ) - 1ULL; for ( int i = 0; i < 13615 * NRUNS; ++i ) { uint64_t uVal = sphRand(); uVal = ( uVal << 32 ) | sphRand(); uVal &= uMask; dValues[i] = uVal; ZipValueBE ( [this] ( BYTE b ) mutable { dBufBE.Add ( b ); }, uVal & 0xFFFFFFFF ); } uMask = ( 1ULL << 3 * 7 ) - 1ULL; for ( int i = 0; i < 5 * NRUNS; ++i ) { uint64_t uVal = sphRand(); uVal = ( uVal << 32 ) | sphRand(); uVal &= uMask; dValues[i] = uVal; ZipValueBE ( [this] ( BYTE b ) mutable { dBufBE.Add ( b ); }, uVal & 0xFFFFFFFF ); } iRes = 0; // printf ( "SetUp with mask: %d, %p. %d %d %d %d\n", (int)NSEPTETS, (void*)uMask, // dBufBE.GetLength(), dBufLE.GetLength(), dBufBE64.GetLength(), dBufLE64.GetLength()); } CSphVector<uint64_t> dValues; CSphVector<BYTE> dBufBE; volatile int iRes = 0; void UpdateCache() override; }; int heavy::GetByte() { if ( m_iBuffPos >= m_iBuffUsed ) { UpdateCache(); if ( m_iBuffPos >= m_iBuffUsed ) { m_bError = true; m_sError.SetSprintf ( "pread error in: pos=" INT64_FMT ", len=%d", (int64_t)m_iBuffPos, 1 ); return 0; // unexpected io failure } } assert ( m_iBuffPos < m_iBuffUsed ); return m_pBuff[m_iBuffPos++]; } void zipunzip::UpdateCache() { m_iBuffUsed = dBufBE.GetLengthBytes(); } void realunzip::UpdateCache() { m_iBuffUsed = dBufBE.GetLengthBytes(); } template<typename T, typename WRITER> inline int ZipValueBElog2 ( WRITER fnPut, T tValue ) { int nBytes = ( sphLog2 ( tValue ) + 6 ) / 7; for ( int i = nBytes - 1; i >= 0; --i ) fnPut ( ( 0x7f & ( tValue >> ( 7 * i ) ) ) | ( i ? 0x80 : 0 ) ); return nBytes; } // big-endian (most significant septets first) template<typename T> inline int ZipToPtrBElog2 ( BYTE* pData, T tValue ) { return ZipValueBElog2 ( [pData] ( BYTE b ) mutable { *pData++ = b; }, tValue ); } // 32 bits integer packing BENCHMARK_DEFINE_F ( zipunzip, zipbe32 ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { BYTE* pBuf = dBufBE.begin(); for ( auto i = 0; i < NRUNS; ++i ) pBuf += ZipToPtrBE ( pBuf, (DWORD)dValues[i] ); iBytes += pBuf-dBufBE.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, zipbe32log2 ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { BYTE* pBuf = dBufBE.begin(); for ( auto i = 0; i < NRUNS; ++i ) pBuf += ZipToPtrBElog2 ( pBuf, (DWORD)dValues[i] ); iBytes += pBuf - dBufBE.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, ziple32 ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { BYTE* pBuf = dBufLE.begin(); for ( auto i = 0; i < NRUNS; ++i ) pBuf += ZipToPtrLE ( pBuf, (DWORD)dValues[i] ); iBytes += pBuf - dBufLE.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } static constexpr int MINRANGE = 2; static constexpr int MAXRANGE=512; static constexpr int STEPRANGE = 8; BENCHMARK_REGISTER_F ( zipunzip, zipbe32 )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, zipbe32log2 )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, ziple32 )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); // 64 bits integers BENCHMARK_DEFINE_F ( zipunzip, zipbe64 ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { BYTE* pBuf = dBufBE64.begin(); for ( auto i = 0; i < NRUNS; ++i ) pBuf += ZipToPtrBE ( pBuf, dValues[i] ); iBytes += pBuf - dBufBE64.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, zipbe64log2 ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { BYTE* pBuf = dBufBE64.begin(); for ( auto i = 0; i < NRUNS; ++i ) pBuf += ZipToPtrBElog2 ( pBuf, dValues[i] ); iBytes += pBuf - dBufBE64.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, ziple64 ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { BYTE* pBuf = dBufLE64.begin(); for ( auto i = 0; i < NRUNS; ++i ) pBuf += ZipToPtrLE ( pBuf, dValues[i] ); iBytes += pBuf - dBufLE64.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_REGISTER_F ( zipunzip, zipbe64 )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 10, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, zipbe64log2 )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 10, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, ziple64 )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 10, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); template<typename T, typename READER> T UnzipValueLE2 ( READER fnGet ) { BYTE b = fnGet(); BYTE iOff = 0; T res = 0; #pragma clang loop unroll_count( sizeof( T ) * CHAR_BIT / 7 ) for (; iOff < sizeof(T)*CHAR_BIT && ( b & 0x80 ); iOff+=7, b = fnGet() ) res |= ( T ( b & 0x7FU ) ) << iOff; return res | ( T ( b ) ) << iOff; } inline DWORD UnzipIntBEref ( const BYTE*& pBuf ) { return UnzipValueBE_reference<DWORD> ( [&pBuf]() mutable { return *pBuf++; } ); } inline DWORD UnzipIntLEref ( const BYTE*& pBuf ) { return UnzipValueLE_reference<DWORD> ( [&pBuf]() mutable { return *pBuf++; } ); } inline DWORD UnzipIntLE2 ( const BYTE*& pBuf ) { return UnzipValueLE2<DWORD> ( [&pBuf]() mutable { return *pBuf++; } ); } inline SphOffset_t UnzipOffsetBEref ( const BYTE*& pBuf ) { return UnzipValueBE_reference<SphOffset_t> ( [&pBuf]() mutable { return *pBuf++; } ); } inline SphOffset_t UnzipOffsetLEref ( const BYTE*& pBuf ) { return UnzipValueLE_reference<SphOffset_t> ( [&pBuf]() mutable { return *pBuf++; } ); } inline SphOffset_t UnzipOffsetLE2 ( const BYTE*& pBuf ) { return UnzipValueLE2<SphOffset_t> ( [&pBuf]() mutable { return *pBuf++; } ); } BENCHMARK_DEFINE_F ( zipunzip, unzipbe32_fastest ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufBE.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipIntBE ( pBuf ) ); iBytes += pBuf - dBufBE.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unzipbe32ref ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufBE.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipIntBEref ( pBuf ) ); iBytes += pBuf - dBufBE.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unzipbe32refGetByte ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { m_pBuff = dBufBE.begin(); m_iBuffPos = m_iBuffUsed = 0; for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipValueBEDWORD_reference() ); iBytes += m_iBuffPos; } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unzipbe32GetByte ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { m_pBuff = dBufBE.begin(); m_iBuffPos = m_iBuffUsed = 0; for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipValueBEDWORD() ); iBytes += m_iBuffPos; } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unzipbe32macroGetByte ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { m_pBuff = dBufBE.begin(); m_iBuffPos = m_iBuffUsed = 0; for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipValueBEDWORD_macro() ); iBytes += m_iBuffPos; } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unziple32_fastest ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufLE.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipIntLE ( pBuf ) ); iBytes += pBuf - dBufLE.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unziple32ref ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufLE.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipIntLEref ( pBuf ) ); iBytes += pBuf - dBufLE.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unziple32opt ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufLE.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipIntLE2 ( pBuf ) ); iBytes += pBuf - dBufLE.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_REGISTER_F ( zipunzip, unzipbe32_fastest )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unzipbe32ref )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unziple32_fastest )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unziple32ref )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unziple32opt )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unzipbe32refGetByte )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unzipbe32macroGetByte )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unzipbe32GetByte )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 5, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_DEFINE_F ( realunzip, unzipbe32refGetByte ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 0 ); for ( auto _ : st ) { m_pBuff = dBufBE.begin(); m_iBuffPos = m_iBuffUsed = 0; for ( auto i = 0; i < NRUNS* iProfile; ++i ) benchmark::DoNotOptimize ( UnzipValueBEDWORD_reference() ); iBytes += m_iBuffPos; } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( realunzip, unzipbe32GetByte ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 0 ); for ( auto _ : st ) { m_pBuff = dBufBE.begin(); m_iBuffPos = m_iBuffUsed = 0; for ( auto i = 0; i < NRUNS*iProfile; ++i ) benchmark::DoNotOptimize ( UnzipValueBEDWORD() ); iBytes += m_iBuffPos; } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( realunzip, unzipbe32macroGetByte ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 0 ); for ( auto _ : st ) { m_pBuff = dBufBE.begin(); m_iBuffPos = m_iBuffUsed = 0; for ( auto i = 0; i < NRUNS*iProfile; ++i ) benchmark::DoNotOptimize ( UnzipValueBEDWORD_macro() ); iBytes += m_iBuffPos; } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_REGISTER_F ( realunzip, unzipbe32GetByte )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 4, 1 ) } ); BENCHMARK_REGISTER_F ( realunzip, unzipbe32refGetByte )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 4, 1 ) } ); BENCHMARK_REGISTER_F ( realunzip, unzipbe32macroGetByte )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 4, 1 ) } ); BENCHMARK_DEFINE_F ( zipunzip, unzipbe64_fastest ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufBE64.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipOffsetBE ( pBuf ) ); iBytes += pBuf - dBufBE64.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unzipbe64ref ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufBE64.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipOffsetBEref ( pBuf ) ); iBytes += pBuf - dBufBE64.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unziple64_fastest ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufLE64.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipOffsetLE ( pBuf ) ); iBytes += pBuf - dBufLE64.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unziple64ref ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufLE64.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipOffsetLEref ( pBuf ) ); iBytes += pBuf - dBufLE64.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_DEFINE_F ( zipunzip, unziple64opt ) ( benchmark::State& st ) { int64_t iBytes = 0; auto NRUNS = st.range ( 1 ); for ( auto _ : st ) { const BYTE* pBuf = dBufLE64.begin(); for ( auto i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( UnzipOffsetLE2 ( pBuf ) ); iBytes += pBuf - dBufLE64.begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); st.SetBytesProcessed ( iBytes ); } BENCHMARK_REGISTER_F ( zipunzip, unzipbe64_fastest )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 10, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unzipbe64ref )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 10, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unziple64_fastest )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 10, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unziple64ref )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 10, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); BENCHMARK_REGISTER_F ( zipunzip, unziple64opt )->ArgsProduct ( { benchmark::CreateDenseRange ( 1, 10, 1 ), benchmark::CreateRange ( MINRANGE, MAXRANGE, STEPRANGE ) } ); /* Run on (8 X 3900 MHz CPU s) CPU Caches: L1 Data 32 KiB (x4) L1 Instruction 32 KiB (x4) L2 Unified 256 KiB (x4) L3 Unified 8192 KiB (x1) Load Average: 0.41, 0.13, 0.45 --------------------------------------------------------------------------------------- Benchmark Time CPU Iterations --------------------------------------------------------------------------------------- bench_popcount/artificial_no_division 2.05 ns 2.05 ns 340980780 bench_popcount/artificial_with_division 2.75 ns 2.75 ns 254919225 bench_popcount/artificial_long_no_division 2.05 ns 2.05 ns 340869726 bench_popcount/intrinsic_dword 1.88 ns 1.88 ns 372735795 bench_popcount/intrinsic_uint64 1.88 ns 1.88 ns 372419634 bench_popcount/artificial_byte 1.09 ns 1.09 ns 640643179 Broadcom BCM2711, Cortex-A72 (ARM v8) 64-bit SoC @ 1.5GHz Run on (4 X 1500 MHz CPU s) Load Average: 1.75, 2.63, 1.61 ***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead. --------------------------------------------------------------------------------------- Benchmark Time CPU Iterations --------------------------------------------------------------------------------------- bench_popcount/artificial_no_division 5.57 ns 5.57 ns 125755867 bench_popcount/artificial_with_division 6.16 ns 6.15 ns 113984067 bench_popcount/artificial_long_no_division 6.02 ns 6.01 ns 116447607 bench_popcount/intrinsic_dword 3.89 ns 3.88 ns 180829207 bench_popcount/intrinsic_uint64 3.95 ns 3.94 ns 177579307 bench_popcount/artificial_byte 3.56 ns 3.56 ns 196519955 */
28,871
C++
.cpp
851
31.80376
176
0.649375
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,030
stripper.cpp
manticoresoftware_manticoresearch/src/gbenches/stripper.cpp
// // 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 // #include <benchmark/benchmark.h> #include "fileutils.h" #include "std/string.h" #include "stripper/html_stripper.h" class BM_stripper: public benchmark::Fixture { public: void SetUp ( const ::benchmark::State& state ) { auto sPath = GetPathOnly(__FILE__); auto sTestFile = SphSprintf("%s../../test/bench/sphinx.html", sPath.cstr()); FILE* fp = fopen ( sTestFile.cstr(), "rb" ); if ( !fp ) { printf ( "benchmark failed: unable to read %s\n", sTestFile.cstr() ); return; } sBuf = new char[MAX_SIZE]; iLen = (int)fread ( sBuf, 1, MAX_SIZE - 1, fp ); sBuf[iLen] = '\0'; fclose ( fp ); sRef = new char[MAX_SIZE]; memcpy ( sRef, sBuf, iLen + 1 ); } void TearDown ( const ::benchmark::State& state ) { SafeDeleteArray ( sBuf ); SafeDeleteArray ( sRef ); } static constexpr int MAX_SIZE = 1048576; char* sBuf = nullptr; char* sRef = nullptr; int iLen=0; }; BENCHMARK_F ( BM_stripper, bench_default ) ( benchmark::State& st ) { CSphHTMLStripper tStripper ( true ); int iBytes = 0; for ( auto _ : st ) { tStripper.Strip ( (BYTE*)sBuf ); st.PauseTiming(); memcpy ( sBuf, sRef, iLen + 1 ); iBytes += iLen; st.ResumeTiming(); } st.SetBytesProcessed ( iBytes ); } BENCHMARK_F ( BM_stripper, bench_nostyle_script ) ( benchmark::State& st ) { CSphHTMLStripper tStripper ( true ); CSphString sError; tStripper.SetRemovedElements ( "style, script", sError ); int iBytes = 0; for ( auto _ : st ) { tStripper.Strip ( (BYTE*)sBuf ); st.PauseTiming(); memcpy ( sBuf, sRef, iLen + 1 ); iBytes += iLen; st.ResumeTiming(); } st.SetLabel ( "Without tags 'style' and 'scrypt'" ); st.SetBytesProcessed ( iBytes ); }
2,152
C++
.cpp
78
25.448718
80
0.685078
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,031
locators.cpp
manticoresoftware_manticoresearch/src/gbenches/locators.cpp
// // Copyright (c) 2017-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/ // #include <benchmark/benchmark.h> #include "schema/locator.h" #include "match.h" ////////////////////////////////////////////////////////////////////////// static void BM_Locators ( benchmark::State & st ) { static const int MAX_ITEMS = 10; static const int NUM_MATCHES = 1000; CSphRowitem dStatic[MAX_ITEMS]; CSphRowitem dDynamic[MAX_ITEMS]; CSphAttrLocator tLoc[NUM_MATCHES]; CSphMatch tMatch[NUM_MATCHES]; for ( int i = 0; i<MAX_ITEMS; i++ ) dStatic[i] = dDynamic[i] = i; srand ( 0 ); for ( int i = 0; i<NUM_MATCHES; ++i ) { tLoc[i].m_iBitCount = 32; tLoc[i].m_iBitOffset = 32 * ( rand () % MAX_ITEMS ); // NOLINT tLoc[i].m_bDynamic = ( rand () % 2 )==1; // NOLINT tMatch[i].m_pStatic = dStatic; tMatch[i].m_pDynamic = dDynamic; } int iSum = 0; int j = 0; for ( auto _ : st ) { benchmark::DoNotOptimize ( iSum += (int) tMatch[j].GetAttr ( tLoc[j] ) ); ++j; if (j>=NUM_MATCHES) j=0; } // manually cleanup to avoid automatic delete for ( auto & m : tMatch ) m.m_pDynamic = nullptr; } BENCHMARK( BM_Locators );
1,437
C++
.cpp
45
29.866667
80
0.644718
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,032
geodist.cpp
manticoresoftware_manticoresearch/src/gbenches/geodist.cpp
// // 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 // #include <benchmark/benchmark.h> #include "sphinxexpr.h" #include <cmath> // conversion between degrees and radians static const double MY_PI = 3.14159265358979323846; static const double TO_RADD = MY_PI / 180.0; static const double TO_DEGD = 180.0 / MY_PI; void DestVincenty ( double lat1, double lon1, double brng, double dist, double* lat2, double* lon2 ) { double a = 6378137, b = 6356752.3142, f = 1 / 298.257223563; // WGS-84 ellipsiod double s = dist; double alpha1 = brng * TO_RADD; double sinAlpha1 = sin ( alpha1 ); double cosAlpha1 = cos ( alpha1 ); double tanU1 = ( 1 - f ) * tan ( lat1 * TO_RADD ); double cosU1 = 1 / sqrt ( 1 + tanU1 * tanU1 ), sinU1 = tanU1 * cosU1; double sigma1 = atan2 ( tanU1, cosAlpha1 ); double sinAlpha = cosU1 * sinAlpha1; double cosSqAlpha = 1 - sinAlpha * sinAlpha; double uSq = cosSqAlpha * ( a * a - b * b ) / ( b * b ); double A = 1 + uSq / 16384 * ( 4096 + uSq * ( -768 + uSq * ( 320 - 175 * uSq ) ) ); double B = uSq / 1024 * ( 256 + uSq * ( -128 + uSq * ( 74 - 47 * uSq ) ) ); double sigma = s / ( b * A ), sigmaP = 2 * MY_PI; double cos2SigmaM = 0, sinSigma = 0, cosSigma = 0; while ( fabs ( sigma - sigmaP ) > 1e-12 ) { cos2SigmaM = cos ( 2 * sigma1 + sigma ); sinSigma = sin ( sigma ); cosSigma = cos ( sigma ); double deltaSigma = B * sinSigma * ( cos2SigmaM + B / 4 * ( cosSigma * ( -1 + 2 * cos2SigmaM * cos2SigmaM ) - B / 6 * cos2SigmaM * ( -3 + 4 * sinSigma * sinSigma ) * ( -3 + 4 * cos2SigmaM * cos2SigmaM ) ) ); sigmaP = sigma; sigma = s / ( b * A ) + deltaSigma; } double tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1; *lat2 = atan2 ( sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, ( 1 - f ) * sqrt ( sinAlpha * sinAlpha + tmp * tmp ) ); double lambda = atan2 ( sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1 ); double C = f / 16 * cosSqAlpha * ( 4 + f * ( 4 - 3 * cosSqAlpha ) ); double L = lambda - ( 1 - C ) * f * sinAlpha * ( sigma + C * sinSigma * ( cos2SigmaM + C * cosSigma * ( -1 + 2 * cos2SigmaM * cos2SigmaM ) ) ); *lon2 = ( lon1 * TO_RADD + L + 3 * MY_PI ); while ( *lon2 > 2 * MY_PI ) *lon2 -= 2 * MY_PI; *lon2 -= MY_PI; *lat2 *= TO_DEGD; *lon2 *= TO_DEGD; } static constexpr int NFUNCS = 3; float CalcGeofunc ( int iFunc, double* t ) { switch ( iFunc ) { case 0: return GeodistSphereDeg ( float ( t[0] ), float ( t[1] ), float ( t[2] ), float ( t[3] ) ); case 1: return GeodistAdaptiveDeg ( float ( t[0] ), float ( t[1] ), float ( t[2] ), float ( t[3] ) ); case 2: return GeodistFlatDeg ( float ( t[0] ), float ( t[1] ), float ( t[2] ), float ( t[3] ) ); default: return 0; } return 0; } CSphVector<double> callonce() { CSphVector<double> dBench; for ( int adist = 10; adist <= 10 * 1000 * 1000; adist *= 10 ) for ( int dist = adist; dist < 10 * adist && dist < 20 * 1000 * 1000; dist += 2 * adist ) { double avgerr[NFUNCS] = { 0 }, maxerr[NFUNCS] = { 0 }; int n = 0; for ( int lat = -80; lat <= 80; lat += 10 ) { for ( int lon = -179; lon < 180; lon += 3 ) { for ( int b = 0; b < 360; b += 3, ++n ) { double t[4] = { double ( lat ), double ( lon ), 0, 0 }; DestVincenty ( t[0], t[1], b, dist, t + 2, t + 3 ); for ( int j = 0; j < 4; j++ ) dBench.Add ( t[j] ); for ( int f = 0; f < NFUNCS; ++f ) { float fDist = CalcGeofunc ( f, t ); double err = fabs ( 100 * ( double ( fDist ) - double ( dist ) ) / double ( dist ) ); // relative error, in percents avgerr[f] += err; maxerr[f] = Max ( err, maxerr[f] ); } } } } // for ( int f = 0; f < NFUNCS; ++f ) // avgerr[f]/=n; // printf ( "Sphere err max %f, avg %f\n", maxerr[0], avgerr[0] ); // printf ( "Adaptive err max %f, avg %f\n", maxerr[1], avgerr[1] ); // printf ( "Flat err max %f, avg %f\n", maxerr[2], avgerr[2] ); } return dBench; } CSphVector<double>& stbench() { static CSphVector<double> dBench = callonce(); return dBench; } class Geodist: public benchmark::Fixture { public: void SetUp ( const ::benchmark::State& state ) { tmax = dBench.Begin() + dBench.GetLength(); fDist = 0; } // void TearDown ( const ::benchmark::State & state ) { } CSphVector<double>& dBench = stbench(); float fDist = 0; double* tmax; }; BENCHMARK_DEFINE_F ( Geodist, SphereDeg ) ( benchmark::State& st ) { double* t = dBench.Begin(); auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( int i = 0; i < NRUNS; ++i ) { fDist += GeodistSphereDeg ( float ( t[0] ), float ( t[1] ), float ( t[2] ), float ( t[3] ) ); t += 4; if ( t >= tmax ) t = dBench.Begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); } BENCHMARK_REGISTER_F ( Geodist, SphereDeg )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_DEFINE_F ( Geodist, FlatDeg ) ( benchmark::State& st ) { double* t = dBench.Begin(); auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( int i = 0; i < NRUNS; ++i ) { fDist += GeodistFlatDeg ( float ( t[0] ), float ( t[1] ), float ( t[2] ), float ( t[3] ) ); t += 4; if ( t >= tmax ) t = dBench.Begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); } BENCHMARK_REGISTER_F ( Geodist, FlatDeg )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_DEFINE_F ( Geodist, AdaptiveDeg ) ( benchmark::State& st ) { double* t = dBench.Begin(); auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( int i = 0; i < NRUNS; ++i ) { fDist += GeodistAdaptiveDeg ( float ( t[0] ), float ( t[1] ), float ( t[2] ), float ( t[3] ) ); t += 4; if ( t >= tmax ) t = dBench.Begin(); } st.SetItemsProcessed ( st.iterations() * NRUNS ); } BENCHMARK_REGISTER_F ( Geodist, AdaptiveDeg )->RangeMultiplier ( 10 )->Range ( 10, 1000 );
6,261
C++
.cpp
172
33.662791
209
0.592952
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,033
text.cpp
manticoresoftware_manticoresearch/src/gbenches/text.cpp
// // 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 <benchmark/benchmark.h> #include "sphinxint.h" #include "sphinxutils.h" #include "sphinxstem.h" class BM_parse_expr : public benchmark::Fixture { public: void SetUp ( const ::benchmark::State & state ) { CSphColumnInfo tCol; tCol.m_sName = "id"; tCol.m_eAttrType = SPH_ATTR_BIGINT; tSchema.AddAttr ( tCol, false ); tCol.m_sName = "aaa"; tCol.m_eAttrType = SPH_ATTR_INTEGER; tSchema.AddAttr ( tCol, false ); tCol.m_sName = "bbb"; tCol.m_eAttrType = SPH_ATTR_INTEGER; tSchema.AddAttr ( tCol, false ); tCol.m_sName = "ccc"; tCol.m_eAttrType = SPH_ATTR_INTEGER; tSchema.AddAttr ( tCol, false ); pRow = new CSphRowitem[tSchema.GetRowSize ()]; for ( int i = 1; i<tSchema.GetAttrsCount (); i++ ) sphSetRowAttr ( pRow, tSchema.GetAttr ( i ).m_tLocator, i ); sphSetRowAttr ( pRow, tSchema.GetAttr ( 0 ).m_tLocator, 123 ); tMatch.m_tRowID = 123; tMatch.m_iWeight = 456; tMatch.m_pStatic = pRow; const char* ppTests[] = { "ccc/2+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "1*2*3*4*5*6*7*8*9*10+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "aaa+bbb*sin(0)*ccc+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "if(pow(sqrt(2),2)=2,123,456)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "if(2<2,3,4)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "if(2>=2,3,4)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "pow(7,5)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "sqrt(3)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "log2((2+2)*(2+2))+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "min(3,15)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "max(3,15)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "if(3<15,bbb,ccc)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40" , "id+@weight+if(3<15,bbb,ccc)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa" , "abs(-3-ccc)+id+@weight+if(3<15,bbb,ccc)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa" , "(aaa+bbb)*(ccc-aaa)+abs(-3-ccc)+id+@weight+if(3<15,bbb,ccc)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()" , "(((aaa)))+(aaa+bbb)*(ccc-aaa)+abs(-3-ccc)+id+@weight+if(3<15,bbb,ccc)+aaa+bbb+rand()+ccc+id+12*1562 mod 40+aaa+bbb+rand()" , "aaa-bbb*ccc+(((aaa)))+(aaa+bbb)*(ccc-aaa)+abs(-3-ccc)+id+@weight+if(3<15,bbb,ccc)+aaa+bbb+rand()+ccc+id+12*1562" , " aaa -\tbbb *\t\t\tccc + aaa-bbb*ccc+(((aaa)))+(aaa+bbb)*(ccc-aaa)+abs(-3-ccc)+id+@weight+if(3<15,bbb,ccc)+aaa+bbb" , "bbb+123*aaa+ aaa -\tbbb *\t\t\tccc + aaa-bbb*ccc+(((aaa)))+(aaa+bbb)*(ccc-aaa)+abs(-3-ccc)+id+@weight" , "2.000*2e+1+2+bbb+123*aaa+ aaa -\tbbb *\t\t\tccc + aaa-bbb*ccc+(((aaa)))+(aaa+bbb)*(ccc-aaa)+abs(-3-ccc)+id+@weight" , "3<5+2.000*2e+1+2+bbb+123*aaa+ aaa -\tbbb *\t\t\tccc + aaa-bbb*ccc+(((aaa)))+(aaa+bbb)*(ccc-aaa)+abs(-3-ccc)+id+@weight" , "1 + 2*3 > 4*4+3<5+2.000*2e+1+2+bbb+123*aaa+ aaa -\tbbb *\t\t\tccc + aaa-bbb*ccc+(((aaa)))+(aaa+bbb)*(ccc-aaa)" , "aaa/-bbb+1 + 2*3 > 4*4+3<5+2.000*2e+1+2+bbb+123*aaa+ aaa -\tbbb *\t\t\tccc + aaa-bbb*ccc+(((aaa)))+(aaa+bbb)*(ccc-aaa)" , "-10*-10+aaa/-bbb+1 + 2*3 > 4*4+3<5+2.000*2e+1+2+bbb+123*aaa+ aaa -\tbbb *\t\t\tccc + aaa-bbb*ccc" , "aaa+-bbb*-5+-10*-10+aaa/-bbb+1 + 2*3 > 4*4+3<5+2.000*2e+1+2+bbb+123*aaa+ aaa -\tbbb *\t\t\tccc + aaa-bbb*ccc" , "-aaa>-bbb+aaa+-bbb*-5+-10*-10+aaa/-bbb+1 + 2*3 > 4*4+3<5+2.000*2e+1+2+bbb+123*aaa+ aaa -\tbbb *\t\t\tccc" , "1-aaa+2-3+4-aaa>-bbb+aaa+-bbb*-5+-10*-10+aaa/-bbb+1 + 2*3 > 4*4+3<5+2.000*2e+1+2+bbb+123*aaa+ aaa -\tbbb *\t\t\tccc" , "bbb/1*2/6*3+1-aaa+2-3+4-aaa>-bbb+aaa+-bbb*-5+-10*-10+aaa/-bbb+1 + 2*3 > 4*4+3<5+2.000*2e+1+2+bbb+123*aaa+ aaa " , "(aaa+bbb)/sqrt(3)/sqrt(3)+bbb/1*2/6*3+1-aaa+2-3+4-aaa>-bbb+aaa+-bbb*-5+-10*-10+aaa/-bbb+1 + 2*3 > 4*4+3<5+2.000" , "aaa-bbb-2+(aaa+bbb)/sqrt(3)/sqrt(3)+bbb/1*2/6*3+1-aaa+2-3+4-aaa>-bbb+aaa+-bbb*-5+-10*-10+aaa/-bbb+1 + 2*3" , "ccc mod 10+aaa-bbb-2+(aaa+bbb)/sqrt(3)/sqrt(3)+bbb/1*2/6*3+1-aaa+2-3+4-aaa>-bbb+aaa+-bbb*-5+-10*-10+aaa/-bbb+1 + 2*3" , "ccc/2*4/bbb+ccc mod 10+aaa-bbb-2+(aaa+bbb)/sqrt(3)/sqrt(3)+bbb/1*2/6*3+1-aaa+2-3+4-aaa>-bbb+aaa+-bbb*-5" , "(2+(aaa*bbb))+3+ccc/2*4/bbb+ccc mod 10+aaa-bbb-2+(aaa+bbb)/sqrt(3)/sqrt(3)+bbb/1*2/6*3+1-aaa+2-3+4-aaa>-bbb+aaa+-bbb*-5" , "aaa+bbb*(ccc)-1+(2+(aaa*bbb))+3+ccc/2*4/bbb+ccc mod 10+aaa-bbb-2+(aaa+bbb)/sqrt(3)/sqrt(3)+bbb/1*2/6*3+1" , "aaa+bbb*ccc*2-3/4*5/6*bbb+aaa+bbb*(ccc)-1+(2+(aaa*bbb))+3+ccc/2*4/bbb+ccc mod 10+aaa-bbb-2+(aaa+bbb)/sqrt(3)/sqrt(3)" , "sqrt(2)+aaa+bbb*ccc*2-3/4*5/6*bbb+aaa+bbb*(ccc)-1+(2+(aaa*bbb))+3+ccc/2*4/bbb+ccc mod 10+aaa-bbb-2" , "rand()+sqrt(2)+aaa+bbb*ccc*2-3/4*5/6*bbb+aaa+bbb*(ccc)-1+(2+(aaa*bbb))+3+ccc/2*4/bbb+ccc mod 10+aaa-bbb-2" , "rand()+sqrt(2)+aaa+bbb*ccc*2-3/4*5/6*bbb+aaa+bbb*(ccc)-1+(2+(aaa*bbb))+3+ccc/2*4/bbb+ccc mod 10+aaa-bbb-2" , "FIBONACCI(4)+rand()+sqrt(2)+aaa+bbb*ccc*2-3/4*5/6*bbb+aaa+bbb*(ccc)-1+(2+(aaa*bbb))+3+ccc/2*4/bbb+ccc mod 10+aaa-bbb-2" }; for ( const auto * szTest : ppTests ) dTests.Add ( {szTest, strlen(szTest)} ); i = 0; iBytes = 0; } void TearDown ( const ::benchmark::State & state ) { SafeDeleteArray ( pRow ); } CSphSchema tSchema; CSphMatch tMatch; CSphRowitem * pRow; CSphVector <std::pair<CSphString,int>> dTests; CSphString sError; ExprParseArgs_t tExprArgs; int i = 0; int64_t iBytes = 0; }; BENCHMARK_F( BM_parse_expr, parser ) ( benchmark::State & st ) { for ( auto _ : st ) { ISphExprRefPtr_c pExpr ( sphExprParse ( dTests[i].first.cstr (), tSchema, sError, tExprArgs ) ); iBytes += dTests[i].second; if ( ++i >= dTests.GetLength() ) i = 0; } st.SetBytesProcessed ( iBytes ); st.SetItemsProcessed ( st.iterations() ); }
6,857
C++
.cpp
112
58.267857
135
0.629459
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,034
json.cpp
manticoresoftware_manticoresearch/src/gbenches/json.cpp
// // Copyright (c) 2017-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/ // #include <benchmark/benchmark.h> #include "json/cJSON.h" #include "sphinxjson.h" // Miscelaneous short tests for json/cjson ////////////////////////////////////////////////////////////////////////// // defined in sphinxjson int sphJsonUnescape ( char ** pEscaped, int iLen ); int sphJsonUnescape1 ( char ** pEscaped, int iLen ); // unescaped pEscaped, modify pEscaped to unescaped chain, return the length of unescaped // that is actually used, defined in sphinxjson.cpp int JsonUnescape ( char* pTarget, const char* pEscaped, int iLen ); // defined in cJSON_test extern "C" { int cJsonunescape ( char ** buf, cJSON * pOut ); } class bench_jsonunescape : public benchmark::Fixture { public: void SetUp ( const ::benchmark::State & state ) { iLen = (int) strlen ( sLiteral ); buf = new char[iLen]; pJson = cJSON_CreateObject(); } void TearDown ( const ::benchmark::State & state ) { SafeDelete ( pJson ); SafeDeleteArray (buf); } const char* sLiteral = R"("In `docs/searching/expressions,_functions,_and_operators.rst` which reflected into\\nhttps://manticoresearch.gitlab.io/dev/searching/expressions,_functions,_and_operators.html\\n\\n1. At the top there is a kind of TOC with shortcuts to the functions described in the section.\\nHowever this TOC is not consistent. I.e., it doesn't refer to all function actually described there.\\n\\nMost prominent example is 'PACKEDFACTORS()' - it absent in the TOC.\\n\\n2. Also consider whether it is better or not to sort function descriptions in the section alphabetically ('REMAP' at the end looks strange, as 'WEIGHT' is before it).")"; int iLen; char* buf = nullptr; cJSON* pJson = nullptr; }; BENCHMARK_F( bench_jsonunescape, plain ) ( benchmark::State & st ) { char * sBuf = nullptr; for ( auto _ : st ) { st.PauseTiming (); memcpy ( buf, sLiteral, iLen ); sBuf = buf; st.ResumeTiming (); sphJsonUnescape ( &sBuf, iLen ); } st.SetBytesProcessed ( st.iterations() * iLen ); st.SetLabel("unescaped version by memmove in-place"); } BENCHMARK_F( bench_jsonunescape, nomove ) ( benchmark::State & st ) { char * sBuf = nullptr; for ( auto _ : st ) { st.PauseTiming (); memcpy ( buf, sLiteral, iLen ); sBuf = buf; st.ResumeTiming (); sphJsonUnescape1 ( &sBuf, iLen ); } st.SetBytesProcessed ( st.iterations() * iLen ); st.SetLabel ( "moves nothing" ); } BENCHMARK_F( bench_jsonunescape, cjson ) ( benchmark::State & st ) { cJSON * pJson = cJSON_CreateObject (); char * sBuf = nullptr; for ( auto _ : st ) { st.PauseTiming (); memcpy ( buf, sLiteral, iLen ); sBuf = buf; st.ResumeTiming (); cJsonunescape ( & sBuf, pJson ); } SafeDelete ( pJson ); st.SetBytesProcessed ( st.iterations() * iLen ); st.SetLabel ( "use cjson" ); } class bson_vs_cjson : public benchmark::Fixture { public: void SetUp ( const ::benchmark::State & state ) { iLen = (int)strlen ( sLiteral ); } void TearDown ( const ::benchmark::State & state ) { } const char* sLiteral = R"({"query":{"percolate":{"document":{"title":"A new tree test in the office office"}}}})"; int iLen = 0; CSphString sBuf; }; using namespace bson; BENCHMARK_F( bson_vs_cjson, bson ) ( benchmark::State & st ) { for ( auto _ : st ) { st.PauseTiming (); sBuf.SetBinary ( sLiteral, iLen ); auto buf = (char *) sBuf.cstr (); st.ResumeTiming (); BsonContainer_c dBson { buf }; benchmark::DoNotOptimize ( dBson ); } st.SetBytesProcessed ( st.iterations() * iLen ); } BENCHMARK_F( bson_vs_cjson, bson_without_lowercase ) ( benchmark::State & st ) { for ( auto _ : st ) { st.PauseTiming (); sBuf.SetBinary ( sLiteral, iLen ); auto buf = (char *) sBuf.cstr (); st.ResumeTiming (); BsonContainer_c dBson { buf, false }; benchmark::DoNotOptimize ( dBson ); } st.SetBytesProcessed ( st.iterations() * iLen ); } BENCHMARK_F( bson_vs_cjson, cjson ) ( benchmark::State & st ) { for ( auto _ : st ) { st.PauseTiming (); sBuf.SetBinary ( sLiteral, iLen ); auto buf = (char *) sBuf.cstr (); st.ResumeTiming (); auto pBson = cJSON_Parse ( buf ); benchmark::DoNotOptimize ( pBson ); if ( pBson ) cJSON_Delete ( pBson ); } st.SetBytesProcessed ( st.iterations() * iLen ); } BENCHMARK_F( bson_vs_cjson, bson_via_cjson ) ( benchmark::State & st ) { for ( auto _ : st ) { st.PauseTiming (); sBuf.SetBinary ( sLiteral, iLen ); auto buf = (char *) sBuf.cstr (); st.ResumeTiming (); auto pCjson = cJSON_Parse ( buf ); CSphVector<BYTE> dBson ( iLen ); bson::cJsonToBson ( pCjson, dBson, false, false ); benchmark::DoNotOptimize ( dBson ); if ( pCjson ) cJSON_Delete ( pCjson ); } st.SetBytesProcessed ( st.iterations() * iLen ); } BENCHMARK_F( bson_vs_cjson, cJsonToBson ) ( benchmark::State & st ) { auto pCjson = cJSON_Parse ( sLiteral ); for ( auto _ : st ) { st.PauseTiming (); CSphVector<BYTE> dBson ( iLen ); st.ResumeTiming (); bson::cJsonToBson ( pCjson, dBson, false, false ); benchmark::DoNotOptimize ( dBson ); } st.SetBytesProcessed ( st.iterations() * iLen ); } BENCHMARK_F( bson_vs_cjson, cJsonToBson_with_lowercase ) ( benchmark::State & st ) { auto pCjson = cJSON_Parse ( sLiteral ); for ( auto _ : st ) { st.PauseTiming (); CSphVector<BYTE> dBson ( iLen ); st.ResumeTiming (); bson::cJsonToBson ( pCjson, dBson ); benchmark::DoNotOptimize ( dBson ); } st.SetBytesProcessed ( st.iterations() * iLen ); } BENCHMARK_F ( bson_vs_cjson, bson_child_by_name ) ( benchmark::State& st ) { sBuf.SetBinary ( sLiteral, iLen ); auto buf = (char*)sBuf.cstr(); BsonContainer_c dBson { buf }; for ( auto _ : st ) { benchmark::DoNotOptimize ( dBson.ChildByName ( "query" ).first ); } st.SetItemsProcessed( st.iterations() ); } BENCHMARK_F ( bson_vs_cjson, bson_child_by_namelw ) ( benchmark::State& st ) { sBuf.SetBinary ( sLiteral, iLen ); auto buf = (char*)sBuf.cstr(); BsonContainer_c dBson { buf, false }; for ( auto _ : st ) { benchmark::DoNotOptimize ( dBson.ChildByName ( "query" ).first ); } st.SetItemsProcessed ( st.iterations() ); } BENCHMARK_F ( bson_vs_cjson, cjson_getobjitem ) ( benchmark::State& st ) { sBuf.SetBinary ( sLiteral, iLen ); auto buf = (char*)sBuf.cstr(); auto pBson = cJSON_Parse ( buf ); for ( auto _ : st ) { benchmark::DoNotOptimize ( cJSON_GetObjectItem ( pBson, "query" ) ); } st.SetItemsProcessed ( st.iterations() ); if ( pBson ) cJSON_Delete ( pBson ); } class BM_tolower : public benchmark::Fixture { public: void SetUp ( const ::benchmark::State & state ) { for ( int i = 0; i<192; ++i ) { x[i] = char ( i+64 ); l[i] = (char) ::tolower ( i+64 ); } x[192] = '\0'; l[192] = '\0'; NRUNS = state.range ( 0 ); j = 0; } void TearDown ( const ::benchmark::State & state ) { } char x[193]; char l[193]; int64_t NRUNS = 0; int j; }; BENCHMARK_DEFINE_F( BM_tolower, call_tolower ) ( benchmark::State & st ) { for ( auto _ : st ) { for ( auto i = 0; i < NRUNS; ++i ) { benchmark::DoNotOptimize ( (char) tolower ( x[j++] ) ); if (j>192) j = 0; } } st.SetBytesProcessed ( st.iterations() * NRUNS ); } BENCHMARK_DEFINE_F( BM_tolower, lookup_table ) ( benchmark::State & st ) { for ( auto _ : st ) { for ( auto i = 0; i < NRUNS; ++i ) { benchmark::DoNotOptimize ( l[(int)x[j]] ); if ( j > 192 ) j = 0; } } st.SetBytesProcessed( st.iterations() * NRUNS ); } BENCHMARK_REGISTER_F ( BM_tolower, call_tolower )->Range ( 1, 4096 ); BENCHMARK_REGISTER_F ( BM_tolower, lookup_table )->Range ( 1, 4096 ); class BM_formatter : public benchmark::Fixture { public: void SetUp ( const ::benchmark::State & state ) { dIndexes.Add ( { "test1", "test1_\tpath" } ); dIndexes.Add ( { "test2", "test2_\"path" } ); dIndexes.Add ( { "test3", "test3_path" } ); } void TearDown ( const ::benchmark::State & state ) { } struct MyIndex_t { CSphString m_sName; CSphString m_sPath; }; CSphString sResult; CSphVector<MyIndex_t> dIndexes; }; BENCHMARK_F( BM_formatter, cjson ) ( benchmark::State & st ) { for ( auto _ : st ) { cJSON * pRoot = cJSON_CreateObject (); cJSON * pIndexes = cJSON_CreateArray (); cJSON_AddItemToObject ( pRoot, "indexes", pIndexes ); for ( auto & dIdx : dIndexes ) { cJSON * pIndex = cJSON_CreateObject (); cJSON_AddItemToArray ( pIndexes, pIndex ); cJSON_AddStringToObject ( pIndex, "name", dIdx.m_sName.cstr () ); cJSON_AddStringToObject ( pIndex, "path", dIdx.m_sPath.cstr () ); } char * szResult = cJSON_Print ( pRoot ); sResult = szResult; cJSON_Delete ( pRoot ); } st.SetItemsProcessed ( st.iterations() ); } BENCHMARK_F( BM_formatter, stringbuilder ) ( benchmark::State & st ) { for ( auto _ : st ) { JsonEscapedBuilder tOut; tOut.StartBlock ( dJsonObj ); { ScopedComma_c sIndexes ( tOut, ",", "\"indexes\":[", "]" ); for ( auto & dIdx : dIndexes ) { ScopedComma_c sIndex ( tOut, ",", "{", "}" ); tOut.AppendName ( "name" ).AppendEscaped ( dIdx.m_sName.cstr (), EscBld::eEscape ); tOut.AppendName ( "path" ).AppendEscaped ( dIdx.m_sPath.cstr (), EscBld::eEscape ); } } tOut.FinishBlocks (); tOut.MoveTo ( sResult ); } st.SetItemsProcessed ( st.iterations() ); }
9,565
C++
.cpp
336
26.1875
655
0.6634
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,035
tokenizer.cpp
manticoresoftware_manticoresearch/src/gbenches/tokenizer.cpp
// // 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 // #include <benchmark/benchmark.h> #include "fileutils.h" #include "std/string.h" #include "tokenizer/tokenizer.h" ////////////////////////////////////////////////////////////////////////// static constexpr char g_sTmpfile[] = "__libsphinxtest.tmp"; ////////////////////////////////////////////////////////////////////////// bool CreateSynonymsFile () { FILE* fp = fopen ( g_sTmpfile, "w+" ); if ( !fp ) return false; fprintf ( fp, "AT&T => AT&T\n" " AT & T => AT & T \n" "standarten fuehrer => Standartenfuehrer\n" "standarten fuhrer => Standartenfuehrer\n" "OS/2 => OS/2\n" "Ms-Dos => MS-DOS\n" "MS DOS => MS-DOS\n" "feat. => featuring\n" "U.S. => US\n" "U.S.A. => USA\n" "U.S.B. => USB\n" "U.S.D. => USD\n" "U.S.P. => USP\n" "U.S.A.F. => USAF\n" "life:) => life:)\n" "; => ;\n" ); fclose ( fp ); return true; } char* LoadFile ( const char* sName, int* pLen, bool bReportErrors ) { auto sPath = GetPathOnly ( __FILE__ ); auto sTestFile = SphSprintf ( "%s%s", sPath.cstr(), sName ); FILE* fp = fopen ( sTestFile.cstr(), "rb" ); if ( !fp ) { if ( bReportErrors ) printf ( "benchmark failed: error opening %s\n", sTestFile.cstr() ); return NULL; } const int MAX_DATA = 10485760; char* sData = new char[MAX_DATA]; auto iData = (int)fread ( sData, 1, MAX_DATA, fp ); fclose ( fp ); if ( iData <= 0 ) { if ( bReportErrors ) printf ( "benchmark failed: error reading %s\n", sTestFile.cstr() ); SafeDeleteArray ( sData ); return NULL; } *pLen = iData; return sData; } class BM_tokenizer: public benchmark::Fixture { public: void SetUp ( const ::benchmark::State& state ) { if ( !CreateSynonymsFile () ) { printf ( "benchmark failed: error writing temp synonyms file\n" ); return; } iBytes = 0; sData = LoadFile ( "../CMakeLists.txt", &iBytes, true ); pTokenizer = Tokenizer::Detail::CreateUTF8Tokenizer(); } void TearDown ( const ::benchmark::State& state ) { SafeDeleteArray ( sData ); unlink ( g_sTmpfile ); } int iBytes = 0; StrVec_t dWarnings; CSphString sError; char* sData = nullptr; TokenizerRefPtr_c pTokenizer; }; BENCHMARK_F ( BM_tokenizer, nosynonyms ) ( benchmark::State& st ) { pTokenizer->AddSpecials ( "!-" ); int iTokens = 0; int iAllBytes = 0; for ( auto _ : st ) { pTokenizer->SetBuffer ( (BYTE*)sData, iBytes ); while ( pTokenizer->GetToken() ) ++iTokens; iAllBytes += iBytes; } st.SetBytesProcessed ( iAllBytes ); st.SetItemsProcessed ( iTokens ); } BENCHMARK_F ( BM_tokenizer, synonyms ) ( benchmark::State& st ) { pTokenizer->LoadSynonyms ( g_sTmpfile, NULL, dWarnings, sError ); pTokenizer->AddSpecials ( "!-" ); int iTokens = 0; int iAllBytes = 0; for ( auto _ : st ) { pTokenizer->SetBuffer ( (BYTE*)sData, iBytes ); while ( pTokenizer->GetToken() ) ++iTokens; iAllBytes += iBytes; } st.SetBytesProcessed ( iAllBytes ); st.SetItemsProcessed ( iTokens ); }
3,412
C++
.cpp
126
24.865079
80
0.634363
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,036
functions.cpp
manticoresoftware_manticoresearch/src/gbenches/functions.cpp
// // 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 <benchmark/benchmark.h> #include "sphinxutils.h" #include <cmath> #include "histogram.h" // Miscelaneous short functional tests: TDigest, SpanSearch, // stringbuilder, CJson, TaggedHash, Log2 // simplest way to test searchd internals - include the source, supress main() function there. #define SUPRESS_SEARCHD_MAIN 1 #include "searchd.cpp" ////////////////////////////////////////////////////////////////////////// // benches for EscapeJsonString_t inline static bool IsEscapeChar1 ( char c ) { return memchr ( "\"\\\b\f\n\r\t", c, 8 )!=nullptr; // \ is \x5C, " is \x22 } inline static bool IsEscapeChar2 ( char c ) { return strchr ( "\"\\\b\f\n\r\t", c )!=nullptr; // \ is \x5C, " is \x22 } inline static bool IsEscapeChar3 ( char c ) { switch ( c ) { case '\b': case '\f': case '\n': case '\r': case '\t': case '\"': case '\\' : return true; default: return false; } } inline static bool IsEscapeChar4 ( BYTE c ) // winner! { alignas ( 128 ) static const bool lookup[] = {0,0,0,0,0,0,0,0, 1,1,1,0,1,1,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, }; return ( c & 0x80 ) ? false : lookup[c]; } inline static BYTE GetEscapedChar1 ( BYTE c ) { switch ( c ) { case '\b': return 'b'; // \x08 case '\t': return 't'; // \x09 case '\n': return 'n'; // \x0A case '\f': return 'f'; // \x0C case '\r': return 'r'; // \x0D default: return c; } } inline static BYTE GetEscapedChar2 ( BYTE c ) // winner! { alignas ( 16 ) static const BYTE dTransform[16] = {'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', 'b', 't', 'n', '\x0B', 'f', 'r', '\x0E', '\x0F' }; //return dTransform[(BYTE) c]; return ( c & 0xF0 ) ? c : dTransform[c]; } alignas ( 128 ) static const BYTE g_Transform[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 'b'|0x80, 't'|0x80, 'n'|0x80, 0x0b, 'f'|0x80, 'r'|0x80, 0x0e, 0x0f, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17, 0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f, 0x20,0x21,'\"'|0x80,0x23,0x24,0x25,0x26,0x27, 0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37, 0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47, 0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57, 0x58,0x59,0x5a,0x5b,'\\'|0x80,0x5d,0x5e,0x5f, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67, 0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77, 0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f, }; inline static bool IsEscapeChar5 ( BYTE c ) { return ( c & 0x80 ) ? false : g_Transform[c] & 0x80; } inline static char GetEscapedChar3 ( BYTE c ) { return ( c & 0x80 ) ? c : g_Transform[c]&0x7F; } // here IsEscapeChar5 already excluded bytes with high bit set, so even simpler! inline static char GetEscapedChar3combo ( BYTE c ) { return g_Transform[c] & 0x7F; } class Escaping : public benchmark::Fixture { public: void SetUp ( const ::benchmark::State & state ) { dChars.Resize ( 128 ); for ( char & c: dChars ) c = sphRand () & 0xFF; } // void TearDown ( const ::benchmark::State & state ) { } CSphVector<char> dChars; bool bRes = false; int i = 0; }; BENCHMARK_DEFINE_F ( Escaping, empty_pass ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= !!dChars[++i & 0x7F]; st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, memchr ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= IsEscapeChar1 ( dChars[++i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, strchr ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= IsEscapeChar2 ( dChars[++i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, _switch ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= IsEscapeChar3 ( dChars[++i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, booltable ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= IsEscapeChar4 ( dChars[++i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, bytetable ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= IsEscapeChar5 ( dChars[++i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, transform_switch ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= GetEscapedChar1 ( dChars[++i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, transform_narrow_table ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= GetEscapedChar2 ( dChars[++i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, transform_wide_table ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) bRes |= GetEscapedChar3 ( dChars[++i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, strchr_transform_switch ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) if ( IsEscapeChar2 ( dChars[++i & 0x7F] ) ) // combo usual bRes |= !!GetEscapedChar1 ( dChars[i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_DEFINE_F ( Escaping, and_transform_by_one_table ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( auto i = 0; i < NRUNS; ++i ) if ( IsEscapeChar5 ( dChars[++i & 0x7F] ) ) // combo usual bRes |= !!GetEscapedChar3combo ( dChars[i & 0x7F] ); st.SetBytesProcessed ( NRUNS * st.iterations() ); } BENCHMARK_REGISTER_F ( Escaping, empty_pass )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, memchr )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, strchr )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, _switch )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, booltable )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, bytetable )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, transform_switch )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, transform_narrow_table )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, transform_wide_table )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, strchr_transform_switch )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Escaping, and_transform_by_one_table )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); static void BM_sphSprintf ( benchmark::State & st ) { char sBuf[40]; for ( auto _ : st ) sph::Sprintf ( sBuf, "%d", 1000000 ); st.SetItemsProcessed ( st.iterations() ); } static void BM_stdSprintf ( benchmark::State & st ) { char sBuf[40]; for ( auto _ : st ) snprintf ( sBuf, 39, "%d", 1000000 ); st.SetItemsProcessed ( st.iterations() ); } BENCHMARK( BM_sphSprintf ); BENCHMARK( BM_stdSprintf ); class bench_builder : public benchmark::Fixture { public: void SetUp ( const ::benchmark::State& state ) { sphSrand(0); a = sphRand(); b = sphRand(); c = sphRand(); d = sphRand(); f = sphRand(); g = sphRand(); h = sphRand(); i = sphRand(); j = sphRand(); k = sphRand(); l = sphRand(); m = sphRand(); n = sphRand(); o = sphRand(); p = sphRand(); q = sphRand(); } const char * sFieldFmt = R"({"field":%d, "lcs":%u, "hit_count":%u, "word_count":%u, "tf_idf":%d, "min_idf":%d, )" R"("max_idf":%d, "sum_idf":%d, "min_hit_pos":%d, "min_best_span_pos":%d, "exact_hit":%u, )" R"("max_window_hits":%d, "min_gaps":%d, "exact_order":%u, "lccs":%d, "wlccs":%d, "atc":%d})"; int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q; }; BENCHMARK_F( bench_builder, Appendf_ints ) ( benchmark::State & st ) { StringBuilder_c sBuf; for ( auto _ : st ) { benchmark::DoNotOptimize ( sBuf.Appendf ( sFieldFmt, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q ) ); sBuf.Rewind (); } st.SetLabel ( "use standard sprintf() inside" ); st.SetItemsProcessed ( st.iterations() ); } BENCHMARK_F( bench_builder, Sprintf_ints ) ( benchmark::State & st ) { StringBuilder_c sBuf; for ( auto _ : st ) { benchmark::DoNotOptimize ( sBuf.Sprintf ( sFieldFmt, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q ) ); sBuf.Rewind (); } st.SetLabel ( "own implementation sph::Sprintf" ); st.SetItemsProcessed ( st.iterations() ); } BENCHMARK_F ( bench_builder, Sprint_ints ) ( benchmark::State& st ) { StringBuilder_c sBuf; for ( auto _ : st ) { benchmark::DoNotOptimize ( sBuf.Sprint( "{\"field\":", a, ", \"lcs\":", b, ", \"hit_count\":", c, ", \"word_count\":", d, ", \"tf_idf\":", e, ", \"min_idf\":", f, ", \"max_idf\":", g, ", \"sum_idf\":", h, ", \"min_hit_pos\":", i, ", \"min_best_span_pos\":", j, ", \"exact_hit\":", k, ", \"max_window_hits\":", l, ", \"min_gaps\":", m, ", \"exact_order\":", n, ", \"lccs\":", o, ", \"wlccs\":", p, ", \"atc\":", q, '}') ); sBuf.Rewind(); } st.SetLabel ( "own implementation using templated Sprint" ); st.SetItemsProcessed ( st.iterations() ); } BENCHMARK_F ( bench_builder, Sprint_streaming ) ( benchmark::State& st ) { StringBuilder_c sBuf; for ( auto _ : st ) { benchmark::DoNotOptimize ( sBuf << "{\"field\":" << a << ", \"lcs\":" << b << ", \"hit_count\":" << c << ", \"word_count\":" << d << ", \"tf_idf\":" << e << ", \"min_idf\":" << f << ", \"max_idf\":" << g << ", \"sum_idf\":" << h << ", \"min_hit_pos\":" << i << ", \"min_best_span_pos\":" << j << ", \"exact_hit\":" << k << ", \"max_window_hits\":" << l << ", \"min_gaps\":" << m << ", \"exact_order\":" << n << ", \"lccs\":" << o << ", \"wlccs\":" << p << ", \"atc\":" << q << '}' ); sBuf.Rewind(); } st.SetLabel ( "own implementation using << (mostly inlined)" ); st.SetItemsProcessed ( st.iterations() ); } class rand_numbers: public benchmark::Fixture { public: void SetUp ( const ::benchmark::State& state ) { dNumbers.Resize(1000); sphSrand ( 0 ); for ( auto& iNum: dNumbers ) { int64_t iVal = sphRand(); iVal = ( iVal << 32 ) | sphRand(); iNum = iVal; } } CSphVector<int64_t> dNumbers; char sBuf[32]; }; #if __has_include( <charconv>) #include <charconv> #endif 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; } BENCHMARK_F ( rand_numbers, formatint ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( const auto dNum : dNumbers ) benchmark::DoNotOptimize ( FormatInt<int> ( sBuf, (int)dNum ) ); } st.SetItemsProcessed ( st.iterations() ); } BENCHMARK_F ( rand_numbers, ntoaint ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( const auto dNum : dNumbers ) benchmark::DoNotOptimize ( sph::NtoA ( sBuf, (int)dNum ) ); } st.SetItemsProcessed ( st.iterations() ); } #if __has_include( <charconv>) BENCHMARK_F ( rand_numbers, std_tocharsint ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( const auto dNum : dNumbers ) benchmark::DoNotOptimize ( std::to_chars ( sBuf, sBuf + 32, (int)dNum ) ); } st.SetItemsProcessed ( st.iterations() ); } #endif BENCHMARK_F ( rand_numbers, formatint64 ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( const auto dNum : dNumbers ) benchmark::DoNotOptimize ( FormatInt<int64_t> ( sBuf, dNum ) ); } st.SetItemsProcessed ( st.iterations() ); } BENCHMARK_F ( rand_numbers, ntoaint64 ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( const auto dNum : dNumbers ) benchmark::DoNotOptimize ( sph::NtoA ( sBuf, dNum ) ); } st.SetItemsProcessed ( st.iterations() ); } #if __has_include( <charconv>) BENCHMARK_F ( rand_numbers, std_tocharsint64 ) ( benchmark::State& st ) { for ( auto _ : st ) { for ( const auto dNum : dNumbers ) benchmark::DoNotOptimize ( std::to_chars ( sBuf, sBuf + 32, dNum ) ); } st.SetItemsProcessed ( st.iterations() ); } #endif BENCHMARK_MAIN();
13,657
C++
.cpp
417
30.551559
164
0.61779
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,037
misc.cpp
manticoresoftware_manticoresearch/src/gbenches/misc.cpp
// // 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 // #include "std/string.h" #include "std/rand.h" #include "std/timers.h" #include "threadutils.h" #include <benchmark/benchmark.h> class Misc: public benchmark::Fixture { public: void SetUp ( const ::benchmark::State& state ) { sphSrand ( 0 ); iRes = 0; } void TearDown ( const ::benchmark::State& state ) { } static void BenchTimerThread ( void* pEndtime ) { volatile int iRes = 0; for ( int i = 0; i < 100; ++i ) iRes += (int)sphMicroTimer(); *(int64_t*)pEndtime = sphMicroTimer(); } volatile int iRes; int64_t t; int64_t tmStart; }; BENCHMARK_DEFINE_F ( Misc, rand ) ( benchmark::State& st ) { auto NRUNS = st.range(0); for ( auto _ : st ) for ( int i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( sphRand() ); st.SetItemsProcessed ( st.iterations() * NRUNS ); } BENCHMARK_DEFINE_F ( Misc, randlog2 ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( int i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( sphLog2 ( sphRand() ) ); st.SetItemsProcessed ( st.iterations() * NRUNS ); } BENCHMARK_DEFINE_F ( Misc, timer ) ( benchmark::State& st ) { auto NRUNS = st.range ( 0 ); for ( auto _ : st ) for ( int i = 0; i < NRUNS; ++i ) benchmark::DoNotOptimize ( sphMicroTimer() ); st.SetItemsProcessed ( st.iterations() * NRUNS ); } BENCHMARK_DEFINE_F ( Misc, timer_threaded ) ( benchmark::State& st ) { Threads::Init(); tmStart = sphMicroTimer(); auto THREADS = st.range ( 0 ); CSphFixedVector<SphThread_t> dThd { THREADS }; CSphFixedVector<int64_t> tmEnd { THREADS }; for ( auto _ : st ) { for ( int i = 0; i < THREADS; ++i ) Threads::Create ( &dThd[i], [this, i, THREADS, &tmEnd] { BenchTimerThread ( &tmEnd[i] ); } ); for ( int i = 0; i < THREADS; ++i ) if ( !Threads::Join ( &dThd[i] ) ) sphDie ( "thread_join failed" ); } st.SetItemsProcessed ( st.iterations()*THREADS ); } BENCHMARK_REGISTER_F ( Misc, rand )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Misc, randlog2 )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Misc, timer )->RangeMultiplier ( 10 )->Range ( 10, 1000 ); BENCHMARK_REGISTER_F ( Misc, timer_threaded )->RangeMultiplier ( 2 )->Range ( 1, 16 );
2,701
C++
.cpp
87
29.091954
96
0.668075
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,038
expressions.cpp
manticoresoftware_manticoresearch/src/gbenches/expressions.cpp
// // 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 // #include <benchmark/benchmark.h> #include "schema/columninfo.h" #include "schema/schema.h" #include "match.h" #include "sphinxexpr.h" #include "sphinxdefs.h" #include "std/generics.h" #include <cmath> #if defined( __GNUC__ ) || defined( __clang__ ) #define NOINLINE __attribute__ ( ( noinline ) ) #elif _WIN32 #define NOINLINE __declspec(noinline) #endif #define AAA float(tMatch.m_pStatic[0]) #define BBB float(tMatch.m_pStatic[1]) #define CCC float(tMatch.m_pStatic[2]) NOINLINE float ExprNative1 ( const CSphMatch & tMatch ) { return AAA+BBB*CCC-1.0f;} NOINLINE float ExprNative2 ( const CSphMatch & tMatch ) { return AAA+BBB*CCC*2.0f-3.0f/4.0f*5.0f/6.0f*BBB; } NOINLINE float ExprNative3 ( const CSphMatch & ) { return (float)sqrt ( 2.0f ); } struct ExprBench_t { const char* m_sExpr; float ( *m_pFunc ) ( const CSphMatch& ); }; ExprBench_t dBench[] = { { "aaa+bbb*(ccc)-1", ExprNative1 }, { "aaa+bbb*ccc*2-3/4*5/6*bbb", ExprNative2 }, { "sqrt(2)", ExprNative3 } }; class BM_expressions: public benchmark::Fixture { public: void SetUp ( const ::benchmark::State& state ) override { NBENCH = state.range ( 0 ); CSphColumnInfo tCol; tCol.m_eAttrType = SPH_ATTR_INTEGER; tCol.m_sName = "aaa"; tSchema.AddAttr ( tCol, false ); tCol.m_sName = "bbb"; tSchema.AddAttr ( tCol, false ); tCol.m_sName = "ccc"; tSchema.AddAttr ( tCol, false ); pRow = new CSphRowitem[tSchema.GetRowSize()]; for ( int i = 0; i < tSchema.GetRowSize(); i++ ) pRow[i] = 1 + i; tMatch.m_tRowID = 123; tMatch.m_iWeight = 456; tMatch.m_pStatic = pRow; tExprArgs.m_pAttrType = &uType; } void TearDown ( const ::benchmark::State& state ) override { SafeDeleteArray ( pRow ); } int64_t NBENCH = 0; CSphSchema tSchema; CSphRowitem* pRow = nullptr; CSphMatch tMatch; ESphAttr uType; CSphString sError; ExprParseArgs_t tExprArgs; }; BENCHMARK_DEFINE_F ( BM_expressions, floats ) ( benchmark::State& st ) { ISphExprRefPtr_c pExpr ( sphExprParse ( dBench[NBENCH].m_sExpr, tSchema, sError, tExprArgs ) ); for ( auto _ : st ) { benchmark::DoNotOptimize ( pExpr->Eval ( tMatch ) ); } st.SetItemsProcessed ( st.iterations() ); st.SetLabel ( dBench[NBENCH].m_sExpr ); } BENCHMARK_DEFINE_F ( BM_expressions, ints ) ( benchmark::State& st ) { ISphExprRefPtr_c pExpr ( sphExprParse ( dBench[NBENCH].m_sExpr, tSchema, sError, tExprArgs ) ); // if ( uType != SPH_ATTR_INTEGER ) { // st.SkipWithError ( "attr is NOT integer" ); // return; // } for ( auto _ : st ) { benchmark::DoNotOptimize ( pExpr->IntEval ( tMatch ) ); } st.SetItemsProcessed ( st.iterations() ); st.SetLabel ( dBench[NBENCH].m_sExpr ); } BENCHMARK_DEFINE_F ( BM_expressions, natives ) ( benchmark::State& st ) { for ( auto _ : st ) { benchmark::DoNotOptimize ( dBench[NBENCH].m_pFunc ( tMatch ) ); } st.SetItemsProcessed ( st.iterations() ); st.SetLabel ( dBench[NBENCH].m_sExpr ); } BENCHMARK_REGISTER_F ( BM_expressions, floats )->DenseRange ( 0, 2, 1 ); BENCHMARK_REGISTER_F ( BM_expressions, ints )->Arg ( 0 ); // the only integer here //BENCHMARK_REGISTER_F ( BM_expressions, floats )->DenseRange ( 0, 2, 1 ); BENCHMARK_REGISTER_F ( BM_expressions, natives )->DenseRange ( 0, 2, 1 );
3,684
C++
.cpp
114
30.464912
108
0.700816
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,039
mutex.cpp
manticoresoftware_manticoresearch/src/std/mutex.cpp
// // 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 "mutex.h" #include "fatal.h" #include "timers.h" #include "config.h" #include <cerrno> #include <cstring> ////////////////////////////////////////////////////////////////////////// // MUTEX ////////////////////////////////////////////////////////////////////////// #if _WIN32 // Windows mutex implementation CSphMutex::CSphMutex () noexcept { m_tMutex = CreateMutex ( NULL, FALSE, NULL ); if ( !m_tMutex ) sphDie ( "CreateMutex() failed" ); } CSphMutex::~CSphMutex () noexcept { if ( CloseHandle ( m_tMutex )==FALSE ) sphDie ( "CloseHandle() failed" ); } bool CSphMutex::Lock () { DWORD uWait = WaitForSingleObject ( m_tMutex, INFINITE ); return ( uWait!=WAIT_FAILED && uWait!=WAIT_TIMEOUT ); } bool CSphMutex::TimedLock ( int iMsec ) { DWORD uWait = WaitForSingleObject ( m_tMutex, iMsec ); return ( uWait!=WAIT_FAILED && uWait!=WAIT_TIMEOUT ); } bool CSphMutex::Unlock () { return ReleaseMutex ( m_tMutex )==TRUE; } #else // UNIX mutex implementation CSphMutex::CSphMutex() noexcept { if ( pthread_mutex_init ( &m_tMutex, nullptr ) ) sphDie ( "pthread_mutex_init() failed %s", strerror ( errno ) ); } CSphMutex::~CSphMutex() noexcept { if ( pthread_mutex_destroy ( &m_tMutex ) ) sphDie ( "pthread_mutex_destroy() failed %s", strerror ( errno ) ); } bool CSphMutex::Lock () { return ( pthread_mutex_lock ( &m_tMutex )==0 ); } bool CSphMutex::TimedLock ( int iMsec ) { // pthread_mutex_timedlock is not available on Mac Os. Fallback to lock without a timer. #if defined (HAVE_PTHREAD_MUTEX_TIMEDLOCK) struct timespec ts; clock_gettime ( CLOCK_REALTIME, &ts ); int ns = ts.tv_nsec + ( iMsec % 1000 )*1000000; ts.tv_sec += ( ns / 1000000000 ) + ( iMsec / 1000 ); ts.tv_nsec = ( ns % 1000000000 ); int iRes = pthread_mutex_timedlock ( &m_tMutex, &ts ); return iRes==0; #else int iRes = EBUSY; int64_t tmTill = sphMicroTimer () + iMsec * 1000; do { iRes = pthread_mutex_trylock ( &m_tMutex ); if ( iRes!=EBUSY ) break; // below is inlined sphSleepMsec(1) - placed here to avoid dependency from libsphinx (for wordbreaker) #if _WIN32 Sleep ( 1 ); #else struct timeval tvTimeout; tvTimeout.tv_sec = 0; tvTimeout.tv_usec = 1000; select ( 0, nullptr, nullptr, nullptr, &tvTimeout ); #endif } while ( sphMicroTimer ()<tmTill ); if ( iRes==EBUSY ) iRes = pthread_mutex_trylock ( &m_tMutex ); return iRes!=EBUSY; #endif } bool CSphMutex::Unlock () { return ( pthread_mutex_unlock ( &m_tMutex )==0 ); } #endif
2,960
C++
.cpp
102
27.254902
104
0.667725
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,040
rwlock.cpp
manticoresoftware_manticoresearch/src/std/rwlock.cpp
// // 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 "rwlock.h" ////////////////////////////////////////////////////////////////////////// // RWLOCK ////////////////////////////////////////////////////////////////////////// #if _WIN32 // Windows rwlock implementation RwLock_t::RwLock_t ( bool bPreferWriter ) { Verify ( Init ( bPreferWriter ) ); } bool RwLock_t::Init ( bool ) { assert ( !m_bInitialized ); assert ( !m_hWriteMutex && !m_hReadEvent && !m_iReaders ); m_hReadEvent = CreateEvent ( NULL, TRUE, FALSE, NULL ); if ( !m_hReadEvent ) return false; m_hWriteMutex = CreateMutex ( NULL, FALSE, NULL ); if ( !m_hWriteMutex ) { CloseHandle ( m_hReadEvent ); m_hReadEvent = NULL; return false; } m_bInitialized = true; return true; } bool RwLock_t::Done() { if ( !m_bInitialized ) return true; if ( !CloseHandle ( m_hReadEvent ) ) return false; m_hReadEvent = NULL; if ( !CloseHandle ( m_hWriteMutex ) ) return false; m_hWriteMutex = NULL; m_iReaders = 0; m_bInitialized = false; return true; } bool RwLock_t::ReadLock() { assert ( m_bInitialized ); DWORD uWait = WaitForSingleObject ( m_hWriteMutex, INFINITE ); if ( uWait == WAIT_FAILED || uWait == WAIT_TIMEOUT ) return false; // got the writer mutex, can't be locked for write // so it's OK to add the reader lock, then free the writer mutex // writer mutex also protects readers counter InterlockedIncrement ( &m_iReaders ); // reset writer lock event, we just got ourselves a reader if ( !ResetEvent ( m_hReadEvent ) ) return false; // release writer lock return ReleaseMutex ( m_hWriteMutex ) == TRUE; } bool RwLock_t::WriteLock() { assert ( m_bInitialized ); // try to acquire writer mutex DWORD uWait = WaitForSingleObject ( m_hWriteMutex, INFINITE ); if ( uWait == WAIT_FAILED || uWait == WAIT_TIMEOUT ) return false; // got the writer mutex, no pending readers, rock'n'roll if ( !m_iReaders ) return true; // got the writer mutex, but still have to wait for all readers to complete uWait = WaitForSingleObject ( m_hReadEvent, INFINITE ); if ( uWait == WAIT_FAILED || uWait == WAIT_TIMEOUT ) { // wait failed, well then, release writer mutex ReleaseMutex ( m_hWriteMutex ); return false; } return true; } bool RwLock_t::Unlock() { assert ( m_bInitialized ); // are we unlocking a writer? if ( ReleaseMutex ( m_hWriteMutex ) ) return true; // yes we are if ( GetLastError() != ERROR_NOT_OWNER ) return false; // some unexpected error // writer mutex wasn't mine; we must have a read lock if ( !m_iReaders ) return true; // could this ever happen? // atomically decrement reader counter if ( InterlockedDecrement ( &m_iReaders ) ) return true; // there still are pending readers // no pending readers, fire the event for write lock return SetEvent ( m_hReadEvent ) == TRUE; } #else // UNIX rwlock implementation (pthreads wrapper) RwLock_t::RwLock_t ( bool bPreferWriter ) { m_pLock = new pthread_rwlock_t; Verify ( Init ( bPreferWriter ) ); } bool RwLock_t::Init ( bool bPreferWriter ) { assert ( !m_bInitialized ); assert ( m_pLock ); pthread_rwlockattr_t tAttr; pthread_rwlockattr_t* pAttr = nullptr; if ( bPreferWriter ) { bool bOk = ( pthread_rwlockattr_init ( &tAttr ) == 0 ); assert ( bOk ); if ( bOk ) { #if HAVE_RWLOCK_PREFER_WRITER bOk = ( pthread_rwlockattr_setkind_np ( &tAttr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP ) == 0 ); #else // Mac OS X knows nothing about PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP m_pWritePreferHelper = new CSphMutex(); #endif assert ( bOk ); if ( !bOk ) pthread_rwlockattr_destroy ( &tAttr ); else pAttr = &tAttr; } } m_bInitialized = ( pthread_rwlock_init ( m_pLock, pAttr ) == 0 ); if ( pAttr ) pthread_rwlockattr_destroy ( &tAttr ); return m_bInitialized; } bool RwLock_t::Done() { assert ( m_pLock ); if ( !m_bInitialized ) return true; m_bInitialized = pthread_rwlock_destroy ( m_pLock ) != 0; return !m_bInitialized; } bool RwLock_t::ReadLock() { assert ( m_bInitialized ); assert ( m_pLock ); if ( !m_pWritePreferHelper ) return pthread_rwlock_rdlock ( m_pLock ) == 0; ScopedMutex_t tScopedLock ( *m_pWritePreferHelper ); return pthread_rwlock_rdlock ( m_pLock ) == 0; } bool RwLock_t::WriteLock() { assert ( m_bInitialized ); assert ( m_pLock ); if ( !m_pWritePreferHelper ) return pthread_rwlock_wrlock ( m_pLock ) == 0; ScopedMutex_t tScopedLock ( *m_pWritePreferHelper ); return pthread_rwlock_wrlock ( m_pLock ) == 0; } bool RwLock_t::Unlock() { assert ( m_bInitialized ); assert ( m_pLock ); return pthread_rwlock_unlock ( m_pLock ) == 0; } #endif
5,117
C++
.cpp
175
27.017143
105
0.68603
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,041
crc32.cpp
manticoresoftware_manticoresearch/src/std/crc32.cpp
// // 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 "crc32.h" #include "ints.h" ////////////////////////////////////////////////////////////////////////// DWORD sphCRC32 ( const void* s ) { DWORD uCRC = ~( (DWORD)0 ); for ( auto p = (const BYTE*)s; *p; ++p ) CRC32_step ( uCRC, *p ); return ~uCRC; } DWORD sphCRC32 ( const void* s, int iLen, DWORD uPrevCRC ) { auto uCRC = ~uPrevCRC; auto p = (const BYTE*)s; auto pMax = p + iLen; while ( p < pMax ) CRC32_step ( uCRC, *p++ ); return ~uCRC; }
944
C++
.cpp
30
29.833333
80
0.635061
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,042
string.cpp
manticoresoftware_manticoresearch/src/std/string.cpp
// // 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 "string.h" ////////////////////////////////////////////////////////////////////////// char CSphString::EMPTY[] = ""; void ToLower ( Str_t sVal ) { char * s = const_cast<char *> ( sVal.first ); const char * sEnd = s + sVal.second; for ( ; s<sEnd; s++ ) *s = (char)tolower ( *s ); }
775
C++
.cpp
21
35.428571
80
0.631509
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,043
sys.cpp
manticoresoftware_manticoresearch/src/std/sys.cpp
// // 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 "sys.h" #include "fixedvector.h" #include "string.h" #include <stdlib.h> #include <set> #if defined(__x86_64__) || defined(__i386__) #include <cpuid.h> #endif #if !_WIN32 #include <unistd.h> #endif static int GetNumLogicalCPUsImpl() { #if _WIN32 SYSTEM_INFO tInfo; GetSystemInfo ( &tInfo ); return tInfo.dwNumberOfProcessors; #else return sysconf ( _SC_NPROCESSORS_ONLN ); #endif } int GetNumLogicalCPUs() { static int iCPUs = GetNumLogicalCPUsImpl(); return iCPUs; } static int GetNumPhysicalCPUsImpl() { #if _WIN32 DWORD uResponseSize = 0; if ( GetLogicalProcessorInformationEx ( RelationProcessorCore, nullptr, &uResponseSize ) ) return -1; if ( GetLastError()!=ERROR_INSUFFICIENT_BUFFER ) return -1; CSphFixedVector<uint8_t> dBuffer ( uResponseSize ); if ( !GetLogicalProcessorInformationEx ( RelationProcessorCore, (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)dBuffer.Begin(), &uResponseSize ) ) return -1; int iNumCPUs = 0; uint8_t * pPtr = dBuffer.Begin(); uint8_t * pMax = pPtr + uResponseSize; while ( pPtr < pMax ) { auto pInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)pPtr; pPtr += pInfo->Size; iNumCPUs++; } return iNumCPUs; #else FILE * pFile = fopen ( "/proc/cpuinfo", "r" ); if ( !pFile ) return -1; using ProcCore_t = std::pair<size_t, size_t>; std::set<ProcCore_t> tPCs; ProcCore_t tPC; char szLine[1024]; while ( fgets ( szLine, sizeof(szLine), pFile ) ) { const char * pCol = strchr ( szLine, ':' ); if ( !pCol ) continue; CSphString sKey ( szLine, pCol-szLine ); CSphString sValue ( pCol+1 ); sKey.Trim(); sValue.Trim(); if ( sKey.Begins ( "physical id" ) ) tPC.first = atoi ( sValue.cstr() ); else if ( sKey.Begins ( "core id" ) ) { tPC.second = atoi ( sValue.cstr() ); tPCs.insert(tPC); } } fclose(pFile); return tPCs.empty() ? -1 : tPCs.size(); #endif } int GetNumPhysicalCPUs() { static int iCPUs = GetNumPhysicalCPUsImpl(); return iCPUs; } static bool IsSSE42SupportedImpl() { #if defined(__x86_64__) || defined(__i386__) uint32_t dInfo[4]; __cpuid ( 1, dInfo[0], dInfo[1], dInfo[2], dInfo[3] ); return (dInfo[2] & (1 << 20)) != 0; #else return true; // assumes that it's ARM and simde is used #endif } bool IsSSE42Supported() { static bool bSSE = IsSSE42SupportedImpl(); return bSSE; } static int GetMemPageSizeImpl() { #if _WIN32 SYSTEM_INFO tInfo; GetSystemInfo ( &tInfo ); return tInfo.dwPageSize; #else return getpagesize(); #endif } int GetMemPageSize() { static int iMemPageSize = GetMemPageSizeImpl(); return iMemPageSize; }
3,064
C++
.cpp
122
23.139344
143
0.714139
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,044
timers.cpp
manticoresoftware_manticoresearch/src/std/timers.cpp
// // 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 "timers.h" #if !_WIN32 #include <sys/time.h> // for gettimeofday #include <time.h> #endif ////////////////////////////////////////////////////////////////////////// #if _WIN32 inline static int64_t winMicroTimer() { // Windows time query static int64_t iBase = 0; static int64_t iStart = 0; static int64_t iFreq = 0; LARGE_INTEGER iLarge; if ( !iBase ) { // get start QPC value QueryPerformanceFrequency ( &iLarge ); iFreq = iLarge.QuadPart; QueryPerformanceCounter ( &iLarge ); iStart = iLarge.QuadPart; // get start UTC timestamp // assuming it's still approximately the same moment as iStart, give or take a msec or three FILETIME ft; GetSystemTimeAsFileTime ( &ft ); iBase = ( int64_t ( ft.dwHighDateTime ) << 32 ) + int64_t ( ft.dwLowDateTime ); iBase = ( iBase - 116444736000000000ULL ) / 10; // rebase from 01 Jan 1601 to 01 Jan 1970, and rescale to 1 usec from 100 ns } // we can't easily drag iBase into parens because iBase*iFreq/1000000 overflows 64bit int! QueryPerformanceCounter ( &iLarge ); return iBase + ( iLarge.QuadPart - iStart ) * 1000000 / iFreq; } #endif /// microsecond precision timestamp int64_t sphMicroTimer() { #if _WIN32 return winMicroTimer(); #else // UNIX time query struct timeval tv; gettimeofday ( &tv, NULL ); return int64_t(tv.tv_sec)*int64_t(1000000) + int64_t(tv.tv_usec); #endif // _WIN32 } /// monotonic microsecond precision timestamp int64_t MonoMicroTimer() { #if _WIN32 return winMicroTimer(); #else // UNIX time query struct timespec tp; if ( clock_gettime ( CLOCK_MONOTONIC, &tp ) ) return 0; return tp.tv_sec * 1000000 + tp.tv_nsec / 1000; #endif } volatile bool& sphGetbCpuStat() noexcept; /// return cpu time, in microseconds int64_t sphThreadCpuTimer () { if ( !sphGetbCpuStat() ) return 0; #ifdef HAVE_CLOCK_GETTIME #if defined (CLOCK_THREAD_CPUTIME_ID) // CPU time (user+sys), Linux style, current thread constexpr static clockid_t tClockLoc = CLOCK_THREAD_CPUTIME_ID; #elif defined( CLOCK_PROF ) // CPU time (user+sys), FreeBSD style constexpr static clockid_t tClockLoc = CLOCK_PROF; #else // POSIX fallback (wall time) constexpr static clockid_t tClockLoc = CLOCK_REALTIME; #endif struct timespec tp; if ( clock_gettime ( tClockLoc, &tp ) ) return 0; return tp.tv_sec*1000000 + tp.tv_nsec/1000; #else return sphMicroTimer(); #endif } /// return cpu time, in microseconds int64_t sphProcessCpuTimer() { if ( !sphGetbCpuStat() ) return 0; #ifdef HAVE_CLOCK_GETTIME #if defined( CLOCK_PROCESS_CPUTIME_ID ) // CPU time (user+sys), Linux style, current thread constexpr static clockid_t tClockLoc = CLOCK_PROCESS_CPUTIME_ID; #elif defined( CLOCK_PROF ) // CPU time (user+sys), FreeBSD style constexpr static clockid_t tClockLoc = CLOCK_PROF; #else // POSIX fallback (wall time) constexpr static clockid_t tClockLoc = CLOCK_REALTIME; #endif struct timespec tp; if ( clock_gettime ( tClockLoc, &tp ) ) return 0; return tp.tv_sec * 1000000 + tp.tv_nsec / 1000; #else return sphMicroTimer(); #endif }
3,529
C++
.cpp
118
28.09322
126
0.723304
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,045
fastlog.cpp
manticoresoftware_manticoresearch/src/std/fastlog.cpp
// // 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 "fastlog.h" #include "sphinxutils.h" LogMessage_t::LogMessage_t ( BYTE uLevel ) : m_eLevel ( (ESphLogLevel)uLevel ) {} LogMessage_t::~LogMessage_t() { sphLogf ( m_eLevel, "%s", m_dLog.cstr() ); } LocMessage_c::LocMessage_c ( LocMessages_c* pOwner ) : m_pOwner ( pOwner ) {} LocMessage_c::~LocMessage_c() { m_pOwner->Append ( m_dLog ); } void LocMessages_c::Append ( StringBuilder_c& dMsg ) { auto pLeaf = new MsgList; dMsg.MoveTo ( pLeaf->m_sMsg ); pLeaf->m_pNext = m_sMsgs; m_sMsgs = pLeaf; ++m_iMsgs; } void LocMessages_c::Swap ( LocMessages_c& rhs ) noexcept { ::Swap ( m_sMsgs, rhs.m_sMsgs ); ::Swap ( m_iMsgs, rhs.m_iMsgs ); } int LocMessages_c::Print() const { for ( auto pHead = m_sMsgs; pHead; pHead = pHead->m_pNext ) sphLogDebug ( "%s", pHead->m_sMsg.scstr() ); return m_iMsgs; } LocMessages_c::~LocMessages_c() { for ( auto pHead = m_sMsgs; pHead != nullptr; ) { auto pNext = pHead->m_pNext; SafeDelete ( pHead ); pHead = pNext; } }
1,462
C++
.cpp
55
24.963636
80
0.697208
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,046
smalloc.cpp
manticoresoftware_manticoresearch/src/std/smalloc.cpp
// // 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 "smalloc.h" #include <cassert> #include "mutex.h" ////////////////////////////////////////////////////////////////////////// #if WITH_SMALLALLOC //////////////////////////////////////////////////////////////////////////////// /// FixedAllocator_c, PtrAttrAllocator_c /// Provides fast alloc/dealloc for small objects /// (large objects will be redirected to standard new/delete) //////////////////////////////////////////////////////////////////////////////// static constexpr size_t DEFAULT_CHUNK_SIZE = 4096; //////////////////////////////////////////////////////////////////////////////// /// FixedAllocator_c /// Represents storage for any num of objects of fixed size //////////////////////////////////////////////////////////////////////////////// class FixedAllocator_c: ISphNoncopyable { struct Chunk_t { void Init ( int iBlockSize, BYTE uBlocks ); void Release() const; BYTE* Allocate ( int iBlockSize ); void Deallocate ( BYTE* pBlob, int iBlockSize ); BYTE* m_pData; BYTE m_uFirstAvailable; BYTE m_uAvailable; }; int m_iBlockSize; // size of blobs I can serve Chunk_t* m_pAllocChunk = nullptr; // shortcut to last alloc Chunk_t* m_pDeallocChunk = nullptr; // shortcut to last dealloc Chunk_t* m_pLastFree = nullptr; // CSphVector<Chunk_t> m_dChunks; // my chunks BYTE m_uNumBlocks; // # of blocks per chunk private: void Swap ( FixedAllocator_c& rhs ); void DoDeallocate ( BYTE* pBlob ); Chunk_t* VicinityFind ( const BYTE* pBlob ); public: explicit FixedAllocator_c ( int iBlockSize = 0 ); FixedAllocator_c ( FixedAllocator_c&& ) noexcept; FixedAllocator_c& operator= ( FixedAllocator_c&& ) noexcept; ~FixedAllocator_c(); // allocate block of my m_iBlockSize BYTE* Allocate(); // Deallocate a memory block previously allocated with Allocate() // (if that's not the case, the behavior is undefined) void Deallocate ( BYTE* pBlob ); inline int BlockSize() const { return m_iBlockSize; } // debug/diagnostic size_t GetAllocatedSize() const; // how many allocated right now size_t GetReservedSize() const; // how many pooled from the sys right now }; //////////////////////////////////////////////////////////////////////////////// /// FixedAllocator_c::Chunk_t /// Represents a blob of memory for few objects of fixed size //////////////////////////////////////////////////////////////////////////////// void FixedAllocator_c::Chunk_t::Init ( int iBlockSize, BYTE uBlocks ) { assert ( iBlockSize > 0 ); assert ( uBlocks > 0 ); // Overflow check assert ( ( iBlockSize * uBlocks ) / iBlockSize == uBlocks ); m_pData = new BYTE[iBlockSize * uBlocks]; m_uAvailable = uBlocks; m_uFirstAvailable = 0; auto p = m_pData; for ( BYTE i = 0; i < uBlocks; p += iBlockSize ) *p = ++i; } void FixedAllocator_c::Chunk_t::Release() const { delete[] m_pData; } BYTE* FixedAllocator_c::Chunk_t::Allocate ( int iBlockSize ) { if ( !m_uAvailable ) return nullptr; assert ( ( m_uFirstAvailable * iBlockSize ) / iBlockSize == m_uFirstAvailable ); auto* pResult = m_pData + ( m_uFirstAvailable * iBlockSize ); m_uFirstAvailable = *pResult; --m_uAvailable; return pResult; } void FixedAllocator_c::Chunk_t::Deallocate ( BYTE* pBlob, int iBlockSize ) { assert ( pBlob >= m_pData ); // Alignment check assert ( ( pBlob - m_pData ) % iBlockSize == 0 ); *pBlob = m_uFirstAvailable; m_uFirstAvailable = (BYTE)( ( pBlob - m_pData ) / iBlockSize ); // Truncation check assert ( m_uFirstAvailable == ( pBlob - m_pData ) / iBlockSize ); ++m_uAvailable; } FixedAllocator_c::FixedAllocator_c ( int iBlockSize ) : m_iBlockSize ( iBlockSize ) { if ( !iBlockSize ) return; assert ( m_iBlockSize > 0 ); m_uNumBlocks = (BYTE)Min ( DEFAULT_CHUNK_SIZE / iBlockSize, BYTE ( 0xFF ) ); assert ( m_uNumBlocks && "Too large iBlocksize passed" ); } FixedAllocator_c::FixedAllocator_c ( FixedAllocator_c&& rhs ) noexcept { Swap ( rhs ); } FixedAllocator_c& FixedAllocator_c::operator= ( FixedAllocator_c&& rhs ) noexcept { Swap ( rhs ); return *this; } FixedAllocator_c::~FixedAllocator_c() { for ( auto& dChunk : m_dChunks ) { assert ( dChunk.m_uAvailable == m_uNumBlocks ); dChunk.Release(); } } void FixedAllocator_c::Swap ( FixedAllocator_c& rhs ) { ::Swap ( m_iBlockSize, rhs.m_iBlockSize ); ::Swap ( m_uNumBlocks, rhs.m_uNumBlocks ); m_dChunks.SwapData ( rhs.m_dChunks ); ::Swap ( m_pAllocChunk, rhs.m_pAllocChunk ); ::Swap ( m_pDeallocChunk, rhs.m_pDeallocChunk ); } BYTE* FixedAllocator_c::Allocate() { if ( !m_pAllocChunk || !m_pAllocChunk->m_uAvailable ) { for ( auto& dChunk : m_dChunks ) { if ( dChunk.m_uAvailable ) { m_pAllocChunk = &dChunk; return m_pAllocChunk->Allocate ( m_iBlockSize ); } } // loop finished, we're still here. Create new chunk then Chunk_t& dNewChunk = m_dChunks.Add(); dNewChunk.Init ( m_iBlockSize, m_uNumBlocks ); m_pDeallocChunk = m_dChunks.begin(); m_pAllocChunk = &m_dChunks.Last(); } assert ( m_pAllocChunk ); assert ( m_pAllocChunk->m_uAvailable ); return m_pAllocChunk->Allocate ( m_iBlockSize ); } void FixedAllocator_c::Deallocate ( BYTE* pBlob ) { assert ( !m_dChunks.IsEmpty() ); assert ( m_dChunks.begin() <= m_pDeallocChunk ); assert ( m_dChunks.end() > m_pDeallocChunk ); m_pDeallocChunk = VicinityFind ( pBlob ); assert ( m_pDeallocChunk ); DoDeallocate ( pBlob ); } // Finds the chunk corresponding to a pointer, using an efficient search FixedAllocator_c::Chunk_t* FixedAllocator_c::VicinityFind ( const BYTE* pBlob ) { assert ( !m_dChunks.IsEmpty() ); assert ( m_pDeallocChunk ); const int iChunkLength = m_uNumBlocks * m_iBlockSize; Chunk_t* pLo = m_pDeallocChunk; Chunk_t* pHi = m_pDeallocChunk + 1; Chunk_t* pLoBound = m_dChunks.begin(); Chunk_t* pHiBound = m_dChunks.end(); // Special case: deallocChunk_ is the last in the array if ( pHi == pHiBound ) pHi = nullptr; while ( true ) { if ( pLo ) { if ( pBlob >= pLo->m_pData && pBlob < pLo->m_pData + iChunkLength ) return pLo; if ( pLo == pLoBound ) pLo = nullptr; else --pLo; } if ( pHi ) { if ( pBlob >= pHi->m_pData && pBlob < pHi->m_pData + iChunkLength ) return pHi; if ( ++pHi == pHiBound ) pHi = nullptr; } } } // Performs deallocation. Assumes m_pDeallocChunk points to the correct chunk void FixedAllocator_c::DoDeallocate ( BYTE* pBlob ) { assert ( m_pDeallocChunk->m_pData <= pBlob ); assert ( m_pDeallocChunk->m_pData + m_uNumBlocks * m_iBlockSize > pBlob ); // call into the chunk, will adjust the inner list but won't release memory m_pDeallocChunk->Deallocate ( pBlob, m_iBlockSize ); if ( m_pDeallocChunk->m_uAvailable == m_uNumBlocks ) { // deallocChunk_ is completely free, should we release it? if ( m_pLastFree != m_pDeallocChunk ) { if ( m_pLastFree && m_pLastFree->m_uAvailable == m_uNumBlocks ) { // Two free blocks, discard one m_pLastFree->Release(); auto iIdx = m_pLastFree - m_dChunks.begin(); m_dChunks.RemoveFast ( iIdx ); if ( m_pDeallocChunk == m_dChunks.end() ) m_pDeallocChunk = m_pLastFree; } // move the empty chunk to the end m_pAllocChunk = m_pLastFree = m_pDeallocChunk; m_pDeallocChunk = &m_dChunks.Last(); } } } size_t FixedAllocator_c::GetAllocatedSize() const { size_t uAccum = 0; for ( const auto& dChunk : m_dChunks ) uAccum += m_uNumBlocks - dChunk.m_uAvailable; return uAccum * m_iBlockSize; } size_t FixedAllocator_c::GetReservedSize() const { auto uSize = Max ( m_iBlockSize * m_uNumBlocks, 4096 ); return (size_t)m_dChunks.GetLength() * uSize; } //////////////////////////////////////////////////////////////////////////////// /// class PtrAttrAllocator_c /// Offers fast allocations/deallocations //////////////////////////////////////////////////////////////////////////////// class PtrAttrAllocator_c: public ISphNoncopyable { CSphSwapVector<FixedAllocator_c> m_dPool; FixedAllocator_c* m_pLastAlloc; FixedAllocator_c* m_pLastDealloc; CSphMutex m_dAllocMutex; private: int LowerBound ( int iBytes ) REQUIRES ( m_dAllocMutex ); public: PtrAttrAllocator_c() : m_pLastAlloc ( nullptr ) , m_pLastDealloc ( nullptr ) { m_dPool.Reserve ( MAX_SMALL_OBJECT_SIZE ); } BYTE* Allocate ( int iBytes ); void Deallocate ( BYTE* pBlob, int iBytes ); // debug/diagnostic size_t GetAllocatedSize(); // how many allocated right now size_t GetReservedSize(); // how many pooled from the sys right now }; // returns lower bound for fixed allocators sized 'iBytes'. // i.e. idx of pool (asc sorted) where you can insert new not breaking the sequence. int PtrAttrAllocator_c::LowerBound ( int iBytes ) { if ( m_dPool.IsEmpty() ) return -1; auto pStart = m_dPool.begin(); auto pLast = &m_dPool.Last(); if ( pStart->BlockSize() >= iBytes ) return 0; if ( pLast->BlockSize() < iBytes ) return -1; while ( pLast - pStart > 1 ) { auto pMid = pStart + ( pLast - pStart ) / 2; if ( pMid->BlockSize() < iBytes ) pStart = pMid; else pLast = pMid; } return int ( pLast - m_dPool.begin() ); } // Allocates 'iBytes' memory // Uses an internal pool of FixedAllocator_c objects for small objects BYTE* PtrAttrAllocator_c::Allocate ( int iBytes ) { if ( iBytes > MAX_SMALL_OBJECT_SIZE ) return new BYTE[iBytes]; ScopedMutex_t tScopedLock ( m_dAllocMutex ); if ( m_pLastAlloc && m_pLastAlloc->BlockSize() == iBytes ) return m_pLastAlloc->Allocate(); auto i = LowerBound ( iBytes ); if ( i < 0 ) // required size > any other in the pool { i = m_dPool.GetLength(); m_dPool.Add ( FixedAllocator_c ( iBytes ) ); m_pLastDealloc = m_dPool.begin(); } else if ( m_dPool[i].BlockSize() != iBytes ) { FixedAllocator_c dAlloc ( iBytes ); m_dPool.Insert ( i, dAlloc ); m_pLastDealloc = m_dPool.begin(); } m_pLastAlloc = m_dPool.begin() + i; return m_pLastAlloc->Allocate(); } // Deallocates memory previously allocated with Allocate // (undefined behavior if you pass any other pointer) void PtrAttrAllocator_c::Deallocate ( BYTE* pBlob, int iBytes ) { if ( iBytes > MAX_SMALL_OBJECT_SIZE ) { SafeDeleteArray ( pBlob ); return; } ScopedMutex_t tScopedLock ( m_dAllocMutex ); if ( m_pLastDealloc && m_pLastDealloc->BlockSize() == iBytes ) { m_pLastDealloc->Deallocate ( pBlob ); return; } auto i = LowerBound ( iBytes ); assert ( i >= 0 ); assert ( m_dPool[i].BlockSize() == iBytes ); m_pLastDealloc = m_dPool.begin() + i; m_pLastDealloc->Deallocate ( pBlob ); } size_t PtrAttrAllocator_c::GetAllocatedSize() { ScopedMutex_t tScopedLock ( m_dAllocMutex ); size_t uAccum = 0; for ( const auto& dAlloc : m_dPool ) uAccum += dAlloc.GetAllocatedSize(); return uAccum; } size_t PtrAttrAllocator_c::GetReservedSize() { ScopedMutex_t tScopedLock ( m_dAllocMutex ); size_t uAccum = 0; for ( const auto& dAlloc : m_dPool ) uAccum += dAlloc.GetReservedSize(); return uAccum; } PtrAttrAllocator_c& SmallAllocator() { static PtrAttrAllocator_c dAllocator; return dAllocator; } BYTE* sphAllocateSmall ( int iBytes ) { assert ( iBytes > 0 ); if ( iBytes > MAX_SMALL_OBJECT_SIZE ) return new BYTE[iBytes]; return SmallAllocator().Allocate ( iBytes ); } void sphDeallocateSmall ( const BYTE* pBlob, int iBytes ) { if ( iBytes > MAX_SMALL_OBJECT_SIZE ) { SafeDeleteArray ( pBlob ); return; } SmallAllocator().Deallocate ( const_cast<BYTE*> ( pBlob ), iBytes ); } size_t sphGetSmallAllocatedSize() { return SmallAllocator().GetAllocatedSize(); } size_t sphGetSmallReservedSize() { return SmallAllocator().GetReservedSize(); } #endif
12,051
C++
.cpp
383
29.240209
84
0.66448
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,047
fnv64.cpp
manticoresoftware_manticoresearch/src/std/fnv64.cpp
// // 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 "fnv64.h" #include "ints.h" uint64_t sphFNV64 ( const void * s ) { return sphFNV64cont ( s, SPH_FNV64_SEED ); } uint64_t sphFNV64 ( const void * s, int iLen, uint64_t uPrev ) { const BYTE * p = (const BYTE*)s; uint64_t hval = uPrev; for ( ; iLen>0; iLen-- ) { // xor the bottom with the current octet hval ^= (uint64_t)*p++; // multiply by the 64 bit FNV magic prime mod 2^64 hval += (hval << 1) + (hval << 4) + (hval << 5) + (hval << 7) + (hval << 8) + (hval << 40); // gcc optimization } return hval; } uint64_t sphFNV64cont ( const void * s, uint64_t uPrev ) { const BYTE * p = (const BYTE*)s; if ( !p ) return uPrev; uint64_t hval = uPrev; while ( *p ) { // xor the bottom with the current octet hval ^= (uint64_t)*p++; // multiply by the 64 bit FNV magic prime mod 2^64 hval += (hval << 1) + (hval << 4) + (hval << 5) + (hval << 7) + (hval << 8) + (hval << 40); // gcc optimization } return hval; }
1,430
C++
.cpp
45
29.844444
113
0.653091
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,048
stringbuilder.cpp
manticoresoftware_manticoresearch/src/std/stringbuilder.cpp
// // 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 "stringbuilder.h" #include "sphinxutils.h" #include "generics.h" #include "relimit.h" #include <cassert> #include <cstdarg> #include <cstdio> ////////////////////////////////////////////////////////////////////////// /// StringBuilder implementation ////////////////////////////////////////////////////////////////////////// StringBuilder_c::StringBuilder_c ( const char * sDel, const char * sPref, const char * sTerm ) { if ( sDel || sPref || sTerm ) StartBlock ( sDel, sPref, sTerm ); } StringBuilder_c::~StringBuilder_c() { SafeDeleteArray ( m_szBuffer ); } StringBuilder_c::StringBuilder_c ( StringBuilder_c&& rhs ) noexcept { Swap (rhs); } void StringBuilder_c::Swap ( StringBuilder_c& rhs ) noexcept { ::Swap ( m_szBuffer, rhs.m_szBuffer ); ::Swap ( m_iSize, rhs.m_iSize ); ::Swap ( m_iUsed, rhs.m_iUsed ); ::Swap ( m_dDelimiters, rhs.m_dDelimiters ); } StringBuilder_c & StringBuilder_c::operator= ( StringBuilder_c rhs ) noexcept { Swap (rhs); return *this; } int StringBuilder_c::StartBlock ( const char * sDel, const char * sPref, const char * sTerm ) { m_dDelimiters.Add ( LazyComma_c ( sDel, sPref, sTerm ) ); return m_dDelimiters.GetLength(); } int StringBuilder_c::StartBlock ( const StrBlock_t& dBlock ) { m_dDelimiters.Add ( LazyComma_c ( dBlock ) ); return m_dDelimiters.GetLength(); } int StringBuilder_c::MuteBlock () { m_dDelimiters.Add ( LazyComma_c() ); return m_dDelimiters.GetLength (); } void StringBuilder_c::FinishBlock ( bool bAllowEmpty ) // finish last pushed block { if ( m_dDelimiters.IsEmpty() ) return; if ( !bAllowEmpty && !m_dDelimiters.Last().Started() ) { AppendChunk ( {"\0", 1} ); --m_iUsed; } if ( m_dDelimiters.Last().Started () ) AppendRawChunk ( m_dDelimiters.Last().m_sSuffix ); m_dDelimiters.Pop(); } void StringBuilder_c::FinishBlocks ( int iLevel, bool bAllowEmpty ) { while ( !m_dDelimiters.IsEmpty() && iLevel<=m_dDelimiters.GetLength() ) FinishBlock ( bAllowEmpty ); } StringBuilder_c & StringBuilder_c::vAppendf ( const char * sTemplate, va_list ap ) { if ( !m_szBuffer ) InitBuffer (); assert ( m_szBuffer ); assert ( m_iUsed<m_iSize ); auto sComma = Delim(); while (true) { int64_t iLeft = m_iSize - m_iUsed; if ( sComma.second && sComma.second < iLeft ) // prepend delimiter first... { if ( sComma.second ) memcpy ( m_szBuffer + m_iUsed, sComma.first, sComma.second ); iLeft -= sComma.second; m_iUsed += sComma.second; sComma = dEmptyStr; } // try to append va_list cp; va_copy ( cp, ap ); int iPrinted = vsnprintf ( m_szBuffer + m_iUsed, iLeft, sTemplate, cp ); va_end( cp ); // success? bail // note that we check for strictly less, not less or equal // that is because vsnprintf does *not* count the trailing zero // meaning that if we had N bytes left, and N bytes w/o the zero were printed, // we do not have a trailing zero anymore, but vsnprintf succeeds anyway if ( iPrinted>=0 && iPrinted<iLeft ) { m_iUsed += iPrinted; break; } // we need more chars! // either 256 (happens on Windows; lets assume we need 256 more chars) // or get all the needed chars and 64 more for future calls GrowEnough ( iPrinted<0 ? 256 : iPrinted + sComma.second ); } return *this; } StringBuilder_c & StringBuilder_c::Appendf ( const char * sTemplate, ... ) { va_list ap; va_start ( ap, sTemplate ); vAppendf ( sTemplate, ap ); va_end ( ap ); return *this; } StringBuilder_c & StringBuilder_c::vSprintf ( const char * sTemplate, va_list ap ) { if ( !m_szBuffer ) InitBuffer (); assert ( m_iUsed==0 || m_iUsed<m_iSize ); auto sComma = Delim(); if ( sComma.second ) // prepend delimiter first... { GrowEnough ( sComma.second ); memcpy ( m_szBuffer + m_iUsed, sComma.first, sComma.second ); m_iUsed += sComma.second; } sph::vSprintf ( *this, sTemplate, ap ); return *this; } /* Custom format specifiers for types: 'int' values: %d - decimal int %F - fixed-point int (see notes below about fixed-points) %i - skip int. Prints nothing, just skips parameter. Useful for conditional format. 'DWORD' (uint32) values: %u - decimal uint32 %x - hex uint32 'int64_t' (signed) values: %l - decimal int64 %D - fixed-point int64 %t - timespan (see notes below) %T - timestamp from now 'uint64_t' (unsigned) values: %U - decimal uint64 z-terminated string: %s - print string, or "(null)" etc.: %p - print pointer (16 hex digits) %f - float (fall-back to standard sprintf) Fixed-point ints (both 32 and 64 bits) need precise param to set the decimal point at this place Example: ( "%.4F", 999005 ) will output '99.9005'. ( "%.3D", (int64_t) -10000 ) will output '-10.000' Timespan prints time expressed in useconds in human-readable format. It output number with suffix. Suffixes are 'us', 'ms', 's', 'm', 'h', 'd', 'w' (usecs, msecs, secs, mins, hours, days, weeks). Example: ("%t", 1555555) will print "2s" (2 seconds) ("%t", 3600000000*24*2) will print "2d" (2 days) Timespan may be supplied with precision param, and then it will print up to 7 numbers with suffixes. Example: ("%.2t", 1555555) will print "1.56s" ("%.5t", 1555555) will print "1s 555.56ms" ("%.8t", 71555555) will print "1m 11s 555ms 555us" Timespan also reasonable rounds the value when necessary and doesn't output redundant zeros. Example: ("%.7t", 89999994) will print "1m 29s 999.99ms" ("%.7t", 89999995) will print "1m 30s" Timestamp from now - just takes provided value, compares it with sphMicroTimer() output and print the timespan difference according to the rules: - if given value is in the past, print 'TM ago' (where TM is timespan of the difference) - if given value is in the future, print 'in TM'. - if given value is exactly now, print the word 'now'. */ StringBuilder_c & StringBuilder_c::Sprintf ( const char * sTemplate, ... ) { va_list ap; va_start ( ap, sTemplate ); vSprintf ( sTemplate, ap ); va_end ( ap ); return *this; } BYTE * StringBuilder_c::Leak() { auto pRes = ( BYTE * ) m_szBuffer; NewBuffer (); return pRes; } void StringBuilder_c::MoveTo ( CSphString &sTarget ) { sTarget.Adopt ( &m_szBuffer ); NewBuffer (); } void StringBuilder_c::Grow ( int iLen ) { assert ( m_iSize<m_iUsed + iLen + GROW_STEP ); m_iSize = sph::DefaultRelimit::Relimit ( m_iSize, m_iUsed + iLen + GROW_STEP ); auto * pNew = new char[m_iSize]; if ( m_szBuffer ) memcpy ( pNew, m_szBuffer, m_iUsed + 1 ); ::Swap ( pNew, m_szBuffer ); SafeDeleteArray ( pNew ); } void StringBuilder_c::InitBuffer() { m_iSize = 256; m_szBuffer = new char[m_iSize]; } void StringBuilder_c::NewBuffer() { InitBuffer(); Clear (); } StringBuilder_c& StringBuilder_c::operator<< ( double fVal ) { InitAddPrefix(); GrowEnough ( 32 ); m_iUsed += snprintf ( end(), 31, "%f", fVal ); m_szBuffer[m_iUsed] = '\0'; return *this; } StringBuilder_c& StringBuilder_c::operator<< ( float fVal ) { InitAddPrefix(); GrowEnough ( 32 ); m_iUsed += sph::PrintVarFloat ( end(), 31, fVal ); m_szBuffer[m_iUsed] = '\0'; return *this; } void StringBuilder_c::FtoA ( float fVal ) { InitAddPrefix(); const int MAX_NUMERIC_STR = 64; GrowEnough ( MAX_NUMERIC_STR + 1 ); int iLen = sph::PrintVarFloat ( (char*)m_szBuffer + m_iUsed, MAX_NUMERIC_STR, fVal ); m_iUsed += iLen; m_szBuffer[m_iUsed] = '\0'; } void StringBuilder_c::DtoA ( double fVal ) { InitAddPrefix(); const int MAX_NUMERIC_STR = 64; GrowEnough ( MAX_NUMERIC_STR + 1 ); int iLen = sph::PrintVarDouble ( (char*)m_szBuffer + m_iUsed, MAX_NUMERIC_STR, fVal ); m_iUsed += iLen; m_szBuffer[m_iUsed] = '\0'; } ////////////////////////////////////////////////////////////////////////// StringBuilder_c::LazyComma_c::LazyComma_c ( const char * sDelim, const char * sPrefix, const char * sTerm ) : Comma_c ( sDelim ) { if ( sPrefix ) m_sPrefix = { sPrefix, (int) strlen(sPrefix) }; if ( sTerm ) m_sSuffix = { sTerm, (int) strlen(sTerm ) }; } StringBuilder_c::LazyComma_c::LazyComma_c( const StrBlock_t& dBlock ) : Comma_c ( std::get<0>(dBlock) ) , m_sPrefix ( std::get<1>(dBlock) ) , m_sSuffix ( std::get<2>(dBlock) ) {} const Str_t& StringBuilder_c::LazyComma_c::RawComma ( const std::function<void ()> & fnAddNext ) { if ( m_bSkipNext ) { m_bSkipNext = false; return dEmptyStr; } if ( Started() ) return m_sComma; m_bStarted = true; fnAddNext(); return m_sPrefix; } CSphString StrVec2Str ( const VecTraits_T<CSphString>& tVec, const char* szDelim ) noexcept { StringBuilder_c tOut ( szDelim ); tVec.Apply ( [&tOut] ( const CSphString& sNode ) { tOut << sNode; } ); return CSphString { tOut }; }
9,108
C++
.cpp
288
29.510417
107
0.6747
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,049
autoevent.cpp
manticoresoftware_manticoresearch/src/std/autoevent.cpp
// // 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 "autoevent.h" #include "fatal.h" #include "timers.h" #include "config.h" #include <cerrno> #if _WIN32 EventWrapper_c::EventWrapper_c() { InitializeConditionVariable ( &m_tCond ); InitializeCriticalSection ( &m_tMutex ); m_bInitialized = true; } EventWrapper_c::~EventWrapper_c() { if ( !m_bInitialized ) return; m_bInitialized = false; DeleteCriticalSection ( &m_tMutex ); // no need to deinit m_tCond as it is local } template<> void AutoEvent_T<true>::SetEvent() { EnterCriticalSection ( &m_tMutex ); m_iSent = 1; LeaveCriticalSection ( &m_tMutex ); WakeConditionVariable ( &m_tCond ); } template<> void AutoEvent_T<false>::SetEvent() { EnterCriticalSection ( &m_tMutex ); ++m_iSent; LeaveCriticalSection ( &m_tMutex ); WakeConditionVariable ( &m_tCond ); } template<> bool AutoEvent_T<true>::WaitEvent ( int iMsec ) { if ( !m_bInitialized ) return false; DWORD iTime = ( iMsec == -1 ) ? INFINITE : iMsec; EnterCriticalSection ( &m_tMutex ); while ( !m_iSent ) if ( !SleepConditionVariableCS ( &m_tCond, &m_tMutex, iTime ) && GetLastError() == ERROR_TIMEOUT ) { LeaveCriticalSection ( &m_tMutex ); return false; } m_iSent = 0; LeaveCriticalSection ( &m_tMutex ); return true; } template<> bool AutoEvent_T<false>::WaitEvent ( int iMsec ) { if ( !m_bInitialized ) return false; DWORD iTime = ( iMsec == -1 ) ? INFINITE : iMsec; EnterCriticalSection ( &m_tMutex ); while ( !m_iSent ) if ( !SleepConditionVariableCS ( &m_tCond, &m_tMutex, iTime ) && GetLastError() == ERROR_TIMEOUT ) { LeaveCriticalSection ( &m_tMutex ); return false; } --m_iSent; LeaveCriticalSection ( &m_tMutex ); return true; } #else // UNIX implementation EventWrapper_c::EventWrapper_c() { m_bInitialized = ( pthread_mutex_init ( &m_tMutex, nullptr ) == 0 ); m_bInitialized &= ( pthread_cond_init ( &m_tCond, nullptr ) == 0 ); } EventWrapper_c::~EventWrapper_c() { if ( !m_bInitialized ) return; pthread_cond_destroy ( &m_tCond ); pthread_mutex_destroy ( &m_tMutex ); } template<> void AutoEvent_T<false>::SetEvent() { if ( !m_bInitialized ) return; pthread_mutex_lock ( &m_tMutex ); ++m_iSent; pthread_cond_signal ( &m_tCond ); pthread_mutex_unlock ( &m_tMutex ); } template<> void AutoEvent_T<true>::SetEvent() { if ( !m_bInitialized ) return; pthread_mutex_lock ( &m_tMutex ); m_iSent = 1; pthread_cond_signal ( &m_tCond ); pthread_mutex_unlock ( &m_tMutex ); } template<> bool AutoEvent_T<false>::WaitEvent ( int iMsec ) { if ( !m_bInitialized ) return false; if ( iMsec == -1 ) { pthread_mutex_lock ( &m_tMutex ); while ( !m_iSent ) pthread_cond_wait ( &m_tCond, &m_tMutex ); --m_iSent; pthread_mutex_unlock ( &m_tMutex ); return true; } #ifdef HAVE_PTHREAD_COND_TIMEDWAIT struct timespec ts; clock_gettime ( CLOCK_REALTIME, &ts ); int ns = ts.tv_nsec + ( iMsec % 1000 ) * 1000000; ts.tv_sec += ( ns / 1000000000 ) + ( iMsec / 1000 ); ts.tv_nsec = ( ns % 1000000000 ); int iRes = 0; pthread_mutex_lock ( &m_tMutex ); while ( !m_iSent && !iRes ) iRes = pthread_cond_timedwait ( &m_tCond, &m_tMutex, &ts ); bool bEventHappened = iRes != ETIMEDOUT; if ( bEventHappened ) --m_iSent; pthread_mutex_unlock ( &m_tMutex ); return bEventHappened; #endif } template<> bool AutoEvent_T<true>::WaitEvent ( int iMsec ) { if ( !m_bInitialized ) return false; if ( iMsec == -1 ) { pthread_mutex_lock ( &m_tMutex ); while ( !m_iSent ) pthread_cond_wait ( &m_tCond, &m_tMutex ); m_iSent = 0; pthread_mutex_unlock ( &m_tMutex ); return true; } #ifdef HAVE_PTHREAD_COND_TIMEDWAIT struct timespec ts; clock_gettime ( CLOCK_REALTIME, &ts ); int ns = ts.tv_nsec + ( iMsec % 1000 ) * 1000000; ts.tv_sec += ( ns / 1000000000 ) + ( iMsec / 1000 ); ts.tv_nsec = ( ns % 1000000000 ); int iRes = 0; pthread_mutex_lock ( &m_tMutex ); while ( !m_iSent && !iRes ) iRes = pthread_cond_timedwait ( &m_tCond, &m_tMutex, &ts ); bool bEventHappened = iRes != ETIMEDOUT; if ( bEventHappened ) m_iSent = 0; pthread_mutex_unlock ( &m_tMutex ); return bEventHappened; #endif } #endif
4,594
C++
.cpp
178
23.752809
100
0.688214
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,050
sphwarn.cpp
manticoresoftware_manticoresearch/src/std/sphwarn.cpp
// // 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 "sphwarn.h" #include <cstdarg> #include <cstdio> void sphWarn ( const char* sTemplate, ... ) { va_list ap; va_start ( ap, sTemplate ); fprintf ( stdout, "WARNING: " ); vfprintf ( stdout, sTemplate, ap ); fprintf ( stdout, "\n" ); va_end ( ap ); }
740
C++
.cpp
23
30.782609
80
0.715686
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,051
stringhash.cpp
manticoresoftware_manticoresearch/src/std/stringhash.cpp
// // 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 "stringhash.h" #include "crc32.h" ////////////////////////////////////////////////////////////////////////// int CSphStrHashFunc::Hash ( const CSphString& sKey ) { return sKey.IsEmpty() ? 0 : sphCRC32 ( sKey.cstr() ); } namespace sph { StringSet::StringSet ( std::initializer_list<const char *> dVals ) { for ( const char * sVal : dVals ) Add ( sVal ); } StringSet::StringSet ( const VecTraits_T<CSphString> & dVals ) { for ( const CSphString & sVal : dVals ) Add ( sVal ); } }
975
C++
.cpp
31
30.032258
80
0.667377
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,052
checks.cpp
manticoresoftware_manticoresearch/src/std/checks.cpp
// // 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" #include <cstdlib> #if _WIN32 #ifndef NDEBUG void sphAssert ( const char* sExpr, const char* sFile, int iLine ) { char sBuffer[1024]; _snprintf ( sBuffer, sizeof ( sBuffer ), "%s(%d): assertion %s failed\n", sFile, iLine, sExpr ); if ( MessageBox ( NULL, sBuffer, "Assert failed! Cancel to debug.", MB_OKCANCEL | MB_TOPMOST | MB_SYSTEMMODAL | MB_ICONEXCLAMATION ) != IDOK ) { __debugbreak(); } else { fprintf ( stdout, "%s", sBuffer ); exit ( 1 ); } } #endif // !NDEBUG #endif // _WIN32
1,018
C++
.cpp
31
31.258065
143
0.707739
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,053
rand.cpp
manticoresoftware_manticoresearch/src/std/rand.cpp
// // 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 "rand.h" #if !_WIN32 #include <sys/time.h> #include <unistd.h> #endif ////////////////////////////////////////////////////////////////////////// // RANDOM NUMBERS GENERATOR ////////////////////////////////////////////////////////////////////////// /// MWC (Multiply-With-Carry) RNG, invented by George Marsaglia static DWORD g_dRngState[5] = { 0x95d3474bUL, 0x035cf1f7UL, 0xfd43995fUL, 0x5dfc55fbUL, 0x334a9229UL }; /// seed void sphSrand ( DWORD uSeed ) { for ( int i = 0; i < 5; ++i ) { uSeed = uSeed * 29943829 - 1; g_dRngState[i] = uSeed; } for ( int i = 0; i < 19; ++i ) sphRand(); } /// auto-seed RNG based on time and PID void sphAutoSrand() { // get timestamp DWORD uPID; #if !_WIN32 struct timeval tv; gettimeofday ( &tv, NULL ); uPID = getpid(); #else struct { time_t tv_sec; DWORD tv_usec; } tv; FILETIME ft; GetSystemTimeAsFileTime ( &ft ); uint64_t ts = ( uint64_t ( ft.dwHighDateTime ) << 32 ) + uint64_t ( ft.dwLowDateTime ) - 116444736000000000ULL; // Jan 1, 1970 magic ts /= 10; // to microseconds tv.tv_sec = (DWORD)( ts / 1000000 ); tv.tv_usec = (DWORD)( ts % 1000000 ); uPID = GetCurrentProcessId(); #endif // twist and shout sphSrand ( sphRand() ^ DWORD ( tv.tv_sec ) ^ ( DWORD ( tv.tv_usec ) + uPID ) ); } /// generate another dword DWORD sphRand () { uint64_t uSum; uSum = (uint64_t)g_dRngState[0] * U64C(5115) + (uint64_t)g_dRngState[1] * U64C(1776) + (uint64_t)g_dRngState[2] * U64C(1492) + (uint64_t)g_dRngState[3] * U64C(2111111111) + (uint64_t)g_dRngState[4]; g_dRngState[3] = g_dRngState[2]; g_dRngState[2] = g_dRngState[1]; g_dRngState[1] = g_dRngState[0]; g_dRngState[4] = (DWORD)( uSum>>32 ); g_dRngState[0] = (DWORD)uSum; return g_dRngState[0]; }
2,249
C++
.cpp
75
28.186667
133
0.630143
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,054
tdigest.cpp
manticoresoftware_manticoresearch/src/std/tdigest.cpp
// // 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 "tdigest.h" #include "mem.h" #include "rand.h" #include "vector.h" #include <cfloat> #include <cmath> #if _WIN32 #pragma warning(push,1) #pragma warning(disable:4530) #endif #if NEW_IS_OVERRIDED #undef new #endif #include <map> #if NEW_IS_OVERRIDED #define new new(__FILE__,__LINE__) #endif #if _WIN32 #pragma warning(pop) #endif class TDigest_c::Impl_c final { public: Impl_c () { Reset(); } void Add ( double fValue, int64_t iWeight ) { if ( m_dMap.empty() ) { m_dMap.insert ( std::pair<double, int64_t> ( fValue, iWeight ) ); m_iCount = iWeight; return; } auto tStart = m_dMap.lower_bound(fValue); if ( tStart==m_dMap.end() ) tStart = m_dMap.begin(); else { while ( tStart!=m_dMap.begin() && tStart->first==fValue ) tStart--; } double fMinDist = DBL_MAX; auto tLastNeighbor = m_dMap.end(); for ( auto i=tStart; i!=m_dMap.end(); ++i ) { double fDist = fabs ( i->first - fValue ); if ( fDist < fMinDist ) { tStart = i; fMinDist = fDist; } else if ( fDist > fMinDist ) { // we've passed the nearest nearest neighbor tLastNeighbor = i; break; } } auto tClosest = m_dMap.end(); int64_t iSum = 0; for ( auto i=m_dMap.begin(); i!=tStart; ++i ) iSum += i->second; int64_t iN = 0; const double COMPRESSION = 200.0; for ( auto i=tStart; i!=tLastNeighbor; ++i ) { double fQuantile = m_iCount==1 ? 0.5 : (iSum + (i->second - 1) / 2.0) / (m_iCount - 1); double fThresh = 4.0 * m_iCount * fQuantile * (1 - fQuantile) / COMPRESSION; if ( i->second+iWeight<=fThresh ) { iN++; if ( ( double ( sphRand() ) / UINT_MAX )<1.0/iN ) tClosest = i; } iSum += i->second; } if ( tClosest==m_dMap.end() ) m_dMap.insert ( std::pair<double, int64_t> ( fValue, iWeight ) ); else { double fNewMean = WeightedAvg ( tClosest->first, tClosest->second, fValue, iWeight ); int64_t iNewCount = tClosest->second+iWeight; m_dMap.erase ( tClosest ); m_dMap.insert ( std::pair<double, int64_t> ( fNewMean, iNewCount ) ); } m_iCount += iWeight; const DWORD K=20; if ( m_dMap.size() > K * COMPRESSION ) Compress(); } double Percentile ( int iPercent ) const noexcept { assert ( iPercent>=0 && iPercent<=100 ); if ( m_dMap.empty() ) return 0.0; int64_t iTotalCount = 0; double fPercent = double ( iPercent ) / 100.0; fPercent *= m_iCount; auto iMapFirst = m_dMap.begin(); auto iMapLast = m_dMap.end(); --iMapLast; for ( auto i = iMapFirst; i!=m_dMap.end(); ++i ) { if ( fPercent < iTotalCount + i->second ) { if ( i==iMapFirst || i==iMapLast ) return i->first; else { // get mean from previous iterator; get mean from next iterator; calc delta auto iPrev = i; auto iNext = i; iPrev--; iNext++; double fDelta = ( iNext->first - iPrev->first ) / 2.0; return i->first + ((fPercent - iTotalCount) / i->second - 0.5) * fDelta; } } iTotalCount += i->second; } return iMapLast->first; } private: using BalancedTree_c = std::multimap<double, int64_t, std::less<double>, managed_allocator<std::pair<const double, int64_t>>>; BalancedTree_c m_dMap; int64_t m_iCount; double WeightedAvg ( double fX1, int64_t iW1, double fX2, int64_t iW2 ) { return ( fX1*iW1 + fX2*iW2 ) / ( iW1 + iW2 ); } void Reset() { m_dMap.clear(); m_iCount = 0; } void Compress() { struct Centroid_t { double m_fMean; int64_t m_iCount; }; CSphTightVector<Centroid_t> dValues; dValues.Reserve ( (int) m_dMap.size() ); for ( auto i : m_dMap ) { Centroid_t & tCentroid = dValues.Add(); tCentroid.m_fMean = i.first; tCentroid.m_iCount = i.second; } Reset(); while ( dValues.GetLength() ) { int iValue = sphRand() % dValues.GetLength(); Add ( dValues[iValue].m_fMean, dValues[iValue].m_iCount ); dValues.RemoveFast(iValue); } } }; TDigest_c::TDigest_c () : m_pImpl { std::make_unique<TDigest_c::Impl_c> () } {} TDigest_c::~TDigest_c () = default; void TDigest_c::Add ( double fValue, int64_t iWeight ) { m_pImpl->Add ( fValue, iWeight ); } double TDigest_c::Percentile ( int iPercent ) const noexcept { return m_pImpl->Percentile (iPercent); } std::unique_ptr<TDigest_c> sphCreateTDigest() { return std::make_unique<TDigest_c>(); }
4,829
C++
.cpp
187
22.754011
127
0.645203
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,055
mm.cpp
manticoresoftware_manticoresearch/src/std/mm.cpp
// // 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 "mm.h" #include <cassert> #if _WIN32 #include <cstdlib> void* mmalloc ( size_t uSize, Mode_e, Share_e ) { return ::malloc ( (size_t)uSize ); } bool mmapvalid ( const void* pMem ) { return pMem != nullptr; } int mmfree ( void* pMem, size_t ) { assert ( mmapvalid ( pMem ) ); ::free ( pMem ); return 0; } void mmadvise ( void*, size_t, Advise_e ) {} bool mmlock ( void* pMem, size_t uSize ) { return VirtualLock ( pMem, uSize ) != 0; } bool mmunlock ( void* pMem, size_t uSize ) { return VirtualUnlock ( pMem, uSize ) != 0; } #else #include <sys/mman.h> // couple of helpers int hwShare ( Share_e eAccess ) { switch ( eAccess ) { case Share_e::ANON_PRIVATE: return MAP_ANON | MAP_PRIVATE; case Share_e::ANON_SHARED: return MAP_ANON | MAP_SHARED; case Share_e::SHARED: return MAP_SHARED; } return MAP_SHARED; } int hwMode ( Mode_e eMode ) { switch ( eMode ) { case Mode_e::NONE: return PROT_NONE; case Mode_e::READ: return PROT_READ; case Mode_e::WRITE: return PROT_WRITE; case Mode_e::RW: return PROT_READ | PROT_WRITE; } return PROT_READ | PROT_WRITE; } void* mmalloc ( size_t uSize, Mode_e eMode, Share_e eAccess ) { return mmap ( NULL, uSize, hwMode ( eMode ), hwShare ( eAccess ), -1, 0 ); } bool mmapvalid ( const void* pMem ) { return pMem != MAP_FAILED; } int mmfree ( void* pMem, size_t uSize ) { assert ( mmapvalid ( pMem ) ); return munmap ( pMem, uSize ); } void mmadvise ( void* pMem, size_t uSize, Advise_e eAdvise ) { switch ( eAdvise ) { case Advise_e::NODUMP: #ifdef MADV_DONTDUMP madvise ( pMem, uSize, MADV_DONTDUMP ); #endif break; case Advise_e::NOFORK: madvise ( pMem, uSize, #ifdef MADV_DONTFORK MADV_DONTFORK #else MADV_NORMAL #endif ); break; } } bool mmlock ( void* pMem, size_t uSize ) { return mlock ( pMem, uSize ) == 0; } bool mmunlock ( void* pMem, size_t uSize ) { return munlock ( pMem, uSize ) == 0; } #endif // _WIN32
2,402
C++
.cpp
104
21.442308
80
0.697236
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,056
env.cpp
manticoresoftware_manticoresearch/src/std/env.cpp
// // 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 "env.h" #include "sphinxutils.h" #ifdef _WIN32 #include "fileutils.h" #endif ///////////////////////////////////////////////////////////////////////////// // HELPERS ///////////////////////////////////////////////////////////////////////////// bool val_from_env ( const char* szEnvName, bool bDefault ) { if ( getenv ( szEnvName ) ) return true; return bDefault; } int val_from_env ( const char* szEnvName, int iDefault ) { int iRes = iDefault; const char* szEnv = getenv ( szEnvName ); if ( szEnv ) { char* szEnd = nullptr; iRes = strtol ( szEnv, &szEnd, 10 ); if ( *szEnd != '\0' ) sphWarning ( "%s expects to be numeric. %s provided, failed to parse as numeric since %s", szEnvName, szEnv, szEnd ); } return iRes; } DWORD dwval_from_env ( const char* szEnvName, DWORD uDefault ) { DWORD uRes = uDefault; const char* szEnv = getenv ( szEnvName ); if ( szEnv ) { char* szEnd = nullptr; uRes = strtoul ( szEnv, &szEnd, 10 ); if ( *szEnd != '\0' ) sphWarning ( "%s expects to be numeric. %s provided, failed to parse as numeric since %s", szEnvName, szEnv, szEnd ); } return uRes; } // absolute path from outside, as /usr/share/manticore, when prefix / or /usr. Or /usr/local/share/manticore if prefix /usr/local/ const char* GET_FULL_SHARE_DIR() { const char* szEnv = getenv ( "FULL_SHARE_DIR" ); if ( szEnv ) return szEnv; #if _WIN32 CSphString sInstallDir = GetWinInstallDir(); if ( !sInstallDir.IsEmpty() ) { static CSphString sShare; sShare.SetSprintf ( "%s/share", sInstallDir.cstr() ); return sShare.cstr(); } #endif return FULL_SHARE_DIR; } // galera_soname must be provided by configuration. CSphString GET_GALERA_FULLPATH() { CSphString sResult; const char* szEnv = getenv ( "GALERA_SONAME" ); if ( szEnv ) sResult = szEnv; else sResult.SetSprintf ( "%s/%s", GET_MANTICORE_MODULES(), GALERA_SONAME ); return sResult; } CSphString GetColumnarFullpath() { CSphString sResult; const char* szEnv = getenv ( "LIB_MANTICORE_COLUMNAR" ); if ( szEnv ) sResult = szEnv; else sResult.SetSprintf ( "%s/" LIB_MANTICORE_COLUMNAR, GET_MANTICORE_MODULES() ); return sResult; } CSphString GetSecondaryFullpath() { CSphString sResult; const char* szEnv = getenv ( "LIB_MANTICORE_SECONDARY" ); if ( szEnv ) sResult = szEnv; else sResult.SetSprintf ( "%s/" LIB_MANTICORE_SECONDARY, GET_MANTICORE_MODULES() ); return sResult; } CSphString GetKNNFullpath() { CSphString sResult; const char* szEnv = getenv ( "LIB_MANTICORE_KNN" ); if ( szEnv ) sResult = szEnv; else sResult.SetSprintf ( "%s/" LIB_MANTICORE_KNN, GET_MANTICORE_MODULES() ); return sResult; } static CSphString GetSegmentationDataPath ( const char * szEnvVar, const char * szDir, const char * szMask ) { const char* szEnv = getenv(szEnvVar); if ( szEnv ) return szEnv; #ifdef _WIN32 CSphString sPathToExe = GetPathOnly ( GetExecutablePath() ); CSphString sPathToData; sPathToData.SetSprintf ( "%s/../share/%s/", sPathToExe.cstr(), szDir ); sPathToData = sphNormalizePath ( sPathToData ); CSphString sSearch; sSearch.SetSprintf ( "%s/%s", sPathToData.cstr(), szMask ); StrVec_t dFiles = FindFiles ( sSearch.cstr(), false ); if ( dFiles.GetLength() ) return sPathToData; #endif CSphString sInitModulesPrefix; sInitModulesPrefix.SetSprintf ( "%s/%s", GET_FULL_SHARE_DIR(), szDir ); return sInitModulesPrefix; } CSphString GetICUDataDir() { return GetSegmentationDataPath ( "ICU_DATA_DIR", "icu", "icudt*.dat" ); } CSphString GetJiebaDataDir() { return GetSegmentationDataPath ( "JIEBA_DATA_DIR", "jieba", "*.utf8" ); } const char* GET_MANTICORE_MODULES() { const char* szEnv = getenv ( "MANTICORE_MODULES" ); if ( szEnv ) return szEnv; static CSphString sModulesPrefix; if ( sModulesPrefix.IsEmpty() ) { CSphString sInitModulesPrefix; sInitModulesPrefix.SetSprintf ( "%s/modules", GET_FULL_SHARE_DIR() ); sModulesPrefix.Swap ( sInitModulesPrefix ); } return sModulesPrefix.cstr(); }
4,464
C++
.cpp
151
27.582781
130
0.698646
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,057
mem.cpp
manticoresoftware_manticoresearch/src/std/mem.cpp
// // 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 "mem.h" #include "format.h" #include "fatal.h" #include <cstdlib> ///////////////////////////////////////////////////////////////////////////// // DEBUG MEMORY MANAGER ///////////////////////////////////////////////////////////////////////////// #if SPH_DEBUG_LEAKS #undef new #define SPH_DEBUG_DOFREE 1 // 0 will not actually free returned blocks; helps to catch double deletes etc const DWORD MEMORY_MAGIC_PLAIN = 0xbbbbbbbbUL; const DWORD MEMORY_MAGIC_ARRAY = 0xaaaaaaaaUL; const DWORD MEMORY_MAGIC_END = 0xeeeeeeeeUL; const DWORD MEMORY_MAGIC_DELETED = 0xdedededeUL; struct CSphMemHeader { DWORD m_uMagic; const char* m_sFile; #if SPH_DEBUG_BACKTRACES const char* m_sBacktrace; #endif int m_iLine; size_t m_iSize; int m_iAllocId; BYTE* m_pPointer; CSphMemHeader* m_pNext; CSphMemHeader* m_pPrev; }; static CSphMutex g_tAllocsMutex; static int g_iCurAllocs = 0; static int g_iAllocsId = 0; static CSphMemHeader* g_pAllocs = NULL; static int64_t g_iCurBytes = 0; static int g_iTotalAllocs = 0; static int g_iPeakAllocs = 0; static int64_t g_iPeakBytes = 0; #if SPH_ALLOC_FILL static bool g_bFirstRandomAlloc = true; #endif void* sphDebugNew ( size_t iSize, const char* sFile, int iLine, bool bArray ) { BYTE* pBlock = (BYTE*)::malloc ( iSize + sizeof ( CSphMemHeader ) + sizeof ( DWORD ) ); if ( !pBlock ) sphDie ( "out of memory (unable to allocate " UINT64_FMT " bytes)", (uint64_t)iSize ); // FIXME! this may fail with malloc error too *(DWORD*)( pBlock + iSize + sizeof ( CSphMemHeader ) ) = MEMORY_MAGIC_END; g_tAllocsMutex.Lock(); CSphMemHeader* pHeader = (CSphMemHeader*)pBlock; pHeader->m_uMagic = bArray ? MEMORY_MAGIC_ARRAY : MEMORY_MAGIC_PLAIN; pHeader->m_sFile = sFile; #if SPH_ALLOC_FILL if ( g_bFirstRandomAlloc ) { sphAutoSrand(); g_bFirstRandomAlloc = false; } BYTE* pBlockPtr = (BYTE*)( pHeader + 1 ); for ( size_t i = 0; i < iSize; i++ ) *pBlockPtr++ = BYTE ( sphRand() & 0xFF ); #endif #if SPH_DEBUG_BACKTRACES const char* sTrace = DoBacktrace ( 0, 3 ); if ( sTrace ) { char* pTrace = (char*)::malloc ( strlen ( sTrace ) + 1 ); strcpy ( pTrace, sTrace ); // NOLINT pHeader->m_sBacktrace = pTrace; } else pHeader->m_sBacktrace = NULL; #endif pHeader->m_iLine = iLine; pHeader->m_iSize = iSize; pHeader->m_iAllocId = ++g_iAllocsId; pHeader->m_pPointer = pBlock; pHeader->m_pNext = g_pAllocs; pHeader->m_pPrev = NULL; if ( g_pAllocs ) { assert ( !g_pAllocs->m_pPrev ); g_pAllocs->m_pPrev = pHeader; } g_pAllocs = pHeader; g_iCurAllocs++; g_iCurBytes += iSize; g_iTotalAllocs++; g_iPeakAllocs = Max ( g_iPeakAllocs, g_iCurAllocs ); g_iPeakBytes = Max ( g_iPeakBytes, g_iCurBytes ); g_tAllocsMutex.Unlock(); return pHeader + 1; } void sphDebugDelete ( void* pPtr, bool bArray ) { if ( !pPtr ) return; g_tAllocsMutex.Lock(); CSphMemHeader* pHeader = ( (CSphMemHeader*)pPtr ) - 1; switch ( pHeader->m_uMagic ) { case MEMORY_MAGIC_ARRAY: if ( !bArray ) sphDie ( "delete [] on non-array block %d allocated at %s(%d)", pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine ); break; case MEMORY_MAGIC_PLAIN: if ( bArray ) sphDie ( "delete on array block %d allocated at %s(%d)", pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine ); break; case MEMORY_MAGIC_DELETED: sphDie ( "double delete on block %d allocated at %s(%d)", pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine ); break; default: sphDie ( "delete on unmanaged block at 0x%08x", pPtr ); return; } BYTE* pBlock = (BYTE*)pHeader; if ( *(DWORD*)( pBlock + pHeader->m_iSize + sizeof ( CSphMemHeader ) ) != MEMORY_MAGIC_END ) sphDie ( "out-of-bounds write beyond block %d allocated at %s(%d)", pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine ); // unchain if ( pHeader == g_pAllocs ) g_pAllocs = g_pAllocs->m_pNext; if ( pHeader->m_pPrev ) { assert ( pHeader->m_pPrev->m_uMagic == MEMORY_MAGIC_PLAIN || pHeader->m_pPrev->m_uMagic == MEMORY_MAGIC_ARRAY ); pHeader->m_pPrev->m_pNext = pHeader->m_pNext; } if ( pHeader->m_pNext ) { assert ( pHeader->m_pNext->m_uMagic == MEMORY_MAGIC_PLAIN || pHeader->m_pNext->m_uMagic == MEMORY_MAGIC_ARRAY ); pHeader->m_pNext->m_pPrev = pHeader->m_pPrev; } pHeader->m_pPrev = NULL; pHeader->m_pNext = NULL; // mark and delete pHeader->m_uMagic = MEMORY_MAGIC_DELETED; g_iCurAllocs--; g_iCurBytes -= pHeader->m_iSize; #if SPH_DEBUG_BACKTRACES if ( pHeader->m_sBacktrace ) ::free ( (void*)pHeader->m_sBacktrace ); #endif #if SPH_DEBUG_DOFREE ::free ( pHeader ); #endif g_tAllocsMutex.Unlock(); } int64_t sphAllocBytes() { return g_iCurBytes; } int sphAllocsCount() { return g_iCurAllocs; } int sphAllocsLastID() { return g_iAllocsId; } void sphAllocsDump ( int iFile, int iSinceID ) { g_tAllocsMutex.Lock(); sphSafeInfo ( iFile, "--- dumping allocs since %d ---\n", iSinceID ); uint64_t iTotalBytes = 0; int iTotal = 0; for ( CSphMemHeader* pHeader = g_pAllocs; pHeader && pHeader->m_iAllocId > iSinceID; pHeader = pHeader->m_pNext ) { sphSafeInfo ( iFile, "alloc %d at %s(%d): 0x%0p %d bytes\n", pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine, pHeader->m_pPointer, (int)pHeader->m_iSize ); #if SPH_DEBUG_BACKTRACES sphSafeInfo ( iFile, "Backtrace:\n%s\n", pHeader->m_sBacktrace ); #endif iTotalBytes += pHeader->m_iSize; iTotal++; } sphSafeInfo ( iFile, "total allocs %d: %d.%03d bytes", iTotal, (int)( iTotalBytes / 1024 ), (int)( iTotalBytes % 1000 ) ); sphSafeInfo ( iFile, "--- end of dump ---\n" ); g_tAllocsMutex.Unlock(); } void sphAllocsStats() { fprintf ( stdout, "--- total-allocs=%d, peak-allocs=%d, peak-bytes=" INT64_FMT "\n", g_iTotalAllocs, g_iPeakAllocs, g_iPeakBytes ); } void sphAllocsCheck() { g_tAllocsMutex.Lock(); for ( CSphMemHeader* pHeader = g_pAllocs; pHeader; pHeader = pHeader->m_pNext ) { BYTE* pBlock = (BYTE*)pHeader; if ( !( pHeader->m_uMagic == MEMORY_MAGIC_ARRAY || pHeader->m_uMagic == MEMORY_MAGIC_PLAIN ) ) sphDie ( "corrupted header in block %d allocated at %s(%d)", pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine ); if ( *(DWORD*)( pBlock + pHeader->m_iSize + sizeof ( CSphMemHeader ) ) != MEMORY_MAGIC_END ) sphDie ( "out-of-bounds write beyond block %d allocated at %s(%d)", pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine ); } g_tAllocsMutex.Unlock(); } void sphMemStatInit() {} void sphMemStatDone() {} void sphMemStatDump ( int ) {} ////////////////////////////////////////////////////////////////////////// void* operator new ( size_t iSize, const char* sFile, int iLine ) { return sphDebugNew ( iSize, sFile, iLine, false ); } void* operator new[] ( size_t iSize, const char* sFile, int iLine ) { return sphDebugNew ( iSize, sFile, iLine, true ); } void operator delete ( void* pPtr ) MYTHROW() { sphDebugDelete ( pPtr, false ); } void operator delete[] ( void* pPtr ) MYTHROW() { sphDebugDelete ( pPtr, true ); } /// debug allocate to use in custom allocator void* debugallocate ( size_t iSize ) { return sphDebugNew ( iSize, __FILE__, __LINE__, false ); } /// debug deallocate to use in custom allocator void debugdeallocate ( void* pPtr ) { sphDebugDelete ( pPtr, false ); } ////////////////////////////////////////////////////////////////////////////// // ALLOCACTIONS COUNT/SIZE PROFILER ////////////////////////////////////////////////////////////////////////////// #elif SPH_ALLOCS_PROFILER #undef new static CSphMutex g_tAllocsMutex; static int g_iAllocsId = 0; static int g_iCurAllocs = 0; static int64_t g_iCurBytes = 0; static int g_iTotalAllocs = 0; static int g_iPeakAllocs = 0; static int64_t g_iPeakBytes = 0; // statictic's per memory category struct MemCategorized_t { int64_t m_iSize; int m_iCount; MemCategorized_t() : m_iSize ( 0 ) , m_iCount ( 0 ) { } }; static MemCategory_e sphMemStatGet(); // memory categories storage static MemCategorized_t g_dMemCategoryStat[MEM_TOTAL]; ////////////////////////////////////////////////////////////////////////// // ALLOCATIONS COUNT/SIZE PROFILER ////////////////////////////////////////////////////////////////////////// void* sphDebugNew ( size_t iSize ) { BYTE* pBlock = (BYTE*)::malloc ( iSize + sizeof ( size_t ) * 2 ); if ( !pBlock ) sphDie ( "out of memory (unable to allocate %" PRIu64 " bytes)", (uint64_t)iSize ); // FIXME! this may fail with malloc error too const int iMemType = sphMemStatGet(); assert ( iMemType >= 0 && iMemType < MEM_TOTAL ); g_tAllocsMutex.Lock(); g_iAllocsId++; g_iCurAllocs++; g_iCurBytes += iSize; g_iTotalAllocs++; g_iPeakAllocs = Max ( g_iCurAllocs, g_iPeakAllocs ); g_iPeakBytes = Max ( g_iCurBytes, g_iPeakBytes ); g_dMemCategoryStat[iMemType].m_iSize += iSize; g_dMemCategoryStat[iMemType].m_iCount++; g_tAllocsMutex.Unlock(); size_t* pData = (size_t*)pBlock; pData[0] = iSize; pData[1] = iMemType; return pBlock + sizeof ( size_t ) * 2; } void sphDebugDelete ( void* pPtr ) { if ( !pPtr ) return; size_t* pBlock = (size_t*)pPtr; pBlock -= 2; const int iSize = pBlock[0]; const int iMemType = pBlock[1]; assert ( iMemType >= 0 && iMemType < MEM_TOTAL ); g_tAllocsMutex.Lock(); g_iCurAllocs--; g_iCurBytes -= iSize; g_dMemCategoryStat[iMemType].m_iSize -= iSize; g_dMemCategoryStat[iMemType].m_iCount--; g_tAllocsMutex.Unlock(); ::free ( pBlock ); } void sphAllocsStats() { g_tAllocsMutex.Lock(); fprintf ( stdout, "--- total-allocs=%d, peak-allocs=%d, peak-bytes=" INT64_FMT "\n", g_iTotalAllocs, g_iPeakAllocs, g_iPeakBytes ); g_tAllocsMutex.Unlock(); } int64_t sphAllocBytes() { return g_iCurBytes; } int sphAllocsCount() { return g_iCurAllocs; } int sphAllocsLastID() { return g_iAllocsId; } void sphAllocsDump ( int, int ) {} void sphAllocsCheck() {} void* operator new ( size_t iSize, const char*, int ) { return sphDebugNew ( iSize ); } void* operator new[] ( size_t iSize, const char*, int ) { return sphDebugNew ( iSize ); } void operator delete ( void* pPtr ) MYTHROW() { sphDebugDelete ( pPtr ); } void operator delete[] ( void* pPtr ) MYTHROW() { sphDebugDelete ( pPtr ); } /// debug allocate to use in custom allocator void* debugallocate ( size_t iSize ) { return sphDebugNew ( iSize ); } /// debug deallocate to use in custom allocator void debugdeallocate ( void* pPtr ) { sphDebugDelete ( pPtr ); } ////////////////////////////////////////////////////////////////////////////// // MEMORY STATISTICS ////////////////////////////////////////////////////////////////////////////// STATIC_ASSERT ( MEM_TOTAL < 255, TOO_MANY_MEMORY_CATEGORIES ); // stack of memory categories as we move deeper and deeper class MemCategoryStack_t // NOLINT { #define MEM_STACK_MAX 1024 BYTE m_dStack[MEM_STACK_MAX]; int m_iDepth; public: // ctor ( cross platform ) void Reset() { m_iDepth = 0; m_dStack[0] = MEM_CORE; } void Push ( MemCategory_e eCategory ) { assert ( eCategory >= 0 && eCategory < MEM_TOTAL ); assert ( m_iDepth + 1 < MEM_STACK_MAX ); m_dStack[++m_iDepth] = (BYTE)eCategory; } #ifndef NDEBUG void Pop ( MemCategory_e eCategory ) { assert ( eCategory >= 0 && eCategory < MEM_TOTAL ); #else void Pop ( MemCategory_e ) { #endif assert ( m_iDepth - 1 >= 0 ); assert ( m_dStack[m_iDepth] == eCategory ); m_iDepth--; } MemCategory_e Top() const { assert ( m_iDepth >= 0 && m_iDepth < MEM_STACK_MAX ); assert ( m_dStack[m_iDepth] >= 0 && m_dStack[m_iDepth] < MEM_TOTAL ); return MemCategory_e ( m_dStack[m_iDepth] ); } }; /// TLS key of memory category stack thread_local MemCategoryStack_t* g_tTLSMemCategory; static MemCategoryStack_t* g_pMainTLS = NULL; // category stack of main thread // memory statistic's per thread factory void* sphMemStatThdInit() { MemCategoryStack_t* pTLS = (MemCategoryStack_t*)sphDebugNew ( sizeof ( MemCategoryStack_t ) ); pTLS->Reset(); g_tTLSMemCategory = pTLS; return pTLS; } // per thread cleanup of memory statistic's void sphMemStatThdCleanup ( void* pTLS ) { sphDebugDelete ( (MemCategoryStack_t*)pTLS ); } // init of memory statistic's data void sphMemStatInit() { // main thread statistic's creation assert ( g_pMainTLS == NULL ); g_pMainTLS = (MemCategoryStack_t*)sphMemStatThdInit(); assert ( g_pMainTLS != NULL ); } // cleanup of memory statistic's data void sphMemStatDone() { assert ( g_pMainTLS != NULL ); sphMemStatThdCleanup ( g_pMainTLS ); } // direct access for special category void sphMemStatMMapAdd ( int64_t iSize ) { g_tAllocsMutex.Lock(); g_iCurAllocs++; g_iCurBytes += iSize; g_iTotalAllocs++; g_iPeakAllocs = Max ( g_iCurAllocs, g_iPeakAllocs ); g_iPeakBytes = Max ( g_iCurBytes, g_iPeakBytes ); g_dMemCategoryStat[MEM_MMAPED].m_iSize += iSize; g_dMemCategoryStat[MEM_MMAPED].m_iCount++; g_tAllocsMutex.Unlock(); } void sphMemStatMMapDel ( int64_t iSize ) { g_tAllocsMutex.Lock(); g_iCurAllocs--; g_iCurBytes -= iSize; g_dMemCategoryStat[MEM_MMAPED].m_iSize -= iSize; g_dMemCategoryStat[MEM_MMAPED].m_iCount--; g_tAllocsMutex.Unlock(); } // push new category on arrival void sphMemStatPush ( MemCategory_e eCategory ) { MemCategoryStack_t* pTLS = g_tTLSMemCategory; if ( pTLS ) pTLS->Push ( eCategory ); }; // restore last category void sphMemStatPop ( MemCategory_e eCategory ) { MemCategoryStack_t* pTLS = g_tTLSMemCategory; if ( pTLS ) pTLS->Pop ( eCategory ); }; // get current category static MemCategory_e sphMemStatGet() { MemCategoryStack_t* pTLS = g_tTLSMemCategory; return pTLS ? pTLS->Top() : MEM_CORE; } // human readable category names #define MEM_CATEGORY( _arg ) #_arg static const char* g_dMemCategoryName[] = { MEM_CATEGORIES }; #undef MEM_CATEGORY void sphMemStatDump ( int iFD ) { int64_t iSize = 0; int iCount = 0; for ( int i = 0; i < MEM_TOTAL; i++ ) { iSize += (int64_t)g_dMemCategoryStat[i].m_iSize; iCount += g_dMemCategoryStat[i].m_iCount; } sphSafeInfo ( iFD, "%-24s allocs-count=%d, mem-total=%d.%d Mb", "(total)", iCount, (int)( iSize / 1048576 ), (int)( ( iSize * 10 / 1048576 ) % 10 ) ); for ( int i = 0; i < MEM_TOTAL; i++ ) if ( g_dMemCategoryStat[i].m_iCount > 0 ) { iSize = (int64_t)g_dMemCategoryStat[i].m_iSize; sphSafeInfo ( iFD, "%-24s allocs-count=%d, mem-total=%d.%d Mb", g_dMemCategoryName[i], g_dMemCategoryStat[i].m_iCount, (int)( iSize / 1048576 ), (int)( ( iSize * 10 / 1048576 ) % 10 ) ); } } ////////////////////////////////////////////////////////////////////////////// // PRODUCTION MEMORY MANAGER ////////////////////////////////////////////////////////////////////////////// #elif !DISABLE_MEMROUTINES void* operator new ( std::size_t iSize ) { void* pResult = std::malloc ( iSize ); if ( !pResult ) sphDieRestart ( "out of memory (unable to allocate " UINT64_FMT " bytes)", (uint64_t)iSize ); // FIXME! this may fail with malloc error too return pResult; } void operator delete ( void* pPtr ) noexcept { std::free ( pPtr ); } /* According to https://en.cppreference.com/w/cpp/memory/new/operator_new, code below is not necessary void* operator new[] ( size_t iSize ) { void* pResult = ::malloc ( iSize ); if ( !pResult ) sphDieRestart ( "out of memory (unable to allocate " UINT64_FMT " bytes)", (uint64_t)iSize ); // FIXME! this may fail with malloc error too return pResult; } void operator delete[] ( void* pPtr ) throw() { if ( pPtr ) ::free ( pPtr ); } */ #endif // DISABLE_MEMROUTINES ////////////////////////////////////////////////////////////////////////// // now let the rest of sphinxstd use proper new #if SPH_DEBUG_LEAKS || SPH_ALLOCS_PROFILER #undef new #define new new ( __FILE__, __LINE__ ) #endif
16,164
C++
.cpp
537
28.068901
189
0.660599
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,058
fatal.cpp
manticoresoftware_manticoresearch/src/std/fatal.cpp
// // 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 "fatal.h" #include <cstdlib> #include <cstdio> #include "sphinxutils.h" namespace { volatile bool& IsDied() { static bool bDied = false; return bDied; } SphDieCallback_t& pfDieCallback() { static SphDieCallback_t g_pfDieCallback = nullptr; return g_pfDieCallback; } } // namespace bool sphIsDied() { return IsDied(); } void sphSetDied() { IsDied() = true; } void sphSetDieCallback ( SphDieCallback_t pDieCallback ) { pfDieCallback() = pDieCallback; } void sphDieVa ( const char* sFmt, va_list ap ) { // if there's no callback, // or if callback returns true, // log to stdout sphSetDied(); if ( !pfDieCallback() || pfDieCallback() ( true, sFmt, ap ) ) { char sBuf[1024]; vsnprintf ( sBuf, sizeof ( sBuf ), sFmt, ap ); fprintf ( stdout, "FATAL: %s\n", sBuf ); } } void sphDie ( const char* sFmt, ... ) { va_list ap; va_start ( ap, sFmt ); sphDieVa ( sFmt, ap ); va_end ( ap ); exit ( 1 ); } void sphDieRestart ( const char* sFmt, ... ) { va_list ap; va_start ( ap, sFmt ); sphDieVa ( sFmt, ap ); va_end ( ap ); sphQuickExit ( 2 ); // almost CRASH_EXIT } void sphFatalVa ( const char* sFmt, va_list ap ) { g_pLogger() ( SPH_LOG_FATAL, sFmt, ap ); if ( pfDieCallback() ) pfDieCallback() ( false, sFmt, ap ); exit ( 1 ); } void sphFatal ( const char* sFmt, ... ) { va_list ap; va_start ( ap, sFmt ); g_pLogger() ( SPH_LOG_FATAL, sFmt, ap ); if ( pfDieCallback() ) pfDieCallback() ( false, sFmt, ap ); va_end ( ap ); exit ( 1 ); } void sphFatalLog ( const char* sFmt, ... ) { va_list ap; va_start ( ap, sFmt ); g_pLogger() ( SPH_LOG_FATAL, sFmt, ap ); va_end ( ap ); }
2,108
C++
.cpp
93
21.021505
80
0.67982
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,059
ha_sphinx.cc
manticoresoftware_manticoresearch/mysqlse/ha_sphinx.cc
// // Copyright (c) 2001-2016, Andrew Aksyonoff // Copyright (c) 2008-2016, Sphinx Technologies Inc // Copyright (c) 2017-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/ // #ifdef USE_PRAGMA_IMPLEMENTATION #pragma implementation // gcc: Class implementation #endif #if _MSC_VER>=1400 #define _CRT_SECURE_NO_DEPRECATE 1 #define _CRT_NONSTDC_NO_DEPRECATE 1 #endif #include <mysql_version.h> #if MYSQL_VERSION_ID>=50515 #include "sql_class.h" #include "sql_array.h" #elif MYSQL_VERSION_ID>50100 #include "mysql_priv.h" #include <mysql/plugin.h> #else #include "../mysql_priv.h" #endif #include <mysys_err.h> #include <my_sys.h> #include <mysql.h> // include client for INSERT table (sort of redoing federated..) #ifndef __WIN__ // UNIX-specific #include <my_net.h> #include <netdb.h> #include <sys/un.h> #define RECV_FLAGS MSG_WAITALL #define sphSockClose(_sock) ::close(_sock) #else // Windows-specific #include <io.h> #define strcasecmp stricmp #define snprintf _snprintf #define RECV_FLAGS 0 #define sphSockClose(_sock) ::closesocket(_sock) #endif #include <ctype.h> #include "ha_sphinx.h" #ifndef MSG_WAITALL #define MSG_WAITALL 0 #endif #if _MSC_VER>=1400 #pragma warning(push,4) #endif ///////////////////////////////////////////////////////////////////////////// /// there might be issues with min() on different platforms (eg. Gentoo, they say) #define Min(a,b) ((a)<(b)?(a):(b)) /// unaligned RAM accesses are forbidden on SPARC #if defined(sparc) || defined(__sparc__) #define UNALIGNED_RAM_ACCESS 0 #else #define UNALIGNED_RAM_ACCESS 1 #endif #if UNALIGNED_RAM_ACCESS /// pass-through wrapper template < typename T > inline T sphUnalignedRead ( const T & tRef ) { return tRef; } /// pass-through wrapper template < typename T > void sphUnalignedWrite ( void * pPtr, const T & tVal ) { *(T*)pPtr = tVal; } #else /// unaligned read wrapper for some architectures (eg. SPARC) template < typename T > inline T sphUnalignedRead ( const T & tRef ) { T uTmp; byte * pSrc = (byte *) &tRef; byte * pDst = (byte *) &uTmp; for ( int i=0; i<(int)sizeof(T); i++ ) *pDst++ = *pSrc++; return uTmp; } /// unaligned write wrapper for some architectures (eg. SPARC) template < typename T > void sphUnalignedWrite ( void * pPtr, const T & tVal ) { byte * pDst = (byte *) pPtr; byte * pSrc = (byte *) &tVal; for ( int i=0; i<(int)sizeof(T); i++ ) *pDst++ = *pSrc++; } #endif #if MYSQL_VERSION_ID>=50515 #define sphinx_hash_init my_hash_init #define sphinx_hash_free my_hash_free #define sphinx_hash_search my_hash_search #define sphinx_hash_delete my_hash_delete #else #define sphinx_hash_init hash_init #define sphinx_hash_free hash_free #define sphinx_hash_search hash_search #define sphinx_hash_delete hash_delete #endif ///////////////////////////////////////////////////////////////////////////// // FIXME! make this all dynamic #define SPHINXSE_MAX_FILTERS 32 #define SPHINXAPI_DEFAULT_HOST "127.0.0.1" #define SPHINXAPI_DEFAULT_PORT 9312 #define SPHINXAPI_DEFAULT_INDEX "*" #define SPHINXQL_DEFAULT_PORT 9306 #define SPHINXSE_SYSTEM_COLUMNS 3 #define SPHINXSE_MAX_ALLOC (16*1024*1024) #define SPHINXSE_MAX_KEYWORDSTATS 4096 #define SPHINXSE_VERSION "2.3.3-dev" // FIXME? the following is cut-n-paste from sphinx.h and searchd.cpp // cut-n-paste is somewhat simpler that adding dependencies however.. enum { SPHINX_SEARCHD_PROTO = 1, SEARCHD_COMMAND_SEARCH = 0, VER_COMMAND_SEARCH = 0x119, }; /// search query sorting orders enum ESphSortOrder { SPH_SORT_RELEVANCE = 0, ///< sort by document relevance desc, then by date SPH_SORT_ATTR_DESC = 1, ///< sort by document date desc, then by relevance desc SPH_SORT_ATTR_ASC = 2, ///< sort by document date asc, then by relevance desc SPH_SORT_TIME_SEGMENTS = 3, ///< sort by time segments (hour/day/week/etc) desc, then by relevance desc SPH_SORT_EXTENDED = 4, ///< sort by SQL-like expression (eg. "@relevance DESC, price ASC, @id DESC") SPH_SORT_EXPR = 5, ///< sort by expression SPH_SORT_TOTAL }; /// search query matching mode enum ESphMatchMode { SPH_MATCH_ALL = 0, ///< match all query words SPH_MATCH_ANY, ///< match any query word SPH_MATCH_PHRASE, ///< match this exact phrase SPH_MATCH_BOOLEAN, ///< match this boolean query SPH_MATCH_EXTENDED, ///< match this extended query SPH_MATCH_FULLSCAN, ///< match all document IDs w/o fulltext query, apply filters SPH_MATCH_EXTENDED2, ///< extended engine V2 SPH_MATCH_TOTAL }; /// search query relevance ranking mode enum ESphRankMode { SPH_RANK_PROXIMITY_BM25 = 0, ///< default mode, phrase proximity major factor and BM25 minor one SPH_RANK_BM25 = 1, ///< statistical mode, BM25 ranking only (faster but worse quality) SPH_RANK_NONE = 2, ///< no ranking, all matches get a weight of 1 SPH_RANK_WORDCOUNT = 3, ///< simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts SPH_RANK_PROXIMITY = 4, ///< phrase proximity SPH_RANK_MATCHANY = 5, ///< emulate old match-any weighting SPH_RANK_FIELDMASK = 6, ///< sets bits where there were matches SPH_RANK_SPH04 = 7, ///< codename SPH04, phrase proximity + bm25 + head/exact boost SPH_RANK_EXPR = 8, ///< expression based ranker SPH_RANK_TOTAL, SPH_RANK_DEFAULT = SPH_RANK_PROXIMITY_BM25 }; /// search query grouping mode enum ESphGroupBy { SPH_GROUPBY_DAY = 0, ///< group by day SPH_GROUPBY_WEEK = 1, ///< group by week SPH_GROUPBY_MONTH = 2, ///< group by month SPH_GROUPBY_YEAR = 3, ///< group by year SPH_GROUPBY_ATTR = 4 ///< group by attribute value }; /// known attribute types enum { SPH_ATTR_NONE = 0, ///< not an attribute at all SPH_ATTR_INTEGER = 1, ///< this attr is just an integer SPH_ATTR_TIMESTAMP = 2, ///< this attr is a timestamp SPH_ATTR_ORDINAL = 3, ///< this attr is an ordinal string number (integer at search time, specially handled at indexing time) SPH_ATTR_BOOL = 4, ///< this attr is a boolean bit field SPH_ATTR_FLOAT = 5, SPH_ATTR_BIGINT = 6, SPH_ATTR_STRING = 7, ///< string (binary; in-memory) SPH_ATTR_UINT32SET = 0x40000001UL, ///< this attr is multiple int32 values (0 or more) SPH_ATTR_UINT64SET = 0x40000002UL ///< this attr is multiple int64 values (0 or more) }; /// known answers enum { SEARCHD_OK = 0, ///< general success, command-specific reply follows SEARCHD_ERROR = 1, ///< general failure, error message follows SEARCHD_RETRY = 2, ///< temporary failure, error message follows, client should retry later SEARCHD_WARNING = 3 ///< general success, warning message and command-specific reply follow }; ////////////////////////////////////////////////////////////////////////////// #define SPHINX_DEBUG_OUTPUT 0 #define SPHINX_DEBUG_CALLS 0 #include <stdarg.h> #if SPHINX_DEBUG_OUTPUT inline void SPH_DEBUG ( const char * format, ... ) { va_list ap; va_start ( ap, format ); fprintf ( stderr, "SphinxSE: " ); vfprintf ( stderr, format, ap ); fprintf ( stderr, "\n" ); va_end ( ap ); } #else inline void SPH_DEBUG ( const char *, ... ) {} #endif #if SPHINX_DEBUG_CALLS #define SPH_ENTER_FUNC() { SPH_DEBUG ( "enter %s", __FUNCTION__ ); } #define SPH_ENTER_METHOD() { SPH_DEBUG ( "enter %s(this=%08x)", __FUNCTION__, this ); } #define SPH_RET(_arg) { SPH_DEBUG ( "leave %s", __FUNCTION__ ); return _arg; } #define SPH_VOID_RET() { SPH_DEBUG ( "leave %s", __FUNCTION__ ); return; } #else #define SPH_ENTER_FUNC() #define SPH_ENTER_METHOD() #define SPH_RET(_arg) { return(_arg); } #define SPH_VOID_RET() { return; } #endif #define SafeDelete(_arg) { if ( _arg ) delete ( _arg ); (_arg) = NULL; } #define SafeDeleteArray(_arg) { if ( _arg ) delete [] ( _arg ); (_arg) = NULL; } ////////////////////////////////////////////////////////////////////////////// /// per-table structure that will be shared among all open Sphinx SE handlers struct CSphSEShare { pthread_mutex_t m_tMutex; THR_LOCK m_tLock; char * m_sTable; char * m_sScheme; ///< our connection string char * m_sHost; ///< points into m_sScheme buffer, DO NOT FREE EXPLICITLY char * m_sSocket; ///< points into m_sScheme buffer, DO NOT FREE EXPLICITLY char * m_sIndex; ///< points into m_sScheme buffer, DO NOT FREE EXPLICITLY ushort m_iPort; bool m_bSphinxQL; ///< is this read-only SphinxAPI table, or write-only SphinxQL table? uint m_iTableNameLen; uint m_iUseCount; #if MYSQL_VERSION_ID<50610 CHARSET_INFO * m_pTableQueryCharset; #else const CHARSET_INFO * m_pTableQueryCharset; #endif int m_iTableFields; char ** m_sTableField; enum_field_types * m_eTableFieldType; CSphSEShare () : m_sTable ( NULL ) , m_sScheme ( NULL ) , m_sHost ( NULL ) , m_sSocket ( NULL ) , m_sIndex ( NULL ) , m_iPort ( 0 ) , m_bSphinxQL ( false ) , m_iTableNameLen ( 0 ) , m_iUseCount ( 1 ) , m_pTableQueryCharset ( NULL ) , m_iTableFields ( 0 ) , m_sTableField ( NULL ) , m_eTableFieldType ( NULL ) { thr_lock_init ( &m_tLock ); pthread_mutex_init ( &m_tMutex, MY_MUTEX_INIT_FAST ); } ~CSphSEShare () { pthread_mutex_destroy ( &m_tMutex ); thr_lock_delete ( &m_tLock ); SafeDeleteArray ( m_sTable ); SafeDeleteArray ( m_sScheme ); ResetTable (); } void ResetTable () { for ( int i=0; i<m_iTableFields; i++ ) SafeDeleteArray ( m_sTableField[i] ); SafeDeleteArray ( m_sTableField ); SafeDeleteArray ( m_eTableFieldType ); } }; /// schema attribute struct CSphSEAttr { char * m_sName; ///< attribute name (received from Sphinx) uint32 m_uType; ///< attribute type (received from Sphinx) int m_iField; ///< field index in current table (-1 if none) CSphSEAttr() : m_sName ( NULL ) , m_uType ( SPH_ATTR_NONE ) , m_iField ( -1 ) {} ~CSphSEAttr () { SafeDeleteArray ( m_sName ); } }; /// word stats struct CSphSEWordStats { char * m_sWord; int m_iDocs; int m_iHits; CSphSEWordStats () : m_sWord ( NULL ) , m_iDocs ( 0 ) , m_iHits ( 0 ) {} ~CSphSEWordStats () { SafeDeleteArray ( m_sWord ); } }; /// request stats struct CSphSEStats { public: int m_iMatchesTotal; int m_iMatchesFound; int m_iQueryMsec; int m_iWords; CSphSEWordStats * m_dWords; bool m_bLastError; char m_sLastMessage[1024]; CSphSEStats() : m_dWords ( NULL ) { Reset (); } void Reset () { m_iMatchesTotal = 0; m_iMatchesFound = 0; m_iQueryMsec = 0; m_iWords = 0; SafeDeleteArray ( m_dWords ); m_bLastError = false; m_sLastMessage[0] = '\0'; } ~CSphSEStats() { Reset (); } }; /// thread local storage struct CSphSEThreadTable { static const int MAX_QUERY_LEN = 262144; // 256k should be enough, right? bool m_bStats; CSphSEStats m_tStats; bool m_bQuery; char m_sQuery[MAX_QUERY_LEN]; #if MYSQL_VERSION_ID<50610 CHARSET_INFO * m_pQueryCharset; #else const CHARSET_INFO * m_pQueryCharset; #endif bool m_bReplace; ///< are we doing an INSERT or REPLACE bool m_bCondId; ///< got a value from condition pushdown longlong m_iCondId; ///< value acquired from id=value condition pushdown bool m_bCondDone; ///< index_read() is now over const ha_sphinx * m_pHandler; CSphSEThreadTable * m_pTableNext; CSphSEThreadTable ( const ha_sphinx * pHandler ) : m_bStats ( false ) , m_bQuery ( false ) , m_pQueryCharset ( NULL ) , m_bReplace ( false ) , m_bCondId ( false ) , m_iCondId ( 0 ) , m_bCondDone ( false ) , m_pHandler ( pHandler ) , m_pTableNext ( NULL ) {} }; struct CSphTLS { CSphSEThreadTable * m_pHeadTable; explicit CSphTLS ( const ha_sphinx * pHandler ) { m_pHeadTable = new CSphSEThreadTable ( pHandler ); } ~CSphTLS() { CSphSEThreadTable * pCur = m_pHeadTable; while ( pCur ) { CSphSEThreadTable * pNext = pCur->m_pTableNext; SafeDelete ( pCur ); pCur = pNext; } } }; /// filter types enum ESphFilter { SPH_FILTER_VALUES = 0, ///< filter by integer values set SPH_FILTER_RANGE = 1, ///< filter by integer range SPH_FILTER_FLOATRANGE = 2 ///< filter by float range }; /// search query filter struct CSphSEFilter { public: ESphFilter m_eType; char * m_sAttrName; longlong m_uMinValue; longlong m_uMaxValue; float m_fMinValue; float m_fMaxValue; int m_iValues; longlong * m_pValues; int m_bExclude; public: CSphSEFilter () : m_eType ( SPH_FILTER_VALUES ) , m_sAttrName ( NULL ) , m_uMinValue ( 0 ) , m_uMaxValue ( UINT_MAX ) , m_fMinValue ( 0.0f ) , m_fMaxValue ( 0.0f ) , m_iValues ( 0 ) , m_pValues ( NULL ) , m_bExclude ( 0 ) { } ~CSphSEFilter () { SafeDeleteArray ( m_pValues ); } }; /// float vs dword conversion inline uint32 sphF2DW ( float f ) { union { float f; uint32 d; } u; u.f = f; return u.d; } /// dword vs float conversion inline float sphDW2F ( uint32 d ) { union { float f; uint32 d; } u; u.d = d; return u.f; } /// client-side search query struct CSphSEQuery { public: const char * m_sHost; int m_iPort; private: char * m_sQueryBuffer; const char * m_sIndex; int m_iOffset; int m_iLimit; bool m_bQuery; char * m_sQuery; uint32 * m_pWeights; int m_iWeights; ESphMatchMode m_eMode; ESphRankMode m_eRanker; char * m_sRankExpr; ESphSortOrder m_eSort; char * m_sSortBy; int m_iMaxMatches; int m_iMaxQueryTime; uint32 m_iMinID; uint32 m_iMaxID; int m_iFilters; CSphSEFilter m_dFilters[SPHINXSE_MAX_FILTERS]; ESphGroupBy m_eGroupFunc; char * m_sGroupBy; char * m_sGroupSortBy; int m_iCutoff; int m_iRetryCount; int m_iRetryDelay; char * m_sGroupDistinct; ///< points to query buffer; do NOT delete int m_iIndexWeights; char * m_sIndexWeight[SPHINXSE_MAX_FILTERS]; ///< points to query buffer; do NOT delete int m_iIndexWeight[SPHINXSE_MAX_FILTERS]; int m_iFieldWeights; char * m_sFieldWeight[SPHINXSE_MAX_FILTERS]; ///< points to query buffer; do NOT delete int m_iFieldWeight[SPHINXSE_MAX_FILTERS]; bool m_bGeoAnchor; char * m_sGeoLatAttr; char * m_sGeoLongAttr; float m_fGeoLatitude; float m_fGeoLongitude; char * m_sComment; char * m_sSelect; struct Override_t { union Value_t { uint32 m_uValue; longlong m_iValue64; float m_fValue; }; char * m_sName; ///< points to query buffer int m_iType; Dynamic_array<ulonglong> m_dIds; Dynamic_array<Value_t> m_dValues; }; Dynamic_array<Override_t *> m_dOverrides; public: char m_sParseError[256]; public: CSphSEQuery ( const char * sQuery, int iLength, const char * sIndex ); ~CSphSEQuery (); bool Parse (); int BuildRequest ( char ** ppBuffer ); protected: char * m_pBuf; char * m_pCur; int m_iBufLeft; bool m_bBufOverrun; template < typename T > int ParseArray ( T ** ppValues, const char * sValue ); bool ParseField ( char * sField ); void SendBytes ( const void * pBytes, int iBytes ); void SendWord ( short int v ) { v = ntohs(v); SendBytes ( &v, sizeof(v) ); } void SendInt ( int v ) { v = ntohl(v); SendBytes ( &v, sizeof(v) ); } void SendDword ( uint v ) { v = ntohl(v) ;SendBytes ( &v, sizeof(v) ); } void SendUint64 ( ulonglong v ) { SendDword ( (uint)(v>>32) ); SendDword ( (uint)(v&0xFFFFFFFFUL) ); } void SendString ( const char * v ) { int iLen = strlen(v); SendDword(iLen); SendBytes ( v, iLen ); } void SendFloat ( float v ) { SendDword ( sphF2DW(v) ); } }; template int CSphSEQuery::ParseArray<uint32> ( uint32 **, const char * ); template int CSphSEQuery::ParseArray<longlong> ( longlong **, const char * ); ////////////////////////////////////////////////////////////////////////////// #if MYSQL_VERSION_ID>50100 #if MYSQL_VERSION_ID<50114 #error Sphinx SE requires MySQL 5.1.14 or higher if compiling for 5.1.x series! #endif static handler * sphinx_create_handler ( handlerton * hton, TABLE_SHARE * table, MEM_ROOT * mem_root ); static int sphinx_init_func ( void * p ); static int sphinx_close_connection ( handlerton * hton, THD * thd ); static int sphinx_panic ( handlerton * hton, enum ha_panic_function flag ); static bool sphinx_show_status ( handlerton * hton, THD * thd, stat_print_fn * stat_print, enum ha_stat_type stat_type ); #else static bool sphinx_init_func_for_handlerton (); static int sphinx_close_connection ( THD * thd ); bool sphinx_show_status ( THD * thd ); #endif // >50100 ////////////////////////////////////////////////////////////////////////////// static const char sphinx_hton_name[] = "SPHINX"; static const char sphinx_hton_comment[] = "Sphinx storage engine " SPHINXSE_VERSION; #if MYSQL_VERSION_ID<50100 handlerton sphinx_hton = { #ifdef MYSQL_HANDLERTON_INTERFACE_VERSION MYSQL_HANDLERTON_INTERFACE_VERSION, #endif sphinx_hton_name, SHOW_OPTION_YES, sphinx_hton_comment, DB_TYPE_SPHINX_DB, sphinx_init_func_for_handlerton, 0, // slot 0, // savepoint size sphinx_close_connection, // close_connection NULL, // savepoint NULL, // rollback to savepoint NULL, // release savepoint NULL, // commit NULL, // rollback NULL, // prepare NULL, // recover NULL, // commit_by_xid NULL, // rollback_by_xid NULL, // create_cursor_read_view NULL, // set_cursor_read_view NULL, // close_cursor_read_view HTON_CAN_RECREATE }; #else static handlerton * sphinx_hton_ptr = NULL; #endif ////////////////////////////////////////////////////////////////////////////// // variables for Sphinx shared methods pthread_mutex_t sphinx_mutex; // mutex to init the hash static int sphinx_init = 0; // flag whether the hash was initialized static HASH sphinx_open_tables; // hash used to track open tables ////////////////////////////////////////////////////////////////////////////// // INITIALIZATION AND SHUTDOWN ////////////////////////////////////////////////////////////////////////////// // hashing function #if MYSQL_VERSION_ID>=50120 typedef size_t GetKeyLength_t; #else typedef uint GetKeyLength_t; #endif static byte * sphinx_get_key ( const byte * pSharePtr, GetKeyLength_t * pLength, my_bool ) { CSphSEShare * pShare = (CSphSEShare *) pSharePtr; *pLength = (size_t) pShare->m_iTableNameLen; return (byte*) pShare->m_sTable; } #if MYSQL_VERSION_ID<50100 static int sphinx_init_func ( void * ) // to avoid unused arg warning #else static int sphinx_init_func ( void * p ) #endif { SPH_ENTER_FUNC(); if ( !sphinx_init ) { sphinx_init = 1; void ( pthread_mutex_init ( &sphinx_mutex, MY_MUTEX_INIT_FAST ) ); sphinx_hash_init ( &sphinx_open_tables, system_charset_info, 32, 0, 0, sphinx_get_key, 0, 0 ); #if MYSQL_VERSION_ID > 50100 handlerton * hton = (handlerton*) p; hton->state = SHOW_OPTION_YES; hton->db_type = DB_TYPE_FIRST_DYNAMIC; hton->create = sphinx_create_handler; hton->close_connection = sphinx_close_connection; hton->show_status = sphinx_show_status; hton->panic = sphinx_panic; hton->flags = HTON_CAN_RECREATE; #endif } SPH_RET(0); } #if MYSQL_VERSION_ID<50100 static bool sphinx_init_func_for_handlerton () { return sphinx_init_func ( &sphinx_hton ); } #endif #if MYSQL_VERSION_ID>50100 static int sphinx_close_connection ( handlerton * hton, THD * thd ) { // deallocate common handler data SPH_ENTER_FUNC(); void ** tmp = thd_ha_data ( thd, hton ); CSphTLS * pTls = (CSphTLS *) (*tmp); SafeDelete ( pTls ); *tmp = NULL; SPH_RET(0); } static int sphinx_done_func ( void * ) { SPH_ENTER_FUNC(); int error = 0; if ( sphinx_init ) { sphinx_init = 0; if ( sphinx_open_tables.records ) error = 1; sphinx_hash_free ( &sphinx_open_tables ); pthread_mutex_destroy ( &sphinx_mutex ); } SPH_RET(0); } static int sphinx_panic ( handlerton * hton, enum ha_panic_function ) { return sphinx_done_func ( hton ); } #else static int sphinx_close_connection ( THD * thd ) { // deallocate common handler data SPH_ENTER_FUNC(); CSphTLS * pTls = (CSphTLS *) thd->ha_data[sphinx_hton.slot]; SafeDelete ( pTls ); thd->ha_data[sphinx_hton.slot] = NULL; SPH_RET(0); } #endif // >50100 ////////////////////////////////////////////////////////////////////////////// // SHOW STATUS ////////////////////////////////////////////////////////////////////////////// #if MYSQL_VERSION_ID>50100 static bool sphinx_show_status ( handlerton * hton, THD * thd, stat_print_fn * stat_print, enum ha_stat_type ) #else bool sphinx_show_status ( THD * thd ) #endif { SPH_ENTER_FUNC(); #if MYSQL_VERSION_ID<50100 Protocol * protocol = thd->protocol; List<Item> field_list; #endif char buf1[IO_SIZE]; uint buf1len; char buf2[IO_SIZE]; uint buf2len = 0; String words; buf1[0] = '\0'; buf2[0] = '\0'; #if MYSQL_VERSION_ID>50100 // 5.1.x style stats CSphTLS * pTls = (CSphTLS*) ( *thd_ha_data ( thd, hton ) ); #define LOC_STATS(_key,_keylen,_val,_vallen) \ stat_print ( thd, sphinx_hton_name, strlen(sphinx_hton_name), _key, _keylen, _val, _vallen ); #else // 5.0.x style stats if ( have_sphinx_db!=SHOW_OPTION_YES ) { my_message ( ER_NOT_SUPPORTED_YET, "failed to call SHOW SPHINX STATUS: --skip-sphinx was specified", MYF(0) ); SPH_RET(TRUE); } CSphTLS * pTls = (CSphTLS*) thd->ha_data[sphinx_hton.slot]; field_list.push_back ( new Item_empty_string ( "Type", 10 ) ); field_list.push_back ( new Item_empty_string ( "Name", FN_REFLEN ) ); field_list.push_back ( new Item_empty_string ( "Status", 10 ) ); if ( protocol->send_fields ( &field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF ) ) SPH_RET(TRUE); #define LOC_STATS(_key,_keylen,_val,_vallen) \ protocol->prepare_for_resend (); \ protocol->store ( "SPHINX", 6, system_charset_info ); \ protocol->store ( _key, _keylen, system_charset_info ); \ protocol->store ( _val, _vallen, system_charset_info ); \ if ( protocol->write() ) \ SPH_RET(TRUE); #endif // show query stats if ( pTls && pTls->m_pHeadTable && pTls->m_pHeadTable->m_bStats ) { const CSphSEStats * pStats = &pTls->m_pHeadTable->m_tStats; buf1len = my_snprintf ( buf1, sizeof(buf1), "total: %d, total found: %d, time: %d, words: %d", pStats->m_iMatchesTotal, pStats->m_iMatchesFound, pStats->m_iQueryMsec, pStats->m_iWords ); LOC_STATS ( "stats", 5, buf1, buf1len ); if ( pStats->m_iWords ) { for ( int i=0; i<pStats->m_iWords; i++ ) { CSphSEWordStats & tWord = pStats->m_dWords[i]; buf2len = my_snprintf ( buf2, sizeof(buf2), "%s%s:%d:%d ", buf2, tWord.m_sWord, tWord.m_iDocs, tWord.m_iHits ); } // convert it if we can const char * sWord = buf2; int iWord = buf2len; String sBuf3; if ( pTls->m_pHeadTable->m_pQueryCharset ) { uint iErrors; sBuf3.copy ( buf2, buf2len, pTls->m_pHeadTable->m_pQueryCharset, system_charset_info, &iErrors ); sWord = sBuf3.c_ptr(); iWord = sBuf3.length(); } LOC_STATS ( "words", 5, sWord, iWord ); } } // show last error or warning (either in addition to stats, or on their own) if ( pTls && pTls->m_pHeadTable && pTls->m_pHeadTable->m_tStats.m_sLastMessage && pTls->m_pHeadTable->m_tStats.m_sLastMessage[0] ) { const char * sMessageType = pTls->m_pHeadTable->m_tStats.m_bLastError ? "error" : "warning"; LOC_STATS ( sMessageType, strlen ( sMessageType ), pTls->m_pHeadTable->m_tStats.m_sLastMessage, strlen ( pTls->m_pHeadTable->m_tStats.m_sLastMessage ) ); } else { // well, nothing to show just yet #if MYSQL_VERSION_ID < 50100 LOC_STATS ( "stats", 5, "no query has been executed yet", sizeof("no query has been executed yet")-1 ); #endif } #if MYSQL_VERSION_ID < 50100 send_eof(thd); #endif SPH_RET(FALSE); } ////////////////////////////////////////////////////////////////////////////// // HELPERS ////////////////////////////////////////////////////////////////////////////// static char * sphDup ( const char * sSrc, int iLen=-1 ) { if ( !sSrc ) return NULL; if ( iLen<0 ) iLen = strlen(sSrc); char * sRes = new char [ 1+iLen ]; memcpy ( sRes, sSrc, iLen ); sRes[iLen] = '\0'; return sRes; } static void sphLogError ( const char * sFmt, ... ) { // emit timestamp #ifdef __WIN__ SYSTEMTIME t; GetLocalTime ( &t ); fprintf ( stderr, "%02d%02d%02d %2d:%02d:%02d SphinxSE: internal error: ", (int)t.wYear % 100, (int)t.wMonth, (int)t.wDay, (int)t.wHour, (int)t.wMinute, (int)t.wSecond ); #else // Unix version time_t tStamp; time ( &tStamp ); struct tm * pParsed; #ifdef HAVE_LOCALTIME_R struct tm tParsed; localtime_r ( &tStamp, &tParsed ); pParsed = &tParsed; #else pParsed = localtime ( &tStamp ); #endif // HAVE_LOCALTIME_R fprintf ( stderr, "%02d%02d%02d %2d:%02d:%02d SphinxSE: internal error: ", pParsed->tm_year % 100, pParsed->tm_mon + 1, pParsed->tm_mday, pParsed->tm_hour, pParsed->tm_min, pParsed->tm_sec); #endif // __WIN__ // emit message va_list ap; va_start ( ap, sFmt ); vfprintf ( stderr, sFmt, ap ); va_end ( ap ); // emit newline fprintf ( stderr, "\n" ); } // the following scheme variants are recognized // // sphinx://host[:port]/index // sphinxql://host[:port]/index // unix://unix/domain/socket[:index] static bool ParseUrl ( CSphSEShare * share, TABLE * table, bool bCreate ) { SPH_ENTER_FUNC(); if ( share ) { // check incoming stuff if ( !table ) { sphLogError ( "table==NULL in ParseUrl()" ); return false; } if ( !table->s ) { sphLogError ( "(table->s)==NULL in ParseUrl()" ); return false; } // free old stuff share->ResetTable (); // fill new stuff share->m_iTableFields = table->s->fields; if ( share->m_iTableFields ) { share->m_sTableField = new char * [ share->m_iTableFields ]; share->m_eTableFieldType = new enum_field_types [ share->m_iTableFields ]; for ( int i=0; i<share->m_iTableFields; i++ ) { share->m_sTableField[i] = sphDup ( table->field[i]->field_name ); share->m_eTableFieldType[i] = table->field[i]->type(); } } } // defaults bool bOk = true; bool bQL = false; char * sScheme = NULL; char * sHost = SPHINXAPI_DEFAULT_HOST; char * sIndex = SPHINXAPI_DEFAULT_INDEX; int iPort = SPHINXAPI_DEFAULT_PORT; // parse connection string, if any while ( table->s->connect_string.length!=0 ) { sScheme = sphDup ( table->s->connect_string.str, table->s->connect_string.length ); sHost = strstr ( sScheme, "://" ); if ( !sHost ) { bOk = false; break; } sHost[0] = '\0'; sHost += 3; ///////////////////////////// // sphinxapi via unix socket ///////////////////////////// if ( !strcmp ( sScheme, "unix" ) ) { sHost--; // reuse last slash iPort = 0; if (!( sIndex = strrchr ( sHost, ':' ) )) sIndex = SPHINXAPI_DEFAULT_INDEX; else { *sIndex++ = '\0'; if ( !*sIndex ) sIndex = SPHINXAPI_DEFAULT_INDEX; } bOk = true; break; } ///////////////////// // sphinxapi via tcp ///////////////////// if ( !strcmp ( sScheme, "sphinx" ) ) { char * sPort = strchr ( sHost, ':' ); if ( sPort ) { *sPort++ = '\0'; if ( *sPort ) { sIndex = strchr ( sPort, '/' ); if ( sIndex ) *sIndex++ = '\0'; else sIndex = SPHINXAPI_DEFAULT_INDEX; iPort = atoi(sPort); if ( !iPort ) iPort = SPHINXAPI_DEFAULT_PORT; } } else { sIndex = strchr ( sHost, '/' ); if ( sIndex ) *sIndex++ = '\0'; else sIndex = SPHINXAPI_DEFAULT_INDEX; } bOk = true; break; } //////////// // sphinxql //////////// if ( !strcmp ( sScheme, "sphinxql" ) ) { bQL = true; iPort = SPHINXQL_DEFAULT_PORT; // handle port char * sPort = strchr ( sHost, ':' ); sIndex = sHost; // starting point for index name search if ( sPort ) { *sPort++ = '\0'; sIndex = sPort; iPort = atoi(sPort); if ( !iPort ) { bOk = false; // invalid port; can report ER_FOREIGN_DATA_STRING_INVALID break; } } // find index sIndex = strchr ( sIndex, '/' ); if ( sIndex ) *sIndex++ = '\0'; // final checks // host and index names are required bOk = ( sHost && *sHost && sIndex && *sIndex ); break; } // unknown case bOk = false; break; } if ( !bOk ) { my_error ( bCreate ? ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE : ER_FOREIGN_DATA_STRING_INVALID, MYF(0), table->s->connect_string ); } else { if ( share ) { SafeDeleteArray ( share->m_sScheme ); share->m_sScheme = sScheme; share->m_sHost = sHost; share->m_sIndex = sIndex; share->m_iPort = (ushort)iPort; share->m_bSphinxQL = bQL; } } if ( !bOk && !share ) SafeDeleteArray ( sScheme ); SPH_RET(bOk); } // Example of simple lock controls. The "share" it creates is structure we will // pass to each sphinx handler. Do you have to have one of these? Well, you have // pieces that are used for locking, and they are needed to function. static CSphSEShare * get_share ( const char * table_name, TABLE * table ) { SPH_ENTER_FUNC(); pthread_mutex_lock ( &sphinx_mutex ); CSphSEShare * pShare = NULL; while (true) { // check if we already have this share #if MYSQL_VERSION_ID>=50120 pShare = (CSphSEShare*) sphinx_hash_search ( &sphinx_open_tables, (const uchar *) table_name, strlen(table_name) ); #else #ifdef __WIN__ pShare = (CSphSEShare*) sphinx_hash_search ( &sphinx_open_tables, (const byte *) table_name, strlen(table_name) ); #else pShare = (CSphSEShare*) sphinx_hash_search ( &sphinx_open_tables, table_name, strlen(table_name) ); #endif // win #endif // pre-5.1.20 if ( pShare ) { pShare->m_iUseCount++; break; } // try to allocate new share pShare = new CSphSEShare (); if ( !pShare ) break; // try to setup it if ( !ParseUrl ( pShare, table, false ) ) { SafeDelete ( pShare ); break; } if ( !pShare->m_bSphinxQL ) pShare->m_pTableQueryCharset = table->field[2]->charset(); // try to hash it pShare->m_iTableNameLen = strlen(table_name); pShare->m_sTable = sphDup ( table_name ); if ( my_hash_insert ( &sphinx_open_tables, (const byte *)pShare ) ) { SafeDelete ( pShare ); break; } // all seems fine break; } pthread_mutex_unlock ( &sphinx_mutex ); SPH_RET(pShare); } // Free lock controls. We call this whenever we close a table. If the table had // the last reference to the share then we free memory associated with it. static int free_share ( CSphSEShare * pShare ) { SPH_ENTER_FUNC(); pthread_mutex_lock ( &sphinx_mutex ); if ( !--pShare->m_iUseCount ) { sphinx_hash_delete ( &sphinx_open_tables, (byte *)pShare ); SafeDelete ( pShare ); } pthread_mutex_unlock ( &sphinx_mutex ); SPH_RET(0); } #if MYSQL_VERSION_ID>50100 static handler * sphinx_create_handler ( handlerton * hton, TABLE_SHARE * table, MEM_ROOT * mem_root ) { sphinx_hton_ptr = hton; return new ( mem_root ) ha_sphinx ( hton, table ); } #endif ////////////////////////////////////////////////////////////////////////////// // CLIENT-SIDE REQUEST STUFF ////////////////////////////////////////////////////////////////////////////// CSphSEQuery::CSphSEQuery ( const char * sQuery, int iLength, const char * sIndex ) : m_sHost ( "" ) , m_iPort ( 0 ) , m_sIndex ( sIndex ? sIndex : "*" ) , m_iOffset ( 0 ) , m_iLimit ( 20 ) , m_bQuery ( false ) , m_sQuery ( "" ) , m_pWeights ( NULL ) , m_iWeights ( 0 ) , m_eMode ( SPH_MATCH_ALL ) , m_eRanker ( SPH_RANK_PROXIMITY_BM25 ) , m_sRankExpr ( NULL ) , m_eSort ( SPH_SORT_RELEVANCE ) , m_sSortBy ( "" ) , m_iMaxMatches ( 1000 ) , m_iMaxQueryTime ( 0 ) , m_iMinID ( 0 ) , m_iMaxID ( 0 ) , m_iFilters ( 0 ) , m_eGroupFunc ( SPH_GROUPBY_DAY ) , m_sGroupBy ( "" ) , m_sGroupSortBy ( "@group desc" ) , m_iCutoff ( 0 ) , m_iRetryCount ( 0 ) , m_iRetryDelay ( 0 ) , m_sGroupDistinct ( "" ) , m_iIndexWeights ( 0 ) , m_iFieldWeights ( 0 ) , m_bGeoAnchor ( false ) , m_sGeoLatAttr ( "" ) , m_sGeoLongAttr ( "" ) , m_fGeoLatitude ( 0.0f ) , m_fGeoLongitude ( 0.0f ) , m_sComment ( "" ) , m_sSelect ( "*" ) , m_pBuf ( NULL ) , m_pCur ( NULL ) , m_iBufLeft ( 0 ) , m_bBufOverrun ( false ) { m_sQueryBuffer = new char [ iLength+2 ]; memcpy ( m_sQueryBuffer, sQuery, iLength ); m_sQueryBuffer[iLength] = ';'; m_sQueryBuffer[iLength+1] = '\0'; } CSphSEQuery::~CSphSEQuery () { SPH_ENTER_METHOD(); SafeDeleteArray ( m_sQueryBuffer ); SafeDeleteArray ( m_pWeights ); SafeDeleteArray ( m_pBuf ); for ( int i=0; i<m_dOverrides.elements(); i++ ) SafeDelete ( m_dOverrides.at(i) ); SPH_VOID_RET(); } template < typename T > int CSphSEQuery::ParseArray ( T ** ppValues, const char * sValue ) { SPH_ENTER_METHOD(); assert ( ppValues ); assert ( !(*ppValues) ); const char * pValue; bool bPrevDigit = false; int iValues = 0; // count the values for ( pValue=sValue; *pValue; pValue++ ) { bool bDigit = (*pValue)>='0' && (*pValue)<='9'; if ( bDigit && !bPrevDigit ) iValues++; bPrevDigit = bDigit; } if ( !iValues ) SPH_RET(0); // extract the values T * pValues = new T [ iValues ]; *ppValues = pValues; int iIndex = 0, iSign = 1; T uValue = 0; bPrevDigit = false; for ( pValue=sValue ;; pValue++ ) { bool bDigit = (*pValue)>='0' && (*pValue)<='9'; if ( bDigit ) { if ( !bPrevDigit ) uValue = 0; uValue = uValue*10 + ( (*pValue)-'0' ); } else if ( bPrevDigit ) { assert ( iIndex<iValues ); pValues [ iIndex++ ] = uValue * iSign; iSign = 1; } else if ( *pValue=='-' ) iSign = -1; bPrevDigit = bDigit; if ( !*pValue ) break; } SPH_RET ( iValues ); } static char * chop ( char * s ) { while ( *s && isspace(*s) ) s++; char * p = s + strlen(s); while ( p>s && isspace ( p[-1] ) ) p--; *p = '\0'; return s; } static bool myisattr ( char c ) { return ( c>='0' && c<='9' ) || ( c>='a' && c<='z' ) || ( c>='A' && c<='Z' ) || c=='_'; } static bool myismagic ( char c ) { return c=='@'; } bool CSphSEQuery::ParseField ( char * sField ) { SPH_ENTER_METHOD(); // look for option name/value separator char * sValue = strchr ( sField, '=' ); if ( !sValue || sValue==sField || sValue[-1]=='\\' ) { // by default let's assume it's just query if ( sField[0] ) { if ( m_bQuery ) { snprintf ( m_sParseError, sizeof(m_sParseError), "search query already specified; '%s' is redundant", sField ); SPH_RET(false); } else { m_sQuery = sField; m_bQuery = true; // unescape only 1st one char *s = sField, *d = sField; int iSlashes = 0; while ( *s ) { iSlashes = ( *s=='\\' ) ? iSlashes+1 : 0; if ( ( iSlashes%2 )==0 ) *d++ = *s; s++; } *d = '\0'; } } SPH_RET(true); } // split *sValue++ = '\0'; sValue = chop ( sValue ); int iValue = atoi ( sValue ); // handle options char * sName = chop ( sField ); if ( !strcmp ( sName, "query" ) ) m_sQuery = sValue; else if ( !strcmp ( sName, "host" ) ) m_sHost = sValue; else if ( !strcmp ( sName, "port" ) ) m_iPort = iValue; else if ( !strcmp ( sName, "index" ) ) m_sIndex = sValue; else if ( !strcmp ( sName, "offset" ) ) m_iOffset = iValue; else if ( !strcmp ( sName, "limit" ) ) m_iLimit = iValue; else if ( !strcmp ( sName, "weights" ) ) m_iWeights = ParseArray<uint32> ( &m_pWeights, sValue ); else if ( !strcmp ( sName, "minid" ) ) m_iMinID = iValue; else if ( !strcmp ( sName, "maxid" ) ) m_iMaxID = iValue; else if ( !strcmp ( sName, "maxmatches" ) ) m_iMaxMatches = iValue; else if ( !strcmp ( sName, "maxquerytime" ) ) m_iMaxQueryTime = iValue; else if ( !strcmp ( sName, "groupsort" ) ) m_sGroupSortBy = sValue; else if ( !strcmp ( sName, "distinct" ) ) m_sGroupDistinct = sValue; else if ( !strcmp ( sName, "cutoff" ) ) m_iCutoff = iValue; else if ( !strcmp ( sName, "comment" ) ) m_sComment = sValue; else if ( !strcmp ( sName, "select" ) ) m_sSelect = sValue; else if ( !strcmp ( sName, "mode" ) ) { m_eMode = SPH_MATCH_ALL; if ( !strcmp ( sValue, "any" ) ) m_eMode = SPH_MATCH_ANY; else if ( !strcmp ( sValue, "phrase" ) ) m_eMode = SPH_MATCH_PHRASE; else if ( !strcmp ( sValue, "boolean" ) ) m_eMode = SPH_MATCH_BOOLEAN; else if ( !strcmp ( sValue, "ext" ) ) m_eMode = SPH_MATCH_EXTENDED; else if ( !strcmp ( sValue, "extended" ) ) m_eMode = SPH_MATCH_EXTENDED; else if ( !strcmp ( sValue, "ext2" ) ) m_eMode = SPH_MATCH_EXTENDED2; else if ( !strcmp ( sValue, "extended2" ) ) m_eMode = SPH_MATCH_EXTENDED2; else if ( !strcmp ( sValue, "all" ) ) m_eMode = SPH_MATCH_ALL; else if ( !strcmp ( sValue, "fullscan" ) ) m_eMode = SPH_MATCH_FULLSCAN; else { snprintf ( m_sParseError, sizeof(m_sParseError), "unknown matching mode '%s'", sValue ); SPH_RET(false); } } else if ( !strcmp ( sName, "ranker" ) ) { m_eRanker = SPH_RANK_PROXIMITY_BM25; if ( !strcmp ( sValue, "proximity_bm25" ) ) m_eRanker = SPH_RANK_PROXIMITY_BM25; else if ( !strcmp ( sValue, "bm25" ) ) m_eRanker = SPH_RANK_BM25; else if ( !strcmp ( sValue, "none" ) ) m_eRanker = SPH_RANK_NONE; else if ( !strcmp ( sValue, "wordcount" ) ) m_eRanker = SPH_RANK_WORDCOUNT; else if ( !strcmp ( sValue, "proximity" ) ) m_eRanker = SPH_RANK_PROXIMITY; else if ( !strcmp ( sValue, "matchany" ) ) m_eRanker = SPH_RANK_MATCHANY; else if ( !strcmp ( sValue, "fieldmask" ) ) m_eRanker = SPH_RANK_FIELDMASK; else if ( !strcmp ( sValue, "sph04" ) ) m_eRanker = SPH_RANK_SPH04; else if ( !strncmp ( sValue, "expr:", 5 ) ) { m_eRanker = SPH_RANK_EXPR; m_sRankExpr = sValue+5; } else { snprintf ( m_sParseError, sizeof(m_sParseError), "unknown ranking mode '%s'", sValue ); SPH_RET(false); } } else if ( !strcmp ( sName, "sort" ) ) { static const struct { const char * m_sName; ESphSortOrder m_eSort; } dSortModes[] = { { "relevance", SPH_SORT_RELEVANCE }, { "attr_desc:", SPH_SORT_ATTR_DESC }, { "attr_asc:", SPH_SORT_ATTR_ASC }, { "time_segments:", SPH_SORT_TIME_SEGMENTS }, { "extended:", SPH_SORT_EXTENDED }, { "expr:", SPH_SORT_EXPR } }; int i; const int nModes = sizeof(dSortModes)/sizeof(dSortModes[0]); for ( i=0; i<nModes; i++ ) if ( !strncmp ( sValue, dSortModes[i].m_sName, strlen ( dSortModes[i].m_sName ) ) ) { m_eSort = dSortModes[i].m_eSort; m_sSortBy = sValue + strlen ( dSortModes[i].m_sName ); break; } if ( i==nModes ) { snprintf ( m_sParseError, sizeof(m_sParseError), "unknown sorting mode '%s'", sValue ); SPH_RET(false); } } else if ( !strcmp ( sName, "groupby" ) ) { static const struct { const char * m_sName; ESphGroupBy m_eFunc; } dGroupModes[] = { { "day:", SPH_GROUPBY_DAY }, { "week:", SPH_GROUPBY_WEEK }, { "month:", SPH_GROUPBY_MONTH }, { "year:", SPH_GROUPBY_YEAR }, { "attr:", SPH_GROUPBY_ATTR }, }; int i; const int nModes = sizeof(dGroupModes)/sizeof(dGroupModes[0]); for ( i=0; i<nModes; i++ ) if ( !strncmp ( sValue, dGroupModes[i].m_sName, strlen ( dGroupModes[i].m_sName ) ) ) { m_eGroupFunc = dGroupModes[i].m_eFunc; m_sGroupBy = sValue + strlen ( dGroupModes[i].m_sName ); break; } if ( i==nModes ) { snprintf ( m_sParseError, sizeof(m_sParseError), "unknown groupby mode '%s'", sValue ); SPH_RET(false); } } else if ( m_iFilters<SPHINXSE_MAX_FILTERS && ( !strcmp ( sName, "range" ) || !strcmp ( sName, "!range" ) || !strcmp ( sName, "floatrange" ) || !strcmp ( sName, "!floatrange" ) ) ) { while (true) { char * p = sName; CSphSEFilter & tFilter = m_dFilters [ m_iFilters ]; tFilter.m_bExclude = ( *p=='!' ); if ( tFilter.m_bExclude ) p++; tFilter.m_eType = ( *p=='f' ) ? SPH_FILTER_FLOATRANGE : SPH_FILTER_RANGE; if (!( p = strchr ( sValue, ',' ) )) break; *p++ = '\0'; tFilter.m_sAttrName = chop ( sValue ); sValue = p; if (!( p = strchr ( sValue, ',' ) )) break; *p++ = '\0'; if ( tFilter.m_eType==SPH_FILTER_RANGE ) { tFilter.m_uMinValue = strtoll ( sValue, NULL, 10 ); tFilter.m_uMaxValue = strtoll ( p, NULL, 10 ); } else { tFilter.m_fMinValue = (float)atof(sValue); tFilter.m_fMaxValue = (float)atof(p); } // all ok m_iFilters++; break; } } else if ( m_iFilters<SPHINXSE_MAX_FILTERS && ( !strcmp ( sName, "filter" ) || !strcmp ( sName, "!filter" ) ) ) { while (true) { CSphSEFilter & tFilter = m_dFilters [ m_iFilters ]; tFilter.m_eType = SPH_FILTER_VALUES; tFilter.m_bExclude = ( strcmp ( sName, "!filter" )==0 ); // get the attr name while ( (*sValue) && !( myisattr(*sValue) || myismagic(*sValue) ) ) sValue++; if ( !*sValue ) break; tFilter.m_sAttrName = sValue; while ( (*sValue) && ( myisattr(*sValue) || myismagic(*sValue) ) ) sValue++; if ( !*sValue ) break; *sValue++ = '\0'; // get the values tFilter.m_iValues = ParseArray<longlong> ( &tFilter.m_pValues, sValue ); if ( !tFilter.m_iValues ) { assert ( !tFilter.m_pValues ); break; } // all ok m_iFilters++; break; } } else if ( !strcmp ( sName, "indexweights" ) || !strcmp ( sName, "fieldweights" ) ) { bool bIndex = !strcmp ( sName, "indexweights" ); int * pCount = bIndex ? &m_iIndexWeights : &m_iFieldWeights; char ** pNames = bIndex ? &m_sIndexWeight[0] : &m_sFieldWeight[0]; int * pWeights = bIndex ? &m_iIndexWeight[0] : &m_iFieldWeight[0]; *pCount = 0; char * p = sValue; while ( *p && *pCount<SPHINXSE_MAX_FILTERS ) { // extract attr name if ( !myisattr(*p) ) { snprintf ( m_sParseError, sizeof(m_sParseError), "%s: index name expected near '%s'", sName, p ); SPH_RET(false); } pNames[*pCount] = p; while ( myisattr(*p) ) p++; if ( *p!=',' ) { snprintf ( m_sParseError, sizeof(m_sParseError), "%s: comma expected near '%s'", sName, p ); SPH_RET(false); } *p++ = '\0'; // extract attr value char * sVal = p; while ( isdigit(*p) ) p++; if ( p==sVal ) { snprintf ( m_sParseError, sizeof(m_sParseError), "%s: integer weight expected near '%s'", sName, sVal ); SPH_RET(false); } pWeights[*pCount] = atoi(sVal); (*pCount)++; if ( !*p ) break; if ( *p!=',' ) { snprintf ( m_sParseError, sizeof(m_sParseError), "%s: comma expected near '%s'", sName, p ); SPH_RET(false); } p++; } } else if ( !strcmp ( sName, "geoanchor" ) ) { m_bGeoAnchor = false; while (true) { char * sLat = sValue; char * p = sValue; if (!( p = strchr ( p, ',' ) )) break; *p++ = '\0'; char * sLong = p; if (!( p = strchr ( p, ',' ) )) break; *p++ = '\0'; char * sLatVal = p; if (!( p = strchr ( p, ',' ) )) break; *p++ = '\0'; char * sLongVal = p; m_sGeoLatAttr = chop(sLat); m_sGeoLongAttr = chop(sLong); m_fGeoLatitude = (float)atof ( sLatVal ); m_fGeoLongitude = (float)atof ( sLongVal ); m_bGeoAnchor = true; break; } if ( !m_bGeoAnchor ) { snprintf ( m_sParseError, sizeof(m_sParseError), "geoanchor: parse error, not enough comma-separated arguments" ); SPH_RET(false); } } else if ( !strcmp ( sName, "override" ) ) // name,type,id:value,id:value,... { char * sName = NULL; int iType = 0; CSphSEQuery::Override_t * pOverride = NULL; // get name and type char * sRest = sValue; while (true) { sName = sRest; if ( !*sName ) break; if (!( sRest = strchr ( sRest, ',' ) )) break; *sRest++ = '\0'; char * sType = sRest; if (!( sRest = strchr ( sRest, ',' ) )) break; static const struct { const char * m_sName; int m_iType; } dAttrTypes[] = { { "int", SPH_ATTR_INTEGER }, { "timestamp", SPH_ATTR_TIMESTAMP }, { "bool", SPH_ATTR_BOOL }, { "float", SPH_ATTR_FLOAT }, { "bigint", SPH_ATTR_BIGINT } }; for ( int i=0; i<sizeof(dAttrTypes)/sizeof(*dAttrTypes); i++ ) if ( !strncmp ( sType, dAttrTypes[i].m_sName, sRest - sType ) ) { iType = dAttrTypes[i].m_iType; break; } break; } // fail if ( !sName || !*sName || !iType ) { snprintf ( m_sParseError, sizeof(m_sParseError), "override: malformed query" ); SPH_RET(false); } // grab id:value pairs sRest++; while ( sRest ) { char * sId = sRest; if (!( sRest = strchr ( sRest, ':' ) )) break; *sRest++ = '\0'; if (!( sRest - sId )) break; char * sValue = sRest; if ( ( sRest = strchr ( sRest, ',' ) )!=NULL ) *sRest++ = '\0'; if ( !*sValue ) break; if ( !pOverride ) { pOverride = new CSphSEQuery::Override_t; pOverride->m_sName = chop(sName); pOverride->m_iType = iType; m_dOverrides.append ( pOverride ); } ulonglong uId = strtoull ( sId, NULL, 10 ); CSphSEQuery::Override_t::Value_t tValue; if ( iType==SPH_ATTR_FLOAT ) tValue.m_fValue = (float)atof(sValue); else if ( iType==SPH_ATTR_BIGINT ) tValue.m_iValue64 = strtoll ( sValue, NULL, 10 ); else tValue.m_uValue = (uint32)strtoul ( sValue, NULL, 10 ); pOverride->m_dIds.append ( uId ); pOverride->m_dValues.append ( tValue ); } if ( !pOverride ) { snprintf ( m_sParseError, sizeof(m_sParseError), "override: id:value mapping expected" ); SPH_RET(false); } SPH_RET(true); } else { snprintf ( m_sParseError, sizeof(m_sParseError), "unknown parameter '%s'", sName ); SPH_RET(false); } // !COMMIT handle syntax errors SPH_RET(true); } bool CSphSEQuery::Parse () { SPH_ENTER_METHOD(); SPH_DEBUG ( "query [[ %s ]]", m_sQueryBuffer ); m_bQuery = false; char * pCur = m_sQueryBuffer; char * pNext = pCur; while ( ( pNext = strchr ( pNext, ';' ) )!=NULL ) { // handle escaped semicolons if ( pNext>m_sQueryBuffer && pNext[-1]=='\\' && pNext[1]!='\0' ) { pNext++; continue; } // handle semicolon-separated clauses *pNext++ = '\0'; if ( !ParseField ( pCur ) ) SPH_RET(false); pCur = pNext; } SPH_DEBUG ( "q [[ %s ]]", m_sQuery ); SPH_RET(true); } void CSphSEQuery::SendBytes ( const void * pBytes, int iBytes ) { SPH_ENTER_METHOD(); if ( m_iBufLeft<iBytes ) { m_bBufOverrun = true; SPH_VOID_RET(); } memcpy ( m_pCur, pBytes, iBytes ); m_pCur += iBytes; m_iBufLeft -= iBytes; SPH_VOID_RET(); } int CSphSEQuery::BuildRequest ( char ** ppBuffer ) { SPH_ENTER_METHOD(); // calc request length int iReqSize = 128 + 4*m_iWeights + strlen ( m_sSortBy ) + strlen ( m_sQuery ) + strlen ( m_sIndex ) + strlen ( m_sGroupBy ) + strlen ( m_sGroupSortBy ) + strlen ( m_sGroupDistinct ) + strlen ( m_sComment ) + strlen ( m_sSelect ); if ( m_eRanker==SPH_RANK_EXPR ) iReqSize += 4 + strlen(m_sRankExpr); for ( int i=0; i<m_iFilters; i++ ) { const CSphSEFilter & tFilter = m_dFilters[i]; iReqSize += 12 + strlen ( tFilter.m_sAttrName ); // string attr-name; int type; int exclude-flag switch ( tFilter.m_eType ) { case SPH_FILTER_VALUES: iReqSize += 4 + 8*tFilter.m_iValues; break; case SPH_FILTER_RANGE: iReqSize += 16; break; case SPH_FILTER_FLOATRANGE: iReqSize += 8; break; } } if ( m_bGeoAnchor ) // 1.14+ iReqSize += 16 + strlen ( m_sGeoLatAttr ) + strlen ( m_sGeoLongAttr ); for ( int i=0; i<m_iIndexWeights; i++ ) // 1.15+ iReqSize += 8 + strlen(m_sIndexWeight[i] ); for ( int i=0; i<m_iFieldWeights; i++ ) // 1.18+ iReqSize += 8 + strlen(m_sFieldWeight[i] ); // overrides iReqSize += 4; for ( int i=0; i<m_dOverrides.elements(); i++ ) { CSphSEQuery::Override_t * pOverride = m_dOverrides.at(i); const uint32 uSize = pOverride->m_iType==SPH_ATTR_BIGINT ? 16 : 12; // id64 + value iReqSize += strlen ( pOverride->m_sName ) + 12 + uSize*pOverride->m_dIds.elements(); } // select iReqSize += 4; m_iBufLeft = 0; SafeDeleteArray ( m_pBuf ); m_pBuf = new char [ iReqSize ]; if ( !m_pBuf ) SPH_RET(-1); m_pCur = m_pBuf; m_iBufLeft = iReqSize; m_bBufOverrun = false; (*ppBuffer) = m_pBuf; // build request SendWord ( SEARCHD_COMMAND_SEARCH ); // command id SendWord ( VER_COMMAND_SEARCH ); // command version SendInt ( iReqSize-8 ); // packet body length SendInt ( 0 ); // its a client SendInt ( 1 ); // number of queries SendInt ( m_iOffset ); SendInt ( m_iLimit ); SendInt ( m_eMode ); SendInt ( m_eRanker ); // 1.16+ if ( m_eRanker==SPH_RANK_EXPR ) SendString ( m_sRankExpr ); SendInt ( m_eSort ); SendString ( m_sSortBy ); // sort attr SendString ( m_sQuery ); // query SendInt ( m_iWeights ); for ( int j=0; j<m_iWeights; j++ ) SendInt ( m_pWeights[j] ); // weights SendString ( m_sIndex ); // indexes SendInt ( 1 ); // id64 range follows SendUint64 ( m_iMinID ); // id/ts ranges SendUint64 ( m_iMaxID ); SendInt ( m_iFilters ); for ( int j=0; j<m_iFilters; j++ ) { const CSphSEFilter & tFilter = m_dFilters[j]; SendString ( tFilter.m_sAttrName ); SendInt ( tFilter.m_eType ); switch ( tFilter.m_eType ) { case SPH_FILTER_VALUES: SendInt ( tFilter.m_iValues ); for ( int k=0; k<tFilter.m_iValues; k++ ) SendUint64 ( tFilter.m_pValues[k] ); break; case SPH_FILTER_RANGE: SendUint64 ( tFilter.m_uMinValue ); SendUint64 ( tFilter.m_uMaxValue ); break; case SPH_FILTER_FLOATRANGE: SendFloat ( tFilter.m_fMinValue ); SendFloat ( tFilter.m_fMaxValue ); break; } SendInt ( tFilter.m_bExclude ); } SendInt ( m_eGroupFunc ); SendString ( m_sGroupBy ); SendInt ( m_iMaxMatches ); SendString ( m_sGroupSortBy ); SendInt ( m_iCutoff ); // 1.9+ SendInt ( m_iRetryCount ); // 1.10+ SendInt ( m_iRetryDelay ); SendString ( m_sGroupDistinct ); // 1.11+ SendInt ( m_bGeoAnchor ); // 1.14+ if ( m_bGeoAnchor ) { SendString ( m_sGeoLatAttr ); SendString ( m_sGeoLongAttr ); SendFloat ( m_fGeoLatitude ); SendFloat ( m_fGeoLongitude ); } SendInt ( m_iIndexWeights ); // 1.15+ for ( int i=0; i<m_iIndexWeights; i++ ) { SendString ( m_sIndexWeight[i] ); SendInt ( m_iIndexWeight[i] ); } SendInt ( m_iMaxQueryTime ); // 1.17+ SendInt ( m_iFieldWeights ); // 1.18+ for ( int i=0; i<m_iFieldWeights; i++ ) { SendString ( m_sFieldWeight[i] ); SendInt ( m_iFieldWeight[i] ); } SendString ( m_sComment ); // overrides SendInt ( m_dOverrides.elements() ); for ( int i=0; i<m_dOverrides.elements(); i++ ) { CSphSEQuery::Override_t * pOverride = m_dOverrides.at(i); SendString ( pOverride->m_sName ); SendDword ( pOverride->m_iType ); SendInt ( pOverride->m_dIds.elements() ); for ( int j=0; j<pOverride->m_dIds.elements(); j++ ) { SendUint64 ( pOverride->m_dIds.at(j) ); if ( pOverride->m_iType==SPH_ATTR_FLOAT ) SendFloat ( pOverride->m_dValues.at(j).m_fValue ); else if ( pOverride->m_iType==SPH_ATTR_BIGINT ) SendUint64 ( pOverride->m_dValues.at(j).m_iValue64 ); else SendDword ( pOverride->m_dValues.at(j).m_uValue ); } } // select SendString ( m_sSelect ); // detect buffer overruns and underruns, and report internal error if ( m_bBufOverrun || m_iBufLeft!=0 || m_pCur-m_pBuf!=iReqSize ) SPH_RET(-1); // all fine SPH_RET ( iReqSize ); } ////////////////////////////////////////////////////////////////////////////// // SPHINX HANDLER ////////////////////////////////////////////////////////////////////////////// static const char * ha_sphinx_exts[] = { NullS }; #if MYSQL_VERSION_ID<50100 ha_sphinx::ha_sphinx ( TABLE_ARG * table ) : handler ( &sphinx_hton, table ) #else ha_sphinx::ha_sphinx ( handlerton * hton, TABLE_ARG * table ) : handler ( hton, table ) #endif , m_pShare ( NULL ) , m_iMatchesTotal ( 0 ) , m_iCurrentPos ( 0 ) , m_pCurrentKey ( NULL ) , m_iCurrentKeyLen ( 0 ) , m_pResponse ( NULL ) , m_pResponseEnd ( NULL ) , m_pCur ( NULL ) , m_bUnpackError ( false ) , m_iFields ( 0 ) , m_dFields ( NULL ) , m_iAttrs ( 0 ) , m_dAttrs ( NULL ) , m_bId64 ( 0 ) , m_dUnboundFields ( NULL ) { SPH_ENTER_METHOD(); if ( current_thd ) current_thd->variables.engine_condition_pushdown = true; SPH_VOID_RET(); } // If frm_error() is called then we will use this to to find out what file extentions // exist for the storage engine. This is also used by the default rename_table and // delete_table method in handler.cc. const char ** ha_sphinx::bas_ext() const { return ha_sphinx_exts; } // Used for opening tables. The name will be the name of the file. // A table is opened when it needs to be opened. For instance // when a request comes in for a select on the table (tables are not // open and closed for each request, they are cached). // // Called from handler.cc by handler::ha_open(). The server opens all tables by // calling ha_open() which then calls the handler specific open(). int ha_sphinx::open ( const char * name, int, uint ) { SPH_ENTER_METHOD(); m_pShare = get_share ( name, table ); if ( !m_pShare ) SPH_RET(1); thr_lock_data_init ( &m_pShare->m_tLock, &m_tLock, NULL ); #if MYSQL_VERSION_ID>50100 void ** tmp = thd_ha_data ( table->in_use, ht ); if ( *tmp ) { CSphTLS * pTls = (CSphTLS *)( *tmp ); SafeDelete ( pTls ); *tmp = NULL; } #else if ( table->in_use->ha_data [ sphinx_hton.slot ] ) { CSphTLS * pTls = (CSphTLS *)( table->in_use->ha_data [ sphinx_hton.slot ] ); SafeDelete ( pTls ); table->in_use->ha_data [ sphinx_hton.slot ] = NULL; } #endif SPH_RET(0); } int ha_sphinx::Connect ( const char * sHost, ushort uPort ) { struct sockaddr_in sin; #ifndef __WIN__ struct sockaddr_un saun; #endif int iDomain = 0; int iSockaddrSize = 0; struct sockaddr * pSockaddr = NULL; in_addr_t ip_addr; if ( uPort ) { iDomain = AF_INET; iSockaddrSize = sizeof(sin); pSockaddr = (struct sockaddr *) &sin; memset ( &sin, 0, sizeof(sin) ); sin.sin_family = AF_INET; sin.sin_port = htons(uPort); // prepare host address if ( (int)( ip_addr = inet_addr(sHost) )!=(int)INADDR_NONE ) { memcpy ( &sin.sin_addr, &ip_addr, sizeof(ip_addr) ); } else { int tmp_errno; bool bError = false; #if MYSQL_VERSION_ID>=50515 struct addrinfo * hp = NULL; tmp_errno = getaddrinfo ( sHost, NULL, NULL, &hp ); if ( tmp_errno!=0 || !hp || !hp->ai_addr ) { bError = true; if ( hp ) freeaddrinfo ( hp ); } #else struct hostent tmp_hostent, *hp; char buff2 [ GETHOSTBYNAME_BUFF_SIZE ]; hp = my_gethostbyname_r ( sHost, &tmp_hostent, buff2, sizeof(buff2), &tmp_errno ); if ( !hp ) { my_gethostbyname_r_free(); bError = true; } #endif if ( bError ) { char sError[256]; my_snprintf ( sError, sizeof(sError), "failed to resolve searchd host (name=%s)", sHost ); my_error ( ER_CONNECT_TO_FOREIGN_DATA_SOURCE, MYF(0), sError ); SPH_RET(-1); } #if MYSQL_VERSION_ID>=50515 memcpy ( &sin.sin_addr, &( (struct sockaddr_in *)hp->ai_addr )->sin_addr, sizeof(sin.sin_addr) ); freeaddrinfo ( hp ); #else memcpy ( &sin.sin_addr, hp->h_addr, Min ( sizeof(sin.sin_addr), (size_t)hp->h_length ) ); my_gethostbyname_r_free(); #endif } } else { #ifndef __WIN__ iDomain = AF_UNIX; iSockaddrSize = sizeof(saun); pSockaddr = (struct sockaddr *) &saun; memset ( &saun, 0, sizeof(saun) ); saun.sun_family = AF_UNIX; strncpy ( saun.sun_path, sHost, sizeof(saun.sun_path)-1 ); #else my_error ( ER_CONNECT_TO_FOREIGN_DATA_SOURCE, MYF(0), "UNIX sockets are not supported on Windows" ); SPH_RET(-1); #endif } char sError[512]; int iSocket = socket ( iDomain, SOCK_STREAM, 0 ); if ( iSocket<0 ) { my_error ( ER_CONNECT_TO_FOREIGN_DATA_SOURCE, MYF(0), "failed to create client socket" ); SPH_RET(-1); } if ( connect ( iSocket, pSockaddr, iSockaddrSize )<0 ) { sphSockClose ( iSocket ); my_snprintf ( sError, sizeof(sError), "failed to connect to searchd (host=%s, errno=%d, port=%d)", sHost, errno, (int)uPort ); my_error ( ER_CONNECT_TO_FOREIGN_DATA_SOURCE, MYF(0), sError ); SPH_RET(-1); } return iSocket; } int ha_sphinx::ConnectAPI ( const char * sQueryHost, int iQueryPort ) { SPH_ENTER_METHOD(); const char * sHost = ( sQueryHost && *sQueryHost ) ? sQueryHost : m_pShare->m_sHost; ushort uPort = iQueryPort ? (ushort)iQueryPort : m_pShare->m_iPort; int iSocket = Connect ( sHost, uPort ); if ( iSocket<0 ) SPH_RET ( iSocket ); char sError[512]; int version; if ( ::recv ( iSocket, (char *)&version, sizeof(version), 0 )!=sizeof(version) ) { sphSockClose ( iSocket ); my_snprintf ( sError, sizeof(sError), "failed to receive searchd version (host=%s, port=%d)", sHost, (int)uPort ); my_error ( ER_CONNECT_TO_FOREIGN_DATA_SOURCE, MYF(0), sError ); SPH_RET(-1); } uint uClientVersion = htonl ( SPHINX_SEARCHD_PROTO ); if ( ::send ( iSocket, (char*)&uClientVersion, sizeof(uClientVersion), 0 )!=sizeof(uClientVersion) ) { sphSockClose ( iSocket ); my_snprintf ( sError, sizeof(sError), "failed to send client version (host=%s, port=%d)", sHost, (int)uPort ); my_error ( ER_CONNECT_TO_FOREIGN_DATA_SOURCE, MYF(0), sError ); SPH_RET(-1); } SPH_RET ( iSocket ); } // Closes a table. We call the free_share() function to free any resources // that we have allocated in the "shared" structure. // // Called from sql_base.cc, sql_select.cc, and table.cc. // In sql_select.cc it is only used to close up temporary tables or during // the process where a temporary table is converted over to being a // myisam table. // For sql_base.cc look at close_data_tables(). int ha_sphinx::close() { SPH_ENTER_METHOD(); SPH_RET ( free_share ( m_pShare ) ); } int ha_sphinx::HandleMysqlError ( MYSQL * pConn, int iErrCode ) { CSphSEThreadTable * pTable = GetTls (); if ( pTable ) { strncpy ( pTable->m_tStats.m_sLastMessage, mysql_error ( pConn ), sizeof ( pTable->m_tStats.m_sLastMessage ) ); pTable->m_tStats.m_bLastError = true; } mysql_close ( pConn ); my_error ( iErrCode, MYF(0), pTable->m_tStats.m_sLastMessage ); return -1; } int ha_sphinx::extra ( enum ha_extra_function op ) { CSphSEThreadTable * pTable = GetTls(); if ( pTable ) { if ( op==HA_EXTRA_WRITE_CAN_REPLACE ) pTable->m_bReplace = true; else if ( op==HA_EXTRA_WRITE_CANNOT_REPLACE ) pTable->m_bReplace = false; } return 0; } int ha_sphinx::write_row ( byte * ) { SPH_ENTER_METHOD(); if ( !m_pShare || !m_pShare->m_bSphinxQL ) SPH_RET ( HA_ERR_WRONG_COMMAND ); // SphinxQL inserts only, pretty much similar to abandoned federated char sQueryBuf[1024]; char sValueBuf[1024]; String sQuery ( sQueryBuf, sizeof(sQueryBuf), &my_charset_bin ); String sValue ( sValueBuf, sizeof(sQueryBuf), &my_charset_bin ); sQuery.length ( 0 ); sValue.length ( 0 ); CSphSEThreadTable * pTable = GetTls (); sQuery.append ( pTable && pTable->m_bReplace ? "REPLACE INTO " : "INSERT INTO " ); sQuery.append ( m_pShare->m_sIndex ); sQuery.append ( " (" ); for ( Field ** ppField = table->field; *ppField; ppField++ ) { sQuery.append ( (*ppField)->field_name ); if ( ppField[1] ) sQuery.append ( ", " ); } sQuery.append ( ") VALUES (" ); for ( Field ** ppField = table->field; *ppField; ppField++ ) { if ( (*ppField)->is_null() ) { sQuery.append ( "''" ); } else { if ( (*ppField)->type()==MYSQL_TYPE_TIMESTAMP ) { Item_field * pWrap = new Item_field ( *ppField ); // autofreed by query arena, I assume Item_func_unix_timestamp * pConv = new Item_func_unix_timestamp ( pWrap ); pConv->quick_fix_field(); unsigned int uTs = (unsigned int) pConv->val_int(); snprintf ( sValueBuf, sizeof(sValueBuf), "'%u'", uTs ); sQuery.append ( sValueBuf ); } else { (*ppField)->val_str ( &sValue ); int iLen = sValue.length(); bool bMva = ( iLen>1 && sValue.ptr()[0]=='(' && sValue.ptr()[iLen-1]==')' ); if ( !bMva ) sQuery.append ( "'" ); sValue.print ( &sQuery ); if ( !bMva ) sQuery.append ( "'" ); sValue.length(0); } } if ( ppField[1] ) sQuery.append ( ", " ); } sQuery.append ( ")" ); // FIXME? pretty inefficient to reconnect every time under high load, // but this was intentionally written for a low load scenario.. MYSQL * pConn = mysql_init ( NULL ); if ( !pConn ) SPH_RET ( ER_OUT_OF_RESOURCES ); unsigned int uTimeout = 1; mysql_options ( pConn, MYSQL_OPT_CONNECT_TIMEOUT, (const char*)&uTimeout ); if ( !mysql_real_connect ( pConn, m_pShare->m_sHost, "root", "", "", m_pShare->m_iPort, m_pShare->m_sSocket, 0 ) ) SPH_RET ( HandleMysqlError ( pConn, ER_CONNECT_TO_FOREIGN_DATA_SOURCE ) ); if ( mysql_real_query ( pConn, sQuery.ptr(), sQuery.length() ) ) SPH_RET ( HandleMysqlError ( pConn, ER_QUERY_ON_FOREIGN_DATA_SOURCE ) ); // all ok! mysql_close ( pConn ); SPH_RET(0); } static inline bool IsIntegerFieldType ( enum_field_types eType ) { return eType==MYSQL_TYPE_LONG || eType==MYSQL_TYPE_LONGLONG; } static inline bool IsIDField ( Field * pField ) { enum_field_types eType = pField->type(); if ( eType==MYSQL_TYPE_LONGLONG ) return true; if ( eType==MYSQL_TYPE_LONG && ((Field_num*)pField)->unsigned_flag ) return true; return false; } int ha_sphinx::delete_row ( const byte * ) { SPH_ENTER_METHOD(); if ( !m_pShare || !m_pShare->m_bSphinxQL ) SPH_RET ( HA_ERR_WRONG_COMMAND ); char sQueryBuf[1024]; String sQuery ( sQueryBuf, sizeof(sQueryBuf), &my_charset_bin ); sQuery.length ( 0 ); sQuery.append ( "DELETE FROM " ); sQuery.append ( m_pShare->m_sIndex ); sQuery.append ( " WHERE id=" ); char sValue[32]; snprintf ( sValue, sizeof(sValue), "%lld", table->field[0]->val_int() ); sQuery.append ( sValue ); // FIXME? pretty inefficient to reconnect every time under high load, // but this was intentionally written for a low load scenario.. MYSQL * pConn = mysql_init ( NULL ); if ( !pConn ) SPH_RET ( ER_OUT_OF_RESOURCES ); unsigned int uTimeout = 1; mysql_options ( pConn, MYSQL_OPT_CONNECT_TIMEOUT, (const char*)&uTimeout ); if ( !mysql_real_connect ( pConn, m_pShare->m_sHost, "root", "", "", m_pShare->m_iPort, m_pShare->m_sSocket, 0 ) ) SPH_RET ( HandleMysqlError ( pConn, ER_CONNECT_TO_FOREIGN_DATA_SOURCE ) ); if ( mysql_real_query ( pConn, sQuery.ptr(), sQuery.length() ) ) SPH_RET ( HandleMysqlError ( pConn, ER_QUERY_ON_FOREIGN_DATA_SOURCE ) ); // all ok! mysql_close ( pConn ); SPH_RET(0); } int ha_sphinx::update_row ( const byte *, byte * ) { SPH_ENTER_METHOD(); SPH_RET ( HA_ERR_WRONG_COMMAND ); } // keynr is key (index) number // sorted is 1 if result MUST be sorted according to index int ha_sphinx::index_init ( uint keynr, bool ) { SPH_ENTER_METHOD(); active_index = keynr; CSphSEThreadTable * pTable = GetTls(); if ( pTable ) pTable->m_bCondDone = false; SPH_RET(0); } int ha_sphinx::index_end() { SPH_ENTER_METHOD(); SPH_RET(0); } bool ha_sphinx::CheckResponcePtr ( int iLen ) { if ( m_pCur+iLen>m_pResponseEnd ) { m_pCur = m_pResponseEnd; m_bUnpackError = true; return false; } return true; } uint32 ha_sphinx::UnpackDword () { if ( !CheckResponcePtr ( sizeof(uint32) ) ) // NOLINT { return 0; } uint32 uRes = ntohl ( sphUnalignedRead ( *(uint32*)m_pCur ) ); m_pCur += sizeof(uint32); // NOLINT return uRes; } char * ha_sphinx::UnpackString () { uint32 iLen = UnpackDword (); if ( !iLen ) return NULL; if ( !CheckResponcePtr ( iLen ) ) { return NULL; } char * sRes = new char [ 1+iLen ]; memcpy ( sRes, m_pCur, iLen ); sRes[iLen] = '\0'; m_pCur += iLen; return sRes; } static inline const char * FixNull ( const char * s ) { return s ? s : "(null)"; } bool ha_sphinx::UnpackSchema () { SPH_ENTER_METHOD(); // cleanup if ( m_dFields ) for ( int i=0; i<(int)m_iFields; i++ ) SafeDeleteArray ( m_dFields[i] ); SafeDeleteArray ( m_dFields ); // unpack network packet uint32 uStatus = UnpackDword (); char * sMessage = NULL; if ( uStatus!=SEARCHD_OK ) { sMessage = UnpackString (); CSphSEThreadTable * pTable = GetTls (); if ( pTable ) { strncpy ( pTable->m_tStats.m_sLastMessage, sMessage, sizeof(pTable->m_tStats.m_sLastMessage) ); pTable->m_tStats.m_bLastError = ( uStatus==SEARCHD_ERROR ); } if ( uStatus==SEARCHD_ERROR ) { char sError[1024]; my_snprintf ( sError, sizeof(sError), "searchd error: %s", sMessage ); my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), sError ); SafeDeleteArray ( sMessage ); SPH_RET ( false ); } } m_iFields = UnpackDword (); m_dFields = new char * [ m_iFields ]; if ( !m_dFields ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: UnpackSchema() failed (fields alloc error)" ); SPH_RET(false); } for ( uint32 i=0; i<m_iFields; i++ ) m_dFields[i] = UnpackString (); SafeDeleteArray ( m_dAttrs ); m_iAttrs = UnpackDword (); m_dAttrs = new CSphSEAttr [ m_iAttrs ]; if ( !m_dAttrs ) { for ( int i=0; i<(int)m_iFields; i++ ) SafeDeleteArray ( m_dFields[i] ); SafeDeleteArray ( m_dFields ); my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: UnpackSchema() failed (attrs alloc error)" ); SPH_RET(false); } for ( uint32 i=0; i<m_iAttrs; i++ ) { m_dAttrs[i].m_sName = UnpackString (); m_dAttrs[i].m_uType = UnpackDword (); if ( m_bUnpackError ) // m_sName may be null break; m_dAttrs[i].m_iField = -1; for ( int j=SPHINXSE_SYSTEM_COLUMNS; j<m_pShare->m_iTableFields; j++ ) { const char * sTableField = m_pShare->m_sTableField[j]; const char * sAttrField = m_dAttrs[i].m_sName; if ( m_dAttrs[i].m_sName[0]=='@' ) { const char * sAtPrefix = "_sph_"; if ( strncmp ( sTableField, sAtPrefix, strlen(sAtPrefix) ) ) continue; sTableField += strlen(sAtPrefix); sAttrField++; } if ( !strcasecmp ( sAttrField, sTableField ) ) { // we're almost good, but // let's enforce that timestamp columns can only receive timestamp attributes if ( m_pShare->m_eTableFieldType[j]!=MYSQL_TYPE_TIMESTAMP || m_dAttrs[i].m_uType==SPH_ATTR_TIMESTAMP ) m_dAttrs[i].m_iField = j; break; } } } m_iMatchesTotal = UnpackDword (); m_bId64 = UnpackDword (); if ( m_bId64 && m_pShare->m_eTableFieldType[0]!=MYSQL_TYPE_LONGLONG ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: 1st column must be bigint to accept 64-bit DOCIDs" ); SPH_RET(false); } // network packet unpacked; build unbound fields map SafeDeleteArray ( m_dUnboundFields ); m_dUnboundFields = new int [ m_pShare->m_iTableFields ]; for ( int i=0; i<m_pShare->m_iTableFields; i++ ) { if ( i<SPHINXSE_SYSTEM_COLUMNS ) m_dUnboundFields[i] = SPH_ATTR_NONE; else if ( m_pShare->m_eTableFieldType[i]==MYSQL_TYPE_TIMESTAMP ) m_dUnboundFields[i] = SPH_ATTR_TIMESTAMP; else m_dUnboundFields[i] = SPH_ATTR_INTEGER; } for ( uint32 i=0; i<m_iAttrs; i++ ) if ( m_dAttrs[i].m_iField>=0 ) m_dUnboundFields [ m_dAttrs[i].m_iField ] = SPH_ATTR_NONE; if ( m_bUnpackError ) my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: UnpackSchema() failed (unpack error)" ); SPH_RET ( !m_bUnpackError ); } bool ha_sphinx::UnpackStats ( CSphSEStats * pStats ) { assert ( pStats ); char * pCurSave = m_pCur; for ( uint i=0; i<m_iMatchesTotal && m_pCur<m_pResponseEnd-sizeof(uint32); i++ ) // NOLINT { m_pCur += m_bId64 ? 12 : 8; // skip id+weight for ( uint32 i=0; i<m_iAttrs && m_pCur<m_pResponseEnd-sizeof(uint32); i++ ) // NOLINT { if ( m_dAttrs[i].m_uType==SPH_ATTR_UINT32SET || m_dAttrs[i].m_uType==SPH_ATTR_UINT64SET ) { // skip MVA list uint32 uCount = UnpackDword (); m_pCur += uCount*4; } else if ( m_dAttrs[i].m_uType==SPH_ATTR_STRING ) { uint32 iLen = UnpackDword(); m_pCur += iLen; } else // skip normal value m_pCur += m_dAttrs[i].m_uType==SPH_ATTR_BIGINT ? 8 : 4; } } pStats->m_iMatchesTotal = UnpackDword (); pStats->m_iMatchesFound = UnpackDword (); pStats->m_iQueryMsec = UnpackDword (); pStats->m_iWords = UnpackDword (); if ( m_bUnpackError ) return false; SafeDeleteArray ( pStats->m_dWords ); if ( pStats->m_iWords<0 || pStats->m_iWords>=SPHINXSE_MAX_KEYWORDSTATS ) return false; pStats->m_dWords = new CSphSEWordStats [ pStats->m_iWords ]; if ( !pStats->m_dWords ) return false; for ( int i=0; i<pStats->m_iWords; i++ ) { CSphSEWordStats & tWord = pStats->m_dWords[i]; tWord.m_sWord = UnpackString (); tWord.m_iDocs = UnpackDword (); tWord.m_iHits = UnpackDword (); } if ( m_bUnpackError ) return false; m_pCur = pCurSave; return true; } /// condition pushdown implementation, to properly intercept WHERE clauses on my columns #if MYSQL_VERSION_ID<50610 const COND * ha_sphinx::cond_push ( const COND * cond ) #else const Item * ha_sphinx::cond_push ( const Item *cond ) #endif { // catch the simplest case: query_column="some text" while (true) { if ( cond->type()!=Item::FUNC_ITEM ) break; Item_func * condf = (Item_func *)cond; if ( condf->functype()!=Item_func::EQ_FUNC || condf->argument_count()!=2 ) break; // get my tls CSphSEThreadTable * pTable = GetTls (); if ( !pTable ) break; Item ** args = condf->arguments(); if ( !m_pShare->m_bSphinxQL ) { // on non-QL tables, intercept query=value condition for SELECT if (!( args[0]->type()==Item::FIELD_ITEM && args[1]->type()==Item::STRING_ITEM )) break; Item_field * pField = (Item_field *) args[0]; if ( pField->field->field_index!=2 ) // FIXME! magic key index break; // copy the query, and let know that we intercepted this condition Item_string * pString = (Item_string *) args[1]; pTable->m_bQuery = true; strncpy ( pTable->m_sQuery, pString->str_value.c_ptr(), sizeof(pTable->m_sQuery) ); pTable->m_sQuery[sizeof(pTable->m_sQuery)-1] = '\0'; pTable->m_pQueryCharset = pString->str_value.charset(); } else { if (!( args[0]->type()==Item::FIELD_ITEM && args[1]->type()==Item::INT_ITEM )) break; // on QL tables, intercept id=value condition for DELETE Item_field * pField = (Item_field *) args[0]; if ( pField->field->field_index!=0 ) // FIXME! magic key index break; Item_int * pVal = (Item_int *) args[1]; pTable->m_iCondId = pVal->val_int(); pTable->m_bCondId = true; } // we intercepted this condition return NULL; } // don't change anything return cond; } /// condition popup void ha_sphinx::cond_pop () { CSphSEThreadTable * pTable = GetTls (); if ( pTable ) pTable->m_bQuery = false; } /// get TLS (maybe allocate it, too) CSphSEThreadTable * ha_sphinx::GetTls() { SPH_ENTER_METHOD() // where do we store that pointer in today's version? CSphTLS ** ppTls; #if MYSQL_VERSION_ID>50100 ppTls = (CSphTLS**) thd_ha_data ( table->in_use, ht ); #else ppTls = (CSphTLS**) &current_thd->ha_data[sphinx_hton.slot]; #endif // >50100 CSphSEThreadTable * pTable = NULL; // allocate if needed if ( !*ppTls ) { *ppTls = new CSphTLS ( this ); pTable = (*ppTls)->m_pHeadTable; } else { pTable = (*ppTls)->m_pHeadTable; } while ( pTable && pTable->m_pHandler!=this ) pTable = pTable->m_pTableNext; if ( !pTable ) { pTable = new CSphSEThreadTable ( this ); pTable->m_pTableNext = (*ppTls)->m_pHeadTable; (*ppTls)->m_pHeadTable = pTable; } // errors will be handled by caller return pTable; } // Positions an index cursor to the index specified in the handle. Fetches the // row if available. If the key value is null, begin at the first key of the // index. int ha_sphinx::index_read ( byte * buf, const byte * key, uint key_len, enum ha_rkey_function ) { SPH_ENTER_METHOD(); char sError[256]; // set new data for thd->ha_data, it is used in show_status CSphSEThreadTable * pTable = GetTls(); if ( !pTable ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: TLS malloc() failed" ); SPH_RET ( HA_ERR_END_OF_FILE ); } pTable->m_tStats.Reset (); // sphinxql table, just return the key once if ( m_pShare->m_bSphinxQL ) { // over and out if ( pTable->m_bCondDone ) SPH_RET ( HA_ERR_END_OF_FILE ); // return a value from pushdown, if any if ( pTable->m_bCondId ) { table->field[0]->store ( pTable->m_iCondId, 1 ); pTable->m_bCondDone = true; SPH_RET(0); } // return a value from key longlong iRef = 0; if ( key_len==4 ) iRef = uint4korr ( key ); else if ( key_len==8 ) iRef = uint8korr ( key ); else { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: unexpected key length" ); SPH_RET ( HA_ERR_END_OF_FILE ); } table->field[0]->store ( iRef, 1 ); pTable->m_bCondDone = true; SPH_RET(0); } // parse query if ( pTable->m_bQuery ) { // we have a query from condition pushdown m_pCurrentKey = (const byte *) pTable->m_sQuery; m_iCurrentKeyLen = strlen(pTable->m_sQuery); } else { // just use the key (might be truncated) m_pCurrentKey = key+HA_KEY_BLOB_LENGTH; m_iCurrentKeyLen = uint2korr(key); // or maybe key_len? pTable->m_pQueryCharset = m_pShare ? m_pShare->m_pTableQueryCharset : NULL; } CSphSEQuery q ( (const char*)m_pCurrentKey, m_iCurrentKeyLen, m_pShare->m_sIndex ); if ( !q.Parse () ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), q.m_sParseError ); SPH_RET ( HA_ERR_END_OF_FILE ); } // do connect int iSocket = ConnectAPI ( q.m_sHost, q.m_iPort ); if ( iSocket<0 ) SPH_RET ( HA_ERR_END_OF_FILE ); // my buffer char * pBuffer; // will be free by CSphSEQuery dtor; do NOT free manually int iReqLen = q.BuildRequest ( &pBuffer ); if ( iReqLen<=0 ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: q.BuildRequest() failed" ); SPH_RET ( HA_ERR_END_OF_FILE ); } // send request ::send ( iSocket, pBuffer, iReqLen, 0 ); // receive reply char sHeader[8]; int iGot = ::recv ( iSocket, sHeader, sizeof(sHeader), RECV_FLAGS ); if ( iGot!=sizeof(sHeader) ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "failed to receive response header (searchd went away?)" ); SPH_RET ( HA_ERR_END_OF_FILE ); } short int uRespStatus = ntohs ( sphUnalignedRead ( *(short int*)( &sHeader[0] ) ) ); short int uRespVersion = ntohs ( sphUnalignedRead ( *(short int*)( &sHeader[2] ) ) ); uint uRespLength = ntohl ( sphUnalignedRead ( *(uint *)( &sHeader[4] ) ) ); SPH_DEBUG ( "got response header (status=%d version=%d length=%d)", uRespStatus, uRespVersion, uRespLength ); SafeDeleteArray ( m_pResponse ); if ( uRespLength<=SPHINXSE_MAX_ALLOC ) m_pResponse = new char [ uRespLength+1 ]; if ( !m_pResponse ) { my_snprintf ( sError, sizeof(sError), "bad searchd response length (length=%u)", uRespLength ); my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), sError ); SPH_RET ( HA_ERR_END_OF_FILE ); } int iRecvLength = 0; while ( iRecvLength<(int)uRespLength ) { int iRecv = ::recv ( iSocket, m_pResponse+iRecvLength, uRespLength-iRecvLength, RECV_FLAGS ); if ( iRecv<0 ) break; iRecvLength += iRecv; } ::closesocket ( iSocket ); iSocket = -1; if ( iRecvLength!=(int)uRespLength ) { my_snprintf ( sError, sizeof(sError), "net read error (expected=%d, got=%d)", uRespLength, iRecvLength ); my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), sError ); SPH_RET ( HA_ERR_END_OF_FILE ); } // we'll have a message, at least pTable->m_bStats = true; // parse reply m_iCurrentPos = 0; m_pCur = m_pResponse; m_pResponseEnd = m_pResponse + uRespLength; m_bUnpackError = false; if ( uRespStatus!=SEARCHD_OK ) { char * sMessage = UnpackString (); if ( !sMessage ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "no valid response from searchd (status=%d, resplen=%d)", uRespStatus, uRespLength ); SPH_RET ( HA_ERR_END_OF_FILE ); } strncpy ( pTable->m_tStats.m_sLastMessage, sMessage, sizeof(pTable->m_tStats.m_sLastMessage) ); SafeDeleteArray ( sMessage ); if ( uRespStatus!=SEARCHD_WARNING ) { my_snprintf ( sError, sizeof(sError), "searchd error: %s", pTable->m_tStats.m_sLastMessage ); my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), sError ); pTable->m_tStats.m_bLastError = true; SPH_RET ( HA_ERR_END_OF_FILE ); } } if ( !UnpackSchema () ) SPH_RET ( HA_ERR_END_OF_FILE ); if ( !UnpackStats ( &pTable->m_tStats ) ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: UnpackStats() failed" ); SPH_RET ( HA_ERR_END_OF_FILE ); } SPH_RET ( get_rec ( buf, key, key_len ) ); } // Positions an index cursor to the index specified in key. Fetches the // row if any. This is only used to read whole keys. int ha_sphinx::index_read_idx ( byte *, uint, const byte *, uint, enum ha_rkey_function ) { SPH_ENTER_METHOD(); SPH_RET ( HA_ERR_WRONG_COMMAND ); } // Used to read forward through the index. int ha_sphinx::index_next ( byte * buf ) { SPH_ENTER_METHOD(); SPH_RET ( get_rec ( buf, m_pCurrentKey, m_iCurrentKeyLen ) ); } int ha_sphinx::index_next_same ( byte * buf, const byte * key, uint keylen ) { SPH_ENTER_METHOD(); SPH_RET ( get_rec ( buf, key, keylen ) ); } #ifndef PRIi64 #define PRIi64 "lld" #endif #define INT64_FMT "%" PRIi64 int ha_sphinx::get_rec ( byte * buf, const byte *, uint ) { SPH_ENTER_METHOD(); if ( m_iCurrentPos>=m_iMatchesTotal ) { SafeDeleteArray ( m_pResponse ); SPH_RET ( HA_ERR_END_OF_FILE ); } #if MYSQL_VERSION_ID>50100 my_bitmap_map * org_bitmap = dbug_tmp_use_all_columns ( table, table->write_set ); #endif Field ** field = table->field; // unpack and return the match longlong uMatchID = UnpackDword (); if ( m_bId64 ) uMatchID = ( uMatchID<<32 ) + UnpackDword(); uint32 uMatchWeight = UnpackDword (); field[0]->store ( uMatchID, 1 ); field[1]->store ( uMatchWeight, 1 ); field[2]->store ( (const char*)m_pCurrentKey, m_iCurrentKeyLen, &my_charset_bin ); for ( uint32 i=0; i<m_iAttrs; i++ ) { longlong iValue64 = 0; uint32 uValue = UnpackDword (); if ( m_dAttrs[i].m_uType==SPH_ATTR_BIGINT ) iValue64 = ( (longlong)uValue<<32 ) | UnpackDword(); if ( m_dAttrs[i].m_iField<0 ) { // skip MVA or String if ( m_dAttrs[i].m_uType==SPH_ATTR_UINT32SET || m_dAttrs[i].m_uType==SPH_ATTR_UINT64SET ) { for ( ; uValue>0 && !m_bUnpackError; uValue-- ) UnpackDword(); } else if ( m_dAttrs[i].m_uType==SPH_ATTR_STRING && CheckResponcePtr ( uValue ) ) { m_pCur += uValue; } continue; } Field * af = field [ m_dAttrs[i].m_iField ]; switch ( m_dAttrs[i].m_uType ) { case SPH_ATTR_INTEGER: case SPH_ATTR_ORDINAL: case SPH_ATTR_BOOL: af->store ( uValue, 1 ); break; case SPH_ATTR_FLOAT: af->store ( sphDW2F(uValue) ); break; case SPH_ATTR_TIMESTAMP: if ( af->type()==MYSQL_TYPE_TIMESTAMP ) longstore ( af->ptr, uValue ); // because store() does not accept timestamps else af->store ( uValue, 1 ); break; case SPH_ATTR_BIGINT: af->store ( iValue64, 0 ); break; case SPH_ATTR_STRING: if ( !uValue ) af->store ( "", 0, &my_charset_bin ); else if ( CheckResponcePtr ( uValue ) ) { af->store ( m_pCur, uValue, &my_charset_bin ); m_pCur += uValue; } break; case SPH_ATTR_UINT64SET: case SPH_ATTR_UINT32SET : if ( uValue<=0 ) { // shortcut, empty MVA set af->store ( "", 0, &my_charset_bin ); } else { // convert MVA set to comma-separated string char sBuf[1024]; // FIXME! magic size char * pCur = sBuf; if ( m_dAttrs[i].m_uType==SPH_ATTR_UINT32SET ) { for ( ; uValue>0 && !m_bUnpackError; uValue-- ) { uint32 uEntry = UnpackDword (); if ( pCur < sBuf+sizeof(sBuf)-16 ) // 10 chars per 32bit value plus some safety bytes { snprintf ( pCur, sBuf+sizeof(sBuf)-pCur, "%u", uEntry ); while ( *pCur ) pCur++; if ( uValue>1 ) *pCur++ = ','; // non-trailing commas } } } else { for ( ; uValue>0 && !m_bUnpackError; uValue-=2 ) { longlong uEntry = UnpackDword (); uEntry = uEntry<<32; uEntry += UnpackDword(); if ( pCur < sBuf+sizeof(sBuf)-24 ) // 20 chars per 64bit value plus some safety bytes { snprintf ( pCur, sBuf+sizeof(sBuf)-pCur, INT64_FMT, uEntry ); while ( *pCur ) pCur++; if ( uValue>2 ) *pCur++ = ','; // non-trailing commas } } } af->store ( sBuf, pCur-sBuf, &my_charset_bin ); } break; default: my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: unhandled attr type" ); SafeDeleteArray ( m_pResponse ); SPH_RET ( HA_ERR_END_OF_FILE ); } } if ( m_bUnpackError ) { my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: response unpacker failed" ); SafeDeleteArray ( m_pResponse ); SPH_RET ( HA_ERR_END_OF_FILE ); } // zero out unmapped fields for ( int i=SPHINXSE_SYSTEM_COLUMNS; i<(int)table->s->fields; i++ ) if ( m_dUnboundFields[i]!=SPH_ATTR_NONE ) switch ( m_dUnboundFields[i] ) { case SPH_ATTR_INTEGER: table->field[i]->store ( 0, 1 ); break; case SPH_ATTR_TIMESTAMP: longstore ( table->field[i]->ptr, 0 ); break; default: my_error ( ER_QUERY_ON_FOREIGN_DATA_SOURCE, MYF(0), "INTERNAL ERROR: unhandled unbound field type %d", m_dUnboundFields[i] ); SafeDeleteArray ( m_pResponse ); SPH_RET ( HA_ERR_END_OF_FILE ); } memset ( buf, 0, table->s->null_bytes ); m_iCurrentPos++; #if MYSQL_VERSION_ID > 50100 dbug_tmp_restore_column_map ( table->write_set, org_bitmap ); #endif SPH_RET(0); } // Used to read backwards through the index. int ha_sphinx::index_prev ( byte * ) { SPH_ENTER_METHOD(); SPH_RET ( HA_ERR_WRONG_COMMAND ); } // index_first() asks for the first key in the index. // // Called from opt_range.cc, opt_sum.cc, sql_handler.cc, // and sql_select.cc. int ha_sphinx::index_first ( byte * ) { SPH_ENTER_METHOD(); SPH_RET ( HA_ERR_END_OF_FILE ); } // index_last() asks for the last key in the index. // // Called from opt_range.cc, opt_sum.cc, sql_handler.cc, // and sql_select.cc. int ha_sphinx::index_last ( byte * ) { SPH_ENTER_METHOD(); SPH_RET ( HA_ERR_WRONG_COMMAND ); } int ha_sphinx::rnd_init ( bool ) { SPH_ENTER_METHOD(); SPH_RET(0); } int ha_sphinx::rnd_end() { SPH_ENTER_METHOD(); SPH_RET(0); } int ha_sphinx::rnd_next ( byte * ) { SPH_ENTER_METHOD(); SPH_RET ( HA_ERR_END_OF_FILE ); } void ha_sphinx::position ( const byte * ) { SPH_ENTER_METHOD(); SPH_VOID_RET(); } // This is like rnd_next, but you are given a position to use // to determine the row. The position will be of the type that you stored in // ref. You can use ha_get_ptr(pos,ref_length) to retrieve whatever key // or position you saved when position() was called. // Called from filesort.cc records.cc sql_insert.cc sql_select.cc sql_update.cc. int ha_sphinx::rnd_pos ( byte *, byte * ) { SPH_ENTER_METHOD(); SPH_RET ( HA_ERR_WRONG_COMMAND ); } #if MYSQL_VERSION_ID>=50030 int ha_sphinx::info ( uint ) #else void ha_sphinx::info ( uint ) #endif { SPH_ENTER_METHOD(); if ( table->s->keys>0 ) table->key_info[0].rec_per_key[0] = 1; #if MYSQL_VERSION_ID>50100 stats.records = 20; #else records = 20; #endif #if MYSQL_VERSION_ID>=50030 SPH_RET(0); #else SPH_VOID_RET(); #endif } int ha_sphinx::reset () { SPH_ENTER_METHOD(); CSphSEThreadTable * pTable = GetTls (); if ( pTable ) pTable->m_bQuery = false; SPH_RET(0); } int ha_sphinx::delete_all_rows() { SPH_ENTER_METHOD(); SPH_RET ( HA_ERR_WRONG_COMMAND ); } // First you should go read the section "locking functions for mysql" in // lock.cc to understand this. // This create a lock on the table. If you are implementing a storage engine // that can handle transacations look at ha_berkely.cc to see how you will // want to go about doing this. Otherwise you should consider calling flock() // here. // // Called from lock.cc by lock_external() and unlock_external(). Also called // from sql_table.cc by copy_data_between_tables(). int ha_sphinx::external_lock ( THD *, int ) { SPH_ENTER_METHOD(); SPH_RET(0); } THR_LOCK_DATA ** ha_sphinx::store_lock ( THD *, THR_LOCK_DATA ** to, enum thr_lock_type lock_type ) { SPH_ENTER_METHOD(); if ( lock_type!=TL_IGNORE && m_tLock.type==TL_UNLOCK ) m_tLock.type = lock_type; *to++ = &m_tLock; SPH_RET(to); } int ha_sphinx::delete_table ( const char * ) { SPH_ENTER_METHOD(); SPH_RET(0); } // Renames a table from one name to another from alter table call. // // If you do not implement this, the default rename_table() is called from // handler.cc and it will delete all files with the file extentions returned // by bas_ext(). // // Called from sql_table.cc by mysql_rename_table(). int ha_sphinx::rename_table ( const char *, const char * ) { SPH_ENTER_METHOD(); SPH_RET(0); } // Given a starting key, and an ending key estimate the number of rows that // will exist between the two. end_key may be empty which in case determine // if start_key matches any rows. // // Called from opt_range.cc by check_quick_keys(). ha_rows ha_sphinx::records_in_range ( uint, key_range *, key_range * ) { SPH_ENTER_METHOD(); SPH_RET(3); // low number to force index usage } #if MYSQL_VERSION_ID < 50610 #define user_defined_key_parts key_parts #endif // create() is called to create a database. The variable name will have the name // of the table. When create() is called you do not need to worry about opening // the table. Also, the FRM file will have already been created so adjusting // create_info will not do you any good. You can overwrite the frm file at this // point if you wish to change the table definition, but there are no methods // currently provided for doing that. // // Called from handle.cc by ha_create_table(). int ha_sphinx::create ( const char * name, TABLE * table, HA_CREATE_INFO * ) { SPH_ENTER_METHOD(); char sError[256]; CSphSEShare tInfo; if ( !ParseUrl ( &tInfo, table, true ) ) SPH_RET(-1); // check SphinxAPI table for ( ; !tInfo.m_bSphinxQL; ) { // check system fields (count and types) if ( table->s->fields<SPHINXSE_SYSTEM_COLUMNS ) { my_snprintf ( sError, sizeof(sError), "%s: there MUST be at least %d columns", name, SPHINXSE_SYSTEM_COLUMNS ); break; } if ( !IsIDField ( table->field[0] ) ) { my_snprintf ( sError, sizeof(sError), "%s: 1st column (docid) MUST be unsigned integer or bigint", name ); break; } if ( !IsIntegerFieldType ( table->field[1]->type() ) ) { my_snprintf ( sError, sizeof(sError), "%s: 2nd column (weight) MUST be integer or bigint", name ); break; } enum_field_types f2 = table->field[2]->type(); if ( f2!=MYSQL_TYPE_VARCHAR && f2!=MYSQL_TYPE_BLOB && f2!=MYSQL_TYPE_MEDIUM_BLOB && f2!=MYSQL_TYPE_LONG_BLOB && f2!=MYSQL_TYPE_TINY_BLOB ) { my_snprintf ( sError, sizeof(sError), "%s: 3rd column (search query) MUST be varchar or text", name ); break; } // check attributes int i; for ( i=3; i<(int)table->s->fields; i++ ) { enum_field_types eType = table->field[i]->type(); if ( eType!=MYSQL_TYPE_TIMESTAMP && !IsIntegerFieldType(eType) && eType!=MYSQL_TYPE_VARCHAR && eType!=MYSQL_TYPE_FLOAT ) { my_snprintf ( sError, sizeof(sError), "%s: %dth column (attribute %s) MUST be integer, bigint, timestamp, varchar, or float", name, i+1, table->field[i]->field_name ); break; } } if ( i!=(int)table->s->fields ) break; // check index if ( table->s->keys!=1 || table->key_info[0].user_defined_key_parts!=1 || strcasecmp ( table->key_info[0].key_part[0].field->field_name, table->field[2]->field_name ) ) { my_snprintf ( sError, sizeof(sError), "%s: there must be an index on '%s' column", name, table->field[2]->field_name ); break; } // all good sError[0] = '\0'; break; } // check SphinxQL table for ( ; tInfo.m_bSphinxQL; ) { sError[0] = '\0'; // check that 1st column is id, is of int type, and has an index if ( strcmp ( table->field[0]->field_name, "id" ) ) { my_snprintf ( sError, sizeof(sError), "%s: 1st column must be called 'id'", name ); break; } if ( !IsIDField ( table->field[0] ) ) { my_snprintf ( sError, sizeof(sError), "%s: 'id' column must be INT UNSIGNED or BIGINT", name ); break; } // check index if ( table->s->keys!=1 || table->key_info[0].user_defined_key_parts!=1 || strcasecmp ( table->key_info[0].key_part[0].field->field_name, "id" ) ) { my_snprintf ( sError, sizeof(sError), "%s: 'id' column must be indexed", name ); break; } // check column types for ( int i=1; i<(int)table->s->fields; i++ ) { enum_field_types eType = table->field[i]->type(); if ( eType!=MYSQL_TYPE_TIMESTAMP && !IsIntegerFieldType(eType) && eType!=MYSQL_TYPE_VARCHAR && eType!=MYSQL_TYPE_FLOAT ) { my_snprintf ( sError, sizeof(sError), "%s: column %d(%s) is of unsupported type (use int/bigint/timestamp/varchar/float)", name, i+1, table->field[i]->field_name ); break; } } if ( sError[0] ) break; // all good break; } // report and bail if ( sError[0] ) { my_error ( ER_CANT_CREATE_TABLE, MYF(0), sError, -1 ); SPH_RET(-1); } SPH_RET(0); } // show functions #if MYSQL_VERSION_ID<50100 #define SHOW_VAR_FUNC_BUFF_SIZE 1024 #endif CSphSEStats * sphinx_get_stats ( THD * thd, SHOW_VAR * out ) { #if MYSQL_VERSION_ID>50100 if ( sphinx_hton_ptr ) { CSphTLS * pTls = (CSphTLS *) *thd_ha_data ( thd, sphinx_hton_ptr ); if ( pTls && pTls->m_pHeadTable && pTls->m_pHeadTable->m_bStats ) return &pTls->m_pHeadTable->m_tStats; } #else CSphTLS * pTls = (CSphTLS *) thd->ha_data[sphinx_hton.slot]; if ( pTls && pTls->m_pHeadTable && pTls->m_pHeadTable->m_bStats ) return &pTls->m_pHeadTable->m_tStats; #endif out->type = SHOW_CHAR; out->value = ""; return 0; } int sphinx_showfunc_total ( THD * thd, SHOW_VAR * out, char * ) { CSphSEStats * pStats = sphinx_get_stats ( thd, out ); if ( pStats ) { out->type = SHOW_INT; out->value = (char *) &pStats->m_iMatchesTotal; } return 0; } int sphinx_showfunc_total_found ( THD * thd, SHOW_VAR * out, char * ) { CSphSEStats * pStats = sphinx_get_stats ( thd, out ); if ( pStats ) { out->type = SHOW_INT; out->value = (char *) &pStats->m_iMatchesFound; } return 0; } int sphinx_showfunc_time ( THD * thd, SHOW_VAR * out, char * ) { CSphSEStats * pStats = sphinx_get_stats ( thd, out ); if ( pStats ) { out->type = SHOW_INT; out->value = (char *) &pStats->m_iQueryMsec; } return 0; } int sphinx_showfunc_word_count ( THD * thd, SHOW_VAR * out, char * ) { CSphSEStats * pStats = sphinx_get_stats ( thd, out ); if ( pStats ) { out->type = SHOW_INT; out->value = (char *) &pStats->m_iWords; } return 0; } int sphinx_showfunc_words ( THD * thd, SHOW_VAR * out, char * sBuffer ) { #if MYSQL_VERSION_ID>50100 if ( sphinx_hton_ptr ) { CSphTLS * pTls = (CSphTLS *) *thd_ha_data ( thd, sphinx_hton_ptr ); #else { CSphTLS * pTls = (CSphTLS *) thd->ha_data[sphinx_hton.slot]; #endif if ( pTls && pTls->m_pHeadTable && pTls->m_pHeadTable->m_bStats ) { CSphSEStats * pStats = &pTls->m_pHeadTable->m_tStats; if ( pStats && pStats->m_iWords ) { uint uBuffLen = 0; out->type = SHOW_CHAR; out->value = sBuffer; // the following is partially based on code in sphinx_show_status() sBuffer[0] = 0; for ( int i=0; i<pStats->m_iWords; i++ ) { CSphSEWordStats & tWord = pStats->m_dWords[i]; uBuffLen = my_snprintf ( sBuffer, SHOW_VAR_FUNC_BUFF_SIZE, "%s%s:%d:%d ", sBuffer, tWord.m_sWord, tWord.m_iDocs, tWord.m_iHits ); } if ( uBuffLen > 0 ) { // trim last space sBuffer [ --uBuffLen ] = 0; if ( pTls->m_pHeadTable->m_pQueryCharset ) { // String::c_ptr() will nul-terminate the buffer. // // NOTE: It's not entirely clear whether this conversion is necessary at all. String sConvert; uint iErrors; sConvert.copy ( sBuffer, uBuffLen, pTls->m_pHeadTable->m_pQueryCharset, system_charset_info, &iErrors ); memcpy ( sBuffer, sConvert.c_ptr(), sConvert.length() + 1 ); } } return 0; } } } out->type = SHOW_CHAR; out->value = ""; return 0; } int sphinx_showfunc_error ( THD * thd, SHOW_VAR * out, char * ) { CSphSEStats * pStats = sphinx_get_stats ( thd, out ); if ( pStats && pStats->m_bLastError ) { out->type = SHOW_CHAR; out->value = pStats->m_sLastMessage; } return 0; } #if MYSQL_VERSION_ID>50100 struct st_mysql_storage_engine sphinx_storage_engine = { MYSQL_HANDLERTON_INTERFACE_VERSION }; struct st_mysql_show_var sphinx_status_vars[] = { {"sphinx_total", (char *)sphinx_showfunc_total, SHOW_FUNC}, {"sphinx_total_found", (char *)sphinx_showfunc_total_found, SHOW_FUNC}, {"sphinx_time", (char *)sphinx_showfunc_time, SHOW_FUNC}, {"sphinx_word_count", (char *)sphinx_showfunc_word_count, SHOW_FUNC}, {"sphinx_words", (char *)sphinx_showfunc_words, SHOW_FUNC}, {"sphinx_error", (char *)sphinx_showfunc_error, SHOW_FUNC}, {0, 0, (enum_mysql_show_type)0} }; mysql_declare_plugin(sphinx) { MYSQL_STORAGE_ENGINE_PLUGIN, &sphinx_storage_engine, sphinx_hton_name, "Sphinx developers", sphinx_hton_comment, PLUGIN_LICENSE_GPL, sphinx_init_func, // Plugin Init sphinx_done_func, // Plugin Deinit 0x0001, // 0.1 sphinx_status_vars, NULL, NULL } mysql_declare_plugin_end; #endif // >50100
93,175
C++
.cc
3,086
27.436811
136
0.644302
manticoresoftware/manticoresearch
8,893
493
500
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,061
ha_sphinx.h
manticoresoftware_manticoresearch/mysqlse/ha_sphinx.h
#ifdef USE_PRAGMA_INTERFACE #pragma interface // gcc class implementation #endif #if MYSQL_VERSION_ID>=50515 #define TABLE_ARG TABLE_SHARE #elif MYSQL_VERSION_ID>50100 #define TABLE_ARG st_table_share #else #define TABLE_ARG st_table #endif #if MYSQL_VERSION_ID>=50120 typedef uchar byte; #endif /// forward decls class THD; struct CSphReqQuery; struct CSphSEShare; struct CSphSEAttr; struct CSphSEStats; struct CSphSEThreadTable; /// Sphinx SE handler class class ha_sphinx : public handler { protected: THR_LOCK_DATA m_tLock; ///< MySQL lock CSphSEShare * m_pShare; ///< shared lock info uint m_iMatchesTotal; uint m_iCurrentPos; const byte * m_pCurrentKey; uint m_iCurrentKeyLen; char * m_pResponse; ///< searchd response storage char * m_pResponseEnd; ///< searchd response storage end (points to wilderness!) char * m_pCur; ///< current position into response bool m_bUnpackError; ///< any errors while unpacking response public: #if MYSQL_VERSION_ID<50100 ha_sphinx ( TABLE_ARG * table_arg ); // NOLINT #else ha_sphinx ( handlerton * hton, TABLE_ARG * table_arg ); #endif ~ha_sphinx () {} const char * table_type () const { return "SPHINX"; } ///< SE name for display purposes const char * index_type ( uint ) { return "HASH"; } ///< index type name for display purposes const char ** bas_ext () const; ///< my file extensions #if MYSQL_VERSION_ID>50100 ulonglong table_flags () const { return HA_CAN_INDEX_BLOBS; } ///< bitmap of implemented flags (see handler.h for more info) #else ulong table_flags () const { return HA_CAN_INDEX_BLOBS; } ///< bitmap of implemented flags (see handler.h for more info) #endif ulong index_flags ( uint, uint, bool ) const { return 0; } ///< bitmap of flags that says how SE implements indexes uint max_supported_record_length () const { return HA_MAX_REC_LENGTH; } uint max_supported_keys () const { return 1; } uint max_supported_key_parts () const { return 1; } uint max_supported_key_length () const { return MAX_KEY_LENGTH; } uint max_supported_key_part_length () const { return MAX_KEY_LENGTH; } #if MYSQL_VERSION_ID>50100 virtual double scan_time () { return (double)( stats.records+stats.deleted )/20.0 + 10; } ///< called in test_quick_select to determine if indexes should be used #else virtual double scan_time () { return (double)( records+deleted )/20.0 + 10; } ///< called in test_quick_select to determine if indexes should be used #endif virtual double read_time ( ha_rows rows ) { return (double)rows/20.0 + 1; } ///< index read time estimate public: int open ( const char * name, int mode, uint test_if_locked ); int close (); int write_row ( byte * buf ); int update_row ( const byte * old_data, byte * new_data ); int delete_row ( const byte * buf ); int extra ( enum ha_extra_function op ); int index_init ( uint keynr, bool sorted ); // 5.1.x int index_init ( uint keynr ) { return index_init ( keynr, false ); } // 5.0.x int index_end (); int index_read ( byte * buf, const byte * key, uint key_len, enum ha_rkey_function find_flag ); int index_read_idx ( byte * buf, uint idx, const byte * key, uint key_len, enum ha_rkey_function find_flag ); int index_next ( byte * buf ); int index_next_same ( byte * buf, const byte * key, uint keylen ); int index_prev ( byte * buf ); int index_first ( byte * buf ); int index_last ( byte * buf ); int get_rec ( byte * buf, const byte * key, uint keylen ); int rnd_init ( bool scan ); int rnd_end (); int rnd_next ( byte * buf ); int rnd_pos ( byte * buf, byte * pos ); void position ( const byte * record ); #if MYSQL_VERSION_ID>=50030 int info ( uint ); #else void info ( uint ); #endif int reset(); int external_lock ( THD * thd, int lock_type ); int delete_all_rows (); ha_rows records_in_range ( uint inx, key_range * min_key, key_range * max_key ); int delete_table ( const char * from ); int rename_table ( const char * from, const char * to ); int create ( const char * name, TABLE * form, HA_CREATE_INFO * create_info ); THR_LOCK_DATA ** store_lock ( THD * thd, THR_LOCK_DATA ** to, enum thr_lock_type lock_type ); public: #if MYSQL_VERSION_ID<50610 virtual const COND * cond_push ( const COND *cond ); #else virtual const Item * cond_push ( const Item *cond ); #endif virtual void cond_pop (); private: uint32 m_iFields; char ** m_dFields; uint32 m_iAttrs; CSphSEAttr * m_dAttrs; int m_bId64; int * m_dUnboundFields; private: int Connect ( const char * sQueryHost, ushort uPort ); int ConnectAPI ( const char * sQueryHost, int iQueryPort ); int HandleMysqlError ( struct st_mysql * pConn, int iErrCode ); uint32 UnpackDword (); char * UnpackString (); bool UnpackSchema (); bool UnpackStats ( CSphSEStats * pStats ); bool CheckResponcePtr ( int iLen ); CSphSEThreadTable * GetTls (); }; #if MYSQL_VERSION_ID < 50100 bool sphinx_show_status ( THD * thd ); #endif int sphinx_showfunc_total_found ( THD *, SHOW_VAR *, char * ); int sphinx_showfunc_total ( THD *, SHOW_VAR *, char * ); int sphinx_showfunc_time ( THD *, SHOW_VAR *, char * ); int sphinx_showfunc_word_count ( THD *, SHOW_VAR *, char * ); int sphinx_showfunc_words ( THD *, SHOW_VAR *, char * );
5,399
C++
.h
130
39.5
162
0.678264
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,062
sphinxclient.h
manticoresoftware_manticoresearch/api/libsphinxclient/sphinxclient.h
// // $Id$ // // // 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 Library General Public License version 3 or later. // You should have received a copy of the LGPL license along with this program; // if you did not, you can find it at http://www.gnu.org/ // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING // We strongly recommend you to use SphinxQL instead of the API // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #ifndef _sphinxclient_ #define _sphinxclient_ #ifdef __cplusplus extern "C" { #endif /// known searchd status codes enum { SEARCHD_OK = 0, SEARCHD_ERROR = 1, SEARCHD_RETRY = 2, SEARCHD_WARNING = 3 }; /// known match modes enum { SPH_MATCH_ALL = 0, SPH_MATCH_ANY = 1, SPH_MATCH_PHRASE = 2, SPH_MATCH_BOOLEAN = 3, SPH_MATCH_EXTENDED = 4, SPH_MATCH_FULLSCAN = 5, SPH_MATCH_EXTENDED2 = 6 }; /// known ranking modes (ext2 only) enum { SPH_RANK_PROXIMITY_BM25 = 0, SPH_RANK_BM25 = 1, SPH_RANK_NONE = 2, SPH_RANK_WORDCOUNT = 3, SPH_RANK_PROXIMITY = 4, SPH_RANK_MATCHANY = 5, SPH_RANK_FIELDMASK = 6, SPH_RANK_SPH04 = 7, SPH_RANK_EXPR = 8, SPH_RANK_TOTAL = 9, SPH_RANK_DEFAULT = SPH_RANK_PROXIMITY_BM25 }; /// known sort modes enum { SPH_SORT_RELEVANCE = 0, SPH_SORT_ATTR_DESC = 1, SPH_SORT_ATTR_ASC = 2, SPH_SORT_TIME_SEGMENTS = 3, SPH_SORT_EXTENDED = 4, SPH_SORT_EXPR = 5 }; /// known filter types enum { SPH_FILTER_VALUES = 0, SPH_FILTER_RANGE = 1, SPH_FILTER_FLOATRANGE = 2, SPH_FILTER_STRING = 3 }; /// known attribute types enum { SPH_ATTR_INTEGER = 1, SPH_ATTR_TIMESTAMP = 2, SPH_ATTR_ORDINAL = 3, SPH_ATTR_BOOL = 4, SPH_ATTR_FLOAT = 5, SPH_ATTR_BIGINT = 6, SPH_ATTR_STRING = 7, SPH_ATTR_DOUBLE = 13, SPH_ATTR_FACTORS = 1001, SPH_ATTR_MULTI = 0x40000001UL, SPH_ATTR_MULTI64 = 0x40000002UL }; /// known grouping functions enum { SPH_GROUPBY_DAY = 0, SPH_GROUPBY_WEEK = 1, SPH_GROUPBY_MONTH = 2, SPH_GROUPBY_YEAR = 3, SPH_GROUPBY_ATTR = 4, SPH_GROUPBY_ATTRPAIR = 5 }; ////////////////////////////////////////////////////////////////////////// #if defined(_MSC_VER) typedef __int64 sphinx_int64_t; typedef unsigned __int64 sphinx_uint64_t; #else // !defined(_MSC_VER) typedef long long sphinx_int64_t; typedef unsigned long long sphinx_uint64_t; #endif // !defined(_MSC_VER) typedef int sphinx_bool; #define SPH_TRUE 1 #define SPH_FALSE 0 ////////////////////////////////////////////////////////////////////////// typedef struct st_sphinx_client sphinx_client; typedef struct st_sphinx_wordinfo { const char * word; int docs; int hits; } sphinx_wordinfo; typedef struct st_sphinx_result { const char * error; const char * warning; int status; int num_fields; char ** fields; int num_attrs; char ** attr_names; int * attr_types; int num_matches; void * values_pool; int total; int total_found; int time_msec; int num_words; sphinx_wordinfo * words; } sphinx_result; typedef struct st_sphinx_excerpt_options { const char * before_match; const char * after_match; const char * chunk_separator; const char * html_strip_mode; const char * passage_boundary; int limit; int limit_passages; int limit_words; int around; int start_passage_id; sphinx_bool single_passage; sphinx_bool use_boundaries; sphinx_bool weight_order; sphinx_bool force_all_words; sphinx_bool load_files; sphinx_bool allow_empty; sphinx_bool emit_zones; } sphinx_excerpt_options; typedef struct st_sphinx_keyword_info { char * tokenized; char * normalized; int num_docs; int num_hits; } sphinx_keyword_info; ////////////////////////////////////////////////////////////////////////// sphinx_client * sphinx_create ( sphinx_bool copy_args ); void sphinx_cleanup ( sphinx_client * client ); void sphinx_destroy ( sphinx_client * client ); const char * sphinx_error ( sphinx_client * client ); const char * sphinx_warning ( sphinx_client * client ); sphinx_bool sphinx_set_server ( sphinx_client * client, const char * host, int port ); sphinx_bool sphinx_set_connect_timeout ( sphinx_client * client, float seconds ); sphinx_bool sphinx_open ( sphinx_client * client ); sphinx_bool sphinx_close ( sphinx_client * client ); sphinx_bool sphinx_set_limits ( sphinx_client * client, int offset, int limit, int max_matches, int cutoff ); sphinx_bool sphinx_set_max_query_time ( sphinx_client * client, int max_query_time ); sphinx_bool sphinx_set_match_mode ( sphinx_client * client, int mode ); sphinx_bool sphinx_set_ranking_mode ( sphinx_client * client, int ranker, const char * rankexpr ); sphinx_bool sphinx_set_sort_mode ( sphinx_client * client, int mode, const char * sortby ); sphinx_bool sphinx_set_field_weights ( sphinx_client * client, int num_weights, const char ** field_names, const int * field_weights ); sphinx_bool sphinx_set_index_weights ( sphinx_client * client, int num_weights, const char ** index_names, const int * index_weights ); sphinx_bool sphinx_set_id_range ( sphinx_client * client, sphinx_uint64_t minid, sphinx_uint64_t maxid ); sphinx_bool sphinx_add_filter ( sphinx_client * client, const char * attr, int num_values, const sphinx_int64_t * values, sphinx_bool exclude ); sphinx_bool sphinx_add_filter_string ( sphinx_client * client, const char * attr, const char * value, sphinx_bool exclude ); sphinx_bool sphinx_add_filter_range ( sphinx_client * client, const char * attr, sphinx_int64_t umin, sphinx_int64_t umax, sphinx_bool exclude ); sphinx_bool sphinx_add_filter_float_range ( sphinx_client * client, const char * attr, float fmin, float fmax, sphinx_bool exclude ); sphinx_bool sphinx_set_geoanchor ( sphinx_client * client, const char * attr_latitude, const char * attr_longitude, float latitude, float longitude ); sphinx_bool sphinx_set_groupby ( sphinx_client * client, const char * attr, int groupby_func, const char * group_sort ); sphinx_bool sphinx_set_groupby_distinct ( sphinx_client * client, const char * attr ); sphinx_bool sphinx_set_retries ( sphinx_client * client, int count, int delay ); sphinx_bool sphinx_add_override ( sphinx_client * client, const char * attr, const sphinx_uint64_t * docids, int num_values, const unsigned int * values ); sphinx_bool sphinx_set_select ( sphinx_client * client, const char * select_list ); sphinx_bool sphinx_set_query_flags ( sphinx_client * client, const char * flag_name, sphinx_bool enabled, int max_predicted_msec ); void sphinx_reset_query_flags ( sphinx_client * client ); sphinx_bool sphinx_set_outer_select ( sphinx_client * client, const char * orderby, int offset, int limit ); void sphinx_reset_outer_select ( sphinx_client * client ); void sphinx_reset_filters ( sphinx_client * client ); void sphinx_reset_groupby ( sphinx_client * client ); sphinx_result * sphinx_query ( sphinx_client * client, const char * query, const char * index_list, const char * comment ); int sphinx_add_query ( sphinx_client * client, const char * query, const char * index_list, const char * comment ); sphinx_result * sphinx_run_queries ( sphinx_client * client ); int sphinx_get_num_results ( sphinx_client * client ); sphinx_uint64_t sphinx_get_id ( sphinx_result * result, int match ); int sphinx_get_weight ( sphinx_result * result, int match ); sphinx_int64_t sphinx_get_int ( sphinx_result * result, int match, int attr ); float sphinx_get_float ( sphinx_result * result, int match, int attr ); unsigned int * sphinx_get_mva ( sphinx_result * result, int match, int attr ); sphinx_uint64_t sphinx_get_mva64_value ( unsigned int * mva, int i ); const char * sphinx_get_string ( sphinx_result * result, int match, int attr ); void sphinx_init_excerpt_options ( sphinx_excerpt_options * opts ); char ** sphinx_build_excerpts ( sphinx_client * client, int num_docs, const char ** docs, const char * index, const char * words, sphinx_excerpt_options * opts ); int sphinx_update_attributes ( sphinx_client * client, const char * index, int num_attrs, const char ** attrs, int num_docs, const sphinx_uint64_t * docids, const sphinx_int64_t * values ); int sphinx_update_attributes_mva ( sphinx_client * client, const char * index, const char * attr, sphinx_uint64_t docid, int num_values, const unsigned int * values ); sphinx_keyword_info * sphinx_build_keywords ( sphinx_client * client, const char * query, const char * index, sphinx_bool hits, int * out_num_keywords ); char ** sphinx_status ( sphinx_client * client, int * num_rows, int * num_cols ); char ** sphinx_status_extended ( sphinx_client * client, int * num_rows, int * num_cols, int local ); void sphinx_status_destroy ( char ** status, int num_rows, int num_cols ); ///////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus } #endif #endif // _sphinxclient_ // // $Id$ //
9,454
C++
.h
222
40.986486
196
0.660316
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,063
jsonsi.h
manticoresoftware_manticoresearch/src/jsonsi.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 "sphinx.h" class JsonSIBuilder_i { public: virtual ~JsonSIBuilder_i() = default; virtual void AddRowOffsetSize ( std::pair<SphOffset_t,SphOffset_t> tOffsetSize ) = 0; virtual bool Done ( CSphString & sError ) = 0; }; std::unique_ptr<JsonSIBuilder_i> CreateJsonSIBuilder ( const ISphSchema & tSchema, const CSphString & sSPB, const CSphString & sSIFile, CSphString & sError ); CSphString UnifyJsonFieldName ( const CSphString & sName ); CSphString GetFixedJsonSIAttrName();
880
C++
.h
21
40.47619
158
0.763189
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,064
columnarlib.h
manticoresoftware_manticoresearch/src/columnarlib.h
// // Copyright (c) 2020-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/ // #ifndef _columnarlib_ #define _columnarlib_ #include "sphinxexpr.h" #include "columnar/columnar.h" #include "columnar/builder.h" #include "common/schema.h" class ISphSchema; std::unique_ptr<columnar::Columnar_i> CreateColumnarStorageReader ( const CSphString & sFile, DWORD uNumDocs, CSphString & sError ); std::unique_ptr<columnar::Builder_i> CreateColumnarBuilder ( const ISphSchema & tSchema, const CSphString & sFilename, size_t tBufferSize, CSphString & sError ); void CheckColumnarStorage ( const CSphString & sFile, DWORD uNumRows, std::function<void (const char*)> fnError, std::function<void (const char*)> fnProgress ); common::AttrType_e ToColumnarType ( ESphAttr eAttrType, int iBitCount ); bool InitColumnar ( CSphString & sError ); void ShutdownColumnar(); const char * GetColumnarVersionStr(); bool IsColumnarLibLoaded(); // params rearranged for most frequently used defaults std::unique_ptr<columnar::Iterator_i> CreateColumnarIterator ( const columnar::Columnar_i * pColumnar, const std::string& sName, std::string & sError, const columnar::IteratorHints_t & tHints={}, columnar::IteratorCapabilities_t * pCapabilities=nullptr ); #endif // _columnarlib_
1,571
C++
.h
27
56.851852
256
0.772638
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,065
debug_cmds.h
manticoresoftware_manticoresearch/src/debug_cmds.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 "searchdaemon.h" void HandleMysqlDebug ( RowBuffer_i & tOut, const DebugCmd::DebugCommand_t * pCommand, const QueryProfile_c & tProfile ); void HandleTasks ( RowBuffer_i & tOut ); void HandleSched ( RowBuffer_i & tOut ); void SetShutdownToken ( CSphString sToken ) noexcept;
777
C++
.h
17
44.411765
121
0.760265
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,066
killlist.h
manticoresoftware_manticoresearch/src/killlist.h
// // Copyright (c) 2018-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/ // #ifndef _killlist_ #define _killlist_ #include "fileutils.h" #include "sphinxdefs.h" class CSphReader; class CSphWriter; class DeadRowMap_c { public: virtual ~DeadRowMap_c(){} bool HasDead() const; DWORD GetNumDeads() const; virtual int64_t GetLengthBytes() const = 0; virtual uint64_t GetCoreSize () const = 0; protected: bool m_bHaveDead {false}; mutable int64_t m_iNumDeads = -1; // means 'not initialized' DWORD m_uRows {0}; void CheckForDead ( const DWORD * pData, const DWORD * pDataEnd ); bool Set ( RowID_t tRowID, DWORD * pData ); inline bool IsSet ( RowID_t tRowID, const DWORD * pData ) const { if ( !m_bHaveDead || tRowID==INVALID_ROWID ) return false; assert ( tRowID < m_uRows ); return ( pData [ tRowID>>5U ] & ( 1UL<<( tRowID&31U ) ) )!=0; } private: virtual DWORD CountDeads () const = 0; // heavy doc-by-doc counting #if !(_WIN32) && !(HAVE_SYNC_FETCH) CSphMutex m_tLock; #endif }; class DeadRowMap_Disk_c : public DeadRowMap_c { friend class DeadRowMap_Ram_c; public: ~DeadRowMap_Disk_c() override; bool Set ( RowID_t tRowID ); inline bool IsSet ( RowID_t tRowID ) const { return DeadRowMap_c::IsSet ( tRowID, m_tData.GetReadPtr() ); } int64_t GetLengthBytes() const override; uint64_t GetCoreSize () const override; bool Flush ( bool bWaitComplete, CSphString & sError ) const; bool Prealloc ( DWORD uRows, const CSphString & sFilename, CSphString & sError ); void Dealloc(); void Preread ( const char * sIndexName, const char * sFor, bool bMlock ); private: DWORD CountDeads () const final; CSphMappedBuffer<DWORD> m_tData; }; class DeadRowMap_Ram_c : public DeadRowMap_c { public: explicit DeadRowMap_Ram_c ( DWORD uRows ); bool Set ( RowID_t tRowID ); bool IsSet ( RowID_t tRowID ) const; void Reset ( DWORD uRows ); int64_t GetLengthBytes() const override; uint64_t GetCoreSize () const override; DWORD GetNumAlive() const; void Load ( DWORD uRows, CSphReader & tReader, CSphString & sError ); void Save ( CSphWriter & tWriter ) const; private: DWORD CountDeads () const final; CSphFixedVector<DWORD> m_dData {0}; }; class DocidListReader_c { public: explicit DocidListReader_c ( const VecTraits_T<DocID_t> & dKlist ) : m_pIterator ( dKlist.Begin() ) , m_pMaxIterator ( dKlist.Begin() + dKlist.GetLength() ) // should be this way till VecTraits.End got fixed {} static inline bool Read ( DocID_t & tDocID, RowID_t & tRowID ) { return false; } inline bool ReadDocID ( DocID_t & tDocID ) { if ( m_pIterator>=m_pMaxIterator ) return false; tDocID = *m_pIterator++; return true; } static inline void HintDocID ( DocID_t ) {} private: const DocID_t * m_pIterator {nullptr}; const DocID_t * m_pMaxIterator {nullptr}; }; template<typename READER1, typename READER2, typename FUNCTOR> void Intersect ( READER1& tReader1, READER2& tReader2, FUNCTOR&& fnFunctor ) { RowID_t tRowID1 = INVALID_ROWID; DocID_t tDocID1 = 0, tDocID2 = 0; bool bHaveDocs1 = tReader1.Read ( tDocID1, tRowID1 ); bool bHaveDocs2 = tReader2.ReadDocID ( tDocID2 ); while ( bHaveDocs1 && bHaveDocs2 ) { if ( (uint64_t)tDocID1 < (uint64_t)tDocID2 ) { tReader1.HintDocID ( tDocID2 ); bHaveDocs1 = tReader1.Read ( tDocID1, tRowID1 ); } else if ( (uint64_t)tDocID1 > (uint64_t)tDocID2 ) { tReader2.HintDocID ( tDocID1 ); bHaveDocs2 = tReader2.ReadDocID ( tDocID2 ); } else { fnFunctor ( tRowID1, tDocID1, tReader2 ); bHaveDocs1 = tReader1.Read ( tDocID1, tRowID1 ); bHaveDocs2 = tReader2.ReadDocID ( tDocID2 ); } } } template<typename TARGETREADER, typename KILLERREADER, typename FNACTION> int ProcessIntersected ( TARGETREADER& tReader1, KILLERREADER& tReader2, FNACTION fnAction ) { int iProcessed = 0; Intersect ( tReader1, tReader2, [&iProcessed, fnAction = std::move ( fnAction )] ( RowID_t tRowID, DocID_t tDocID, KILLERREADER& ) { if ( fnAction ( tRowID, tDocID ) ) ++iProcessed; } ); return iProcessed; } template <typename TARGET, typename KILLER, typename MAP> int KillByLookup ( TARGET & tTargetReader, KILLER & tKillerReader, MAP & tDeadRowMap ) { return ProcessIntersected ( tTargetReader, tKillerReader, [&tDeadRowMap] ( RowID_t tRowID, DocID_t ) { return tDeadRowMap.Set ( tRowID ); } ); } bool WriteDeadRowMap ( const CSphString & sFilename, DWORD uTotalDocs, CSphString & sError ); #endif // _killlist_
4,790
C++
.h
143
31.258741
143
0.721824
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,067
datareader.h
manticoresoftware_manticoresearch/src/datareader.h
// // Copyright (c) 2017-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/ // #ifndef _datareader_ #define _datareader_ #include "sphinxdefs.h" #include "indexsettings.h" #define READ_NO_SIZE_HINT 0 // Reader from file or filemap class FileBlockReader_i : public ISphRefcountedMT { public: virtual SphOffset_t GetPos() const = 0; virtual void SeekTo ( SphOffset_t iPos, int iSizeHint ) = 0; virtual void GetBytes ( BYTE * pData, int iSize ) = 0; virtual int GetBytesZerocopy ( const BYTE *& pData, int iMax ) = 0; virtual BYTE GetByte() = 0; virtual DWORD GetDword() = 0; virtual SphOffset_t GetOffset() = 0; virtual DWORD UnzipInt() = 0; virtual uint64_t UnzipOffset() = 0; virtual RowID_t UnzipRowid() = 0; virtual SphWordID_t UnzipWordid() = 0; virtual void Reset () = 0; }; using FileBlockReaderPtr_c = CSphRefcountedPtr<FileBlockReader_i>; class QueryProfile_c; // producer of readers from file or filemap class DataReaderFactory_c : public ISphRefcountedMT { public: enum Kind_e { DOCS, HITS, COLUMNAR }; bool IsValid () const { return m_bValid; } virtual uint64_t GetMappedsize () const = 0; virtual uint64_t GetCoresize () const = 0; virtual SphOffset_t GetFilesize () const = 0; virtual SphOffset_t GetPos () const = 0; virtual void SeekTo ( SphOffset_t ) = 0; virtual FileBlockReader_i * MakeReader ( BYTE * pBuf, int iSize ) = 0; virtual void SetProfile ( QueryProfile_c * ) {} protected: ~DataReaderFactory_c () override {} void SetValid ( bool bValid ) { m_bValid = bValid; } private: bool m_bValid = false; }; using DataReaderFactoryPtr_c = CSphRefcountedPtr<DataReaderFactory_c>; DataReaderFactory_c * NewProxyReader ( const CSphString & sFile, CSphString & sError, DataReaderFactory_c::Kind_e eKind, int iReadBuffer, FileAccess_e eAccess ); #endif // _datareader_
2,169
C++
.h
60
34.25
161
0.731614
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,068
searchdconfig.h
manticoresoftware_manticoresearch/src/searchdconfig.h
// // Copyright (c) 2017-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/ // #ifndef _searchdconfig_ #define _searchdconfig_ #include "sphinxutils.h" #include "indexsettings.h" enum class IndexType_e { PLAIN = 0, TEMPLATE, RT, PERCOLATE, DISTR, ERROR_, // simple "ERROR" doesn't work on win due to '#define ERROR 0' somewhere. }; const char * szIndexType ( IndexType_e eType ); struct ClusterOptions_t { SmallStringHash_T<CSphString> m_hOptions; void Parse ( const CSphString & sOptions ); [[nodiscard]] CSphString AsStr () const; [[nodiscard]] bool IsEmpty() const noexcept; }; // cluster data that gets stored and loaded struct ClusterDesc_t { CSphString m_sName; // cluster name CSphString m_sPath; // path relative to data_dir sph::StringSet m_hIndexes; // list of index name in cluster StrVec_t m_dClusterNodes; // string list of nodes (node - address:API_port) ClusterOptions_t m_tOptions; // options for Galera bool Parse ( const bson::Bson_c & tBson, const CSphString& sName, CSphString & sWarning ); void Save ( JsonEscapedBuilder& tOut ) const; }; struct AgentConfigDesc_t { CSphString m_sConfig; bool m_bPersistent = false; bool m_bBlackhole = false; }; struct IndexDescDistr_t { StrVec_t m_dLocals; CSphVector<AgentConfigDesc_t> m_dAgents; int m_iAgentConnectTimeout = 0; int m_iAgentQueryTimeout = 0; int m_iAgentRetryCount = 0; bool m_bDivideRemoteRanges = false; CSphString m_sHaStrategy; bool Parse ( const bson::Bson_c & tBson, CSphString & sWarning ); void Save ( JsonEscapedBuilder& tOut ) const; void Save ( CSphConfigSection & hIndex ) const; }; struct IndexDesc_t { CSphString m_sName; CSphString m_sPath; IndexType_e m_eType = IndexType_e::ERROR_; IndexDescDistr_t m_tDistr; bool Parse ( const bson::Bson_c & tBson, const CSphString& sName, CSphString & sWarning ); void Save ( JsonEscapedBuilder& tOut ) const; void Save ( CSphConfigSection & hIndex ) const; }; // load data from internal config on daemon start bool LoadConfigInt ( const CSphConfig & hConf, const CSphString & sConfigFile, CSphString & sError ); bool SaveConfigInt ( CSphString & sError ); struct DistributedIndex_t; IndexDescDistr_t GetDistributedDesc ( const DistributedIndex_t & tDist ); // load indexes got from internal config on daemon indexes preload (part of ConfigureAndPreload work done here) void ConfigureAndPreloadConfiglessIndexes ( int & iValidIndexes, int & iCounter ); std::unique_ptr<FilenameBuilder_i> CreateFilenameBuilder ( const char * szIndex ); void ModifyDaemonPaths ( CSphConfigSection & hSearchd, FixPathAbsolute_fn && fnPathFix = nullptr ); CSphString GetDataDirInt(); // create string by join global data_dir and given path CSphString GetDatadirPath ( const CSphString& sPath ); bool IsConfigless(); const CSphVector<ClusterDesc_t> & GetClustersInt(); struct DistributedIndex_t; CSphString BuildCreateTableDistr ( const CSphString & sName, const DistributedIndex_t & tDistr ); bool CreateNewIndexConfigless ( const CSphString & sIndex, const CreateTableSettings_t & tCreateTable, StrVec_t & dWarnings, CSphString & sError ); bool AddExistingIndexConfigless ( const CSphString & sIndex, IndexType_e eType, StrVec_t & dWarnings, CSphString & sError ); bool DropIndexInt ( const CSphString & sIndex, bool bIfExists, CSphString & sError, CSphString * pWarning=nullptr ); bool CopyIndexFiles ( const CSphString & sIndex, const CSphString & sPathToIndex, bool & bPQ, StrVec_t & dWarnings, CSphString & sError ); enum RunIdx_e : int { NOTSERVED = 0, LOCAL, DISTR, }; RunIdx_e IndexIsServed ( const CSphString& sName ); #endif // _searchdconfig_
4,002
C++
.h
97
39.556701
148
0.757802
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,069
sphinxexcerpt.h
manticoresoftware_manticoresearch/src/sphinxexcerpt.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 _sphinxexcerpt_ #define _sphinxexcerpt_ #include "sphinxquery.h" #include "sphinx.h" enum ESphSpz : DWORD { SPH_SPZ_NONE = 0, SPH_SPZ_SENTENCE = 1UL<<0, SPH_SPZ_PARAGRAPH = 1UL<<1, SPH_SPZ_ZONE = 1UL<<2 }; class TextSource_i { public: virtual ~TextSource_i() {} virtual bool PrepareText ( ISphFieldFilter * pFilter, const CSphHTMLStripper * pStripper, CSphString & sError ) = 0; virtual VecTraits_T<BYTE> GetText ( int iField ) const = 0; virtual int GetNumFields() const = 0; virtual const char * GetFieldName ( int iField ) const = 0; virtual bool TextFromIndex() const = 0; }; struct SnippetLimits_t { int m_iLimit = 256; ///< max chars in snippet (0 if unlimited) int m_iLimitWords = 0; ///< max words in snippet int m_iLimitPassages = 0; ///< max passages in snippet void Format ( StringBuilder_c & tOut, const char * szPrefix ) const; }; /// a query to generate an excerpt /// everything string is expected to be UTF-8 struct SnippetQuerySettings_t : public SnippetLimits_t { CSphString m_sBeforeMatch {"<b>"}; ///< string to insert before each match CSphString m_sAfterMatch {"</b>"}; ///< string to insert after each match CSphString m_sChunkSeparator {" ... \0"}; ///< string to insert between matching chunks (in limited mode only) CSphString m_sFieldSeparator {" | "};///< string to insert between fields CSphString m_sStripMode {"index"}; ///< strip mode int m_iAround = 5; ///< how much words to highlight around each match int m_iPassageId = 1; ///< current %PASSAGE_ID% counter value (must start at 1) bool m_bUseBoundaries = false; ///< whether to extract passages by phrase boundaries setup in tokenizer bool m_bWeightOrder = false; ///< whether to order best passages in document (default) or weight order bool m_bForceAllWords = false;///< whether to ignore limit until all needed keywords are highlighted (#448) BYTE m_uFilesMode = 0; ///< sources are text(0), files(1), scattered files(2), only scattered files (3). bool m_bAllowEmpty = false; ///< whether to allow empty snippets (by default, return something from the start) bool m_bEmitZones = false; ///< whether to emit zone for passage bool m_bForcePassages = false; ///< whether to force passages generation bool m_bLimitsPerField = true; ///< whether to apply global or per-field limits SmallStringHash_T<SnippetLimits_t> m_hPerFieldLimits; // snippet per-field limits that override global settings bool m_bHasBeforePassageMacro = false; bool m_bHasAfterPassageMacro = false; CSphString m_sBeforeMatchPassage; CSphString m_sAfterMatchPassage; CSphString m_sQuery; ///< source data ESphSpz m_ePassageSPZ = SPH_SPZ_NONE; bool m_bJsonQuery = false; bool m_bPackFields = false; ///< whether to pack field results as data or as string void Setup(); CSphString AsString() const; }; struct PassageResult_t { CSphVector<BYTE> m_dText; int m_iWeight = 0; bool m_bStartSeparator = false; bool m_bEndSeparator = false; }; struct FieldResult_t { CSphString m_sName; CSphVector<PassageResult_t> m_dPassages; }; struct SnippetResult_t { CSphVector<FieldResult_t> m_dFields; CSphString m_sError; CSphString m_sWarning; }; class SnippetBuilder_c { class Impl_c; Impl_c * m_pImpl = nullptr; SnippetBuilder_c ( const SnippetBuilder_c & rhs ); public: SnippetBuilder_c(); ~SnippetBuilder_c(); void Setup ( const CSphIndex * pIndex, const SnippetQuerySettings_t & tQuery ); bool SetQuery ( const CSphString & sQuery, bool bIgnoreFields, CSphString & sError ); bool Build ( std::unique_ptr<TextSource_i>& pSource, SnippetResult_t & tRes ); CSphVector<BYTE> PackResult ( SnippetResult_t & tRes, const VecTraits_T<int> & dRequestedFields ) const; SnippetBuilder_c* MakeClone() const; }; // helper whether filepath from sPath does not escape area of sPrefix bool TestEscaping( const CSphString& sPrefix, const CSphString& sPath ); ESphSpz GetPassageBoundary ( const CSphString & sPassageBoundaryMode ); const char * PassageBoundarySz ( ESphSpz eBoundary ); bool sphCheckOptionsSPZ ( const SnippetQuerySettings_t & q, ESphSpz eMode, CSphString & sError ); SnippetResult_t UnpackSnippetData ( ByteBlob_t dData ); struct FieldSource_t { CSphString m_sName; VecTraits_T<BYTE> m_dData; }; std::unique_ptr<TextSource_i> CreateSnippetSource ( DWORD uFilesMode, const BYTE * pSource, int iLen ); std::unique_ptr<TextSource_i> CreateHighlightSource ( const CSphVector<FieldSource_t> & dAllFields ); extern CSphString g_sSnippetsFilePrefix; #endif // _sphinxexcerpt_
5,129
C++
.h
117
41.982906
120
0.734698
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,070
net_action_accept.h
manticoresoftware_manticoresearch/src/net_action_accept.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 "networking_daemon.h" enum class NetloopState_e : BYTE; struct ListenTaskInfo_t : public TaskInfo_t { DECLARE_RENDER( ListenTaskInfo_t ); NetloopState_e m_eThdState; DWORD m_uWorks = 0; DWORD m_uTick = 0; }; class NetActionAccept_c final : public ISphNetAction { class Impl_c; std::unique_ptr<Impl_c> m_pImpl; protected: ~NetActionAccept_c () final; public: NetActionAccept_c ( const Listener_t & tListener, CSphNetLoop* pNetLoop ); void Process () final; void NetLoopDestroying() final; };
1,005
C++
.h
32
29.90625
80
0.759049
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,071
task_dispatcher.h
manticoresoftware_manticoresearch/src/task_dispatcher.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 "std/blobs.h" #include "std/stringbuilder.h" #include <memory> namespace Dispatcher { class TaskSource_i { public: virtual ~TaskSource_i() = default; // if iTask<0 - consume new task, // if iTask>=0 - does nothing, returns true. virtual bool FetchTask ( int& iTask ) = 0; }; class TaskDispatcher_i { public: virtual ~TaskDispatcher_i() = default; virtual int GetConcurrency() const = 0; virtual std::unique_ptr<TaskSource_i> MakeSource() = 0; }; // trivial dispatcher just iterates from 0 to iJobs with single monotonic atomic shared across all workers std::unique_ptr<TaskDispatcher_i> MakeTrivial ( int iJobs, int iConcurrency ); // RoundRobin dispatcher provides sequence for iFibers sources, each takes serie of iBatch jobs, as: // let iFibers = 3. For given tasks they will come to follow fiber (1 to 3) depending on the batch: // for tasks 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // batch=1: 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 // batch=2: 1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3 // batch=3: 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 1 1 1 ... // with batch=1 it will give 1,4,7,10.. to 1-st fiber, 2,5,8,11... to 2-nd, 3,6,9,12... to 3-rd. // with batch=3 it will give 1-3,10-12,19-21... to 1-st, 4-6,13-15,22-24... to 2-nd, 7-9,16-18,25-27... to 3-rd. // iFibers should be <= iConcurrency (will be adjusted otherwise) // if iConcurrency > iFibers, extra contexts will be idle // default iFibers=0 makes iConcurrency fibers. std::unique_ptr<TaskDispatcher_i> MakeRoundRobin ( int iJobs, int iConcurrency, int iBatch=1 ); struct Template_t { int concurrency = 0; int batch = 0; }; std::unique_ptr<TaskDispatcher_i> Make ( int iJobs, int iDefaultConcurrency, Template_t tWhat, bool bSingle ); // template is a string like "10/3", where 10 is concurrency, 3 is batch size. // if concurrency = 0, default concurrency will be used. // if batch size = 0, default trivial dispatcher will be used. // Any zero value may be omitted or replaced with '*'. // Default (trivial) dispatcher may be described as empty '', and also '*/*', '0/0', '0/', '*/', '/0', '*', etc. // Trivial dispatcher with 20 threads is '20/*', '20/0', '20/', or simple '20'. // Round-robin dispatcher with batch=2 is '*/2', '0/2', or simple '/2'. // Round-robin dispatcher with 20 threads and batch=3 is '20/3'. Template_t ParseTemplate ( const char* szTemplate ); Template_t ParseTemplate ( Str_t sTemplate ); // basic + pseudo-sharding dispatcher templates, separated by '+', like: // '30+3' - trivial base of 30 threads + trivial pseudo-sharding of 3 threads // '+/2' - trivial base + round-robin pseudo-sharding with default threads and batch=2 // '10' - trivial base of 10 threads + default trivial pseudo-sharding // '/1+10' - round-robin base with default threads and batch=1 + trivial pseudo-sharding with 10 threads // '4/2+2/1' - rr base with 4 threads and batch=2 + rr pseudo-sharding with 2 threads and batch=1 std::pair<Template_t, Template_t> ParseTemplates ( const char* szTemplates ); std::pair<Template_t, Template_t> ParseTemplates ( Str_t sTemplates ); // parse templates and store global void SetGlobalDispatchers ( const char * szTemplates ); // return stored global dispatchers Template_t GetGlobalBaseDispatcherTemplate(); Template_t GetGlobalPseudoShardingDispatcherTemplate(); // override tBase with non-default tNew void Unify ( Template_t& tBase, Template_t tNew ); // render a couple of templates back to string form void RenderTemplates ( StringBuilder_c& tOut, std::pair<Template_t, Template_t> dTemplates ); } // namespace Dispatcher
4,221
C++
.h
79
52.101266
112
0.710788
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,072
tracer.h
manticoresoftware_manticoresearch/src/tracer.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 "sphinxstd.h" #ifdef PERFETTO #include "coroutine.h" #include "client_task_info.h" #include <perfetto.h> PERFETTO_DEFINE_CATEGORIES ( perfetto::Category ( "rt" ).SetDescription ( "Events from rt-index routines" ), perfetto::Category ( "network" ).SetDescription ( "Network upload and download statistics" ), perfetto::Category ( "conn" ).SetDescription ( "One connection scope" ), perfetto::Category ( "wait" ).SetDescription ( "Time spent idle" ), perfetto::Category ( "mem" ).SetDescription ( "Memory counters" ), perfetto::Category ( "sph" ).SetDescription ( "Common disk routines" ), ); // trackfn should be function or external value which can be captured // Name selected to avoid conflict with macro in google-tests #define SCOPED_TRACEP( category, name, trackfn, ... ) \ struct PERFETTO_UID ( ScopedEvent ) { \ struct EventFinalizer { \ EventFinalizer ( ... ) {} \ ~EventFinalizer() { TRACE_EVENT_END ( category, trackfn ); } \ EventFinalizer ( const EventFinalizer& ) = delete; \ inline EventFinalizer& operator= ( const EventFinalizer& ) = delete; \ EventFinalizer ( EventFinalizer&& ) = default; \ EventFinalizer& operator= ( EventFinalizer&& ) = delete; \ } finalizer; \ } PERFETTO_UID ( scoped_event ) { \ [&]() { \ TRACE_EVENT_BEGIN ( category, name, trackfn, ##__VA_ARGS__ ); \ return 0; \ }() \ } // track can be load variable // Notice, it is stored inside, so this variant consumes a bit more memory then just SCOPED_TRACEP #define SCOPED_TRACE_LOCAL(category, name, track, ...) \ struct PERFETTO_UID(ScopedEvent) { \ struct EventFinalizer { \ perfetto::Track m_tTrack; \ explicit EventFinalizer ( perfetto::Track&& tTrack ) : m_tTrack {std::move(tTrack)} {} \ EventFinalizer(...) {} \ ~EventFinalizer() { TRACE_EVENT_END(category, m_tTrack); } \ \ EventFinalizer(const EventFinalizer&) = delete; \ inline EventFinalizer& operator=(const EventFinalizer&) = delete; \ \ EventFinalizer(EventFinalizer&&) = default; \ EventFinalizer& operator=(EventFinalizer&&) = delete; \ } finalizer; \ explicit PERFETTO_UID ( ScopedEvent ) ( perfetto::Track tTrack) : finalizer {std::move(tTrack)} { \ TRACE_EVENT_BEGIN ( category, name, finalizer.m_tTrack, ##__VA_ARGS__ ); \ } \ } PERFETTO_UID(scoped_event) {track} // track of current scheduler #define SCHED_TRACK perfetto::Track::FromPointer ( Threads::Coro::CurrentScheduler() ) // track of current coro #define SCHED_CORO perfetto::Track::FromPointer ( Threads::Coro::CurrentWorker() ) // track of current connection #define CONN_TRACK perfetto::Track ( session::GetConnID() ) // any track #define PERF_TRACK perfetto::Track namespace Tracer { void Init(); void Start ( const CSphString& sFile, int64_t iMaxSize ); void Stop(); } // namespace Tracer #else // not def PERFETTO #define TRACE_EVENT_BEGIN(...) #define TRACE_EVENT_END(...) #define SCOPED_TRACEP(...) #define SCOPED_TRACE_LOCAL(...) #define TRACE_COUNTER(...) namespace Tracer { inline void Init () {}; inline void Start ( const CSphString& sFile, int64_t iMaxSize ) {}; inline void Stop() {}; } // namespace Tracer #endif // ifdef PEFRETTO #define BEGIN_SCHED( category, name, ... ) TRACE_EVENT_BEGIN ( category, name, SCHED_TRACK, ##__VA_ARGS__ ) #define END_SCHED( category, ... ) TRACE_EVENT_END ( category, SCHED_TRACK, ##__VA_ARGS__ ) #define TRACE_SCHED( category, name, ... ) SCOPED_TRACEP ( category, name, SCHED_TRACK, ##__VA_ARGS__ ) #define TRACE_SCHED_ID( category, name, id, ... ) SCOPED_TRACEP ( category, name, PERF_TRACK ( id, SCHED_TRACK ), ##__VA_ARGS__ ) // use instead of TRACE_SCHED_ID when id is local variable, and 'error: reference to local variable 'iId' declared in enclosing' happens #define TRACE_SCHED_VARID( category, name, id, ... ) SCOPED_TRACE_LOCAL ( category, name, PERF_TRACK ( id, SCHED_TRACK ), ##__VA_ARGS__ ) #define BEGIN_CORO( category, name, ... ) TRACE_EVENT_BEGIN ( category, name, SCHED_CORO, ##__VA_ARGS__ ) #define END_CORO( category, ... ) TRACE_EVENT_END ( category, SCHED_CORO, ##__VA_ARGS__ ) #define TRACE_CORO( category, name, ... ) SCOPED_TRACEP ( category, name, SCHED_CORO, ##__VA_ARGS__ ) #define TRACE_CORO_ID( category, name, id, ... ) SCOPED_TRACEP ( category, name, PERF_TRACK ( id, SCHED_CORO ), ##__VA_ARGS__ ) // use instead of TRACE_SCHED_ID when id is local variable, and 'error: reference to local variable 'iId' declared in enclosing' happens #define TRACE_CORO_VARID( category, name, id, ... ) SCOPED_TRACE_LOCAL ( category, name, PERF_TRACK ( id, SCHED_CORO ), ##__VA_ARGS__ ) #define BEGIN_CONN( category, name, ... ) TRACE_EVENT_BEGIN ( category, name, CONN_TRACK, ##__VA_ARGS__ ) #define END_CONN( category, ... ) TRACE_EVENT_END ( category, CONN_TRACK, ##__VA_ARGS__ ) #define TRACE_CONN( category, name, ... ) SCOPED_TRACEP ( category, name, CONN_TRACK, ##__VA_ARGS__ ) #define TRACE_CONN_ID( category, name, id, ... ) SCOPED_TRACEP ( category, name, PERF_TRACK ( id, CONN_TRACK ), ##__VA_ARGS__ ) // use instead of TRACE_CONN when id is local variable, and 'error: reference to local variable 'iId' declared in enclosing' happens #define TRACE_CONN_VARID( category, name, id, ... ) SCOPED_TRACE_LOCAL ( category, name, PERF_TRACK ( id, CONN_TRACK ), ##__VA_ARGS__ ) #define BEGIN_ID( category, name, id, ... ) TRACE_EVENT_BEGIN ( category, name, PERF_TRACK ( id ), ##__VA_ARGS__ ) #define END_ID( category, id, ... ) TRACE_EVENT_END ( category, PERF_TRACK ( id ), ##__VA_ARGS__ ) #define TRACE_ID( category, name, id, ... ) SCOPED_TRACEP ( category, name, PERF_TRACK ( id ), ##__VA_ARGS__ ) // use instead of TRACE_SCHED_ID when id is local variable, and 'error: reference to local variable 'iId' declared in enclosing' happens #define TRACE_VARID( category, name, id, ... ) SCOPED_TRACE_LOCAL ( category, name, PERF_TRACK ( id ), ##__VA_ARGS__ )
7,503
C++
.h
115
61.347826
137
0.587556
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,073
snippetindex.h
manticoresoftware_manticoresearch/src/snippetindex.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 _snippetindex_ #define _snippetindex_ #include "sphinxquery.h" ////////////////////////////////////////////////////////////////////////// /// mini-index for a single document /// keeps query words /// keeps hit lists for every query keyword class SnippetsDocIndex_c { friend struct KeywordCmp_t; friend struct TermCmp_t; public: SnippetsDocIndex_c ( const XQQuery_t & tQuery ); void SetupHits(); int FindWord ( SphWordID_t iWordID, const BYTE * sWord, int iWordLen ) const; int FindStarred ( const char * sWord ) const; void AddHits ( SphWordID_t iWordID, const BYTE * sWord, int iWordLen, DWORD uPosition ); void ParseQuery ( const DictRefPtr_c& pDict, DWORD eExtQuerySPZ ); int GetTermWeight ( int iQueryPos ) const; int GetNumTerms () const; DWORD GetLastPos() const { return m_uLastPos; } void SetLastPos ( DWORD uLastPos ) { m_uLastPos=uLastPos; } const XQQuery_t & GetQuery() const { return m_tQuery; } const CSphVector<CSphVector<DWORD>> & GetDocHits() const { return m_dDocHits; } const CSphVector<DWORD> * GetHitlist ( const XQKeyword_t & tWord, const DictRefPtr_c & pDict ) const; private: struct Keyword_t { int m_iWord; int m_iLength; bool m_bStar; int m_iWeight; int m_iQueryPos; }; struct Term_t { SphWordID_t m_iWordId; int m_iWeight; int m_iQueryPos; }; DWORD m_uLastPos; CSphVector<CSphVector<DWORD>> m_dDocHits; const XQQuery_t & m_tQuery; CSphVector<Term_t> m_dTerms; CSphVector<SphWordID_t> m_dStarred; CSphVector<Keyword_t> m_dStars; CSphVector<BYTE> m_dStarBuffer; CSphVector<int> m_dQposToWeight; mutable BYTE m_sTmpWord [ 3*SPH_MAX_WORD_LEN + 16 ]; bool MatchStar ( const Keyword_t & tTok, const BYTE * sWord ) const; void AddWord ( SphWordID_t iWordID, int iLengthCP, int iQpos ); void AddWordStar ( const char * sWord, int iLengthCP, int iQpos ); int ExtractWords ( XQNode_t * pNode, const DictRefPtr_c& pDict, int iQpos ); }; #endif // _snippetindex_
2,474
C++
.h
66
35.484848
102
0.707307
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,074
docidlookup.h
manticoresoftware_manticoresearch/src/docidlookup.h
// // Copyright (c) 2018-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/ // #ifndef _docidlookup_ #define _docidlookup_ #include "secondaryindex.h" class CSphWriter; struct DocidRowidPair_t { DocID_t m_tDocID; RowID_t m_tRowID; }; struct DocidLookupCheckpoint_t { DocID_t m_tBaseDocID {0}; SphOffset_t m_tOffset {0}; }; class DocidLookupWriter_c { public: DocidLookupWriter_c ( CSphWriter& tWriter, DWORD nDocs ); void Start(); void AddPair ( const DocidRowidPair_t & tPair ); bool Finalize ( CSphString & sError ); private: static const int DOCS_PER_LOOKUP_CHECKPOINT = 64; CSphWriter& m_tWriter; DWORD m_nDocs; int m_iProcessed {0}; int m_iCheckpoint {0}; SphOffset_t m_tCheckpointStart {0}; DocID_t m_tLastDocID {0}; CSphFixedVector<DocidLookupCheckpoint_t> m_dCheckpoints {0}; }; class LookupReader_c { public: LookupReader_c() = default; explicit LookupReader_c ( const BYTE * pData ); void SetData ( const BYTE * pData ); inline RowID_t Find ( DocID_t tDocID ) const { if ( !m_pCheckpoints || (uint64_t)tDocID<(uint64_t)m_pCheckpoints->m_tBaseDocID || (uint64_t)tDocID>(uint64_t)m_tMaxDocID ) return INVALID_ROWID; const DocidLookupCheckpoint_t * pFound = FindCheckpoint ( tDocID, m_pCheckpoints ); if ( !pFound ) return INVALID_ROWID; const BYTE * pCur = m_pData + pFound->m_tOffset; DocID_t tCurDocID = pFound->m_tBaseDocID; // 1st entry doesnt have docid RowID_t tRowID = sphUnalignedRead ( *(const RowID_t*)pCur ); pCur += sizeof(RowID_t); if ( tCurDocID==tDocID ) return tRowID; int iDocsInCheckpoint = GetNumDocsInCheckpoint(pFound); for ( int i = 1; i < iDocsInCheckpoint; i++ ) { uint64_t tDeltaDocID = UnzipOffsetBE(pCur); tRowID = sphUnalignedRead ( *(const RowID_t*)pCur ); pCur += sizeof(RowID_t); tCurDocID += tDeltaDocID; if ( tCurDocID==tDocID ) return tRowID; else if ( (uint64_t)tCurDocID>(uint64_t)tDocID ) return INVALID_ROWID; } return INVALID_ROWID; } protected: DWORD m_nDocs {0}; DWORD m_nDocsPerCheckpoint {0}; int m_nCheckpoints {0}; DocID_t m_tMaxDocID {0}; const BYTE * m_pData {nullptr}; const DocidLookupCheckpoint_t * m_pCheckpoints {nullptr}; inline const DocidLookupCheckpoint_t * FindCheckpoint ( DocID_t tDocID, const DocidLookupCheckpoint_t * pStart ) const { if ( (uint64_t)tDocID<(uint64_t)pStart->m_tBaseDocID || (uint64_t)tDocID>(uint64_t)m_tMaxDocID ) return nullptr; const DocidLookupCheckpoint_t * pEnd = m_pCheckpoints+m_nCheckpoints-1; const DocidLookupCheckpoint_t * pFound = sphBinarySearchFirst ( pStart, pEnd, []( const DocidLookupCheckpoint_t & i ){ return (uint64_t)i.m_tBaseDocID; }, (uint64_t)tDocID ); assert ( pFound ); if ( (uint64_t)pFound->m_tBaseDocID>(uint64_t)tDocID ) { if ( pFound==m_pCheckpoints ) return nullptr; return pFound-1; } return pFound; } inline bool IsLastCheckpoint ( const DocidLookupCheckpoint_t * pCheckpoint ) const { return pCheckpoint==m_pCheckpoints+m_nCheckpoints-1; } inline int GetNumDocsInCheckpoint ( const DocidLookupCheckpoint_t * pCheckpoint ) const { if ( !IsLastCheckpoint(pCheckpoint) ) return m_nDocsPerCheckpoint; int iLeftover = m_nDocs % m_nDocsPerCheckpoint; return iLeftover ? iLeftover : m_nDocsPerCheckpoint; } }; class LookupReaderIterator_c : private LookupReader_c { public: LookupReaderIterator_c ( const BYTE * pData ); void SetData ( const BYTE * pData ); inline bool Read ( DocID_t & tDocID, RowID_t & tRowID ) { if ( IsEnd() ) return false; // step to next checkpoint if ( m_iProcessedDocs==m_iCheckpointDocs ) { if ( IsLastCheckpoint() ) { m_pCurCheckpoint = nullptr; return false; } SetCheckpoint ( m_pCurCheckpoint+1 ); } // no docid stored for first entry if ( !m_iProcessedDocs ) { tDocID = m_tCurDocID; tRowID = sphUnalignedRead ( *(RowID_t*)const_cast<BYTE*>(m_pCur) ); m_pCur += sizeof(RowID_t); m_iProcessedDocs++; return true; } uint64_t tDelta = UnzipOffsetBE ( m_pCur ); tRowID = sphUnalignedRead ( *(RowID_t*)const_cast<BYTE*>(m_pCur) ); m_pCur += sizeof(RowID_t); m_tCurDocID += tDelta; tDocID = m_tCurDocID; m_iProcessedDocs++; return true; } inline bool ReadDocID ( DocID_t & tDocID ) { RowID_t tRowID; return Read ( tDocID, tRowID ); } inline void HintDocID ( DocID_t tDocID ) { // inside last block? do nothing if ( IsEnd() || IsLastCheckpoint() ) return; // tDocID is inside current block (check with next min docid)? do nothing if ( (uint64_t)tDocID < uint64_t ( ( m_pCurCheckpoint+1 )->m_tBaseDocID ) ) return; // perform binary search starting with next checkpoint SetCheckpoint ( FindCheckpoint ( tDocID, m_pCurCheckpoint+1 ) ); } private: const DocidLookupCheckpoint_t * m_pCurCheckpoint {nullptr}; const BYTE * m_pCur {nullptr}; DocID_t m_tCurDocID {0}; int m_iProcessedDocs; int m_iCheckpointDocs; inline bool IsLastCheckpoint() const { return LookupReader_c::IsLastCheckpoint(m_pCurCheckpoint); } inline bool IsEnd() const { return !m_pCurCheckpoint; } inline void SetCheckpoint ( const DocidLookupCheckpoint_t * pCheckpoint ) { m_pCurCheckpoint = pCheckpoint; if ( !m_pCurCheckpoint ) return; m_iProcessedDocs = 0; m_iCheckpointDocs = GetNumDocsInCheckpoint(m_pCurCheckpoint); m_pCur = m_pData + m_pCurCheckpoint->m_tOffset; m_tCurDocID = m_pCurCheckpoint->m_tBaseDocID; } }; RowIteratorsWithEstimates_t CreateLookupIterator ( CSphVector<SecondaryIndexInfo_t> & dSIInfo, const CSphVector<CSphFilterSettings> & dFilters, const BYTE * pDocidLookup, uint32_t uTotalDocs ); bool WriteDocidLookup ( const CSphString & sFilename, const VecTraits_T<DocidRowidPair_t> & dLookup, CSphString & sError ); struct CmpDocidLookup_fn { static inline bool IsLess ( const DocidRowidPair_t & a, const DocidRowidPair_t & b ) { if ( a.m_tDocID==b.m_tDocID ) return a.m_tRowID < b.m_tRowID; return (uint64_t)a.m_tDocID < (uint64_t)b.m_tDocID; } }; #endif
6,410
C++
.h
197
29.725888
193
0.720091
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,075
sphinxplugin.h
manticoresoftware_manticoresearch/src/sphinxplugin.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 _sphinxplugin_ #define _sphinxplugin_ #include "sphinxexpr.h" extern "C" { #include "sphinxudf.h" } ////////////////////////////////////////////////////////////////////////// // call prototypes for all the known external plugin symbol types typedef void (*PluginLogCb_fn) ( void (*) ( const char *, int )); typedef int (*PluginVer_fn) (); typedef void (*PluginReinit_fn) (); typedef int (*PluginLoad_fn) ( char * error ); typedef int (*PluginUnload_fn) ( char * error ); typedef int (*UdfInit_fn) ( SPH_UDF_INIT * init, SPH_UDF_ARGS * args, char * error ); typedef void (*UdfDeinit_fn) ( SPH_UDF_INIT * init ); typedef int (*RankerInit_fn) ( void ** userdata, SPH_RANKER_INIT * ranker, char * error ); typedef void (*RankerUpdate_fn) ( void * userdata, SPH_RANKER_HIT * hit ); typedef unsigned int (*RankerFinalize_fn) ( void * userdata, int match_weight ); typedef int (*RankerDeinit_fn) ( void * userdata ); typedef int (*TokenFilterInit_fn) ( void ** userdata, int num_fields, const char ** field_names, const char * options, char * error_message ); typedef int (*TokenFilterBeginDocument_fn) ( void * userdata, const char * options, char * error_message ); typedef void (*TokenFilterBeginField_fn) ( void * userdata, int field_index ); typedef char * (*TokenFilterPushToken_fn) ( void * userdata, char * token, int * extra, int * delta ); typedef char * (*TokenFilterGetExtraToken_fn) ( void * userdata, int * delta ); typedef int (*TokenFilterEndField_fn) ( void * userdata ); typedef void (*TokenFilterDeinit_fn) ( void * userdata ); typedef int (*TokenFilterIsBlended_fn) ( void * userdata ); typedef int (*TokenFilterIsBlendedPart_fn) ( void * userdata ); typedef int (*QueryTokenFilterInit_fn) ( void ** userdata, int max_len, const char * options, char * error ); typedef void (*QueryTokenFilterPreMorph_fn) ( void * userdata, char * token, int * stopword ); typedef int (*QueryTokenFilterPostMorph_fn) ( void * userdata, char * token, int * stopword ); typedef char * (*QueryTokenFilterPushToken_fn) ( void * userdata, char * token, int * delta, const char * raw_token_start, int raw_token_len ); typedef void (*QueryTokenFilterDeinit_fn) ( void * userdata ); ////////////////////////////////////////////////////////////////////////// /// forward refs class PluginLib_c; using PluginLibRefPtr_c = CSphRefcountedPtr<PluginLib_c>; class CSphWriter; /// plugin types /// MUST be in sync with sphPluginSaveState(), sphPluginGetType() enum PluginType_e { PLUGIN_FUNCTION = 0, PLUGIN_RANKER, PLUGIN_INDEX_TOKEN_FILTER, PLUGIN_QUERY_TOKEN_FILTER, PLUGIN_TOTAL }; /// common plugin descriptor part class PluginDesc_c : public ISphRefcountedMT { protected: PluginLibRefPtr_c m_pLib; ///< library descriptor (pointer to library hash value) public: explicit PluginDesc_c ( PluginLibRefPtr_c pLib ); virtual ESphAttr GetUdfRetType() const { return SPH_ATTR_NONE; } const CSphString & GetLibName() const; PluginLibRefPtr_c GetLib() const; protected: ~PluginDesc_c() override; }; using PluginDescRefPtr_c = CSphRefcountedPtr<PluginDesc_c>; /// registered user-defined function descriptor class PluginUDF_c : public PluginDesc_c { public: ESphAttr m_eRetType; ///< function type, currently FLOAT or INT UdfInit_fn m_fnInit = nullptr; ///< per-query init function, mandatory UdfDeinit_fn m_fnDeinit = nullptr; ///< per-query deinit function, optional void * m_fnFunc = nullptr; ///< per-row worker function, mandatory PluginUDF_c ( PluginLibRefPtr_c pLib, ESphAttr eRetType ); ESphAttr GetUdfRetType() const override { return m_eRetType; } }; using PluginUDFRefPtr_c = CSphRefcountedPtr<PluginUDF_c>; /// registered user-defined ranker descriptor class PluginRanker_c : public PluginDesc_c { public: RankerInit_fn m_fnInit = nullptr; ///< init function (called once when ranker is created), optional RankerUpdate_fn m_fnUpdate = nullptr; ///< per-hit update function, optional RankerFinalize_fn m_fnFinalize = nullptr; ///< per-document finalize function, mandatory RankerDeinit_fn m_fnDeinit = nullptr; ///< deinit function (called once when ranker is destroyed), optional explicit PluginRanker_c ( PluginLibRefPtr_c pLib ); }; using PluginRankerRefPtr_c = CSphRefcountedPtr<PluginRanker_c>; /// registered user-defined token filter descriptor class PluginTokenFilter_c : public PluginDesc_c { public: TokenFilterInit_fn m_fnInit = nullptr; TokenFilterBeginDocument_fn m_fnBeginDocument = nullptr; TokenFilterBeginField_fn m_fnBeginField = nullptr; TokenFilterPushToken_fn m_fnPushToken = nullptr; TokenFilterGetExtraToken_fn m_fnGetExtraToken = nullptr; TokenFilterEndField_fn m_fnEndField = nullptr; TokenFilterDeinit_fn m_fnDeinit = nullptr; TokenFilterIsBlended_fn m_fnTokenIsBlended = nullptr; TokenFilterIsBlendedPart_fn m_fnTokenIsBlendedPart = nullptr; explicit PluginTokenFilter_c ( PluginLibRefPtr_c pLib ); }; using PluginTokenFilterRefPtr_c = CSphRefcountedPtr<PluginTokenFilter_c>; /// registered user-defined token filter descriptor class PluginQueryTokenFilter_c : public PluginDesc_c { public: QueryTokenFilterInit_fn m_fnInit = nullptr; QueryTokenFilterPreMorph_fn m_fnPreMorph = nullptr; QueryTokenFilterPostMorph_fn m_fnPostMorph = nullptr; QueryTokenFilterPushToken_fn m_fnPushToken = nullptr; QueryTokenFilterDeinit_fn m_fnDeinit = nullptr; explicit PluginQueryTokenFilter_c ( PluginLibRefPtr_c pLib ); }; using PluginQueryTokenRefPtr_c = CSphRefcountedPtr<PluginQueryTokenFilter_c>; /// human readable plugin description (basically for SHOW PLUGINS) struct PluginInfo_t { PluginType_e m_eType; ///< plugin type CSphString m_sName; ///< plugin name CSphString m_sLib; ///< dynamic library file name int m_iUsers; ///< current user threads count (just because we can) CSphString m_sExtra; ///< extra plugin info (eg UDF return type) }; ////////////////////////////////////////////////////////////////////////// /// plugin type to human readable name extern const char * g_dPluginTypes[PLUGIN_TOTAL]; ////////////////////////////////////////////////////////////////////////// /// initialize plugin manager void sphPluginInit ( const char * sDir ); /// save SphinxQL state (ie. all active functions) void sphPluginSaveState ( CSphWriter & tWriter ); /// convert plugin type string to enum PluginType_e sphPluginGetType ( const CSphString & s ); /// splits and checks plugin spec string in "mylib.dll:plugname[:options]" format bool sphPluginParseSpec ( const CSphString & sParams, StrVec_t & dParams, CSphString & sError ); /// check if plugin exists (but do not acquire an instance) bool sphPluginExists ( PluginType_e eType, const char * sName ); /// create plugin /// that is, load the library if not yet loaded, import the symbols, register the plugin internally /// eRetType is only used for UDF type; might wanna change it to (void*) and pass a generic argument instead bool sphPluginCreate ( const char * sLib, PluginType_e eType, const char * sName, ESphAttr eUDFRetType, CSphString & sError ); bool sphPluginCreate ( const char * sLib, PluginType_e eType, const char * sName, ESphAttr eUDFRetType, bool bDlGlobal, CSphString & sError ); /// get plugin instance descriptor by name PluginDescRefPtr_c PluginGetDesc ( PluginType_e eType, const char * sName ); template<typename PLUGIN> CSphRefcountedPtr<PLUGIN> PluginGet ( PluginType_e eType, const char* sName ) { return CSphRefcountedPtr<PLUGIN> { (PLUGIN*)PluginGetDesc ( eType, sName ).Leak() }; } /// acquire plugin instance; get-or-create-and-get essentially PluginDescRefPtr_c PluginAcquireDesc ( const char * sLib, PluginType_e eType, const char * sName, CSphString & sError ); template <typename PLUGIN> CSphRefcountedPtr<PLUGIN> PluginAcquire ( const char* sLib, PluginType_e eType, const char* sName, CSphString& sError ) { return CSphRefcountedPtr<PLUGIN> { (PLUGIN*)PluginAcquireDesc ( sLib, eType, sName, sError ).Leak() }; } /// drop plugin by name bool sphPluginDrop ( PluginType_e eType, const char * sName, CSphString & sError ); /// reload all plugins from a given library bool sphPluginReload ( const char * sName, CSphString & sError ); /// list all plugins (basically for SHOW PLUGINS) void sphPluginList ( CSphVector<PluginInfo_t> & dResult ); /// get directory of plugins const CSphString & PluginGetDir(); #endif // _sphinxplugin_
8,945
C++
.h
176
49.221591
147
0.72964
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,076
searchdddl.h
manticoresoftware_manticoresearch/src/searchdddl.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 _searchdddl_ #define _searchdddl_ #include "searchdsql.h" bool ParseDdl ( Str_t sQuery, CSphVector<SqlStmt_t> & dStmt, CSphString & sError ); ParseResult_e ParseDdlEx ( Str_t sQuery, CSphVector<SqlStmt_t>& dStmt, CSphString& sError ); #endif // _searchdddl_
747
C++
.h
17
42.647059
92
0.751724
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,077
attrindex_builder.h
manticoresoftware_manticoresearch/src/attrindex_builder.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 "sphinxstd.h" #include "sphinxdefs.h" class CSphSchema; struct CSphAttrLocator; // FIXME!!! for over INT_MAX attributes /// attr min-max builder class AttrIndexBuilder_c : ISphNoncopyable { public: explicit AttrIndexBuilder_c ( const CSphSchema & tSchema ); AttrIndexBuilder_c() = default; void Init ( const CSphSchema & tSchema ); void Collect ( const CSphRowitem * pRow ); void FinishCollect(); const CSphTightVector<CSphRowitem> & GetCollected() const; private: CSphVector<CSphAttrLocator> m_dIntAttrs; CSphVector<CSphAttrLocator> m_dFloatAttrs; CSphVector<SphAttr_t> m_dIntMin; CSphVector<SphAttr_t> m_dIntMax; CSphVector<float> m_dFloatMin; CSphVector<float> m_dFloatMax; CSphVector<SphAttr_t> m_dIntIndexMin; CSphVector<SphAttr_t> m_dIntIndexMax; CSphVector<float> m_dFloatIndexMin; CSphVector<float> m_dFloatIndexMax; DWORD m_uStride {0}; int m_nLocalCollected {0}; CSphTightVector<CSphRowitem> m_dMinMaxRows; void ResetLocal(); void FlushComputed(); };
1,530
C++
.h
44
32.977273
80
0.759322
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,078
secondarylib.h
manticoresoftware_manticoresearch/src/secondarylib.h
// // Copyright (c) 2020-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/ // #ifndef _secondarylib_ #define _secondarylib_ #include "secondary/builder.h" #include "secondary/secondary.h" // FWD struct CSphString; bool InitSecondary ( CSphString & sError ); void ShutdownSecondary(); const char * GetSecondaryVersionStr(); bool IsSecondaryLibLoaded(); SI::Index_i * CreateSecondaryIndex ( const char * sFile, CSphString & sError ); std::unique_ptr<SI::Builder_i> CreateSecondaryIndexBuilder ( const common::Schema_t & tSchema, int64_t iMemoryLimit, const CSphString & sFile, int iBufferSize, CSphString & sError ); enum class SIDefault_e { DISABLED, ENABLED, FORCE }; void SetSecondaryIndexDefault ( SIDefault_e eState ); SIDefault_e GetSecondaryIndexDefault (); #endif // _secondarylib_
1,112
C++
.h
30
35.7
182
0.767225
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,079
stackmock.h
manticoresoftware_manticoresearch/src/stackmock.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 "client_task_info.h" #include "coroutine.h" #include "std/sys.h" using StackSizeTuplet_t = std::pair<int,int>; // create, eval template<typename T> int EvalMaxTreeHeight ( const VecTraits_T<T>& dTree, int iStartNode ) { CSphVector<std::pair<int, int>> dNodes; dNodes.Reserve ( dTree.GetLength() / 2 ); int iMaxHeight = 1; dNodes.Add ( { iStartNode, 1 } ); while ( dNodes.GetLength() ) { auto tParent = dNodes.Pop(); const auto& tItem = dTree[tParent.first]; iMaxHeight = Max ( iMaxHeight, tParent.second ); if ( tItem.m_iLeft >= 0 ) dNodes.Add ( { tItem.m_iLeft, tParent.second + 1 } ); if ( tItem.m_iRight >= 0 ) dNodes.Add ( { tItem.m_iRight, tParent.second + 1 } ); } return iMaxHeight; } template <typename T> bool EvalStackForTree ( const VecTraits_T<T> & dTree, int iStartNode, StackSizeTuplet_t tNodeStackSize, int iTreeSizeThresh, int & iStackNeeded, const char * szName, CSphString & sError ) { enum eStackSizePurpose { CREATE, EVAL }; iStackNeeded = -1; int64_t iCalculatedStack = Threads::GetStackUsed() + (int64_t)dTree.GetLength()*std::get<EVAL>(tNodeStackSize); int64_t iCurStackSize = Threads::MyStackSize(); if ( dTree.GetLength()<=iTreeSizeThresh ) return true; int iMaxHeight = EvalMaxTreeHeight ( dTree, iStartNode ); iCalculatedStack = Threads::GetStackUsed() + iMaxHeight* std::get<CREATE> ( tNodeStackSize ); if ( iCalculatedStack<=iCurStackSize ) return true; if ( iCalculatedStack > Threads::GetMaxCoroStackSize() ) { sError.SetSprintf ( "query %s too complex, not enough stack (thread_stack=%dK or higher required)", szName, (int)( ( iCalculatedStack + 1024 - ( iCalculatedStack%1024 ) ) / 1024 ) ); return false; } iStackNeeded = (int)iCalculatedStack + 32*1024; iStackNeeded = sphRoundUp( iStackNeeded, GetMemPageSize() ); // round up to memory page. // in case we're in real query processing - propagate size of stack need for evaluations (only additional part) session::ExpandDesiredStack ( iMaxHeight * std::get<EVAL> ( tNodeStackSize )); return true; } void DetermineNodeItemStackSize(); void DetermineFilterItemStackSize(); void DetermineMatchStackSize();
2,646
C++
.h
62
40.709677
187
0.738336
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,080
icu.h
manticoresoftware_manticoresearch/src/icu.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 _icu_ #define _icu_ #include "sphinxstd.h" #include "sphinxutils.h" #include "indexsettings.h" bool sphCheckConfigICU ( CSphIndexSettings & tSettings, CSphString & sError ); bool sphSpawnFilterICU ( std::unique_ptr<ISphFieldFilter> & pFieldFilter, const CSphIndexSettings & m_tSettings, const CSphTokenizerSettings & tTokSettings, const char * szIndex, CSphString & sError ); #endif // _icu_
880
C++
.h
19
45.105263
201
0.765461
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,081
sphinxrt.h
manticoresoftware_manticoresearch/src/sphinxrt.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 _sphinxrt_ #define _sphinxrt_ #include "sphinxutils.h" #include "sphinxstem.h" #include "sphinxint.h" #include "killlist.h" #include "attribute.h" #include "docstore.h" #include "columnarrt.h" #include "coroutine.h" #include "tokenizer/tokenizer.h" #include "indexing_sources/source_document.h" class RtAccum_t; using VisitChunk_fn = std::function<void ( const CSphIndex* pIndex )>; class InsertDocData_c { public: CSphMatch m_tDoc; CSphVector<VecTraits_T<const char>> m_dFields; CSphVector<const char*> m_dStrings; CSphAttrLocator m_tDocIDLocator; CSphVector<SphAttr_t> m_dColumnarAttrs; int m_iColumnarID = -1; int64_t m_iTotalBytes = 0; explicit InsertDocData_c ( const ISphSchema & tSchema ); void SetID ( SphAttr_t tDocID ); SphAttr_t GetID() const; void AddMVALength ( int iLength, bool bDefault=false ); void AddMVAValue ( int64_t iValue ) { m_dMvas.Add(iValue); } void ResetMVAs() { m_dMvas.Resize(0); } const int64_t * GetMVA ( int iMVA ) const { return m_dMvas.Begin()+iMVA; } void FixParsedMVAs ( const CSphVector<int64_t> & dParsed, int iCount ); static std::pair<int, bool> ReadMVALength ( const int64_t * & pMVA ); private: static const uint64_t DEFAULT_FLAG = 1ULL << 63; CSphVector<int64_t> m_dMvas; }; struct OptimizeTask_t { enum OptimizeVerb_e { eManualOptimize, eDrop, eCompress, eSplit, eMerge, eAutoOptimize, eDedup, }; OptimizeVerb_e m_eVerb; int m_iCutoff = 0; int m_iFrom = -1; int m_iTo = -1; bool m_bByOrder = false; CSphString m_sUvarFilter; }; struct CSphReconfigureSettings { CSphTokenizerSettings m_tTokenizer; CSphDictSettings m_tDict; CSphIndexSettings m_tIndex; CSphFieldFilterSettings m_tFieldFilter; CSphSchema m_tSchema; MutableIndexSettings_c m_tMutableSettings; bool m_bChangeSchema = false; }; struct CSphReconfigureSetup { TokenizerRefPtr_c m_pTokenizer; DictRefPtr_c m_pDict; CSphIndexSettings m_tIndex; std::unique_ptr<ISphFieldFilter> m_pFieldFilter; CSphSchema m_tSchema; MutableIndexSettings_c m_tMutableSettings; bool m_bChangeSchema = false; }; /// RAM based updateable backend interface class RtIndex_i : public CSphIndexStub { public: RtIndex_i ( CSphString sIndexName, CSphString sPath ) : CSphIndexStub { std::move ( sIndexName ), std::move ( sPath ) } {} /// get internal schema (to use for Add calls) virtual const CSphSchema & GetInternalSchema () const { return m_tSchema; } virtual uint64_t GetSchemaHash () const = 0; /// insert/update document in current txn /// fails in case of two open txns to different indexes virtual bool AddDocument ( InsertDocData_c & tDoc, bool bReplace, const CSphString & sTokenFilterOptions, CSphString & sError, CSphString & sWarning, RtAccum_t * pAccExt ) = 0; /// delete document in current txn /// fails in case of two open txns to different indexes virtual bool DeleteDocument ( const VecTraits_T<DocID_t> & dDocs, CSphString & sError, RtAccum_t * pAccExt ) = 0; /// commit pending changes virtual bool Commit ( int * pDeleted, RtAccum_t * pAccExt, CSphString* pError = nullptr ) = 0; /// undo pending changes virtual void RollBack ( RtAccum_t * pAccExt ) = 0; /// forcibly flush RAM chunk to disk virtual void ForceRamFlush ( const char* szReason ) = 0; virtual bool IsFlushNeed() const = 0; /// get time of last flush happened virtual int64_t GetLastFlushTimestamp() const = 0; /// forcibly save RAM chunk as a new disk chunk virtual bool ForceDiskChunk () = 0; /// attach a disk chunk to current index virtual bool AttachDiskIndex ( CSphIndex * pIndex, bool bTruncate, bool & bFatal, CSphString & sError ) { return true; } /// attach all the content of the RT index (flush ramchunk then disk chunks) to the current index virtual bool AttachRtIndex ( RtIndex_i * pIndex, bool bTruncate, bool & bFatal, CSphString & sError ) { return true; } /// truncate index (that is, kill all data) enum Truncate_e : bool { TRUNCATE, DROP }; virtual bool Truncate ( CSphString & sError, Truncate_e eAction ) = 0; virtual void Optimize ( OptimizeTask_t tTask ) {} virtual bool StartOptimize ( OptimizeTask_t tTask ) { return true; } virtual int OptimizesRunning () const noexcept { return 0; } virtual int GetNumOfLocks () const noexcept { return 0; } /// check settings vs current and return back tokenizer and dictionary in case of difference virtual bool IsSameSettings ( CSphReconfigureSettings & tSettings, CSphReconfigureSetup & tSetup, StrVec_t & dWarnings, CSphString & sError ) const = 0; /// reconfigure index by using new tokenizer, dictionary and index settings /// current data got saved with current settings virtual bool Reconfigure ( CSphReconfigureSetup & tSetup ) = 0; // generation typically changes on Reconfigure virtual int GetAlterGeneration() const { return 0; } /// do something const with disk chunk (query settings, status, etc.) /// hides internal disk chunks storage virtual void ProcessDiskChunk ( int iChunk, VisitChunk_fn&& fnVisitor ) const {}; /// bind indexing accumulator /// returns false if another index already uses it in an open txn virtual bool BindAccum ( RtAccum_t * pAccExt, CSphString * pError ) = 0; // instead of cloning for each AddDocument() call we could just call this method and improve batch inserts speed virtual TokenizerRefPtr_c CloneIndexingTokenizer() const = 0; // hint an index that it was deleted and should cleanup its files when destructed virtual void IndexDeleted() = 0; virtual void ProhibitSave() = 0; virtual void EnableSave() = 0; virtual void LockFileState ( CSphVector<CSphString> & dFiles ) = 0; virtual bool NeedStoreWordID () const = 0; virtual int64_t GetMemLimit() const = 0; virtual int GetChunkId () const { return 0; }; protected: bool PrepareAccum ( RtAccum_t* pAccExt, bool bWordDict, CSphString* pError ); }; /// initialize subsystem class CSphConfigSection; void sphRTInit ( CSphString sBinlogPath, bool bCommonBinlog = false, const CSphConfigSection * pCommon = nullptr ); bool sphRTSchemaConfigure ( const CSphConfigSection & hIndex, CSphSchema & tSchema, const CSphIndexSettings & tSettings, StrVec_t * pWarnings, CSphString & sError, bool bSkipValidation, bool bPQ ); void sphRTSetTestMode (); /// RT index factory std::unique_ptr<RtIndex_i> sphCreateIndexRT ( CSphString sIndexName, CSphString sPath, CSphSchema tSchema, int64_t iRamSize, bool bKeywordDict ); typedef void ProgressCallbackSimple_t (); ////////////////////////////////////////////////////////////////////////// /// Exposed internal stuff (for pq and for testing) #define SPH_MAX_KEYWORD_LEN (3*SPH_MAX_WORD_LEN+4) STATIC_ASSERT ( SPH_MAX_KEYWORD_LEN<255, MAX_KEYWORD_LEN_SHOULD_FITS_BYTE ); struct RtDoc_t { RowID_t m_tRowID { INVALID_ROWID }; ///< row id DWORD m_uDocFields = 0; ///< fields mask DWORD m_uHits = 0; ///< hit count DWORD m_uHit = 0; ///< either index into segment hits, or the only hit itself (if hit count is 1) }; struct RtWord_t { union { SphWordID_t m_uWordID; ///< my keyword id const BYTE * m_sWord; INIT_WITH_0 ( SphWordID_t, const BYTE* ); }; DWORD m_uDocs = 0; ///< document count (for stats and/or BM25) DWORD m_uHits = 0; ///< hit count (for stats and/or BM25) DWORD m_uDoc = 0; ///< index into segment docs bool m_bHasHitlist = true; }; struct RtWordCheckpoint_t { union { SphWordID_t m_uWordID; const char * m_szWord; }; int m_iOffset; }; // this is what actually stores index data // RAM chunk consists of such segments struct RtSegment_t final : IndexSegment_c, ISphRefcountedMT { public: mutable int m_iLocked = 0; // if segment currently used in an op mutable Threads::Coro::RWLock_c m_tLock; // fine-grain lock CSphTightVector<BYTE> m_dWords; CSphVector<RtWordCheckpoint_t> m_dWordCheckpoints; CSphTightVector<uint64_t> m_dInfixFilterCP; CSphTightVector<BYTE> m_dDocs; CSphTightVector<BYTE> m_dHits; DWORD m_uRows = 0; ///< number of actually allocated rows std::atomic<int64_t> m_tAliveRows { 0 }; ///< number of alive (non-killed) rows CSphTightVector<CSphRowitem> m_dRows GUARDED_BY ( m_tLock ); ///< row data storage CSphTightVector<BYTE> m_dBlobs GUARDED_BY ( m_tLock ); ///< storage for blob attrs CSphVector<BYTE> m_dKeywordCheckpoints; std::atomic<int64_t> * m_pRAMCounter = nullptr;///< external RAM counter OpenHashTable_T<DocID_t, RowID_t> m_tDocIDtoRowID; ///< speeds up docid-rowid lookups DeadRowMap_Ram_c m_tDeadRowMap; std::unique_ptr<DocstoreRT_i> m_pDocstore; std::unique_ptr<ColumnarRT_i> m_pColumnar; const ISphSchema& m_tSchema; mutable bool m_bConsistent{false}; RtSegment_t ( DWORD uDocs, const ISphSchema& tSchema ); int64_t GetUsedRam() const; // get cached ram usage counter void UpdateUsedRam() const; // recalculate ram usage, update index ram counter DWORD GetMergeFactor() const; int GetStride() const; const CSphRowitem * FindAliveRow ( DocID_t tDocid ) const; const CSphRowitem * GetDocinfoByRowID ( RowID_t tRowID ) const; RowID_t GetAliveRowidByDocid ( DocID_t tDocid ) const; RowID_t GetRowidByDocid ( DocID_t tDocID ) const; int Kill ( DocID_t tDocID ) override; int KillMulti ( const VecTraits_T<DocID_t> & dKlist ) override; void SetupDocstore ( const CSphSchema * pSchema ); void BuildDocID2RowIDMap ( const CSphSchema & tSchema ); void MaybeAddPostponedUpdate ( const RowsToUpdate_t& dRows, const UpdateContext_t& tCtx ); void UpdateAttributesOffline ( VecTraits_T<PostponedUpdate_t>& dPostUpdates ) final; private: mutable int64_t m_iUsedRam = 0; ///< ram usage counter ~RtSegment_t () final; void FixupRAMCounter ( int64_t iDelta ) const; bool Update_WriteBlobRow ( UpdateContext_t& tCtx, RowID_t tRowID, ByteBlob_t tBlob, int nBlobAttrs, const CSphAttrLocator& tBlobRowLoc, bool& bCritical, CSphString& sError ) final; }; using RtSegmentRefPtf_t = CSphRefcountedPtr<RtSegment_t>; using ConstRtSegmentRefPtf_t = CSphRefcountedPtr<const RtSegment_t>; class RtWordReader_c { BYTE m_tPackedWord[SPH_MAX_KEYWORD_LEN + 1]; RtWord_t m_tWord; int m_iWords = 0; bool m_bWordDict; int m_iWordsCheckpoint; int m_iCheckpoint = 0; const ESphHitless m_eHitlessMode = SPH_HITLESS_NONE; public: const BYTE* m_pCur = nullptr; const BYTE* m_pMax = nullptr; RtWordReader_c ( const RtSegment_t * pSeg, bool bWordDict, int iWordsCheckpoint, ESphHitless eHitlessMode ); void Reset ( const RtSegment_t * pSeg ); inline int Checkpoint() const { return m_iCheckpoint; } const RtWord_t* UnzipWord(); inline explicit operator RtWord_t*() { return &m_tWord; } inline RtWord_t* operator->() { return &m_tWord; } inline const RtWord_t& operator*() const { return m_tWord; } }; class RtDocReader_c { const BYTE* m_pDocs = nullptr; int m_iLeft = 0; RtDoc_t m_tDoc; public: RtDocReader_c() = default; RtDocReader_c ( const RtSegment_t* pSeg, const RtWord_t& tWord ); void Init ( const RtSegment_t* pSeg, const RtWord_t& tWord ); void Reset () { m_pDocs = nullptr; m_iLeft = 0; } bool UnzipDoc(); inline explicit operator RtDoc_t*() { return &m_tDoc; } inline RtDoc_t* operator->() { return &m_tDoc; } inline const RtDoc_t& operator*() const { return m_tDoc; } }; class RtHitReader_c { const BYTE* m_pCur = nullptr; DWORD m_uLeft = 0; DWORD m_uValue = 0; public: RtHitReader_c() = default; RtHitReader_c ( const RtSegment_t& dSeg, const RtDoc_t& dDoc ); void Seek ( const RtSegment_t& dSeg, const RtDoc_t& dDoc ); void Seek ( const BYTE* pHits, DWORD uHits ); inline DWORD operator*() const { return m_uValue; } DWORD UnzipHit (); }; ByteBlob_t GetHitsBlob ( const RtSegment_t* pSeg, const RtDoc_t* pDoc ); class CSphSource_StringVector : public CSphSource { public: explicit CSphSource_StringVector ( const VecTraits_T<VecTraits_T<const char >> &dFields, const CSphSchema &tSchema ); ~CSphSource_StringVector () override = default; bool Connect ( CSphString & ) override; void Disconnect () override; bool IterateStart ( CSphString & ) override { m_iPlainFieldsLength = m_tSchema.GetFieldsCount(); return true; } bool IterateMultivaluedStart ( int, CSphString & ) override { return false; } bool IterateMultivaluedNext ( int64_t & iDocID, int64_t & iMvaValue ) override { return false; } CSphVector<int64_t> * GetFieldMVA ( int iAttr ) override { return nullptr; } bool IterateKillListStart ( CSphString & ) override { return false; } bool IterateKillListNext ( DocID_t & ) override { return false; } BYTE ** NextDocument ( bool &, CSphString & ) override { return m_dFields.Begin(); } const int * GetFieldLengths () const override { return m_dFieldLengths.Begin(); } void SetMorphFields ( const CSphBitvec & tMorphFields ) { m_tMorphFields = tMorphFields; } protected: CSphVector<BYTE *> m_dFields; CSphVector<int> m_dFieldLengths; }; #define BLOOM_PER_ENTRY_VALS_COUNT 8 #define BLOOM_HASHES_COUNT 2 #define BLOOM_NGRAM_0 2 #define BLOOM_NGRAM_1 4 struct BloomGenTraits_t { uint64_t * m_pBuf = nullptr; explicit BloomGenTraits_t ( uint64_t * pBuf ) : m_pBuf ( pBuf ) {} void Set ( int iPos, uint64_t uVal ) { m_pBuf[iPos] |= uVal; } bool IterateNext () const { return true; } }; struct BloomCheckTraits_t { const uint64_t * m_pBuf = nullptr; bool m_bSame = true; explicit BloomCheckTraits_t ( const uint64_t * pBuf ) : m_pBuf ( pBuf ) {} void Set ( int iPos, uint64_t uVal ) { m_bSame = ( ( m_pBuf[iPos] & uVal )==uVal ); } bool IterateNext () const { return m_bSame; } }; bool BuildBloom ( const BYTE * sWord, int iLen, int iInfixCodepointCount, bool bUtf8, int iKeyValCount, BloomGenTraits_t &tBloom ); bool BuildBloom ( const BYTE * sWord, int iLen, int iInfixCodepointCount, bool bUtf8, int iKeyValCount, BloomCheckTraits_t &tBloom ); void BuildSegmentInfixes ( RtSegment_t * pSeg, bool bHasMorphology, bool bKeywordDict, int iMinInfixLen, int iWordsCheckpoint, bool bUtf8, ESphHitless eHitlessMode ); bool ExtractInfixCheckpoints ( const char * sInfix, int iBytes, int iMaxCodepointLength, int iDictCpCount, const CSphTightVector<uint64_t> &dFilter, CSphVector<DWORD> &dCheckpoints ); void SetupExactTokenizer ( const TokenizerRefPtr_c & pTokenizer ); void SetupStarTokenizer ( const TokenizerRefPtr_c & pTokenizer ); bool CreateReconfigure ( const CSphString & sIndexName, bool bIsStarDict, const ISphFieldFilter * pFieldFilter, const CSphIndexSettings & tIndexSettings, uint64_t uTokHash, uint64_t uDictHash, int iMaxCodepointLength, int64_t iMemLimit, bool bSame, CSphReconfigureSettings & tSettings, CSphReconfigureSetup & tSetup, StrVec_t & dWarnings, CSphString & sError ); // Get global flag of w-available RT volatile bool &RTChangesAllowed () noexcept; // Get global flag of autooptimize volatile int & AutoOptimizeCutoffMultiplier() noexcept; volatile int AutoOptimizeCutoff() noexcept; #endif // _sphinxrt_
15,541
C++
.h
355
41.690141
197
0.735827
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,082
threadutils.h
manticoresoftware_manticoresearch/src/threadutils.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/ // /// @file threadutils.h /// Different thread-related things (moved here from searchd.cpp) #ifndef MANTICORE_THREADUTILS_H #define MANTICORE_THREADUTILS_H #include "sphinxstd.h" #include "sphinxint.h" #include "hazard_pointer.h" struct CSphQuery; enum class TaskState_e { UNKNOWN, HANDSHAKE, NET_READ, NET_WRITE, QUERY, NET_IDLE, RETIRED, }; enum class Proto_e { UNKNOWN, SPHINX, MYSQL41, HTTP, REPLICATION, HTTPS, SPHINXSE, }; const char* TaskStateName ( TaskState_e eState ); const char* ProtoName ( Proto_e eProto ); const char* RelaxedProtoName ( Proto_e eProto ); int GetOsThreadId (); int GetOsProcessId(); /// my thread handle and thread func magic #if _WIN32 using SphThread_t = HANDLE; #else using SphThread_t = pthread_t; #endif namespace Threads { namespace details { class SchedulerOperation_t; } // most basic struct with details interested not only to thread itself, but also observable from outside // Describes just 'execution'. Used as is from main to handle detached threads on shutdown // each thread own such structure by design, ref from inside m.b. accessed by Threads::MyThd() struct LowThreadDesc_t { SphThread_t m_tThread; ///< m.b. used to send signals to the thread int m_iThreadID; ///< OS thread id int64_t m_tmStart; ///< when did the current thread started? Initialized from thread itself int64_t m_tmLastJobStartTimeUS = -1; ///< last time where I've started something useful int64_t m_tmLastJobStartCPUTimeUS = -1; ///< last time where I've started something useful int64_t m_tmLastJobDoneTimeUS = -1; ///< last time where I've done something useful int64_t m_tmTotalWorkedTimeUS = 0; ///< total time I've worked on useful tasks int64_t m_tmTotalWorkedCPUTimeUS = 0; ///< total time I've worked on useful tasks int64_t m_iTotalJobsDone = 0; ///< total jobs I've completed CSphString m_sThreadName; std::atomic<void *> m_pTaskInfo; ///< what kind of task I'm doing now (nullptr - idle, i.e. nothing) std::atomic<void *> m_pHazards; ///< my hazard pointers void * m_pWorker = nullptr; ///< my coro worker (m.b. empty in generic threads) StringBuilder_c m_sThreadMsg; std::atomic<StringBuilder_c*> m_pTlsMsg { &m_sThreadMsg }; }; // thread-local description available globaly from any thread LowThreadDesc_t& MyThd () noexcept; // save name from my local LowThreadDesc into OS thread name void SetSysThreadName(); using ThreadFN = std::function<void ( Threads::LowThreadDesc_t * )>; using ThreadIteratorFN = std::function<void ( ThreadFN& )>; // apply handler to all running threads void IterateActive ( ThreadFN fnHandler ); // add function which will be invoked from IterateActive void RegisterIterator ( ThreadIteratorFN fnIterator ); int GetNumOfRunning (); // track the time void JobStarted(); void JobFinished( bool bIsDone=true ); // RAII time tracker struct JobTracker_t { JobTracker_t () { JobStarted (); } ~JobTracker_t () { JobFinished (); } }; struct IdleTimer_t { IdleTimer_t () { JobFinished (false); } ~IdleTimer_t () { JobStarted (); } }; ////////////////////////////////////////////////////////////////////////// /// functional threadpool with minimum footprint using Handler = std::function<void ()>; using Predicate = std::function<bool ()>; using Handlers = std::initializer_list<Handler>; // used to RAII keep Scheduler running (when work finished - it is usually destroyed) using Keeper_t = SharedPtrCustom_t<void>; struct Scheduler_i { virtual ~Scheduler_i() = default; virtual void ScheduleOp ( Threads::details::SchedulerOperation_t* pOp, bool bVip ) = 0; virtual void ScheduleContinuationOp ( Threads::details::SchedulerOperation_t* pOp ) // if task already started { ScheduleOp ( pOp, false ); } // RAII keeper of scheduler (when it exists, scheduler will not finish). That is necessary, say, if the only work is // paused and moved somewhere (for example, as cb in epoll polling). Without keeper scheduler then finish and it will // be impossible to resume it later. virtual Keeper_t KeepWorking() = 0; // number of parallel contextes might be necessary when working via this scheduler // alone and strand obviously has 1 worker; threadpool has many. virtual int WorkingThreads() const { return 1; }; virtual const char* Name() const { return "unnamed_sched"; } template<typename HANDLER> void Schedule ( HANDLER handler, bool bVip ) noexcept; template<typename HANDLER> void ScheduleContinuation ( HANDLER handler ) noexcept; }; struct SchedulerWithBackend_i: public Scheduler_i { virtual bool SetBackend ( Scheduler_i* pBackend ) = 0; }; struct NTasks_t { // snapshot length of Op queue int iPri; int iSec; }; struct Worker_i: public Scheduler_i { virtual int Works() const = 0; virtual NTasks_t Tasks() const noexcept = 0; virtual int CurTasks() const noexcept = 0; virtual void StopAll () = 0; virtual void DiscardOnFork() {} virtual void IterateChildren ( ThreadFN & fnHandler ) noexcept {} }; using SchedulerSharedPtr_t = SharedPtr_t<Scheduler_i>; using WorkerSharedPtr_t = SharedPtr_t<Worker_i>; // none of the functions below used in the code. Both maybe only in tests. WorkerSharedPtr_t MakeThreadPool ( size_t iThreadCount, const char* szName = "" ); WorkerSharedPtr_t MakeAloneThread ( size_t iOrderNum, const char* szName = "" ); // Alone scheduler works on top of another scheduler and provides sequental execution of the tasks (each time only one // task may be performed, no concurrent execution). It also gives FIFO ordering of the tasks. SchedulerSharedPtr_t MakeAloneScheduler ( Scheduler_i* pBase, const char* szName = nullptr ); SchedulerSharedPtr_t WrapRawScheduler ( Scheduler_i* pBase, const char* szName = nullptr ); class OperationsQueue_c { class Impl_c; Impl_c * m_pImpl = nullptr; public: OperationsQueue_c(); ~OperationsQueue_c(); void AddOp (Handler fnOp); void RunAll(); bool IsEmpty() const; }; /// stack of a thread (that is NOT stack of the coroutine!) static const DWORD STACK_SIZE = 128 * 1024; /// get the pointer to my thread's stack const void * TopOfStack (); /// limit size for my coro stacks void SetMaxCoroStackSize ( int iStackSize ); int GetMaxCoroStackSize (); /// store the address in the TLS and prepare whole thread (name, hazards, etc.) void PrepareMainThread ( const void * PStack ); /// owerwrite top ot stack pointer (m.b. need for mocking) void SetTopStack ( const void * pNewStack ); /// my threading initialize routine void * Init ( bool bDetached = false ); /// my threading deinitialize routine void Done ( int iFD ); /// get name of a thread CSphString GetName ( const SphThread_t * pThread ); /// my join thread wrapper bool Join ( SphThread_t * pThread ); /// my own thread SphThread_t Self (); /// compares two thread ids bool Same ( const LowThreadDesc_t * pFirst, const LowThreadDesc_t * pSecond ); /// my create thread wrapper /// for threads serving clients use CreateQ instead bool Create ( SphThread_t * pThread, Handler fnRun, bool bDetached = false, const char * sName = nullptr, int iNum=-1 ); /// create thread and run thread func having global CrashQuery_t initialized bool CreateQ ( SphThread_t * pThread, Handler fnRun, bool bDetached = false, const char * sName = nullptr, int iNum=-1 ); /// place copy of current crash query into fnHandler context Handler WithCopiedCrashQuery ( Handler fnHandler ); } // namespace Threads extern ThreadRole MainThread; namespace CrashLogger { #if !_WIN32 void HandleCrash( int ); #else LONG WINAPI HandleCrash ( EXCEPTION_POINTERS * pExc ); #endif void SetupTimePID(); }; // Scheduler to global thread pool Threads::Worker_i* GlobalWorkPool (); void SetMaxChildrenThreads ( int iThreads ); void StartGlobalWorkPool (); void StopGlobalWorkPool(); /// schedule stop of the global thread pool void WipeGlobalSchedulerOnShutdownAndFork (); void WipeSchedulerOnFork ( Threads::Worker_i * ); // Scheduler to dedicated thread (or nullptr, if current N of such threads >= iMaxThreads) // you MUST schedule at least one job, or explicitly delete non-engaged scheduler (it will leak otherwise). Threads::Scheduler_i* MakeSingleThreadExecutor ( int iMaxThreads, const char* szName = nullptr ); // add handler which will be called on daemon's shutdown right after // sphInterrupted() is set to true. Returns cookie for refer the callback in future. namespace searchd { // add global (process-wide) callback to be called on shutdown. // That is stack, i.e. LIFO sequence. void AddShutdownCb ( Threads::Handler fnCb ); // add global cb to be called on fork. LIFO void AddOnForkCleanupCb ( Threads::Handler fnCb ); // execute shutdown handlers void FireShutdownCbs (); // Shutdown cb chain also forked, but don't need to be executed on fork void CleanAfterFork(); } // add and remove unjoined threads to global tracer which will // send them SIGTERM on shutdown namespace Detached { void AddThread ( Threads::LowThreadDesc_t* pThread ); void RemoveThread ( Threads::LowThreadDesc_t* pThread ); // schedule global watchdog to gracefully join alone threads on exit void MakeAloneIteratorAvailable (); void ShutdownAllAlones(); } #include "threadutils_impl.h" #endif //MANTICORE_THREADUTILS_H
9,720
C++
.h
247
37.700405
121
0.751834
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,083
mini_timer.h
manticoresoftware_manticoresearch/src/mini_timer.h
// // Copyright (c) 2021-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 <cstdint> #include "timeout_queue.h" #include "threadutils.h" namespace sph { /// we use useconds for timestamps, however sleep obey mseconds. Interval less than granularity should be considered as 0, timestamps inside granularity should be considered as equal constexpr int64_t TICKS_GRANULARITY = 1000ll; inline bool TimeExceeded ( int64_t iTimestampUS, int64_t iPivotUS, int64_t GRANULARITY=TICKS_GRANULARITY ) { assert ( iPivotUS > 0 ); return ( iTimestampUS - GRANULARITY ) < iPivotUS; } /// call sphMicroTime, track value and return it int64_t MicroTimer(); /// return last tracked value of MicroTimer (don't call sphMicroTime) int64_t LastTimestamp(); /// returns true if provided timestamp is already reached or not /// it IMPLIES timer is engaged to given limit timestamp. /// non-engaged timer doesn't tick and may infinitely return false. bool TimeExceeded ( int64_t iTimestampUS ); /// should be called on shutdown void ShutdownMiniTimer(); struct ScheduleInfo_t { int64_t m_iTimeoutStamp; CSphString m_sTask; }; CSphVector<ScheduleInfo_t> GetSchedInfo(); } /// RAII timer thread ticker. class MiniTimer_c final : public EnqueuedTimeout_t, public ISphNoncopyable { friend class TinyTimer_c; const char* m_szName; Threads::Handler m_fnOnTimer; // notice, will be called from naked thread, not coroutine ctx! public: // name is used to display engaged timer in 'debug sched', or 'select ... from @@system.sched' // fnOnTimer callback is optional, that is ok to work without it, and just check TimeExceeded() periodically. explicit MiniTimer_c ( const char* szName = "mini-timer", Threads::Handler&& fnOnTimer=nullptr ) : m_szName ( szName ) , m_fnOnTimer { std::move ( fnOnTimer ) } {} /// on period<=0 does nothing, returns 0. On positive - engage tick after given period; returns timestamp where it should tick. int64_t Engage ( int64_t iTimePeriodMS ); int64_t Engage ( int64_t iTimePeriodMS, Threads::Handler&& fnOnTimer ); // fnOnTimer may be set here alternatively to be set in ctr /// engage to be kicked at absolute time (in microseconds) void EngageAt ( int64_t iTimeStampUS ); void EngageAt ( int64_t iTimeStampUS, Threads::Handler&& fnOnTimer ); // fnOnTimer may be set here alternatively to be set in ctr void UnEngage(); // dtr calls UnEngage(), so it is safe to delete engaged timer ~MiniTimer_c(); };
2,793
C++
.h
62
43.032258
183
0.755064
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,084
snippetfunctor.h
manticoresoftware_manticoresearch/src/snippetfunctor.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 _snippetfunctor_ #define _snippetfunctor_ #include "sphinxstd.h" #include "sphinxquery.h" #include "sphinxsearch.h" #include "sphinxdefs.h" struct TokenInfo_t { int m_iStart; int m_iLen; const BYTE * m_sWord; DWORD m_uPosition; bool m_bWord; bool m_bStopWord; int m_iTermIndex; int m_iMultiPosLen; SphWordID_t m_uWordId; }; struct FunctorZoneInfo_t { SmallStringHash_T<int> m_hZones; CSphVector<int> m_dZonePos; CSphVector<int> m_dZoneParent; }; typedef uint64_t ZonePacked_t; struct SnippetQuerySettings_t; struct SnippetResult_t; struct Passage_t; struct PassageContext_t; class CacheStreamer_i; class TokenFunctor_i { public: virtual ~TokenFunctor_i() {} virtual bool OnToken ( const TokenInfo_t & tTok, const CSphVector<SphWordID_t> & dTokens, const CSphVector<int> * pMultiPosDelta ) = 0; virtual bool OnOverlap ( int iStart, int iLen, int iBoundary ) = 0; virtual void OnSkipHtml ( int iStart, int iLen ) = 0; virtual void OnSPZ ( BYTE iSPZ, DWORD uPosition, const char * szZone, int iZone ) = 0; virtual void OnTail ( int iStart, int iLen, int iBoundary ) = 0; virtual void OnFinish() = 0; }; class SnippetsDocIndex_c; class HitCollector_i : public TokenFunctor_i { public: virtual DictRefPtr_c & GetDict() = 0; virtual TokenizerRefPtr_c & GetTokenizer() = 0; virtual const CSphIndexSettings & GetIndexSettings() = 0; virtual const SnippetQuerySettings_t & GetSnippetQuery() = 0; virtual CSphVector<ZonePacked_t> & GetZones() = 0; virtual FunctorZoneInfo_t & GetZoneInfo() = 0; virtual bool NeedExtraZoneInfo() const = 0; virtual DWORD GetFoundWords() const = 0; }; std::unique_ptr<TokenFunctor_i> CreateDocStartHighlighter ( TokenizerRefPtr_c pTokenizer, const SnippetQuerySettings_t & tQuery, const SnippetLimits_t & tLimits, const CSphIndexSettings & tIndexSettings, const char * szDoc, int iDocLen, int iField, int & iResultCP, SnippetResult_t & tRes ); std::unique_ptr<TokenFunctor_i> CreateQueryHighlighter ( TokenizerRefPtr_c pTokenizer, const SnippetQuerySettings_t & tQuery, const CSphIndexSettings & tIndexSettings, const char * szDoc, int iDocLen, const CSphVector<SphHitMark_t> & dHits, int iField, SnippetResult_t & tRes ); std::unique_ptr<TokenFunctor_i> CreatePassageExtractor ( const SnippetsDocIndex_c & tContainer, PassageContext_t & tContext, TokenizerRefPtr_c pTokenizer, const SnippetQuerySettings_t & tQuery, const SnippetLimits_t & tLimits, const CSphIndexSettings & tIndexSettings, const char * szDoc, int iDocLen, const CSphVector<SphHitMark_t> & dHits, int iField, SnippetResult_t & tRes ); std::unique_ptr<TokenFunctor_i> CreatePassageHighlighter ( CSphVector<Passage_t*> & dPassages, TokenizerRefPtr_c pTokenizer, const SnippetQuerySettings_t & tQuery, const CSphIndexSettings & tIndexSettings, const char * szDoc, int iDocLen, const CSphVector<SphHitMark_t> & dHits, const FunctorZoneInfo_t & tZoneInfo, int iField, SnippetResult_t & tRes ); std::unique_ptr<HitCollector_i> CreateHitCollector ( SnippetsDocIndex_c & tContainer, TokenizerRefPtr_c pTokenizer, DictRefPtr_c pDict, const SnippetQuerySettings_t & tQuery, const CSphIndexSettings & tIndexSettings, const char * szDoc, int iDocLen, int iField, CacheStreamer_i & tTokenContainer, CSphVector<ZonePacked_t> & dZones, FunctorZoneInfo_t & tZoneInfo, SnippetResult_t & tRes ); #endif // _snippetfunctor_
3,875
C++
.h
76
49.276316
226
0.770982
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,085
queryprofile.h
manticoresoftware_manticoresearch/src/queryprofile.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 _queryprofile_ #define _queryprofile_ #include "sphinxdefs.h" class CSphSchema; #define SPH_QUERY_STATES \ SPH_QUERY_STATE ( UNKNOWN, "unknown" ) \ SPH_QUERY_STATE ( NET_READ, "net_read" ) \ SPH_QUERY_STATE ( IO, "io" ) \ SPH_QUERY_STATE ( DIST_CONNECT, "dist_connect" ) \ SPH_QUERY_STATE ( LOCAL_DF, "local_df" ) \ SPH_QUERY_STATE ( LOCAL_SEARCH, "local_search" ) \ SPH_QUERY_STATE ( SQL_PARSE, "sql_parse" ) \ SPH_QUERY_STATE ( SETUP_ITER, "setup_iter" ) \ SPH_QUERY_STATE ( FULLSCAN, "fullscan" ) \ SPH_QUERY_STATE ( DICT_SETUP, "dict_setup" ) \ SPH_QUERY_STATE ( PARSE, "parse" ) \ SPH_QUERY_STATE ( TRANSFORMS, "transforms" ) \ SPH_QUERY_STATE ( INIT, "init" ) \ SPH_QUERY_STATE ( INIT_SEGMENT, "init_segment" ) \ SPH_QUERY_STATE ( OPEN, "open" ) \ SPH_QUERY_STATE ( READ_DOCS, "read_docs" ) \ SPH_QUERY_STATE ( READ_HITS, "read_hits" ) \ SPH_QUERY_STATE ( GET_DOCS, "get_docs" ) \ SPH_QUERY_STATE ( GET_HITS, "get_hits" ) \ SPH_QUERY_STATE ( FILTER, "filter" ) \ SPH_QUERY_STATE ( RANK, "rank" ) \ SPH_QUERY_STATE ( QCACHE_UP, "qcache_update" ) \ SPH_QUERY_STATE ( QCACHE_FINAL, "qcache_final" ) \ SPH_QUERY_STATE ( SORT, "sort" ) \ SPH_QUERY_STATE ( FINALIZE, "finalize" ) \ SPH_QUERY_STATE ( DYNAMIC, "clone_attrs" ) \ SPH_QUERY_STATE ( DIST_WAIT, "dist_wait" ) \ SPH_QUERY_STATE ( AGGREGATE, "aggregate" ) \ SPH_QUERY_STATE ( NET_WRITE, "net_write" ) \ SPH_QUERY_STATE ( EVAL_POST, "eval_post" ) \ SPH_QUERY_STATE ( EVAL_GETFIELD,"eval_getfield" ) \ SPH_QUERY_STATE ( SNIPPET, "eval_snippet" ) \ SPH_QUERY_STATE ( EVAL_UDF, "eval_udf" ) \ SPH_QUERY_STATE ( TABLE_FUNC, "table_func" ) /// possible query states, used for profiling enum ESphQueryState { SPH_QSTATE_INFINUM = -1, #define SPH_QUERY_STATE(_name,_desc) SPH_QSTATE_##_name, SPH_QUERY_STATES #undef SPH_QUERY_STATE SPH_QSTATE_TOTAL }; STATIC_ASSERT ( SPH_QSTATE_UNKNOWN==0, BAD_QUERY_STATE_ENUM_BASE ); struct XQNode_t; enum class PLAN_FLAVOUR { ENONE, EDESCR, EOBJ, EBOTH }; /// search query profile class QueryProfile_c { public: ESphQueryState m_eState; ///< current state int64_t m_tmStamp; ///< timestamp when we entered the current state int m_dSwitches [ SPH_QSTATE_TOTAL+1 ]; ///< number of switches to given state int64_t m_tmTotal [ SPH_QSTATE_TOTAL+1 ]; ///< total time spent per state CSphVector<BYTE> m_dPlan; ///< bson with plan PLAN_FLAVOUR m_eNeedPlan = PLAN_FLAVOUR::EBOTH; bool m_bNeedProfile = true; int m_iMaxMatches = 0; int m_iPseudoShards = 1; /// create empty and stopped profile QueryProfile_c(); virtual ~QueryProfile_c() {} /// switch to a new query state, and record a timestamp /// returns previous state, to simplify Push/Pop like scenarios ESphQueryState Switch ( ESphQueryState eNew ); /// reset everything and start profiling from a given state void Start ( ESphQueryState eNew ); /// stop profiling void Stop(); void AddMetric ( const QueryProfile_c & tData ); void BuildResult ( XQNode_t * pRoot, const CSphSchema & tSchema, const StrVec_t & dZones ); }; class CSphScopedProfile { public: CSphScopedProfile ( QueryProfile_c * pProfile, ESphQueryState eNewState ); ~CSphScopedProfile(); private: QueryProfile_c * m_pProfile; ESphQueryState m_eOldState; }; // acquire common pattern 'check, then switch if not null' inline void SwitchProfile ( QueryProfile_c * pProfile, ESphQueryState eState ) { if ( pProfile ) pProfile->Switch ( eState ); } #endif // _queryprofile_
4,036
C++
.h
104
36.701923
94
0.697187
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,086
binlog_defs.h
manticoresoftware_manticoresearch/src/binlog_defs.h
// // Copyright (c) 2021-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 "std/ints.h" #include <functional> namespace Binlog { struct CheckTnxResult_t { bool m_bValid = false; bool m_bApply = false; }; using CheckTxn_fn = std::function<CheckTnxResult_t ()>; }
696
C++
.h
22
30.136364
80
0.743666
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,087
hyperloglog.h
manticoresoftware_manticoresearch/src/hyperloglog.h
// // Copyright (c) 2023-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/ // #ifndef _hyperloglog_ #define _hyperloglog_ #include "sphinxstd.h" #include "farmhash/farmhash.h" #include <algorithm> #include <vector> #include <cmath> template<typename T> struct FarmHash_T { static inline uint64_t Hash (const T & x ); }; template<> inline uint64_t FarmHash_T<uint64_t>::Hash ( const uint64_t & x ) { return farmhash::Fingerprint(x); } inline double FastInversePow2 ( int iExp ) { union { double d; uint64_t i; } tValue; tValue.i = ( 1023ULL - iExp ) << 52; return tValue.d; } double LinearCounting ( int iV, int iM ); // Non-packed registers; uses 6 bits out of 8 class RegistersNonPacked_c { public: RegistersNonPacked_c ( int iBitsPerBucket, int iBuckets ); FORCE_INLINE void Update ( int iBucket, uint8_t uValue ) { assert ( uValue<=m_uMaxValue ); auto & tStored = m_dValues[iBucket]; if ( uValue > tStored ) { m_iUsed += !tStored; tStored = uValue; } } FORCE_INLINE uint8_t Get ( int iBucket ) const { return m_dValues[iBucket]; } int GetNumUnused() const { return m_dValues.GetLength()-m_iUsed; } void Reset(); private: CSphFixedVector<uint8_t> m_dValues; uint8_t m_uMaxValue = 0; int m_iUsed = 0; }; template <typename T=uint64_t> class RegistersPacked_T { public: RegistersPacked_T ( int iBitsPerBucket, int iBuckets ) : m_dData ( ( iBuckets*iBitsPerBucket + ELEM_BITS - 1 ) / ELEM_BITS ) , m_iBitsPerBucket ( iBitsPerBucket ) , m_iNumBuckets ( iBuckets ) , m_uMask ( ( 1 << iBitsPerBucket ) - 1 ) { m_dData.ZeroVec(); } FORCE_INLINE void Update ( int iBucket, uint8_t uValue ) { int iBitOffset = uint64_t(iBucket)*m_iBitsPerBucket; int iIdx = iBitOffset >> ELEM_SHIFT; iBitOffset -= iIdx << ELEM_SHIFT; if ( iBitOffset + m_iBitsPerBucket <= ELEM_BITS) { T & tElem = m_dData[iIdx]; uint8_t uStored = ( tElem >> iBitOffset ) & m_uMask; if ( uValue > uStored ) { m_iUsed += !uStored; tElem = ( tElem & ~( m_uMask << iBitOffset ) ) | ( (T)uValue << iBitOffset ); } } else { T & tElem1 = m_dData[iIdx]; T & tElem2 = m_dData[iIdx + 1]; int iBitShift = ELEM_BITS-iBitOffset; uint8_t uStored = ( tElem1 >> iBitOffset ) | ( ( tElem2 << iBitShift ) & m_uMask ); if ( uValue > uStored ) { m_iUsed += !uStored; tElem1 = ( tElem1 & ~( m_uMask << iBitOffset ) ) | ( (T)uValue << iBitOffset ); tElem2 = ( tElem2 & ~( m_uMask >> m_iBitsPerBucket ) ) | ( (T)uValue >> iBitShift ); } } } FORCE_INLINE uint8_t Get ( int iBucket ) const { int iBitOffset = uint64_t(iBucket)*m_iBitsPerBucket; int iIdx = iBitOffset >> ELEM_SHIFT; iBitOffset -= iIdx << ELEM_SHIFT; if ( iBitOffset + m_iBitsPerBucket <= ELEM_BITS) return ( m_dData[iIdx] >> iBitOffset ) & m_uMask; return ( m_dData[iIdx] >> iBitOffset ) | ( ( m_dData[iIdx + 1] << ( ELEM_BITS-iBitOffset ) ) & m_uMask ); } int GetNumUnused() const { return m_iNumBuckets-m_iUsed; } void Reset() { m_dData.ZeroVec(); m_iUsed = 0; } private: static const int ELEM_BITS = sizeof(T)*8; static const int ELEM_SHIFT = sphLog2const(ELEM_BITS) - 1; CSphFixedVector<T> m_dData; int m_iBitsPerBucket = 0; int m_iNumBuckets = 0; T m_uMask = 0; int m_iUsed = 0; }; extern const std::vector<std::vector<double>> g_dRawEstimateData; extern const std::vector<std::vector<double>> g_dBiasData; // implementation based on "HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm" template<typename T=uint64_t, typename HASH=FarmHash_T<T>, typename STORAGE=RegistersPacked_T<>> class HyperLogLogDense_T { template<int, int, typename, typename> friend class HyperLogLogSparse_T; public: HyperLogLogDense_T ( int iAccuracy=14 ) : m_tStorage ( 6, 1 << iAccuracy ) , m_iP ( iAccuracy ) , m_iM ( 1 << m_iP ) , m_uMask ( ( 1ULL << ( 64-m_iP ) ) - 1 ) { assert ( iAccuracy>=MIN_P && iAccuracy<=18 ); } FORCE_INLINE void Add ( const T & tValue ) { uint64_t uHash = HASH::Hash(tValue); int iRegister = uHash >> ( 64 - m_iP ); uint8_t uCount = ( uHash ? GetLeadingZeroBits ( uHash & m_uMask ) : sizeof(uint64_t)*8 ) - m_iP + 1; m_tStorage.Update ( iRegister, uCount ); } uint64_t Estimate() const { int iV = m_tStorage.GetNumUnused(); if ( iV ) { uint64_t uH = LinearCounting ( iV, m_iM ); if ( uH<=GetThreshold() ) return uH; } return (uint64_t)round ( CalcEstimate() ); } FORCE_INLINE void Clear() { m_tStorage.Reset(); } void Merge ( const HyperLogLogDense_T & tRhs ) { assert ( m_iP==tRhs.m_iP && m_iM==tRhs.m_iM ); for ( int i = 0; i < m_iM; i++ ) m_tStorage.Update ( i, tRhs.m_tStorage.Get(i) ); } private: static const int MIN_P = 14; STORAGE m_tStorage; int m_iP = 0; int m_iM = 0; uint64_t m_uMask = 0; double GetAlpha() const { return 0.7213 / ( 1.0 + (1.079 / m_iM ) ); } double GetThreshold() const { switch ( m_iP ) { case 14: return 11500; case 15: return 20000; case 16: return 50000; case 17: return 120000; case 18: return 350000; default: assert ( 0 && "Unsupported HLL accuracy" ); return 0; } } double EstimateBias ( double fEstimate ) const { const auto & dRawEstimate = g_dRawEstimateData[m_iP - MIN_P]; const auto & dBias = g_dBiasData[m_iP - MIN_P]; auto tFound = std::lower_bound ( dRawEstimate.begin(), dRawEstimate.end(), fEstimate ); int iFound = 0; int iNumRawEstimates = (int)dRawEstimate.size(); if ( tFound==dRawEstimate.end() ) iFound = iNumRawEstimates - 1; else iFound = int ( tFound - dRawEstimate.begin() ); const int NUM_NEIGHBOURS = 6; std::pair<int, double> dNearest[NUM_NEIGHBOURS*2 + 1]; int iNumNearest = 0; for ( int i = std::max ( iFound - NUM_NEIGHBOURS, 0 ); i <= std::min ( iFound + NUM_NEIGHBOURS, iNumRawEstimates-1 ); i++ ) dNearest[iNumNearest++] = { i, std::fabs ( dRawEstimate[i] - fEstimate ) }; sphSort ( dNearest, iNumNearest, ::bind ( &std::pair<int, double>::second ) ); double fAvg = 0; for ( int i = 0; i < NUM_NEIGHBOURS; i++ ) fAvg += dBias[dNearest[i].first]; return fAvg/NUM_NEIGHBOURS; } double CalcEstimate() const { double fE = 0.0; for ( int i = 0; i < m_iM; i++ ) fE += FastInversePow2 ( m_tStorage.Get(i) ); fE = GetAlpha()*m_iM*m_iM/fE; if ( fE <= 5.0*m_iM ) fE = std::max ( fE - EstimateBias(fE), 0.0 ); return fE; } }; // Sparse HyperLogLog implementation. Unused for now. #if 0 template<int SORTED_ARRAY_SIZE, int UNSORTED_ARRAY_SIZE, typename T=uint64_t, typename HASH=FarmHash_T<T>> class HyperLogLogSparse_T { public: HyperLogLogSparse_T ( int iAccuracy=14 ) : m_pCurSorted ( &m_dSorted1 ) , m_iP ( iAccuracy ) , m_iM ( 1 << m_iP ) , m_uHashMask ( ( 1ULL << ( 64-m_iP ) ) - 1 ) , m_uCountMask ( ( 1UL << 6 ) - 1 ) , m_uRegMask ( ~m_uCountMask ) { m_dSorted1.Reserve ( SORTED_ARRAY_SIZE/4 ); m_dSorted2.Reserve ( SORTED_ARRAY_SIZE/4 ); } FORCE_INLINE void Add ( const T & tValue ) { if ( !tValue ) return; uint64_t uHash = HASH::Hash(tValue); uint32_t uRegister = uHash >> ( 64 - m_iP ); uint8_t uCount = ( uHash ? GetLeadingZeroBits ( uHash & m_uMask ) : sizeof(uint64_t)*8 ) - m_iP + 1; m_dUnsorted.Add ( ( uRegister << 6 ) + uCount ); if ( m_dUnsorted.GetLength()==UNSORTED_ARRAY_SIZE ) MergeUnsorted(); } FORCE_INLINE void Clear() { m_pCurSorted = &m_dSorted1; m_dSorted1.Resize(0); m_dSorted2.Resize(0); m_dUnsorted.Resize(0); } FORCE_INLINE bool IsFull() const { return m_pCurSorted && ( m_pCurSorted->GetLength() + m_dUnsorted.GetLength() )>=SORTED_ARRAY_SIZE; } uint64_t Estimate() { assert ( m_pCurSorted ); MergeUnsorted(); return LinearCounting ( m_iM - m_pCurSorted->GetLength(), m_iM ); } template<typename STORAGE=RegistersNonPacked_c> void CopyToDense ( HyperLogLogDense_T<T,HASH, STORAGE> & tDense ) { assert ( m_iP > tDense.m_iP ); MergeUnsorted(); int iPDiff = m_iP - tDense.m_iP; int iBitsToNewReg = 6 + iPDiff; int iRegDiff = 32 - iBitsToNewReg; uint32_t uNewCountMask = ( 1ULL << iBitsToNewReg ) - 1; uint32_t uPDiffMask = uNewCountMask & ~m_uCountMask; assert ( m_pCurSorted ); for ( auto i : *m_pCurSorted ) { int iNewRegister = i >> ( 6 + iPDiff ); uint8_t uNewCount; uint32_t uPDiff = i & uPDiffMask; if ( uPDiff ) uNewCount = GetLeadingZeroBits ( uPDiff ) - iRegDiff + 1; else uNewCount = ( i & m_uCountMask ) + iPDiff; tDense.m_tStorage.Update ( iNewRegister, uNewCount ); } } private: using SortedArray_c = CSphTightVector<uint32_t>; using UnsortedArray_c = LazyVector_T<uint32_t, sph::DefaultRelimit, UNSORTED_ARRAY_SIZE>; SortedArray_c m_dSorted1; SortedArray_c m_dSorted2; UnsortedArray_c m_dUnsorted; SortedArray_c * m_pCurSorted = nullptr; int m_iP = 0; int m_iM = 0; uint64_t m_uHashMask = 0; uint32_t m_uCountMask = 0; uint32_t m_uRegMask = 0; FORCE_INLINE void MergeRegisters ( uint32_t * & pRes, uint32_t * & pPtr ) { uint32_t & uLastAdded = *(pRes-1); uint32_t uRegister1 = uLastAdded & m_uRegMask; uint32_t uRegister2 = (*pPtr) & m_uRegMask; if ( uRegister1==uRegister2 ) { uint8_t uMaxCount = Max ( uLastAdded & m_uCountMask, (*pPtr) & m_uCountMask ); uLastAdded = uRegister1 | uMaxCount; pPtr++; } else *pRes++ = *pPtr++; } void MergeUnsorted() { if ( m_dUnsorted.IsEmpty() ) return; m_dUnsorted.Sort(); assert ( m_pCurSorted ); SortedArray_c & tRes = m_pCurSorted==&m_dSorted1 ? m_dSorted2 : m_dSorted1; tRes.Resize ( m_pCurSorted->GetLength() + m_dUnsorted.GetLength() ); uint32_t * pA = m_pCurSorted->Begin(); uint32_t * pMaxA = m_pCurSorted->end(); // end() accounts for empty array; End() does not uint32_t * pB = m_dUnsorted.Begin(); uint32_t * pMaxB = m_dUnsorted.end(); uint32_t * pRes = tRes.Begin(); // add at least one value (for the next loop to work) if ( pA < pMaxA && pB < pMaxB ) { if ( *pA < *pB ) *pRes++ = *pA++; else *pRes++ = *pB++; } while ( pA < pMaxA && pB < pMaxB ) { if ( *pA < *pB ) MergeRegisters ( pRes, pA ); else MergeRegisters ( pRes, pB ); } // we can have a duplicate here, but only the first one if ( pRes!=tRes.Begin() && pA < pMaxA ) MergeRegisters ( pRes, pA ); while ( pA < pMaxA ) *pRes++ = *pA++; // add at least one value (for the next loop to work) if ( pRes==tRes.Begin() && pB < pMaxB ) *pRes++ = *pB++; while ( pB < pMaxB ) MergeRegisters ( pRes, pB ); tRes.Resize ( pRes-tRes.Begin() ); m_dUnsorted.Resize(0); m_pCurSorted = &tRes; } }; #endif #endif
10,941
C++
.h
357
27.837535
132
0.65985
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,088
attribute.h
manticoresoftware_manticoresearch/src/attribute.h
// // Copyright (c) 2017-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/ // #ifndef _attribute_ #define _attribute_ #include "sphinxdefs.h" #include "sphinxexpr.h" class CSphMatch; class ISphSchema; class CSphSchema; struct CSphAttrLocator; ////////////////////////////////////////////////////////////////////////// // blob attributes struct ThrottleState_t; class DebugCheckReader_i; class BlobRowBuilder_i { public: virtual ~BlobRowBuilder_i() {} virtual bool SetAttr ( int iAttr, const BYTE * pData, int iDataLen, CSphString & sError ) = 0; virtual std::pair<SphOffset_t,SphOffset_t> Flush() = 0; virtual std::pair<SphOffset_t,SphOffset_t> Flush ( const BYTE * pOldRow ) = 0; virtual bool Done ( CSphString & sError ) = 0; }; struct TypedAttribute_t { CSphString m_sName; ESphAttr m_eType; }; // create file-based blob row builder std::unique_ptr<BlobRowBuilder_i> sphCreateBlobRowBuilder ( const ISphSchema & tSchema, const CSphString & sFile, SphOffset_t tSpaceForUpdates, int iBufferSize, CSphString & sError ); // create file-based blob row builder with JSON already packed std::unique_ptr<BlobRowBuilder_i> sphCreateBlobRowJsonBuilder ( const ISphSchema & tSchema, const CSphString & sFile, SphOffset_t tSpaceForUpdates, int iBufferSize, CSphString & sError ); // create mem-based blob row builder std::unique_ptr<BlobRowBuilder_i> sphCreateBlobRowBuilder ( const ISphSchema & tSchema, CSphTightVector<BYTE> & dPool ); // create mem-based blob row builder for updates std::unique_ptr<BlobRowBuilder_i> sphCreateBlobRowBuilderUpdate ( const ISphSchema & tSchema, const CSphVector<TypedAttribute_t> & dAttrs, CSphTightVector<BYTE> & dPool, const CSphBitvec & dAttrsUpdated ); // fetches a attribute data and its length from the pool const BYTE * sphGetBlobAttr ( const CSphMatch & tMatch, const CSphAttrLocator & tLocator, const BYTE * pBlobPool, int & iLengthBytes ); ByteBlob_t sphGetBlobAttr ( const CSphMatch & tMatch, const CSphAttrLocator & tLocator, const BYTE * pBlobPool ); // fetch attribute data from a given blob row ByteBlob_t sphGetBlobAttr ( const BYTE * pBlobRow, const CSphAttrLocator & tLocator ); // same as above, but works with docinfo const BYTE * sphGetBlobAttr ( const CSphRowitem * pDocinfo, const CSphAttrLocator & tLocator, const BYTE * pBlobPool, int & iLengthBytes ); ByteBlob_t sphGetBlobAttr ( const CSphRowitem * pDocinfo, const CSphAttrLocator & tLocator, const BYTE * pBlobPool ); // returns blob attribute length int sphGetBlobAttrLen ( const CSphMatch & tMatch, const CSphAttrLocator & tLocator, const BYTE * pBlobPool ); // return the total length (in bytes) of a given blob row DWORD sphGetBlobTotalLen ( const BYTE * pBlobRow, int nBlobAttrs ); // copy whole blob row, return offset in new pool int64_t sphCopyBlobRow ( CSphTightVector<BYTE> & dDstPool, const CSphTightVector<BYTE> & dSrcPool, int64_t iOffset, int nBlobs ); // add a new blob attr to a row (on ALTER) void sphAddAttrToBlobRow ( const CSphRowitem * pDocinfo, CSphTightVector<BYTE> & dBlobRow, const BYTE * pPool, int nBlobs, const CSphAttrLocator * pOldBlobRowLoc ); // remove a blob attr from a blob row (on ALTER) void sphRemoveAttrFromBlobRow ( const CSphRowitem * pDocinfo, CSphTightVector<BYTE> & dBlobRow, const BYTE * pPool, int nBlobs, int iBlobAttrId, const CSphAttrLocator & tBlobRowLoc ); // verify blob row record bool sphCheckBlobRow ( int64_t iOff, DebugCheckReader_i & tBlobs, const CSphSchema & tSchema, CSphString & sError ); // return blob locator attribute name const char * sphGetBlobLocatorName(); // return null mask attribute name const char * GetNullMaskAttrName(); // current docid attribute name const char * sphGetDocidName(); const CSphString & sphGetDocidStr(); // returns true if this is a blob attr type bool sphIsBlobAttr ( ESphAttr eAttr ); // returns true if this is a blob attr type; returns false for columnar attrs bool sphIsBlobAttr ( const CSphColumnInfo & tAttr ); bool IsMvaAttr ( ESphAttr eAttr ); ////////////////////////////////////////////////////////////////////////// // data ptr attributes // pack byteblob (length+data), return allocated storage BYTE * sphPackPtrAttr ( ByteBlob_t dBlob ); // pack byteblob attr to preallocated storage, return size of placed packet int sphPackPtrAttr ( BYTE * pPrealloc, ByteBlob_t dBlob ); // pack byteblob attr in-place (add place for size and write packed length before the blob) void sphPackPtrAttrInPlace ( TightPackedVec_T<BYTE>& dAttr, int iSize=-1 ); // allocate buffer, store zipped length, set pointer to free space in buffer BYTE * sphPackPtrAttr ( int iLengthBytes, BYTE ** pData ); // unpack data pointer attr, return length ByteBlob_t sphUnpackPtrAttr ( const BYTE * pData ); // calculate packed data attr length int sphCalcPackedLength ( int iLengthBytes ); BYTE * sphPackedBlob ( ByteBlob_t dBlob ); // convert plain attr type to corresponding in-memort (_PTR) attr type ESphAttr sphPlainAttrToPtrAttr ( ESphAttr eAttrType ); // is this a data ptr attribute? bool sphIsDataPtrAttr ( ESphAttr eAttrType ); namespace sph { // just repack (matter of optimizing) BYTE * CopyPackedAttr ( const BYTE * pData ); } ////////////////////////////////////////////////////////////////////////// // misc attribute-related bool sphIsInternalAttr ( const CSphString & sAttrName ); bool sphIsInternalAttr ( const CSphColumnInfo & tCol ); void sphMVA2Str ( ByteBlob_t dMVA, bool b64bit, StringBuilder_c & dStr ); void sphPackedMVA2Str ( const BYTE * pMVA, bool b64bit, StringBuilder_c & dStr ); void sphFloatVec2Str ( ByteBlob_t dFloatVec, StringBuilder_c & dStr ); void sphPackedFloatVec2Str ( const BYTE * pData, StringBuilder_c & dStr ); /// check if tColumn is actually stored field (so, can't be used in filters/expressions) bool IsNotRealAttribute ( const CSphColumnInfo & tColumn ); inline DocID_t sphGetDocID ( const CSphRowitem * pData ) { assert ( pData ); return sphUnalignedRead ( *(DocID_t*)(const_cast<CSphRowitem *>(pData)) ); } const char * AttrType2Str ( ESphAttr eAttrType ); #endif
6,428
C++
.h
115
54.365217
205
0.741657
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,089
exprdocstore.h
manticoresoftware_manticoresearch/src/exprdocstore.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 "sphinxexpr.h" ISphExpr * CreateExpr_GetStoredField ( const CSphString & sName ); ISphExpr * CreateExpr_GetStoredAttr ( const CSphString & sName, ESphAttr eAttr );
665
C++
.h
15
43.133333
81
0.760433
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,090
netreceive_http.h
manticoresoftware_manticoresearch/src/netreceive_http.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 "networking_daemon.h" void HttpServe ( std::unique_ptr<AsyncNetBuffer_c> pBuf );
582
C++
.h
14
40.357143
80
0.753982
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,091
sphinxexpr.h
manticoresoftware_manticoresearch/src/sphinxexpr.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 _sphinxexpr_ #define _sphinxexpr_ #include "collation.h" #include "std/refcounted_mt.h" #include "std/string.h" #include "std/sharedptr.h" /// forward decls class CSphMatch; class ISphSchema; class CSphSchema; struct CSphString; struct CSphColumnInfo; /// known attribute types enum ESphAttr { // these types are full types // their typecodes are saved in the index schema, and thus, // TYPECODES MUST NOT CHANGE ONCE INTRODUCED SPH_ATTR_NONE = 0, ///< not an attribute at all SPH_ATTR_INTEGER = 1, ///< unsigned 32-bit integer SPH_ATTR_TIMESTAMP = 2, ///< this attr is a timestamp // there was SPH_ATTR_ORDINAL=3 once SPH_ATTR_BOOL = 4, ///< this attr is a boolean bit field SPH_ATTR_FLOAT = 5, ///< floating point number (IEEE 32-bit) SPH_ATTR_BIGINT = 6, ///< signed 64-bit integer SPH_ATTR_STRING = 7, ///< string (binary; in-memory) // there was SPH_ATTR_WORDCOUNT=8 once SPH_ATTR_POLY2D = 9, ///< vector of floats, 2D polygon (see POLY2D) SPH_ATTR_STRINGPTR = 10, ///< string (binary, in-memory, stored as pointer to the zero-terminated string) SPH_ATTR_TOKENCOUNT = 11, ///< field token count, 32-bit integer SPH_ATTR_JSON = 12, ///< JSON subset; converted, packed, and stored as string SPH_ATTR_DOUBLE = 13, ///< floating point number (IEEE 64-bit) SPH_ATTR_UINT64 = 14, ///< unsigned 64-bit integer SPH_ATTR_FLOAT_VECTOR = 15, SPH_ATTR_UINT32SET = 0x40000001UL, ///< MVA, set of unsigned 32-bit integers SPH_ATTR_INT64SET = 0x40000002UL, ///< MVA, set of signed 64-bit integers // these types are runtime only // used as intermediate types in the expression engine SPH_ATTR_MAPARG = 1000, SPH_ATTR_FACTORS = 1001, ///< packed search factors (binary, in-memory, pooled) SPH_ATTR_JSON_FIELD = 1002, ///< points to particular field in JSON column subset SPH_ATTR_FACTORS_JSON = 1003, ///< packed search factors (binary, in-memory, pooled, provided to client json encoded) SPH_ATTR_UINT32SET_PTR, // in-memory version of MVA32 SPH_ATTR_INT64SET_PTR, // in-memory version of MVA64 SPH_ATTR_JSON_PTR, // in-memory version of JSON SPH_ATTR_JSON_FIELD_PTR, // in-memory version of JSON_FIELD SPH_ATTR_STORED_FIELD, SPH_ATTR_FLOAT_VECTOR_PTR // in-memory version of FLOAT_VECTOR }; /// column evaluation stage enum ESphEvalStage { SPH_EVAL_STATIC = 0, ///< static data, no real evaluation needed SPH_EVAL_PREFILTER, ///< expression needed for candidate matches filtering SPH_EVAL_PRESORT, ///< expression needed for final matches sorting SPH_EVAL_SORTER, ///< expression evaluated by sorter object SPH_EVAL_FINAL, ///< expression not (!) used in filters/sorting; can be postponed until final result set cooking SPH_EVAL_POSTLIMIT ///< expression needs to be postponed until we apply all the LIMIT clauses (say, too expensive) }; /// expression tree wide commands /// FIXME? maybe merge with ExtraData_e? enum ESphExprCommand { SPH_EXPR_SET_BLOB_POOL, SPH_EXPR_SET_DOCSTORE_ROWID, ///< interface to fetch docs by rowid (final stage) SPH_EXPR_SET_DOCSTORE_DOCID, ///< interface to fetch docs by docid (postlimit stage) SPH_EXPR_SET_QUERY, SPH_EXPR_SET_EXTRA_DATA, SPH_EXPR_GET_DEPENDENT_COLS, ///< used to determine proper evaluating stage SPH_EXPR_GET_GEODIST_SETTINGS, SPH_EXPR_GET_POLY2D_BBOX, SPH_EXPR_GET_UDF, SPH_EXPR_GET_STATEFUL_UDF, SPH_EXPR_SET_COLUMNAR, SPH_EXPR_SET_COLUMNAR_COL, SPH_EXPR_GET_COLUMNAR_COL, SPH_EXPR_SET_ITERATOR, ///< set link between JsonIn expr and iterator SPH_EXPR_FORMAT_AS_TEXT, SPH_EXPR_COLLECT_CONST_ARGS }; class CSphFilterSettings; class SIContainer_c; /// expression evaluator /// can always be evaluated in floats using Eval() /// can sometimes be evaluated in integers using IntEval(), depending on type as returned from sphExprParse() class ISphExpr : public ISphRefcountedMT { public: /// evaluate this expression for that match virtual float Eval ( const CSphMatch & tMatch ) const = 0; /// evaluate this expression for that match, using int math virtual int IntEval ( const CSphMatch & tMatch ) const { assert ( 0 ); return (int) Eval ( tMatch ); } /// evaluate this expression for that match, using int64 math virtual int64_t Int64Eval ( const CSphMatch & tMatch ) const { assert ( 0 ); return (int64_t) Eval ( tMatch ); } /// Evaluate string attr. /// Note, that sometimes this method returns pointer to a static buffer /// and sometimes it allocates a new buffer, so aware of memory leaks. /// IsDataPtrAttr() returns true if this method allocates a new buffer and false otherwise. virtual int StringEval ( const CSphMatch &, const BYTE ** ppStr ) const { *ppStr = NULL; return 0; } /// Evaluate string as a packed data ptr attr. By default it re-packs StringEval result, but can be overridden virtual const BYTE * StringEvalPacked ( const CSphMatch & tMatch ) const; /// return string len without calculating/fetching the string (if supported) virtual int StringLenEval ( const CSphMatch & tMatch ) const { return -1; } /// evaluate MVA attr virtual ByteBlob_t MvaEval ( const CSphMatch & ) const { assert( 0 ); return {nullptr, 0}; } /// evaluate PACKEDFACTORS virtual const BYTE * FactorEval ( const CSphMatch & ) const { assert ( 0 ); return nullptr; } /// evaluate PACKEDFACTORS as a packed data ptr attr virtual const BYTE * FactorEvalPacked ( const CSphMatch & ) const { assert ( 0 ); return nullptr; } /// check for arglist subtype /// FIXME? replace with a single GetType() call? virtual bool IsArglist () const { return false; } /// was this expression spawned in place of a columnar attr? virtual bool IsColumnar ( bool * pStored = nullptr ) const { return false; } /// was this expression spawned in place of a columnar expression? virtual bool IsStored() const { return false; } /// does this expression use docstore (at any eval stage)? virtual bool UsesDocstore() const { return false; } /// check for stringptr subtype virtual bool IsDataPtrAttr () const { return false; } /// get Nth arg of an arglist virtual ISphExpr * GetArg ( int ) const { return NULL; } /// get the number of args in an arglist virtual int GetNumArgs() const { return 0; } /// change the expressions's locator when changing schemas virtual void FixupLocator ( const ISphSchema * pOldSchema, const ISphSchema * pNewSchema ) = 0; /// run a tree wide action (1st arg is an action, 2nd is its parameter) /// usually sets something into ISphExpr like string pool or gets something from it like dependent columns virtual void Command ( ESphExprCommand, void * ) {} /// check for const type virtual bool IsConst () const { return false; } virtual bool IsJson ( bool & bConverted ) const { return false; } /// setup a filter that works as this expression (if possible) virtual bool SetupAsFilter ( CSphFilterSettings & tFilter, const ISphSchema & tSchema, const SIContainer_c & tSI ) const { return false; } /// get expression hash (for query cache) virtual uint64_t GetHash ( const ISphSchema & tSorterSchema, uint64_t uPrevHash, bool & bDisable ) = 0; /// make undependent clone of self virtual ISphExpr* Clone() const = 0; protected: ~ISphExpr() override {} }; using ISphExprRefPtr_c = CSphRefcountedPtr<ISphExpr>; inline ISphExpr* SafeClone ( ISphExpr * pRhs ) { if ( pRhs ) return pRhs->Clone(); return nullptr; } inline void FreeDataPtr ( const ISphExpr & tExpr, const void * pData ) { if ( tExpr.IsDataPtrAttr () && pData ) delete[] ( (const BYTE *) pData ); } inline void FreeDataPtr ( const ISphExpr * pExpr, const void * pData ) { if ( pExpr ) FreeDataPtr ( *pExpr, pData ); } /// named int/string variant /// used for named expression function arguments block /// ie. {..} part in, for example, BM25F(1.2, 0.8, {title=3}) call enum class VariantType_e { EMPTY, IDENT, STRING, BIGINT, FLOAT }; struct CSphNamedVariant { CSphString m_sKey; ///< key CSphString m_sValue; ///< value for strings, empty for ints int64_t m_iValue; ///< value for ints float m_fValue; VariantType_e m_eType = VariantType_e::EMPTY; }; /// string expression traits struct ISphStringExpr : public ISphExpr { float Eval ( const CSphMatch & tMatch ) const final; int IntEval ( const CSphMatch & tMatch ) const final; int64_t Int64Eval ( const CSphMatch & tMatch ) const final; }; /// hook to extend expressions /// lets one to add her own identifier and function handlers struct ISphExprHook { virtual ~ISphExprHook () {} /// checks for an identifier known to the hook /// returns -1 on failure, a non-negative OID on success virtual int IsKnownIdent ( const char * sIdent ) const = 0; /// checks for a valid function call /// returns -1 on failure, a non-negative OID on success (possibly adjusted) virtual int IsKnownFunc ( const char * sFunc ) const = 0; /// create node by OID /// pEvalStage is an optional out-parameter /// hook may fill it, but that is *not* required virtual ISphExpr * CreateNode ( int iID, ISphExpr * pLeft, const ISphSchema * pRsetSchema, ESphEvalStage * pEvalStage, bool * pNeedDocIds, CSphString & sError ) = 0; /// get identifier return type by OID virtual ESphAttr GetIdentType ( int iID ) const = 0; /// get function return type by OID and argument types vector /// must return SPH_ATTR_NONE and fill the message on failure virtual ESphAttr GetReturnType ( int iID, const CSphVector<ESphAttr> & dArgs, bool bAllConst, CSphString & sError ) const = 0; /// recursive scope check virtual void CheckEnter ( int iID ) = 0; /// recursive scope check virtual void CheckExit ( int iID ) = 0; }; // an expression that has no locator class Expr_NoLocator_c : public ISphExpr { public: void FixupLocator ( const ISphSchema * /*pOldSchema*/, const ISphSchema * /*pNewSchema*/ ) override {} }; /// a container used to pass maps of constants/variables around the evaluation tree class Expr_MapArg_c : public Expr_NoLocator_c { public: SharedPtrArr_t<CSphNamedVariant> m_pValues; int64_t m_iCount = 0; // c-tr from raw vector - adopt values explicit Expr_MapArg_c ( CSphVector<CSphNamedVariant> & dValues ) { m_iCount = dValues.GetLength(); m_pValues = dValues.LeakData (); } float Eval ( const CSphMatch & ) const final { assert ( 0 && "one just does not simply evaluate a const hash" ); return 0.0f; } uint64_t GetHash ( const ISphSchema &, uint64_t, bool & ) final { assert ( 0 && "calling GetHash from a const hash" ); return 0; } ISphExpr * Clone () const final { return new Expr_MapArg_c ( *this ); } private: Expr_MapArg_c ( const Expr_MapArg_c& rhs ) : m_pValues ( rhs.m_pValues ) , m_iCount ( rhs.m_iCount ) {} }; enum { SPH_FACTOR_DISABLE = 0, SPH_FACTOR_ENABLE = 1, SPH_FACTOR_CALC_ATC = 1 << 1, SPH_FACTOR_JSON_OUT = 1 << 2 }; /// parses given expression, builds evaluator /// returns NULL and fills sError on failure /// returns pointer to evaluator on success /// fills pAttrType with result type (for now, can be SPH_ATTR_SINT or SPH_ATTR_FLOAT) /// fills pUsesWeight with a flag whether match relevance is referenced in expression AST /// fills pEvalStage with a required (!) evaluation stage class QueryProfile_c; struct ExprParseArgs_t { ESphAttr * m_pAttrType = nullptr; bool * m_pUsesWeight = nullptr; QueryProfile_c * m_pProfiler = nullptr; ESphCollation m_eCollation = SPH_COLLATION_DEFAULT; ISphExprHook * m_pHook = nullptr; bool * m_pZonespanlist = nullptr; DWORD * m_pPackedFactorsFlags = nullptr; ESphEvalStage * m_pEvalStage = nullptr; DWORD * m_pStoredField = nullptr; bool * m_pNeedDocIds = nullptr; }; struct JoinArgs_t { const ISphSchema & m_tJoinedSchema; CSphString m_sIndex1; CSphString m_sIndex2; JoinArgs_t ( const ISphSchema & tJoinedSchema, const CSphString & sIndex1, const CSphString & sIndex2 ); }; struct CommonFilterSettings_t; ISphExpr * sphExprParse ( const char * szExpr, const ISphSchema & tSchema, const CSphString * pJoinIdx, CSphString & sError, ExprParseArgs_t & tArgs ); ISphExpr * sphJsonFieldConv ( ISphExpr * pExpr ); ISphExpr * ExprJsonIn ( const VecTraits_T<CSphString> & dVals, ISphExpr * pArg, ESphCollation eCollation ); ISphExpr * ExprJsonIn ( const VecTraits_T<int64_t> & dVals, ISphExpr * pArg, ESphCollation eCollation ); ISphExpr * ExprJsonRange ( const CommonFilterSettings_t & tFilter, ISphExpr * pArg ); void FetchAttrDependencies ( StrVec_t & dAttrNames, const ISphSchema & tSchema ); bool CanAliasedExprSetupAsFilter ( const CSphFilterSettings & tFilter, bool & bExclude ); void SetExprNodeStackItemSize ( int iCreateSize, int iEvalSize ); /// provide mysql version string namespace sphinxexpr { CSphString& MySQLVersion(); } #endif // _sphinxexpr_
13,224
C++
.h
306
41.313725
166
0.73517
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,092
collation.h
manticoresoftware_manticoresearch/src/collation.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 _collation_ #define _collation_ #include "std/fnv64.h" #include <locale> class LibcCSHash_fn { public: static uint64_t Hash ( const BYTE * pStr, int iLen, uint64_t uPrev=SPH_FNV64_SEED ); }; class LibcCIHash_fn { public: static uint64_t Hash ( const BYTE * pStr, int iLen, uint64_t uPrev=SPH_FNV64_SEED ); }; class Utf8CIHash_fn { public: static uint64_t Hash ( const BYTE * pStr, int iLen, uint64_t uPrev=SPH_FNV64_SEED ); }; class BinaryHash_fn { public: static uint64_t Hash ( const BYTE * pStr, int iLen, uint64_t uPrev=SPH_FNV64_SEED ); }; /// known collations enum ESphCollation { SPH_COLLATION_LIBC_CI, SPH_COLLATION_LIBC_CS, SPH_COLLATION_UTF8_GENERAL_CI, SPH_COLLATION_BINARY, SPH_COLLATION_DEFAULT = SPH_COLLATION_LIBC_CI }; // iLen1 and iLen2 don't need to be specified for STRINGPTR attrs using SphStringCmp_fn = int (*) ( ByteBlob_t dStr1, ByteBlob_t dStr2, bool bDataPtr ); using StrHashCalc_fn = uint64_t (*) ( const BYTE * pStr, int iLen, uint64_t uPrev ); SphStringCmp_fn GetStringCmpFunc ( ESphCollation eCollation ); StrHashCalc_fn GetStringHashCalcFunc ( ESphCollation eCollation ); void sphCollationInit(); volatile ESphCollation& GlobalCollation(); ESphCollation sphCollationFromName ( const CSphString & sName, CSphString * pError ); void SetLocale ( const CSphString & sLocale, bool bSet ); const std::locale & GlobalLocale(); bool IsGlobalLocaleSet(); #endif // _collation_
1,908
C++
.h
56
32.625
86
0.762527
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,093
aggregate.h
manticoresoftware_manticoresearch/src/aggregate.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 _aggregate_ #define _aggregate_ #include "match.h" #include "columnarlib.h" class AggrFunc_i { public: virtual ~AggrFunc_i() {} virtual void Ungroup ( CSphMatch & tDst ) {} virtual void Update ( CSphMatch & tDst, const CSphMatch & tSrc, bool bGrouped, bool bMerge ) = 0; virtual void Setup ( CSphMatch & tDst, const CSphMatch & tSrc, bool bMerge ) {} virtual void Finalize ( CSphMatch & tDst ) {} virtual void SetColumnar ( columnar::Columnar_i * pColumnar ) {} }; AggrFunc_i * CreateAggrSum ( const CSphColumnInfo & tAttr ); AggrFunc_i * CreateAggrAvg ( const CSphColumnInfo & tAttr, const CSphAttrLocator & tCount ); AggrFunc_i * CreateAggrMin ( const CSphColumnInfo & tAttr ); AggrFunc_i * CreateAggrMax ( const CSphColumnInfo & tAttr ); AggrFunc_i * CreateAggrConcat ( const CSphColumnInfo & tAttr ); #endif // _aggregate_
1,327
C++
.h
31
41.354839
98
0.743789
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,094
timeout_queue.h
manticoresoftware_manticoresearch/src/timeout_queue.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 "std/ints.h" #include "std/vector.h" #include "std/string.h" #include <functional> /// member type for priority queue used for timeout task managing struct EnqueuedTimeout_t { int64_t m_iTimeoutTimeUS = -1; // active timeout (used for bin heap morph in comparing) mutable int m_iTimeoutIdx = -1; // idx inside timeouts bin heap (or -1 if not there), internal }; /// priority queue for timeouts - as CSphQueue, /// but specific (can resize, stores internal index in an object) class TimeoutQueue_c final { CSphTightVector<EnqueuedTimeout_t*> m_dQueue; void ShiftUp ( int iHole ); void ShiftDown ( int iHole ); void Push ( EnqueuedTimeout_t* pTask ); public: /// remove root (ie. top priority) entry void Pop(); /// add new, or change already added entry void Change ( EnqueuedTimeout_t* pTask ); /// erase elem (uses stored m_iTimeoutIdx) void Remove ( EnqueuedTimeout_t* pTask ); inline bool IsEmpty() const { return m_dQueue.IsEmpty(); } /// get minimal (root) elem EnqueuedTimeout_t* Root() const; CSphString DebugDump ( const char* sPrefix ) const; void DebugDump ( const std::function<void ( EnqueuedTimeout_t* )>& fcb ) const; };
1,666
C++
.h
46
34.5
95
0.741294
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,095
aggrexpr.h
manticoresoftware_manticoresearch/src/aggrexpr.h
// // Copyright (c) 2017-2023, 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 _aggsexpr_ #define _aggsexpr_ #include "sphinxdefs.h" #include "sphinxexpr.h" #include <variant> using AggrBound_t = std::variant<int64_t, float>; struct RangeSetting_t { int m_iIdx = 0; union { int64_t m_iFrom = LLONG_MIN; ///< range from float m_fFrom; }; union { int64_t m_iTo = LLONG_MAX; ///< range to float m_fTo; }; }; struct AggrRangeSetting_t : public CSphVector<RangeSetting_t> { bool m_bFloat = false; bool m_bOpenLeft = false; bool m_bOpenRight = false; bool m_bKeyed = false; }; struct AggrHistSetting_t { AggrBound_t m_tInterval; AggrBound_t m_tOffset; bool m_bFloat = false; bool m_bKeyed = false; }; enum class Aggr_e { NONE, SIGNIFICANT, HISTOGRAM, DATE_HISTOGRAM, RANGE, DATE_RANGE, COMPOSITE, COUNT, MIN, MAX, SUM, AVG }; struct DateRangeSetting_t { int m_iIdx = 0; CSphString m_sFrom; CSphString m_sTo; }; struct AggrDateRangeSetting_t : public CSphVector<DateRangeSetting_t> { bool m_bKeyed = false; }; struct AggrDateHistSetting_t { CSphString m_sInterval; bool m_bKeyed = false; }; struct AggrSettings_t { Aggr_e m_eAggrFunc { Aggr_e::NONE }; AggrRangeSetting_t m_tRange; AggrHistSetting_t m_tHist; AggrDateRangeSetting_t m_tDateRange; AggrDateHistSetting_t m_tDateHist; }; ISphExpr * CreateExprRange ( ISphExpr * pAttr, const AggrRangeSetting_t & tRanges ); bool ParseAggrRange ( const VecTraits_T< VecTraits_T < CSphNamedVariant > > & dRanges, bool bDate, int iNow, AggrRangeSetting_t & tRanges, CSphString & sError ); CSphString GetAggrName ( int iItem, const CSphString & sCol ); struct RangeKeyDesc_t { CSphString m_sKey; CSphString m_sFrom; CSphString m_sTo; }; using RangeNameHash_t = CSphOrderedHash<RangeKeyDesc_t, int, IdentityHash_fn, 256>; void GetRangeKeyNames ( const AggrRangeSetting_t & tRanges, RangeNameHash_t & hRangeNames ); void GetRangeKeyNames ( const AggrDateRangeSetting_t & tRanges, int iNow, RangeNameHash_t & hRangeNames ); void FormatDate ( time_t tDate, CSphString & sRes ); void FormatDate ( time_t tDate, StringBuilder_c & sRes ); ISphExpr * CreateExprHistogram ( ISphExpr * pAttr, const AggrHistSetting_t & tHist ); bool ParseAggrHistogram ( const VecTraits_T < CSphNamedVariant > & dVariants, AggrHistSetting_t & tHist, CSphString & sError ); ISphExpr * CreateExprDateHistogram ( ISphExpr * pAttr, const AggrDateHistSetting_t & tHist ); bool ParseAggrDateHistogram ( const VecTraits_T < CSphNamedVariant > & dVariants, AggrDateHistSetting_t & tHist, CSphString & sError ); CSphString DumpAggr ( const CSphString & sCol, const AggrSettings_t & tAggr ); void FixFloat ( AggrHistSetting_t & tHist ); #endif // _aggsexpr_
3,141
C++
.h
104
28.5
161
0.759376
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,096
taskpreread.h
manticoresoftware_manticoresearch/src/taskpreread.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 MANTICORE_TASKPREREAD_H #define MANTICORE_TASKPREREAD_H #include "sphinxstd.h" void PrereadIndexes (bool bForce); bool WaitPrereadFinished ( int64_t uSec ); #endif //MANTICORE_TASKPREREAD_H
677
C++
.h
17
38.647059
80
0.770167
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,097
taskmalloctrim.h
manticoresoftware_manticoresearch/src/taskmalloctrim.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 "sphinxutils.h" constexpr int64_t DEFAULT_MALLOC_TRIM_PERIOD = 30*60*1000000ll; void ScheduleMallocTrim (); int PerformMallocTrim ( size_t iPad );
649
C++
.h
16
39.3125
80
0.761526
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,098
sphinxutils.h
manticoresoftware_manticoresearch/src/sphinxutils.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/ // /// @file sphinxutils.h /// Declarations for the stuff shared by all Sphinx utilities. #ifndef _sphinxutils_ #define _sphinxutils_ #include <ctype.h> #include <stdarg.h> #include "sphinxstd.h" ////////////////////////////////////////////////////////////////////////// /// my own isalpha (let's build our own theme park!) inline int sphIsAlpha ( int c ) { return ( c>='0' && c<='9' ) || ( c>='a' && c<='z' ) || ( c>='A' && c<='Z' ) || c=='-' || c=='_'; } inline int sphIsAlphaOnly ( int c ) { return ( c>='0' && c<='9' ) || ( c>='a' && c<='z' ) || ( c>='A' && c<='Z' ); } inline bool sphIsInteger ( char c ) { return ( c>='0' && c<='9' ) || c=='+' || c=='-'; } /// symbols allowed in numbers (like 1.84E-20) inline bool sphIsDigital ( char c ) { return ( c>='0' && c<='9' ) || c=='.' || c=='E' || c=='e' || c=='+' || c=='-'; } /// pointer to the last number in the buf, touching it's end inline const char * sphFindLastNumeric ( const char * pBuf, int iLen ) { if ( !pBuf || !iLen ) return pBuf; for ( auto pLast = pBuf + iLen - 1; pLast>=pBuf; --pLast ) if ( !sphIsDigital ( *pLast ) ) return pLast + 1; return pBuf; } /// my own isspace inline bool sphIsSpace ( int iCode ) { return memchr ( " \t\n\r", iCode, 4 ) != nullptr; } /// check for keyword modifiers inline bool sphIsModifier ( int iSymbol ) { return iSymbol=='^' || iSymbol=='$' || iSymbol=='=' || iSymbol=='*'; } /// all wildcards template < typename T > inline bool sphIsWild ( T c ) { return c=='*' || c=='?' || c=='%'; } bool HasWildcards ( const char * sWord ); namespace sph { /* Custom format specifiers for types: 'int' values: %d - decimal int %F - fixed-point int (see notes below about fixed-points) %i - skip int. Prints nothing, just skips parameter. Useful for conditional format. 'DWORD' (uint32) values: %u - decimal uint32 %x - hex uint32 'int64_t' (signed) values: %l - decimal int64 %D - fixed-point int64 %t - timespan (see notes below) %T - timestamp from now 'uint64_t' (unsigned) values: %U - decimal uint64 z-terminated string: %s - print string, or "(null)" etc.: %p - print pointer (16 hex digits) %f - float (fall-back to standard sprintf) Fixed-point ints (both 32 and 64 bits) need precise param to set the decimal point at this place Example: ( "%.4F", 999005 ) will output '99.9005'. ( "%.3D", (int64_t) -10000 ) will output '-10.000' Timespan prints time expressed in useconds in human-readable format. It output number with suffix. Suffixes are 'us', 'ms', 's', 'm', 'h', 'd', 'w' (usecs, msecs, secs, mins, hours, days, weeks). Example: ("%t", 1555555) will print "2s" (2 seconds) ("%t", 3600000000*24*2) will print "2d" (2 days) Timespan may be supplied with precision param, and then it will print up to 7 numbers with suffixes. Example: ("%.2t", 1555555) will print "1.56s" ("%.5t", 1555555) will print "1s 555.56ms" ("%.8t", 71555555) will print "1m 11s 555ms 555us" Timespan also reasonable rounds the value when necessary and doesn't output redundant zeros. Example: ("%.7t", 89999994) will print "1m 29s 999.99ms" ("%.7t", 89999995) will print "1m 30s" Timestamp from now - just takes provided value, compares it with sphMicroTimer() output and print the timespan difference according to the rules: - if given value is in the past, print 'TM ago' (where TM is timespan of the difference) - if given value is in the future, print 'in TM'. - if given value is exactly now, print the word 'now'. */ int vSprintf ( char * pOutput, const char * sFmt, va_list ap ); int Sprintf ( char * pOutput, const char * sFmt, ... ); void vSprintf ( StringBuilder_c &pOutput, const char * sFmt, va_list ap ); void Sprintf ( StringBuilder_c& pOutput, const char * sFmt, ...); /// output fVal with arbitrary 6 or 8 digits /// ensure that sBuffer has enough space to fit fVal! int PrintVarFloat ( char* sBuffer, int iSize, float fVal ); int PrintVarDouble ( char* sBuffer, int iSize, double fVal ); } /// string splitter, extracts sequences of alphas (as in sphIsAlpha) void sphSplit ( StrVec_t & dOut, const char * sIn ); /// string splitter, splits by the given boundaries void sphSplit ( StrVec_t & dOut, const char * sIn, const char * sBounds ); void sphSplit ( StrVec_t & dOut, const char * sIn, int iLen, const char * sBounds ); StrVec_t sphSplit ( const char * sIn, const char * sBounds ); StrVec_t sphSplit ( const char * sIn, int iLen, const char * sBounds ); /// perform sphSplit by whitespaces, but applies a functor instead of add a chunk to the vector using StrFunctor = std::function<void ( const char*, int )>; void sphSplitApply ( const char * sIn, int iSize, StrFunctor &&dFunc ); void sphSplitApply ( const char * sIn, int iSize, const char * sBounds, StrFunctor && dFunc ); /// string wildcard matching (case-sensitive, supports * and ? patterns) bool sphWildcardMatch ( const char * sSstring, const char * sPattern, const int * pPattern = NULL ); bool HasWildcard ( const char * sVal ); /// parse size from text (int, or K/M/G/T suffix), or return provided default value. /// *ppErr, if provided, will point to parsing error, if any int64_t sphGetSize64 ( const char * sValue, char ** ppErr = nullptr, int64_t iDefault=-1 ); /// parse time from text (seconds, or us/ms/s/m/h/d/w suffix), or return provided default value. /// \return result in uSeconds, i.e. may be directly compared with sphMicroTimer(), etc. /// *ppErr, if provided, will point to parsing error, if any. By default scale is 's', seconds. int64_t sphGetTime64 ( const char* sValue, char** ppErr = nullptr, int64_t iDefault = -1 ); int64_t GetUTC ( const CSphString & sTime, const char * sFormat=nullptr ); bool ParseDateMath ( const CSphString & sMathExpr, int iNow, time_t & tDateTime ); enum class DateUnit_e { ms, sec, minute, hour, day, week, month, year, total_units }; void RoundDate ( DateUnit_e eUnit, time_t & tDateTime ); DateUnit_e ParseDateInterval ( const CSphString & sExpr, CSphString & sError ); ////////////////////////////////////////////////////////////////////////// namespace sph { template<typename FnFilter> void Split ( const char * sIn, int iLen, const char * sBounds, FnFilter fnFilter ) { if ( !sIn ) return; const char * p = sIn; if ( iLen<0 ) iLen = (int)strlen (sIn); const char * pEnd = p + iLen; while (p<pEnd) { // skip until the first non-boundary character const char * sNext = p; while (p<pEnd && !strchr ( sBounds, *p )) ++p; // add the token, skip the char fnFilter ( sNext, int(p-sNext) ); // skip all boundaries while (p<pEnd && strchr ( sBounds, *p )) ++p; } } // common parser for 'foo=1;bar=2;baz=str, me=here' constructions. SmallStringHash_T<CSphString> ParseKeyValueStrings ( const char * sBuf ); SmallStringHash_T<CSphVariant> ParseKeyValueVars ( const char * sBuf ); template<typename FnFilter> void ParseKeyValues ( const char * sBuf, FnFilter fnFilter, const char* szDelim = ",; \t\n\r" ) { if ( !sBuf || ( !*sBuf )) return; sph::Split ( sBuf, -1, szDelim, [&] (const char* sToken, int iLen) { auto dOption = sphSplit ( sToken, iLen, "=" ); assert ( dOption.GetLength ()==2 ); // as 'key' = 'value' dOption.Apply ( [] ( CSphString & sVal ) { sVal.Trim (); } ); fnFilter ( std::move ( dOption[0] ), std::move ( dOption[1] )); }); } /// zero-copy split by the given boundaries, result valid until sIn lives. void Split ( StrtVec_t& dOut, const char* sIn, const char* sBounds ); void Split ( StrtVec_t& dOut, const char* sIn, int iLen, const char* sBounds ); StrtVec_t Split ( const char* sIn, const char* sBounds ); StrtVec_t Split ( const char* sIn, int iLen, const char* sBounds ); /// zero-copy trim leading and trailing spaces; result valid until tIn lives Str_t Trim ( Str_t tIn ); Str_t Trim ( Str_t tIn, char cGarbage ); } // namespace sph /// config section (hash of variant values) class CSphConfigSection : public SmallStringHash_T < CSphVariant > { public: CSphConfigSection () : m_iTag ( 0 ) {} void AddEntry ( const char * szKey, const char * szValue ); /// get integer option value by key and default value int GetInt ( const char * sKey, int iDefault=0 ) const { CSphVariant * pEntry = (*this)( sKey ); return pEntry ? pEntry->intval() : iDefault; } /// get float option value by key and default value float GetFloat ( const char * sKey, float fDefault=0.0f ) const { CSphVariant * pEntry = (*this)( sKey ); return pEntry ? pEntry->floatval() : fDefault; } /// get string option value by key and default value CSphString GetStr ( const char * sKey, const char * sDefault="" ) const { CSphVariant * pEntry = (*this)( sKey ); return pEntry ? pEntry->strval() : sDefault; } /// get bool option value by key and default value bool GetBool ( const char * sKey, bool bDefault = true ) const { CSphVariant * pEntry = ( *this ) ( sKey ); return pEntry ? (pEntry->intval ()!=0) : bDefault; } /// get size option (plain int, or with K/M suffix) value by key and default value int GetSize ( const char * sKey, int iDefault ) const; int64_t GetSize64 ( const char * sKey, int64_t iDefault ) const; /// get time option in useconds (1000*1000 useconds = 1 second) /// (plain integer, or with us/ms/s/m/h/d/w suffix) value by key and default value /// if no key specified, GetTime64 considers num in seconds, GetTime64ms in milliseconds. int64_t GetUsTime64S ( const char* sKey, int64_t iDefault ) const; int64_t GetUsTime64Ms ( const char* sKey, int64_t iDefault ) const; // same as GetUsTime, but returns value expressed in int milliseconds and seconds int GetSTimeS ( const char* sKey, int iDefault=0 ) const; // default seconds int GetMsTimeMs ( const char* sKey, int iDefault=0 ) const; // default milliseconds void Swap ( CSphConfigSection& other ) noexcept { ::Swap(m_iTag, other.m_iTag); SmallStringHash_T<CSphVariant>::Swap(other); } /// copying CSphConfigSection& operator= ( CSphConfigSection rhs ) { Swap ( rhs ); return *this; } int m_iTag; }; /// config section type (hash of sections) using CSphConfigType = SmallStringHash_T < CSphConfigSection >; /// config (hash of section types) using CSphConfig = SmallStringHash_T < CSphConfigType >; /// load or run (she-bang) given file. Return content and flag whether it was changed since last load std::pair<bool, CSphVector<char>> FetchAndCheckIfChanged ( const CSphString& sFilename ); ///////////////////////////////////////////////////////////////////////////// /// Provided or default config file CSphString sphGetConfigFile ( const char * szHint = nullptr ); /// load config file (will die inside if an error happened) CSphConfig sphLoadConfig ( const CSphString & sPath, bool bTraceToStdout, CSphString & sActualPath ); CSphConfig sphLoadConfig ( const CSphString & sPath, bool bTraceToStdout ); CSphConfig sphLoadConfigWithoutIndexes ( const CSphString & sPath, bool bTraceToStdout ); /// load config file into provided hConfig (on error hConfig is unchanged) bool ParseConfig ( CSphConfig* pConfig, CSphString sFileName, const VecTraits_T<char>& dData ); enum ESphLogLevel : BYTE { SPH_LOG_FATAL = 0, SPH_LOG_WARNING = 1, SPH_LOG_INFO = 2, SPH_LOG_DEBUG = 3, SPH_LOG_RPL_DEBUG = 4, SPH_LOG_VERBOSE_DEBUG = 5, SPH_LOG_VERY_VERBOSE_DEBUG = 6, SPH_LOG_MAX = SPH_LOG_VERY_VERBOSE_DEBUG }; extern ESphLogLevel g_eLogLevel; // current log level, can be changed on the fly typedef void ( *SphLogger_fn )( ESphLogLevel, const char *, va_list ); volatile SphLogger_fn& g_pLogger(); void sphLogVa ( const char * sFmt, va_list ap, ESphLogLevel eLevel = SPH_LOG_WARNING ); void sphWarning_impl ( const char * sFmt, ... ) __attribute__((format(printf,1,2))); //NOLINT void sphLogf ( ESphLogLevel eLevel, const char* sFmt, ... ) __attribute__ ( ( format ( printf, 2, 3 ) ) ); // NOLINT; void sphInfo_impl ( const char * sFmt, ... ) __attribute__((format(printf,1,2))); //NOLINT void sphLogFatal ( const char * sFmt, ... ) __attribute__((format(printf,1,2))); //NOLINT void sphLogDebug_impl ( const char * sFmt, ... ) __attribute__((format(printf,1,2))); //NOLINT void sphLogDebugv_impl ( const char * sFmt, ... ) __attribute__((format(printf,1,2))); //NOLINT void sphLogDebugvv_impl ( const char * sFmt, ... ) __attribute__((format(printf,1,2))); //NOLINT void sphLogDebugRpl_impl ( const char * sFmt, ... ) __attribute__((format(printf,1,2))); //NOLINT #define sphWarning( ... ) do if ( g_eLogLevel>=SPH_LOG_WARNING ) sphWarning_impl (__VA_ARGS__); while(0) #define sphInfo( ... ) do if ( g_eLogLevel>=SPH_LOG_INFO ) sphInfo_impl (__VA_ARGS__); while(0) #define sphLogDebug( ... ) do if ( g_eLogLevel>=SPH_LOG_DEBUG ) sphLogDebug_impl (__VA_ARGS__); while(0) #define sphLogDebugv( ... ) do if ( g_eLogLevel>=SPH_LOG_VERBOSE_DEBUG ) sphLogDebugv_impl (__VA_ARGS__); while(0) #define sphLogDebugvv( ... ) do if ( g_eLogLevel>=SPH_LOG_VERY_VERBOSE_DEBUG ) sphLogDebugvv_impl (__VA_ARGS__); while(0) #define sphLogDebugRpl( ... ) do if ( g_eLogLevel>=SPH_LOG_RPL_DEBUG ) sphLogDebugRpl_impl (__VA_ARGS__); while(0) // set the prefix to supress the log void sphLogSupress ( const char * sPrefix, ESphLogLevel eLevel = SPH_LOG_WARNING ); void sphLogSupressRemove ( const char * sPrefix, ESphLogLevel eLevel = SPH_LOG_WARNING ); // TimePrefixed logging - output "prefix [ms] ...'; 'ms' is reset to 0 by TimeStart(). namespace TimePrefixed { void TimeStart (); int64_t TimeStamp(); void LogDebugv ( const char* sPrefix, const char* sFmt, ... ); } namespace CustomLog { void Warning_impl ( const char* sFmt, ... ); void Info_impl ( const char* sFmt, ... ); } #define LogWarning( ... ) do if ( g_eLogLevel >= SPH_LOG_WARNING ) CustomLog::Warning_impl ( __VA_ARGS__ ); while ( 0 ) #define LogInfo( ... ) do if ( g_eLogLevel >= SPH_LOG_INFO ) CustomLog::Info_impl ( __VA_ARGS__ ); while ( 0 ) ////////////////////////////////////////////////////////////////////////// /// how do we properly exit from the crash handler? #if !_WIN32 #define CRASH_EXIT_CORE { signal ( sig, SIG_DFL ); kill ( getpid(), sig ); } #ifndef NDEBUG // UNIX debug build, die and dump core #define CRASH_EXIT CRASH_EXIT_CORE #else // UNIX release build, just die #define CRASH_EXIT { sphQuickExit ( 2 ); } #endif #else #define CRASH_EXIT_CORE return EXCEPTION_CONTINUE_SEARCH #ifndef NDEBUG // Windows debug build, show prompt to attach debugger #define CRASH_EXIT CRASH_EXIT_CORE #else // Windows release build, just die #define CRASH_EXIT return EXCEPTION_EXECUTE_HANDLER #endif #endif /// async safe, BUT NOT THREAD SAFE, fprintf void sphSafeInfo ( int iFD, const char * sFmt, ... ); #if !_WIN32 /// UNIX backtrace gets printed out to a stream void sphBacktrace ( int iFD, bool bSafe=false ); #else /// Windows minidump gets saved to a file void sphBacktrace ( EXCEPTION_POINTERS * pExc, const char * sFile ); #endif /// dummy call of backtrace to alloc internal structures and prevent deadlock at malloc on crash void sphBacktraceInit(); /// calls actual (libc or jemalloc) malloc stats void sphMallocStats ( const char* szParams = nullptr ); /// actualy dump of process sName with pid sPid and sink output to iFD /// (warning, that function uses fork!) bool sphDumpGdb ( int iFD, const char* sName, const char* sPid ); void sphBacktraceSetBinaryName ( const char * sName ); volatile int& getParentPID (); /// set by watchdog init and allows children to signal parent volatile bool& getSafeGDB (); /// if we detected that jemalloc is available /// plain backtrace - returns static buffer with the text of the call stack const char * DoBacktrace ( int iDepth=0, int iSkip=0 ); void sphCheckDuplicatePaths ( const CSphConfig & hConf ); using FixPathAbsolute_fn = std::function<void ( CSphString & sPath )>; /// set globals from the common config section void sphConfigureCommon ( const CSphConfig & hConf, FixPathAbsolute_fn && fnPathFix = nullptr ); /// my own is chinese FORCE_INLINE bool sphIsChineseCode ( int iCode ) { return ( ( iCode>=0x2E80 && iCode<=0x2EF3 ) || // CJK radicals ( iCode>=0x2F00 && iCode<=0x2FD5 ) || // Kangxi radicals ( iCode>=0x3000 && iCode<=0x303F ) || // CJK Symbols and Punctuation ( iCode>=0x3105 && iCode<=0x312D ) || // Bopomofo ( iCode>=0x31C0 && iCode<=0x31E3 ) || // CJK strokes ( iCode>=0x3400 && iCode<=0x4DB5 ) || // CJK Ideograph Extension A ( iCode>=0x4E00 && iCode<=0x9FFF ) || // Ideograph ( iCode>=0xF900 && iCode<=0xFAD9 ) || // compatibility ideographs ( iCode>=0xFF00 && iCode<=0xFFEF ) || // Halfwidth and fullwidth forms ( iCode>=0x20000 && iCode<=0x2FA1D ) ); // CJK Ideograph Extensions B/C/D, and compatibility ideographs } /// detect chinese chars in a buffer bool sphDetectChinese ( const BYTE * szBuffer, int iLength ); class CSphDynamicLibrary : public ISphNoncopyable { bool m_bReady; // whether the lib is valid or not void * m_pLibrary; // internal handle public: explicit CSphDynamicLibrary ( const char* sPath, bool bGlobal=true ); void CSphDynamicLibraryAlternative ( const char* sPath, bool bGlobal = true ); // We are suppose, that library is loaded once when necessary, and will alive whole lifetime of utility. // So, no need to explicitly desctruct it, this is intended leak. ~CSphDynamicLibrary (); bool LoadSymbols ( const char** sNames, void*** pppFuncs, int iNum ); inline void * GetLib() const noexcept { return m_pLibrary; } }; /// collect warnings/errors from any suitable context. /// on multiple calls appends new message, separating it with '; ' from previous. class Warner_c : public ISphNoncopyable { StringBuilder_c m_sWarnings; StringBuilder_c m_sErrors; const char * m_sDel = nullptr; const char * m_sPref = nullptr; const char * m_sTerm = nullptr; public: Warner_c ( const char * sDel = ", ", const char * sPref = nullptr, const char * sTerm = nullptr ); Warner_c ( Warner_c&& rhs ) noexcept; Warner_c& operator= ( Warner_c &&rhs ) noexcept; // append message as error. // always return false (in order to simplify pattern {error='foo'; return false;}) void Err ( const char * sFmt, ... ); void Err ( const CSphString &sMsg ); StringBuilder_c& Err() { return m_sErrors; } void Warn ( const char * sFmt, ... ); void Warn ( const CSphString &sMsg ); StringBuilder_c& Warn() { return m_sWarnings; } void Clear (); const char * sError () const; const char * sWarning () const; bool ErrEmpty () const { return m_sErrors.IsEmpty (); } bool WarnEmpty () const { return m_sWarnings.IsEmpty (); } void AddStringsFrom ( const Warner_c &sSrc ); void MoveErrorsTo ( CSphString &sTarget ); void MoveWarningsTo ( CSphString &sTarget ); void MoveAllTo ( CSphString &sTarget ); }; namespace TlsMsg { // format error, then return false bool Err( const char* sFmt, ... ); // put error from string, then return false bool Err( const CSphString& sMsg ); // return builder for user manipulations StringBuilder_c& Err(); void ResetErr(); // return last error const char* szError(); // move error to given string, or leave it intact if no error void MoveError( CSphString& sError ); // return error msg (if any) and reset buff CSphString MoveToString(); // true if some error was reported. bool HasErr(); // RAII keep previous msg; restore it on destroy class KeepError_c : public ISphNoncopyable, public ISphNonmovable { CSphString m_sPrevError; public: KeepError_c() { MoveError ( m_sPrevError ); } ~KeepError_c() { Err ( m_sPrevError); } // to use as legacy error collector operator CSphString&() { return m_sPrevError;} }; } /// link given var to be reported at scope exit #define TLS_MSG_CATCH( STR ) AT_SCOPE_EXIT ( [&STR] {if ( !STR.IsEmpty() ) TlsMsg::Err(STR); } ) /// declare str var and link it to be reported #define TLS_MSG_STRING( STR ) CSphString STR; TLS_MSG_CATCH ( STR ) // extract basename from path const char * GetBaseName ( const CSphString & sFullPath ); bool HasMvaUpdated ( const CSphString & sIndexPath ); // uuid short generator - static across daemon // bytes value // 1 server_id & 0x7f // 4 startup time of server in seconds // 3 increment base part int64_t UidShort(); int64_t GetIndexUid(); // server - is server id used as iServer & 0x7f // started - is a server start time \ Unix timestamp in seconds void UidShortSetup ( int iServer, int iStarted ); BYTE Pearson8 ( const BYTE * pBuf, int iLen ); #if _WIN32 void CheckWinInstall(); CSphString GetWinInstallDir(); #endif void PauseAt ( const CSphString& sName, bool bPause ); void PauseCheck ( const CSphString& sName ); #endif // _sphinxutils_
21,111
C++
.h
467
43.152034
121
0.691719
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,099
netpoll.h
manticoresoftware_manticoresearch/src/netpoll.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 "searchdaemon.h" #include "std/ints.h" #include "std/refcounted_mt.h" #include "std/threadrole.h" #include "timeout_queue.h" #include <boost/intrusive/slist.hpp> #include <functional> #include <memory> ////////////////////////////////////////////////////////////////////////// // Universal work with select/poll/epoll/kqueue ////////////////////////////////////////////////////////////////////////// // wrapper around epoll/kqueue/poll extern ThreadRole NetPoollingThread; using netlist_hook_t = boost::intrusive::slist_member_hook<>; struct NetPollEvent_t : public EnqueuedTimeout_t, public ISphRefcountedMT { netlist_hook_t m_tBackHook; // opaque hook for intrusive list linkage int m_iBackIdx = -1; // or opaque index to internals of poller int m_iSock = -1; BYTE m_uIOChange = SET_NONE; BYTE m_uIOActive = SET_NONE; BYTE m_uGotEvents = IS_NONE; explicit NetPollEvent_t ( int iSock ) : m_iSock ( iSock ) {} enum SetMask_e : BYTE { SET_NONE = 0, SET_READ = 1 << 0, // 1 - poll read events SET_WRITE = 1 << 1, // 2 - poll write events SET_RW = SET_READ | SET_WRITE, // 3 - poll read and write events SET_ONESHOT = 1 << 2, // 4 - will be deactivated/removed once shot SET_ON_EDGE = 1 << 3, // 8 - edge-triggered (if non set - level-triggered) SET_EDGEONESHOT = SET_ONESHOT | SET_ON_EDGE, SET_CLOSED = 1 << 4, // 16 - socket is closed, remove the event from timeout/task queues }; enum GotMask_e : BYTE { IS_NONE = 0, IS_READ = 1 << 0, // 1 - ready for reading IS_WRITE = 1 << 1, // 2 - ready for writing IS_RW = SET_READ | SET_WRITE, // 3 - ready for reading and writing IS_HUP = 1 << 2, // 4 - has HUP IS_ERR = 1 << 3, // 8 - has ERR IS_ERRHUP = IS_ERR | IS_HUP, // 12 - has HUP & ERR IS_TIMEOUT = 1 << 4, // 16 - timed out }; inline bool IsLinked() const { return m_tBackHook.is_linked() || m_iBackIdx!=-1; } inline bool CheckSocketError () const { bool bReadError = ( ( m_uGotEvents & IS_READ ) && ( m_uGotEvents & IS_ERRHUP ) ); bool bWriteError = ( ( m_uGotEvents & IS_WRITE ) && ( m_uGotEvents & IS_ERR ) ); if ( bReadError && ( ( m_uGotEvents & IS_ERRHUP ) == IS_ERRHUP ) ) sphSockSetErrno ( ECONNRESET ); return bReadError || bWriteError; } }; using NetPoolEventRefPtr_c = CSphRefcountedPtr<NetPollEvent_t>; constexpr static int64_t WAIT_UNTIL_TIMEOUT = -1LL; class NetPooller_c; class NetPollReadyIterator_c { int m_iIterEv = -1; NetPooller_c * m_pOwner = nullptr; public: explicit NetPollReadyIterator_c ( NetPooller_c* pOwner ) : m_pOwner ( pOwner ) { if ( pOwner ) operator++(); } NetPollEvent_t & operator* () REQUIRES ( NetPoollingThread ); NetPollReadyIterator_c & operator++ () REQUIRES ( NetPoollingThread ); bool operator!= ( const NetPollReadyIterator_c & rhs ) const REQUIRES ( NetPoollingThread ); }; class NetPooller_c : public ISphNoncopyable { class Impl_c; std::unique_ptr<Impl_c> m_pImpl; friend class NetPollReadyIterator_c; public: explicit NetPooller_c ( int iSizeHint, int iMaxReady=0 ); ~NetPooller_c(); void SetupEvent ( NetPollEvent_t * pEvent ) REQUIRES ( NetPoollingThread ); void Wait ( int64_t iUS ) REQUIRES ( NetPoollingThread ); int GetNumOfReady () const; void ProcessAll ( std::function<void (NetPollEvent_t*)>&& fnAction ) REQUIRES ( NetPoollingThread ); void RemoveTimeout ( NetPollEvent_t * pEvent ) REQUIRES ( NetPoollingThread ); void RemoveEvent ( NetPollEvent_t * pEvent ) REQUIRES ( NetPoollingThread ); int64_t TickGranularity() const; NetPollReadyIterator_c begin () { return NetPollReadyIterator_c ( this ); } static NetPollReadyIterator_c end () { return NetPollReadyIterator_c ( nullptr ); } }; // determine which branch will be used // defs placed here for easy switch between/debug #define NETPOLL_EPOLL 1 #define NETPOLL_KQUEUE 2 #define NETPOLL_POLL 3 #if HAVE_EPOLL #define POLLING_EPOLL 1 #define NETPOLL_TYPE NETPOLL_EPOLL #elif HAVE_KQUEUE #define POLLING_KQUEUE 1 #define NETPOLL_TYPE NETPOLL_KQUEUE #elif HAVE_POLL #define POLLING_POLL 1 #define NETPOLL_TYPE NETPOLL_POLL #endif // #define NETPOLL_TYPE NETPOLL_POLL
4,695
C++
.h
122
36.483607
101
0.686551
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,100
exprgeodist.h
manticoresoftware_manticoresearch/src/exprgeodist.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 class ISphExpr; struct CSphQuery; class ISphSchema; struct CSphString; ISphExpr * CreateExprGeodist ( const CSphQuery & tQuery, const ISphSchema & tSchema, CSphString & sError );
672
C++
.h
17
38.294118
107
0.768049
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,101
coro_stack.h
manticoresoftware_manticoresearch/src/coro_stack.h
// // Copyright (c) 2021-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 "config.h" #if __has_include( <valgrind/valgrind.h>) #define BOOST_USE_VALGRIND 1 #include <valgrind/valgrind.h> #else #undef BOOST_USE_VALGRIND #endif #include <boost/context/stack_context.hpp> #include "std/vector.h" #include "std/ints.h" namespace Threads { static constexpr size_t STACK_ALIGN = 16; // stack align - let it be 16 bytes for convenience static constexpr size_t DEFAULT_CORO_STACK_SIZE = 1024 * 128; // stack size - 128K enum class StackFlavour_E { fixedsize, protected_fixedsize, mocked_prealloc }; // what allocator is in game using CoroStack_t = std::pair<boost::context::stack_context, StackFlavour_E>; CoroStack_t AllocateStack ( size_t iSize ); CoroStack_t MockedStack ( VecTraits_T<BYTE> dStack ); void DeallocateStack ( CoroStack_t tStack ); } // namespace Threads
1,205
C++
.h
30
38.866667
107
0.759863
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,102
fileutils.h
manticoresoftware_manticoresearch/src/fileutils.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 _fileutils_ #define _fileutils_ #include "sphinxstd.h" #include "std/strerrorm.h" #include <fcntl.h> #include <sys/stat.h> #if !_WIN32 #include <sys/mman.h> #endif #if _WIN32 #include <direct.h> #define stat _stat64 #define fstat _fstat64 #if _MSC_VER<1400 #define struct_stat __stat64 #else #define struct_stat struct _stat64 #endif #else #define struct_stat struct stat #endif #ifdef O_BINARY #define SPH_O_BINARY O_BINARY #else #define SPH_O_BINARY 0 #endif #define SPH_O_READ ( O_RDONLY | SPH_O_BINARY ) #define SPH_O_NEW ( O_CREAT | O_RDWR | O_TRUNC | SPH_O_BINARY ) #define SPH_O_APPEND ( O_CREAT | O_RDWR | O_APPEND | SPH_O_BINARY ) class CSphIOStats { public: int64_t m_iReadTime = 0; DWORD m_iReadOps = 0; int64_t m_iReadBytes = 0; int64_t m_iWriteTime = 0; DWORD m_iWriteOps = 0; int64_t m_iWriteBytes = 0; ~CSphIOStats(); void Start(); void Stop(); void Add ( const CSphIOStats & b ); bool IsEnabled() { return m_bEnabled; } private: bool m_bEnabled = false; CSphIOStats * m_pPrev = nullptr; }; class CSphReader; namespace bson { class Bson_c; } struct CSphSavedFile { CSphString m_sFilename; SphOffset_t m_uSize = 0; SphOffset_t m_uCTime = 0; SphOffset_t m_uMTime = 0; DWORD m_uCRC32 = 0; bool Collect ( const char * szFilename, CSphString * pError=nullptr ); void Read ( CSphReader & tReader, const char * szFilename, bool bSharedStopwords, CSphString * sWarning = nullptr ); void Read ( const bson::Bson_c& tNode, const char* szFilename, bool bSharedStopwords, CSphString* sWarning = nullptr ); }; /// open file for reading int sphOpenFile ( const char * sFile, CSphString & sError, bool bWrite ); /// check if file exists and is a readable file bool sphIsReadable ( const char * szFilename, CSphString * pError=NULL ); bool sphIsReadable ( const CSphString & sFilename, CSphString * pError = NULL ); bool sphFileExists ( const char * szFilename, CSphString * pError=nullptr ); bool sphFileExists ( const CSphString& sFilename, CSphString * pError=nullptr ); bool sphDirExists ( const char * szFilename, CSphString * pError=nullptr ); bool sphDirExists ( const CSphString& sFilename, CSphString * pError=nullptr ); /// return size of file descriptor int64_t sphGetFileSize ( int iFD, CSphString * sError = nullptr ); int64_t sphGetFileSize ( const CSphString & sFile, CSphString * sError = nullptr ); /// truncate file bool sphTruncate ( int iFD ); /// initialize IO statistics collecting void sphInitIOStats(); /// clean up IO statistics collector void sphDoneIOStats(); CSphIOStats * GetIOStats(); /// calculate file crc32 bool sphCalcFileCRC32 ( const char * szFilename, DWORD & uCRC32 ); // unwind different tricks like "../../../etc/passwd" CSphString sphNormalizePath ( const CSphString& sOrigPath ); CSphString sphGetCwd(); // a tiny wrapper over ::read() which additionally performs IO stats update int64_t sphRead ( int iFD, void * pBuf, size_t iCount ); /// try to obtain an exclusive lock on specified file /// bWait specifies whether to wait bool sphLockEx ( int iFile, bool bWait ); /// remove existing locks void sphLockUn ( int iFile ); /// create and lock the file bool RawFileLock ( const CSphString& sFile, int& iLockFD, CSphString& sError ); /// unlock and unlink file void RawFileUnLock ( const CSphString& sFile, int& iLockFD ); void SafeClose ( int& iFD ); /// simple write wrapper /// simplifies partial write checks, and also supresses "fortified" glibc warnings bool sphWrite ( int iFD, const void * pBuf, size_t iSize ); bool sphWrite ( int iFD, const Str_t& dBuf ); StrVec_t FindFiles ( const char * szPath, bool bNeedDirs=false ); bool MkDir ( const char * szDir ); bool CopyFile ( const CSphString & sSource, const CSphString & sDest, CSphString & sError, int iMode=SPH_O_NEW ); bool RenameFiles ( const StrVec_t & dSrc, const StrVec_t & dDst, CSphString & sError ); bool RenameWithRollback ( const StrVec_t & dSrc, const StrVec_t & dDst, CSphString & sError ); // check if path exists and also check if daemon can write there bool CheckPath ( const CSphString & sPath, bool bCheckWrite, CSphString & sError, const char * sCheckFileName="tmp" ); bool IsPathAbsolute ( const CSphString & sPath ); CSphString GetExecutablePath(); CSphString & StripPath ( CSphString & sPath ); CSphString GetPathOnly ( const CSphString & sFullPath ); const char * GetExtension ( const CSphString & sFullPath ); CSphString RealPath ( const CSphString& sPath ); bool IsSymlink ( const CSphString & sFile ); bool ResolveSymlink ( const CSphString & sFile, CSphString & sResult ); class CSphWriter; void SeekAndPutOffset ( CSphWriter & tWriter, SphOffset_t tOffset, SphOffset_t tValue ); // FIXME! unify this weird zoo of file function naming namespace sph { int rename ( const char * sOld, const char * sNew ); } template < typename T > class CSphMappedBuffer : public CSphBufferTrait < T > { public: /// ctor CSphMappedBuffer () { #if _WIN32 m_iFD = INVALID_HANDLE_VALUE; m_iMap = INVALID_HANDLE_VALUE; #else m_iFD = -1; #endif } /// dtor ~CSphMappedBuffer() override { this->Reset(); } bool Setup ( const CSphString & sFile, CSphString & sError, bool bWrite = false ) { m_sFilename = sFile; m_bWrite = bWrite; #if _WIN32 assert ( m_iFD==INVALID_HANDLE_VALUE ); #else assert ( m_iFD==-1 ); #endif assert ( !this->GetReadPtr() && !this->GetLength64() ); T * pData = NULL; int64_t iCount = 0; #if _WIN32 int iAccessMode = GENERIC_READ; if ( bWrite ) iAccessMode |= GENERIC_WRITE; DWORD uShare = FILE_SHARE_READ | FILE_SHARE_DELETE; if ( bWrite ) uShare |= FILE_SHARE_WRITE; // wo this flag indexer and indextool unable to open attribute file that was opened by daemon HANDLE iFD = CreateFile ( sFile.cstr(), iAccessMode, uShare, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if ( iFD==INVALID_HANDLE_VALUE ) { sError.SetSprintf ( "failed to open file '%s' (errno %u)", sFile.cstr(), ::GetLastError() ); return false; } m_iFD = iFD; LARGE_INTEGER tLen; if ( GetFileSizeEx ( iFD, &tLen )==0 ) { sError.SetSprintf ( "failed to fstat file '%s' (errno %u)", sFile.cstr(), ::GetLastError() ); Reset(); return false; } // FIXME!!! report abount tail, ie m_iLen*sizeof(T)!=tLen.QuadPart iCount = tLen.QuadPart / sizeof(T); // mmap fails to map zero-size file if ( tLen.QuadPart>0 ) { int iProtectMode = PAGE_READONLY; if ( bWrite ) iProtectMode = PAGE_READWRITE; m_iMap = ::CreateFileMapping ( iFD, NULL, iProtectMode, 0, 0, NULL ); int iMapAccessMode = FILE_MAP_READ; if ( bWrite ) iMapAccessMode |= FILE_MAP_WRITE; pData = (T *)::MapViewOfFile ( m_iMap, iMapAccessMode, 0, 0, 0 ); if ( !pData ) { sError.SetSprintf ( "failed to map file '%s': (errno %u, length=" INT64_FMT ")", sFile.cstr(), ::GetLastError(), (int64_t)tLen.QuadPart ); Reset(); return false; } } #else int iFD = sphOpenFile ( sFile.cstr(), sError, bWrite ); if ( iFD<0 ) return false; m_iFD = iFD; int64_t iFileSize = sphGetFileSize ( iFD, &sError ); if ( iFileSize<0 ) return false; // FIXME!!! report about tail, ie m_iLen*sizeof(T)!=st.st_size iCount = iFileSize / sizeof(T); // mmap fails to map zero-size file if ( iFileSize>0 ) { int iProt = PROT_READ; if ( bWrite ) iProt |= PROT_WRITE; pData = (T *)mmap ( NULL, iFileSize, iProt, MAP_SHARED, iFD, 0 ); if ( pData==MAP_FAILED ) { sError.SetSprintf ( "failed to mmap file '%s': %s (length=" INT64_FMT ")", sFile.cstr(), strerrorm(errno), iFileSize ); Reset(); return false; } mmadvise ( pData, iFileSize, Advise_e::NOFORK ); mmadvise ( pData, iFileSize, Advise_e::NODUMP ); } #endif this->Set ( pData, iCount ); return true; } void Reset() override { this->MemUnlock(); #if _WIN32 if ( this->GetReadPtr() ) ::UnmapViewOfFile ( this->GetReadPtr() ); if ( m_iMap!=INVALID_HANDLE_VALUE ) ::CloseHandle ( m_iMap ); m_iMap = INVALID_HANDLE_VALUE; if ( m_iFD!=INVALID_HANDLE_VALUE ) ::CloseHandle ( m_iFD ); m_iFD = INVALID_HANDLE_VALUE; #else if ( this->GetReadPtr() ) ::munmap ( this->GetWritePtr(), this->GetLengthBytes() ); SafeClose ( m_iFD ); #endif this->Set ( NULL, 0 ); } bool Resize ( uint64_t uNewSize, CSphString & sWarning, CSphString & sError ) { if ( !this->GetReadPtr() ) return false; bool bMlock = this->m_bMemLocked; if ( bMlock ) this->MemUnlock(); #if _WIN32 assert ( m_iMap ); ::UnmapViewOfFile ( this->GetReadPtr() ); ::CloseHandle ( m_iMap ); m_iMap = ::CreateFileMapping ( m_iFD, nullptr, m_bWrite ? PAGE_READWRITE : PAGE_READONLY, (DWORD)( uNewSize >> 32 ), (DWORD) ( uNewSize & 0xFFFFFFFFULL ), nullptr ); if ( !m_iMap ) { sError.SetSprintf ( "CreateFileMapping failed for '%s': (errno %u, length=" UINT64_FMT ")", m_sFilename.cstr(), ::GetLastError(), uNewSize ); Reset(); return false; } void * pMapped = (T *)::MapViewOfFile ( m_iMap, FILE_MAP_READ | ( m_bWrite ? FILE_MAP_WRITE : 0 ), 0, 0, 0 ); if ( !pMapped ) { sError.SetSprintf ( "MapViewOfFile failed for '%s': (errno %u, length=" UINT64_FMT ")", m_sFilename.cstr(), ::GetLastError(), uNewSize ); Reset(); return false; } #else if ( sphSeek ( m_iFD, uNewSize, SEEK_SET ) < 0 ) { sError.SetSprintf ( "failed to seek '%s': %s (length=" UINT64_FMT ")", m_sFilename.cstr(), strerror(errno), uNewSize ); Reset(); return false; } if ( !sphTruncate(m_iFD) ) { sError.SetSprintf ( "failed to truncate '%s': %s (length=" UINT64_FMT ")", m_sFilename.cstr(), strerror(errno), uNewSize ); Reset(); return false; } #if HAVE_MREMAP void * pMapped = mremap ( this->GetWritePtr(), this->GetLengthBytes(), uNewSize, MREMAP_MAYMOVE ); if ( pMapped==MAP_FAILED ) { sError.SetSprintf ( "mremap failed for '%s': %s (length=" UINT64_FMT ")", m_sFilename.cstr(), strerror(errno), uNewSize ); Reset(); return false; } #else void * pMapped = mmap ( nullptr, uNewSize, PROT_READ | ( m_bWrite ? PROT_WRITE : 0 ), MAP_SHARED, m_iFD, 0 ); if ( pMapped==MAP_FAILED ) { sError.SetSprintf ( "mmap failed for '%s': %s (length=" UINT64_FMT ")", m_sFilename.cstr(), strerror(errno), uNewSize ); Reset(); return false; } if ( this->GetReadPtr() ) ::munmap ( this->GetWritePtr(), this->GetLengthBytes() ); #endif #endif if ( bMlock ) this->MemLock ( sWarning ); this->Set ( (T*)pMapped, uNewSize / sizeof(T) ); return true; } uint64_t GetCoreSize () const { #if !_WIN32 using PAGETYPE = #if HAVE_UNSIGNED_MINCORE BYTE #else char #endif ; auto uPageSize = GetMemPageSize (); auto uSize = this->GetLengthBytes(); auto uPages = ( uSize+uPageSize-1 ) / uPageSize; CSphFixedVector<PAGETYPE> dMap ( uPages ); if ( mincore ( (void *) this->GetWritePtr (), uSize, dMap.begin () )==0 ) { for ( auto uData : dMap ) if ( !( ((BYTE) uData) & 1U ) ) --uPages; } return uPages * uPageSize; #else return 0; // fixme! implement... #endif } bool Flush ( bool bWaitComplete, CSphString & sError ) const { if ( !this->GetReadPtr() ) return true; #if _WIN32 if ( !::FlushViewOfFile ( this->GetReadPtr(), this->GetLengthBytes() ) ) { sError.SetSprintf ( "FlushViewOfFile failed for '%s': errno %u", m_sFilename.cstr(), ::GetLastError() ); return false; } if ( bWaitComplete && !::FlushFileBuffers(m_iFD) ) { sError.SetSprintf ( "FlushFileBuffers failed for '%s': errno %u", m_sFilename.cstr(), ::GetLastError() ); return false; } #else if ( ::msync ( this->GetWritePtr(), this->GetLengthBytes(), bWaitComplete ? MS_SYNC : MS_ASYNC ) ) { sError.SetSprintf ( "msync failed for '%s': %s", m_sFilename.cstr(), strerror(errno) ); return false; } #endif return true; } const char * GetFileName() const { return m_sFilename.cstr(); } private: #if _WIN32 HANDLE m_iFD; HANDLE m_iMap; #else int m_iFD; #endif bool m_bWrite {false}; CSphString m_sFilename; }; #endif // _fileutils_
12,643
C++
.h
378
30.801587
167
0.684137
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,103
threadutils_impl.h
manticoresoftware_manticoresearch/src/threadutils_impl.h
// // Copyright (c) 2020-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/ // /// @file threadutils.inc /// internal implementations with templates #ifndef MANTICORE_THREADUTILS_INC #define MANTICORE_THREADUTILS_INC namespace Threads { namespace details { // list (FIFO queue) of operations to perform. Used in service queue. template<typename Operation> class OpQueue_T : public ISphNoncopyable { Operation * m_pFront = nullptr; // The front of the queue. Operation * m_pBack = nullptr; // The back of the queue. DWORD m_uLen = 0; public: // destroys all operations. ~OpQueue_T () { while (Operation * pOp = m_pFront) { Pop (); pOp->Destroy(); } } // Get the operation at the front of the queue. Operation * Front () const noexcept { return m_pFront; } // Pop an operation from the front of the queue. void Pop () noexcept { if ( m_pFront ) { auto * tmp = m_pFront; m_pFront = tmp->m_pNext; if ( !m_pFront ) m_pBack = nullptr; tmp->m_pNext = nullptr; --m_uLen; } } // Push an operation on to the back of the queue. void Push ( Operation * pOp ) noexcept { pOp->m_pNext = nullptr; if ( m_pBack ) { m_pBack->m_pNext = pOp; m_pBack = pOp; } else m_pFront = m_pBack = pOp; ++m_uLen; } // Push an operation on to the front of the queue. void Push_front ( Operation * pOp ) noexcept { if ( m_pFront ) { pOp->m_pNext = m_pFront; m_pFront = pOp; } else { pOp->m_pNext = nullptr; m_pFront = m_pBack = pOp; } ++m_uLen; } // Push all operations from another queue on to the back of the queue. The // source queue may contain operations of a derived type. template<typename OtherOperation> void Push ( OpQueue_T<OtherOperation> & rhs ) noexcept { auto pRhsFront = rhs.m_pFront; if ( pRhsFront ) { if ( m_pBack ) m_pBack->m_pNext = pRhsFront; else m_pFront = pRhsFront; m_pBack = rhs.m_pBack; rhs.m_pFront = nullptr; rhs.m_pBack = nullptr; m_uLen += std::exchange ( rhs.m_uLen, 0 ); } } // Whether the queue is empty. bool Empty () const noexcept { return m_pFront==nullptr; } inline DWORD GetLength() const noexcept { return m_uLen; } // Test whether an operation is already enqueued. bool IsEnqueued ( Operation * pOp ) const noexcept { return pOp->m_pNext || m_pBack==pOp; } // find elem (linear search), remove from list and destroy void RemoveAndDestroy ( Operation * pOp ) noexcept { if ( !pOp ) return; if ( m_pFront==pOp ) { m_pFront = pOp->m_pNext; } else { for ( auto pCurOp = m_pFront; pCurOp!=nullptr; pCurOp = pCurOp->m_pNext ) { if ( pCurOp->m_pNext==pOp ) { pCurOp->m_pNext = pOp->m_pNext; if ( !pCurOp->m_pNext ) m_pBack = pCurOp; break; } } } if ( !m_pFront ) m_pBack = nullptr; pOp->Destroy (); --m_uLen; } class Iterator_c { Operation * m_pIterator = nullptr; public: explicit Iterator_c ( Operation * pIterator = nullptr ) : m_pIterator ( pIterator ) {} Operation & operator* () noexcept { return *m_pIterator; } Iterator_c & operator++ () noexcept { m_pIterator = m_pIterator->m_pNext; return *this; } bool operator!= ( const Iterator_c & rhs ) const noexcept { return m_pIterator!=rhs.m_pIterator; } }; // c++11 style iteration Iterator_c begin () const noexcept { return Iterator_c ( m_pFront ); } Iterator_c end () const noexcept { return Iterator_c(); } }; // Base class for all operations. A function pointer is used instead of virtual // functions to avoid the associated overhead. class SchedulerOperation_t { protected: using fnFuncType = void ( void*, SchedulerOperation_t* ); friend class OpQueue_T<SchedulerOperation_t>; private: SchedulerOperation_t* m_pNext = nullptr; fnFuncType* m_fnFunc; public: void Complete ( void* pOwner ) noexcept { m_fnFunc ( pOwner, this ); } void Destroy() noexcept { m_fnFunc ( nullptr, this ); } protected: // protect ctr and dtr of this type explicit SchedulerOperation_t ( fnFuncType* fnFunc ) : m_fnFunc ( fnFunc ) {} ~SchedulerOperation_t() = default; // protected d-tr }; // actual operation which completes given Handler template<typename Handler> class CompletionHandler_c: public SchedulerOperation_t { Handler m_Handler; public: explicit CompletionHandler_c ( Handler h ) : SchedulerOperation_t ( &CompletionHandler_c::DoComplete ) , m_Handler ( static_cast<const Handler&> ( h ) ) // force copying {} static void DoComplete ( void* pOwner, SchedulerOperation_t* pBase ) noexcept { // Take ownership of the handler object. auto* pHandler = static_cast<CompletionHandler_c*> ( pBase ); // make a copy of handler before upcall. Handler dLocalHandler ( static_cast<const Handler&> ( pHandler->m_Handler ) ); // deallocate before the upcall SafeDelete ( pHandler ); // Make the upcall if required. if ( pOwner ) { Threads::JobTracker_t dTrack; dLocalHandler(); // barrier ensures that no operations till here would be reordered below. std::atomic_thread_fence ( std::memory_order_release ); } } }; template<typename HANDLER> Threads::details::SchedulerOperation_t* Handler2Op ( HANDLER handler ) noexcept { return new Threads::details::CompletionHandler_c<HANDLER> ( std::move ( handler ) ); } }} template<typename HANDLER> void Threads::Scheduler_i::Schedule ( HANDLER handler, bool bVip ) noexcept { ScheduleOp ( Threads::details::Handler2Op ( std::move ( handler ) ), bVip ); } template<typename HANDLER> void Threads::Scheduler_i::ScheduleContinuation ( HANDLER handler ) noexcept { ScheduleContinuationOp ( Threads::details::Handler2Op ( std::move ( handler ) ) ); } #endif //MANTICORE_THREADUTILS_INC
6,055
C++
.h
235
23.106383
85
0.697803
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,104
sphinxudf.h
manticoresoftware_manticoresearch/src/sphinxudf.h
// // Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com) // Copyright (c) 2011-2016, Andrew Aksyonoff // Copyright (c) 2011-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/ // // // Sphinx plugin interface header // // This file will be included by plugin implementations, so it should be // portable plain C, stay standalone, and change as rarely as possible. // // Refer to src/udfexample.c for a working UDF example, and refer to // docs/exdending.rst for more information on writing // plugins and UDFs. // #ifndef _sphinxudf_ #define _sphinxudf_ #ifdef __cplusplus extern "C" { #endif /// current udf version #define SPH_UDF_VERSION 11 /// error buffer size #define SPH_UDF_ERROR_LEN 256 ////////////////////////////////////////////////////////////////////////// // UDF PLUGINS ////////////////////////////////////////////////////////////////////////// /// UDF argument and result value types enum sphinx_udf_argtype { SPH_UDF_TYPE_UINT32 = 1, ///< unsigned 32-bit integer SPH_UDF_TYPE_UINT32SET = 2, ///< sorted set of unsigned 32-bit integers SPH_UDF_TYPE_INT64 = 3, ///< signed 64-bit integer SPH_UDF_TYPE_FLOAT = 4, ///< single-precision IEEE 754 float SPH_UDF_TYPE_STRING = 5, ///< non-ASCIIZ string, with a separately stored length SPH_UDF_TYPE_INT64SET = 6, ///< sorted set of signed 64-bit integers SPH_UDF_TYPE_FACTORS = 7, ///< packed ranking factors SPH_UDF_TYPE_JSON = 8 ///< whole json or particular field as a string }; /// our malloc() replacement type /// results that are returned to searchd MUST be allocated using this replacement typedef void * sphinx_malloc_fn ( int ); /// message callback /// if plugin implements LIBRARYNAME_setlogcb, it will be invoked just after /// version checking and populated with valid pointer to callback. /// plugin then may invoke cb and it will write provided message into searchd.log /// message might be either with provided len, either asciiz, /// in the case 2-nd param must be set to -1 typedef void sphinx_log_fn ( const char*, int ); /// UDF call arguments typedef struct st_sphinx_udf_args { int arg_count; ///< number of arguments enum sphinx_udf_argtype * arg_types; ///< argument types char ** arg_values; ///< argument values (strings are not (!) ASCIIZ; see str_lengths below) char ** arg_names; ///< argument names (ASCIIZ argname in 'expr AS argname' case; NULL otherwise) int * str_lengths; ///< string argument lengths, or N of MVA values sphinx_malloc_fn * fn_malloc; ///< malloc() replacement to allocate returned values } SPH_UDF_ARGS; /// fixme! arg_names field above are actually never set and always contains null /// UDF initialization typedef struct st_sphinx_udf_init { void * func_data; ///< function data (will be passed to calls, deinit) char is_const; ///< whether a function returns a constant } SPH_UDF_INIT; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wlanguage-extension-token" #endif /// integer return types #if defined(_MSC_VER) || defined(__WIN__) typedef __int64 sphinx_int64_t; typedef unsigned __int64 sphinx_uint64_t; #else typedef long long sphinx_int64_t; typedef unsigned long long sphinx_uint64_t; #endif #ifdef __clang__ #pragma clang diagnostic pop #endif ////////////////////////////////////////////////////////////////////////// /// ranking factors interface, v1 /// functions that unpack PACKEDFACTORS() blob into a few helper C structures /// slower because of malloc()s and copying, but easier to use /// unpacked representation of all the field-level ranking factors typedef struct st_sphinx_field_factors { unsigned int hit_count; unsigned int id; unsigned int lcs; unsigned int word_count; float tf_idf; float min_idf; float max_idf; float sum_idf; int min_hit_pos; int min_best_span_pos; char exact_hit; int max_window_hits; int min_gaps; ///< added in v.3 char exact_order; ///< added in v.4 float atc; ///< added in v.4 int lccs; ///< added in v.5 float wlccs; ///< added in v.5 } SPH_UDF_FIELD_FACTORS; /// unpacked representation of all the term-level ranking factors typedef struct st_sphinx_term_factors { unsigned int keyword_mask; unsigned int id; int tf; float idf; } SPH_UDF_TERM_FACTORS; /// unpacked representation of all the ranking factors (document, field, and term-level) typedef struct st_sphinx_factors { int doc_bm25; float doc_bm25a; unsigned int matched_fields; int doc_word_count; int num_fields; int max_uniq_qpos; SPH_UDF_FIELD_FACTORS * field; SPH_UDF_TERM_FACTORS * term; int * field_tf; } SPH_UDF_FACTORS; /// helper function that must be called to initialize the SPH_UDF_FACTORS structure /// before it is passed to sphinx_factors_unpack /// returns 0 on success /// returns an error code on error int sphinx_factors_init ( SPH_UDF_FACTORS * out ); /// helper function that unpacks PACKEDFACTORS() blob into SPH_UDF_FACTORS structure /// MUST be in sync with PackFactors() method in sphinxsearch.cpp /// returns 0 on success /// returns an error code on error int sphinx_factors_unpack ( const unsigned int * in, SPH_UDF_FACTORS * out ); /// helper function that must be called to free the memory allocated by the sphinx_factors_unpack /// function call /// returns 0 on success /// returns an error code on error int sphinx_factors_deinit ( SPH_UDF_FACTORS * out ); ////////////////////////////////////////////////////////////////////////// /// ranking factors interface, v2 /// functions that access factor values directly in the PACKEDFACTORS() blob /// /// faster, as no memory allocations are guaranteed, but type-punned /// meaning that you have to call a proper get_xxx_factor_int() or xxx_float() variant /// the accessor functions themselves will NOT perform any type checking or conversions /// or in other words, sphinx_get_field_factor_int() on a float factor like min_idf is legal, /// but returns "garbage" (floating value from the blob reinterpreted as an integer) enum sphinx_doc_factor { SPH_DOCF_BM25 = 1, ///< int SPH_DOCF_BM25A = 2, ///< float SPH_DOCF_MATCHED_FIELDS = 3, ///< unsigned int SPH_DOCF_DOC_WORD_COUNT = 4, ///< int SPH_DOCF_NUM_FIELDS = 5, ///< int SPH_DOCF_MAX_UNIQ_QPOS = 6, ///< int SPH_DOCF_EXACT_HIT_MASK = 7, ///< unsigned int SPH_DOCF_EXACT_ORDER_MASK = 8 ///< v.4, unsigned int }; enum sphinx_field_factor { SPH_FIELDF_HIT_COUNT = 1, ///< unsigned int SPH_FIELDF_LCS = 2, ///< unsigned int SPH_FIELDF_WORD_COUNT = 3, ///< unsigned int SPH_FIELDF_TF_IDF = 4, ///< float SPH_FIELDF_MIN_IDF = 5, ///< float SPH_FIELDF_MAX_IDF = 6, ///< float SPH_FIELDF_SUM_IDF = 7, ///< float SPH_FIELDF_MIN_HIT_POS = 8, ///< int SPH_FIELDF_MIN_BEST_SPAN_POS = 9, ///< int SPH_FIELDF_MAX_WINDOW_HITS = 10, ///< int SPH_FIELDF_MIN_GAPS = 11, ///< v.3, int SPH_FIELDF_ATC = 12, ///< v.4, float SPH_FIELDF_LCCS = 13, ///< v.5, int SPH_FIELDF_WLCCS = 14 ///< v.5, float }; enum sphinx_term_factor { SPH_TERMF_KEYWORD_MASK = 1, ///< unsigned int SPH_TERMF_TF = 2, ///< int SPH_TERMF_IDF = 3 ///< float }; /// returns a pointer to the field factors, or NULL for a non-matched field index const unsigned int * sphinx_get_field_factors ( const unsigned int * in, int field ); /// returns a pointer to the term factors, or NULL for a non-matched field index const unsigned int * sphinx_get_term_factors ( const unsigned int * in, int term ); /// returns a document factor value, interpreted as integer int sphinx_get_doc_factor_int ( const unsigned int * in, enum sphinx_doc_factor f ); /// returns a document factor value, interpreted as float float sphinx_get_doc_factor_float ( const unsigned int * in, enum sphinx_doc_factor f ); /// returns a field factor value, interpreted as integer int sphinx_get_field_factor_int ( const unsigned int * in, enum sphinx_field_factor f ); /// returns a field factor value, interpreted as float float sphinx_get_field_factor_float ( const unsigned int * in, enum sphinx_field_factor f ); /// returns a term factor value, interpreted as integer int sphinx_get_term_factor_int ( const unsigned int * in, enum sphinx_term_factor f ); /// returns a term factor value, interpreted as float float sphinx_get_term_factor_float ( const unsigned int * in, enum sphinx_term_factor f ); /// returns a pointer to document factor value, interpreted as vector of integers const unsigned int * sphinx_get_doc_factor_ptr ( const unsigned int * in, enum sphinx_doc_factor f ); ////////////////////////////////////////////////////////////////////////// // RANKER PLUGINS ////////////////////////////////////////////////////////////////////////// /// ranker plugin intialization info typedef struct st_plugin_rankerinfo { int num_field_weights; int * field_weights; const char * options; unsigned int payload_mask; int num_query_words; int max_qpos; } SPH_RANKER_INIT; /// a structure that represents a hit typedef struct st_plugin_hit { sphinx_uint64_t doc_id; unsigned int hit_pos; unsigned short query_pos; unsigned short node_pos; unsigned short span_length; unsigned short match_length; unsigned int weight; unsigned int query_pos_mask; } SPH_RANKER_HIT; #ifdef __cplusplus } #endif #endif // _sphinxudf_
9,699
C++
.h
238
39.214286
104
0.685921
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,105
sorterprecalc.h
manticoresoftware_manticoresearch/src/sorterprecalc.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 "queuecreator.h" class ISphMatchComparator; ISphMatchSorter * CreatePrecalcSorter ( const PrecalculatedSorterResults_t & tPrecalc, const CSphGroupSorterSettings & tSettings );
677
C++
.h
15
43.933333
131
0.778452
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,106
tasksavestate.h
manticoresoftware_manticoresearch/src/tasksavestate.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/ // /// @file tasksavestate.h /// On-demand save sphinxql state and user variables #ifndef MANTICORE_TASKSAVESTATE_H #define MANTICORE_TASKSAVESTATE_H #include "sphinxint.h" ////////////////////////////////////////////////////////////////////////// /// available uservar types enum Uservar_e { USERVAR_INT_SET, USERVAR_INT_SET_TMP, // this one is not stored in state }; /// uservar name to value binding struct Uservar_t { Uservar_e m_eType { USERVAR_INT_SET }; UservarIntSet_c m_pVal; }; // create or update the variable void SetLocalUserVar ( const CSphString& sName, CSphVector<SphAttr_t>& dSetValues ); void SetLocalTemporaryUserVar ( const CSphString & sName, VecTraits_T<DocID_t> dSetValues ); // provide variable to outside void ServeUserVars(); void SphinxqlStateFlush (); bool InitSphinxqlState ( CSphString dStateFilePath, CSphString& sError); using NamedRefVectorPair_t = std::pair<CSphString, Uservar_t>; using UservarFn = std::function<void ( const NamedRefVectorPair_t & )>; void IterateUservars ( UservarFn&& fnSample ); #endif //MANTICORE_TASKSAVESTATE_H
1,557
C++
.h
40
37.575
92
0.736563
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,107
snippetstream.h
manticoresoftware_manticoresearch/src/snippetstream.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 _snippetstream_ #define _snippetstream_ #include "snippetfunctor.h" class CacheStreamer_i { public: virtual ~CacheStreamer_i() {} virtual void StoreToken ( const TokenInfo_t & tTok, int iTermIndex ) = 0; virtual void StoreOverlap ( int iStart, int iLen, int iBoundary ) = 0; virtual void StoreSkipHtml ( int iStart, int iLen ) = 0; virtual void StoreSPZ ( BYTE iSPZ, DWORD uPosition, const char *, int iZone ) = 0; virtual void StoreTail ( int iStart, int iLen, int iBoundary ) = 0; virtual void SetZoneInfo ( const FunctorZoneInfo_t & tZoneInfo ) = 0; virtual void Tokenize ( TokenFunctor_i & tFunctor ) = 0; virtual bool IsEmpty() const = 0; }; CacheStreamer_i * CreateCacheStreamer ( int iDocLen ); void TokenizeDocument ( HitCollector_i & tFunctor, const CSphHTMLStripper * pStripper, DWORD iSPZ ); #endif // _snippetstream_
1,337
C++
.h
30
42.933333
103
0.746338
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,108
jieba.h
manticoresoftware_manticoresearch/src/jieba.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 "indexsettings.h" #if WITH_JIEBA bool CheckConfigJieba ( CSphIndexSettings & tSettings, CSphString & sError ); bool StrToJiebaMode ( JiebaMode_e & eMode, const CSphString & sValue, CSphString & sError ); bool SpawnFilterJieba ( std::unique_ptr<ISphFieldFilter> & pFieldFilter, const CSphIndexSettings & tSettings, const CSphTokenizerSettings & tTokSettings, const char * szIndex, FilenameBuilder_i * pFilenameBuilder, CSphString & sError ); #else inline bool CheckConfigJieba ( CSphIndexSettings & tSettings, CSphString & sError ) { if ( tSettings.m_ePreprocessor==Preprocessor_e::JIEBA ) { tSettings.m_ePreprocessor = Preprocessor_e::NONE; sError.SetSprintf ( "Jieba options specified, but no Jieba support compiled; ignoring" ); return false; } return true; } inline bool SpawnFilterJieba ( std::unique_ptr<ISphFieldFilter> &, const CSphIndexSettings &, const CSphTokenizerSettings &, const char *, CSphString & ) { return true; } #endif
1,359
C++
.h
32
40.75
236
0.773728
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,109
sphinxql_extra.h
manticoresoftware_manticoresearch/src/sphinxql_extra.h
// // Copyright (c) 2021-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 "searchdsql.h" ParseResult_e ParseExtra ( Str_t sQuery, CSphVector<SqlStmt_t>& dStmt, CSphString& sError );
608
C++
.h
14
42.285714
92
0.755068
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,110
index_rotator.h
manticoresoftware_manticoresearch/src/index_rotator.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 "searchdaemon.h" enum class RotateFrom_e : BYTE { NONE, NEW, // move index from idx.new.ext into idx.ext REENABLE, // just load the index NEW_AND_OLD, }; class CheckIndexRotate_c { RotateFrom_e m_eRotateFrom; public: enum eCheckLink { CheckLink }; explicit CheckIndexRotate_c ( const ServedDesc_t& tServed ); explicit CheckIndexRotate_c ( const CSphString& tPath ); CheckIndexRotate_c ( const CSphString & tPath, eCheckLink ); CheckIndexRotate_c ( const ServedDesc_t & tServed, eCheckLink ); bool NothingToRotate() const noexcept; bool RotateFromNew() const noexcept; bool RotateReenable() const noexcept; inline operator RotateFrom_e() const noexcept { return m_eRotateFrom; } }; class StepAction_c { public: virtual bool Action() = 0; virtual bool Rollback() = 0; virtual ~StepAction_c() = default; }; using StepActionPtr_c = std::unique_ptr<StepAction_c>; StepActionPtr_c RenameIdx ( CSphIndex* pIdx, const CSphString& sTo ); StepActionPtr_c RenameIdxSuffix ( const cServedIndexRefPtr_c& pIdx, const char* szToExt ); class IndexFiles_c; StepActionPtr_c RenameFiles ( IndexFiles_c& tFiles, const char* szFromExt, const char* szToExt ); class ActionSequence_c: public ISphNoncopyable { CSphSwapVector<StepActionPtr_c> m_dActions; std::pair<CSphString, bool> m_tError; int m_iRun = 0; public: void Defer ( StepActionPtr_c&& pAction ); bool RunDefers(); bool UnRunDefers(); std::pair<CSphString, bool> GetError() const; };
1,954
C++
.h
55
33.872727
97
0.766296
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,111
dynamic_idx.h
manticoresoftware_manticoresearch/src/dynamic_idx.h
// // Copyright (c) 2020, 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 "searchdaemon.h" // generator, should feed given RowBuffer_i with table data (i.e., first header, then data rows) using TableFeeder_fn = std::function<void ( RowBuffer_i* )>; // serve any generic table of columns as index with possibility to filter (full-scan) ServedIndexRefPtr_c MakeDynamicIndex ( TableFeeder_fn fnFeed ); // schema of any generic table of columns as index with possibility to filter (full-scan) ServedIndexRefPtr_c MakeDynamicIndexSchema ( TableFeeder_fn fnFeed );
984
C++
.h
19
50.473684
96
0.769552
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,112
sphinxquery.h
manticoresoftware_manticoresearch/src/sphinxquery.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 _sphinxquery_ #define _sphinxquery_ #include "sphinxstd.h" #include "sphinx.h" ////////////////////////////////////////////////////////////////////////////// /// extended query word with attached position within atom struct XQKeyword_t { CSphString m_sWord; int m_iAtomPos = -1; int m_iSkippedBefore = 0; ///< positions skipped before this token (because of blended chars) bool m_bFieldStart = false; ///< must occur at very start bool m_bFieldEnd = false; ///< must occur at very end float m_fBoost = 1.0f; ///< keyword IDF will be multiplied by this bool m_bExpanded = false; ///< added by prefix expansion bool m_bExcluded = false; ///< excluded by query (rval to operator NOT) bool m_bMorphed = false; ///< morphology processing (wordforms, stemming etc) already done void * m_pPayload = nullptr; bool m_bRegex = false; XQKeyword_t() = default; XQKeyword_t ( const char * sWord, int iPos ) : m_sWord ( sWord ) , m_iAtomPos ( iPos ) {} }; /// extended query operator enum XQOperator_e { SPH_QUERY_AND, SPH_QUERY_OR, SPH_QUERY_MAYBE, SPH_QUERY_NOT, SPH_QUERY_ANDNOT, SPH_QUERY_BEFORE, SPH_QUERY_PHRASE, SPH_QUERY_PROXIMITY, SPH_QUERY_QUORUM, SPH_QUERY_NEAR, SPH_QUERY_NOTNEAR, SPH_QUERY_SENTENCE, SPH_QUERY_PARAGRAPH, SPH_QUERY_NULL, SPH_QUERY_SCAN, SPH_QUERY_TOTAL }; // the limit of field or zone or zonespan struct XQLimitSpec_t { bool m_bFieldSpec = false; ///< whether field spec was already explicitly set FieldMask_t m_dFieldMask; ///< fields mask (spec part) int m_iFieldMaxPos = 0; ///< max position within field (spec part) CSphVector<int> m_dZones; ///< zone indexes in per-query zones list bool m_bZoneSpan = false; ///< if we need to hits within only one span public: XQLimitSpec_t () { m_dFieldMask.SetAll (); } inline void Reset () { m_bFieldSpec = false; m_iFieldMaxPos = 0; m_bZoneSpan = false; m_dFieldMask.SetAll(); m_dZones.Reset(); } bool IsEmpty() const { return !m_bFieldSpec && m_iFieldMaxPos==0 && !m_bZoneSpan && m_dZones.GetLength()==0; } XQLimitSpec_t ( const XQLimitSpec_t& dLimit ) { if ( dLimit.m_bFieldSpec ) SetFieldSpec ( dLimit.m_dFieldMask, dLimit.m_iFieldMaxPos ); else m_dFieldMask.SetAll (); if ( !dLimit.m_dZones.IsEmpty ()) SetZoneSpec ( dLimit.m_dZones, dLimit.m_bZoneSpan ); } XQLimitSpec_t ( XQLimitSpec_t&& rhs ) noexcept : XQLimitSpec_t () { Swap ( rhs ); } void Swap ( XQLimitSpec_t& rhs ) noexcept { ::Swap ( m_bFieldSpec, rhs.m_bFieldSpec ); ::Swap ( m_dFieldMask, rhs.m_dFieldMask ); ::Swap ( m_iFieldMaxPos, rhs.m_iFieldMaxPos ); ::Swap ( m_dZones, rhs.m_dZones ); ::Swap ( m_bZoneSpan, rhs.m_bZoneSpan ); } XQLimitSpec_t & operator = ( XQLimitSpec_t dLimit ) { Swap ( dLimit ); return *this; } public: void SetZoneSpec ( const CSphVector<int> & dZones, bool bZoneSpan ); void SetFieldSpec ( const FieldMask_t& uMask, int iMaxPos ); }; /// extended query node /// plain nodes are just an atom /// non-plain nodes are a logical function over children nodes struct XQNode_t : public ISphNoncopyable { XQNode_t * m_pParent = nullptr; ///< my parent node (NULL for root ones) private: XQOperator_e m_eOp { SPH_QUERY_AND }; ///< operation over childen int m_iOrder = 0; int m_iCounter = 0; private: mutable uint64_t m_iMagicHash = 0; mutable uint64_t m_iFuzzyHash = 0; public: CSphVector<XQNode_t*> m_dChildren; ///< non-plain node children XQLimitSpec_t m_dSpec; ///< specification by field, zone(s), etc. CSphVector<XQKeyword_t> m_dWords; ///< query words (plain node) int m_iOpArg = 0; ///< operator argument (proximity distance, quorum count) int m_iAtomPos = -1; ///< atom position override (currently only used within expanded nodes) int m_iUser = 0; bool m_bVirtuallyPlain = false; ///< "virtually plain" flag (currently only used by expanded nodes) bool m_bNotWeighted = false; ///< this our expanded but empty word's node bool m_bPercentOp = false; public: /// ctor explicit XQNode_t ( const XQLimitSpec_t & dSpec ); /// dtor ~XQNode_t (); /// check if i'm empty bool IsEmpty () const { assert ( m_dWords.GetLength()==0 || m_dChildren.GetLength()==0 ); return m_dWords.GetLength()==0 && m_dChildren.GetLength()==0; } /// setup field limits void SetFieldSpec ( const FieldMask_t& uMask, int iMaxPos ); /// setup zone limits void SetZoneSpec ( const CSphVector<int> & dZones, bool bZoneSpan=false ); /// copy field/zone limits from another node void CopySpecs ( const XQNode_t * pSpecs ); /// unconditionally clear field mask void ClearFieldMask (); public: /// get my operator XQOperator_e GetOp () const { return m_eOp; } /// get my cache order DWORD GetOrder () const { return m_iOrder; } /// get my cache counter int GetCount () const { return m_iCounter; } /// setup common nodes for caching void TagAsCommon ( int iOrder, int iCounter ) { m_iCounter = iCounter; m_iOrder = iOrder; } /// hash me uint64_t GetHash () const; /// fuzzy hash ( a hash value is equal for proximity and phrase nodes /// with similar keywords ) uint64_t GetFuzzyHash () const; /// setup new operator and args void SetOp ( XQOperator_e eOp, XQNode_t * pArg1, XQNode_t * pArg2=NULL ); /// setup new operator and args void SetOp ( XQOperator_e eOp, CSphVector<XQNode_t*> & dArgs ) { m_eOp = eOp; m_dChildren.SwapData(dArgs); ARRAY_FOREACH ( i, m_dChildren ) m_dChildren[i]->m_pParent = this; } /// setup new operator (careful parser/transform use only) void SetOp ( XQOperator_e eOp ) { m_eOp = eOp; } /// fixup atom positions in case of proximity queries and blended chars /// we need to handle tokens with blended characters as simple tokens in this case /// and we need to remove possible gaps in atom positions int FixupAtomPos(); /// return node like current inline XQNode_t * Clone (); /// force resetting magic hash value ( that changed after transformation ) inline bool ResetHash (); #ifndef NDEBUG /// consistency check void Check ( bool bRoot ) { assert ( bRoot || !IsEmpty() || m_eOp==SPH_QUERY_SCAN ); // empty leaves must be removed from the final tree; empty root is allowed assert (!( m_dWords.GetLength() && m_eOp!=SPH_QUERY_AND && m_eOp!=SPH_QUERY_OR && m_eOp!=SPH_QUERY_PHRASE && m_eOp!=SPH_QUERY_PROXIMITY && m_eOp!=SPH_QUERY_QUORUM )); // words are only allowed in these node types assert ( ( m_dWords.GetLength()==1 && ( m_eOp==SPH_QUERY_AND || m_eOp==SPH_QUERY_OR ) ) || m_dWords.GetLength()!=1 ); // 1-word leaves must be of AND | OR ARRAY_FOREACH ( i, m_dChildren ) { assert ( m_dChildren[i]->m_pParent==this ); m_dChildren[i]->Check ( false ); } } #else void Check ( bool ) {} #endif }; /// extended query struct XQQuery_t : public ISphNoncopyable { CSphString m_sParseError; CSphString m_sParseWarning; StrVec_t m_dZones; XQNode_t * m_pRoot = nullptr; bool m_bNeedSZlist = false; bool m_bSingleWord = false; bool m_bEmpty = false; /// dtor ~XQQuery_t () { SafeDelete ( m_pRoot ); } }; struct NodeEstimate_t { float m_fCost = 0.0f; int64_t m_iDocs = 0; int64_t m_iTerms = 0; NodeEstimate_t & operator+= ( const NodeEstimate_t & tRhs ); }; class QueryParser_i { public: virtual ~QueryParser_i() = default; virtual bool IsFullscan ( const CSphQuery & tQuery ) const { return tQuery.m_sQuery.IsEmpty(); }; virtual bool IsFullscan ( const XQQuery_t & tQuery ) const = 0; virtual bool ParseQuery ( XQQuery_t & tParsed, const char * sQuery, const CSphQuery * pQuery, TokenizerRefPtr_c pQueryTokenizer, TokenizerRefPtr_c pQueryTokenizerJson, const CSphSchema * pSchema, const DictRefPtr_c& pDict, const CSphIndexSettings & tSettings, const CSphBitvec * pMorphFields ) const = 0; virtual QueryParser_i * Clone() const = 0; }; class PluginQueryTokenFilter_c; using PluginQueryTokenRefPtr_c = CSphRefcountedPtr<PluginQueryTokenFilter_c>; class XQParseHelper_c { public: virtual ~XQParseHelper_c() = default; void SetString ( const char * szString ); bool AddField ( FieldMask_t & dFields, const char * szField, int iLen ); bool ParseFields ( FieldMask_t & dFields, int & iMaxFieldPos, bool & bIgnore ); void Setup ( const CSphSchema * pSchema, TokenizerRefPtr_c pTokenizer, DictRefPtr_c pDict, XQQuery_t * pXQQuery, const CSphIndexSettings & tSettings ); bool Error ( const char * sTemplate, ... ) __attribute__ ( ( format ( printf, 2, 3 ) ) ); void Warning ( const char * sTemplate, ... ) __attribute__ ( ( format ( printf, 2, 3 ) ) ); XQNode_t * FixupTree ( XQNode_t * pRoot, const XQLimitSpec_t & tLimitSpec, const CSphBitvec * pMorphFields, bool bOnlyNotAllowed ); const CSphSchema * GetSchema() const { return m_pSchema; } DictRefPtr_c& GetDict() { return m_pDict; } bool IsError() { return m_bError; } virtual void Cleanup(); void SetZone ( const StrVec_t & dZones ); const StrVec_t & GetZone() const; protected: struct MultiformNode_t { XQNode_t * m_pNode; int m_iDestStart; int m_iDestCount; }; static const int MAX_TOKEN_BYTES = 3*SPH_MAX_WORD_LEN + 16; const CSphSchema * m_pSchema {nullptr}; TokenizerRefPtr_c m_pTokenizer; DictRefPtr_c m_pDict; bool m_bStopOnInvalid {true}; XQQuery_t * m_pParsed {nullptr}; bool m_bError {false}; PluginQueryTokenRefPtr_c m_pPlugin; void * m_pPluginData {nullptr}; int m_iAtomPos {0}; bool m_bEmptyStopword {false}; bool m_bWasBlended {false}; CSphVector<XQNode_t*> m_dSpawned; StrVec_t m_dDestForms; CSphVector<MultiformNode_t> m_dMultiforms; virtual bool HandleFieldBlockStart ( const char * & pPtr ) = 0; virtual bool HandleSpecialFields ( const char * & /*pPtr*/, FieldMask_t & /*dFields*/ ) { return false; } virtual bool NeedTrailingSeparator() { return true; } private: XQNode_t * SweepNulls ( XQNode_t * pNode, bool bOnlyNotAllowed ); bool FixupNots ( XQNode_t * pNode, bool bOnlyNotAllowed, XQNode_t ** ppRoot ); void FixupNulls ( XQNode_t * pNode ); void DeleteNodesWOFields ( XQNode_t * pNode ); void FixupDestForms(); bool CheckQuorumProximity ( XQNode_t * pNode ); }; ////////////////////////////////////////////////////////////////////////////// /// setup tokenizer for query parsing (ie. add all specials and whatnot) TokenizerRefPtr_c sphCloneAndSetupQueryTokenizer ( const TokenizerRefPtr_c& pTokenizer, bool bWildcards, bool bExact, bool bJson ); // a wrapper for sphParseExtendedQuery std::unique_ptr<QueryParser_i> sphCreatePlainQueryParser(); /// parses the query and returns the resulting tree /// return false and fills tQuery.m_sParseError on error /// WARNING, parsed tree might be NULL (eg. if query was empty) /// lots of arguments here instead of simply the index pointer, because /// a) we do not always have an actual real index class, and /// b) might need to tweak stuff even we do /// FIXME! remove either pQuery or sQuery bool sphParseExtendedQuery ( XQQuery_t & tQuery, const char * sQuery, const CSphQuery * pQuery, const TokenizerRefPtr_c& pTokenizer, const CSphSchema * pSchema, const DictRefPtr_c& pDict, const CSphIndexSettings & tSettings, const CSphBitvec * pMorphFields ); // perform boolean optimization on tree void sphOptimizeBoolean ( XQNode_t ** pXQ, const ISphKeywordsStat * pKeywords ); /// analyze vector of trees and tag common parts of them (to cache them later) int sphMarkCommonSubtrees ( int iXQ, const XQQuery_t * pXQ ); XQQuery_t * CloneXQQuery ( const XQQuery_t & tQuery ); /// whatever to allow alone operator NOT at query void AllowOnlyNot ( bool bAllowed ); bool IsAllowOnlyNot(); CSphString sphReconstructNode ( const XQNode_t * pNode, const CSphSchema * pSchema ); int GetExpansionLimit ( int iQueryLimit, int iIndexLimit ); #endif // _sphinxquery_
12,388
C++
.h
331
35.265861
305
0.702547
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,113
chunksearchctx.h
manticoresoftware_manticoresearch/src/chunksearchctx.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 "sphinx.h" struct DiskChunkSearcherCtx_t { using Sorters_t = VecTraits_T<ISphMatchSorter *>; Sorters_t & m_dSorters; CSphQueryResultMeta & m_tMeta; DiskChunkSearcherCtx_t ( Sorters_t & dSorters, CSphQueryResultMeta & tMeta ); // called from finalize void MergeChild ( DiskChunkSearcherCtx_t tChild ) const; bool IsClonable () const; }; struct DiskChunkSearcherCloneCtx_t { CSphVector<ISphMatchSorter *> m_dSorters; CSphQueryResultMeta m_tMeta; explicit DiskChunkSearcherCloneCtx_t ( const DiskChunkSearcherCtx_t & dParent ); ~DiskChunkSearcherCloneCtx_t(); explicit operator DiskChunkSearcherCtx_t(); };
1,133
C++
.h
31
34.741935
81
0.773602
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,114
netfetch.h
manticoresoftware_manticoresearch/src/netfetch.h
// // Copyright (c) 2022-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 "std/string.h" CSphString FetchUrl ( const CSphString& sUrl ); std::pair<bool, CSphString> PostToHelperUrl ( CSphString sUrl, Str_t sQuery, const VecTraits_T<CSphString>& dHeaders ); void ShutdownCurl(); bool IsCurlAvailable();
633
C++
.h
15
40.866667
119
0.763458
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,115
sphinxstem.h
manticoresoftware_manticoresearch/src/sphinxstem.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 _sphinxstem_ #define _sphinxstem_ #include "sphinxstd.h" class ISphTokenizer; using TokenizerRefPtr_c = CSphRefcountedPtr<ISphTokenizer>; class CSphDict; using DictRefPtr_c = CSphRefcountedPtr<CSphDict>; /// initialize English stemmer void stem_en_init (); /// initialize Russian stemmer void stem_ru_init (); /// stem lowercase English word void stem_en ( BYTE * pWord, int iLen ); /// stem lowercase Russian word in Windows-1251 encoding void stem_ru_cp1251 ( BYTE * pWord ); /// stem lowercase Russian word in UTF-8 encoding void stem_ru_utf8 ( WORD * pWord ); /// initialize Czech stemmer void stem_cz_init (); /// stem lowercase Czech word void stem_cz ( BYTE * pWord ); /// stem Arabic word in UTF-8 encoding void stem_ar_utf8 ( BYTE * word ); /// calculate soundex in-place if the word is lowercase English letters only; /// do nothing if it's not void stem_soundex ( BYTE * pWord ); /// double metaphone stemmer void stem_dmetaphone ( BYTE * pWord ); /// pre-init AOT setup, cache size (in bytes) void sphAotSetCacheSize ( int iCacheSize ); // simple order aot languages enum AOT_LANGS {AOT_BEGIN=0, AOT_RU=AOT_BEGIN, AOT_EN, AOT_DE, AOT_UK, AOT_LENGTH}; // aot lemmatize names extern const char* AOT_LANGUAGES [AOT_LENGTH]; /// init AOT lemmatizer bool sphAotInit ( const CSphString & sDictFile, CSphString & sError, int iLang ); // functions below by design used in indexing time /// lemmatize (or guess a normal form) a Russian word in Windows-1251 encoding void sphAotLemmatizeRu1251 ( BYTE * pWord, int iLen ); /// lemmatize (or guess a normal form) a Russian word in UTF-8 encoding, return a single "best" lemma void sphAotLemmatizeRuUTF8 ( BYTE * pWord ); /// lemmatize (or guess a normal form) a German word in Windows-1252 encoding void sphAotLemmatizeDe1252 ( BYTE * pWord, int iLen ); /// lemmatize (or guess a normal form) a German word in UTF-8 encoding, return a single "best" lemma void sphAotLemmatizeDeUTF8 ( BYTE * pWord ); /// lemmatize (or guess a normal form) a word in single-byte ASCII encoding, return a single "best" lemma void sphAotLemmatize ( BYTE * pWord, int iLang ); // functions below by design used in search time /// lemmatize (or guess a normal form) a Russian word, return all lemmas void sphAotLemmatizeRu ( StrVec_t & dLemmas, const BYTE * pWord ); void sphAotLemmatizeDe ( StrVec_t & dLemmas, const BYTE * pWord ); void sphAotLemmatize ( StrVec_t & dLemmas, const BYTE * pWord, int iLang ); /// get lemmatizer dictionary info (file name, crc) const CSphNamedInt & sphAotDictinfo ( int iLang ); /// create token filter that returns all morphological hypotheses /// NOTE, takes over wordforms from pDict, in AOT case they must be handled by the fitler void sphAotTransformFilter ( TokenizerRefPtr_c& pTokenizer, const DictRefPtr_c& pDict, bool bIndexExact, DWORD uLangMask ); /// free lemmatizers on shutdown void sphAotShutdown (); class LemmatizerTrait_i { public: LemmatizerTrait_i() = default; virtual ~LemmatizerTrait_i() {} virtual BYTE * GetToken ( const BYTE * pWord, int & iExtra ) = 0; virtual BYTE * GetExtraToken() = 0; }; /// lemmatize (or guess a normal form) a Ukrainian word in UTF-8 encoding, return a single "best" lemma void sphAotLemmatizeUk ( BYTE * pWord, LemmatizerTrait_i * pLemmatizer ); // functions below by design used in search time /// lemmatize (or guess a normal form) return all lemmas void sphAotLemmatizeUk ( StrVec_t & dLemmas, const BYTE * pWord, LemmatizerTrait_i * pLemmatizer ); std::unique_ptr<LemmatizerTrait_i> CreateLemmatizer ( int iLang ); #endif // _sphinxstem_
4,077
C++
.h
85
46.552941
127
0.755617
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,116
netreceive_ql.h
manticoresoftware_manticoresearch/src/netreceive_ql.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 "networking_daemon.h" void SqlServe ( std::unique_ptr<AsyncNetBuffer_c> pBuf ); RowBuffer_i * CreateSqlRowBuffer ( BYTE * pPacketID, GenericOutputBuffer_c * pOut );
667
C++
.h
15
43.2
84
0.756173
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,117
columnarfilter.h
manticoresoftware_manticoresearch/src/columnarfilter.h
// // Copyright (c) 2020-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/ // #ifndef _columnarfilter_ #define _columnarfilter_ #include "sphinxfilter.h" std::unique_ptr<ISphFilter> TryToCreateColumnarFilter ( int iAttr, const ISphSchema & tSchema, const CSphFilterSettings & tSettings, const CommonFilterSettings_t & tFixedSettings, ESphCollation eCollation, CSphString & sError, CSphString & sWarning ); bool AddColumnarFilter ( std::vector<common::Filter_t> & dDst, const CSphFilterSettings & tSrc, ESphCollation eCollation, const ISphSchema & tSchema, CSphString & sWarning ); bool ToColumnarFilter ( common::Filter_t & tFilter, const CSphFilterSettings & tSrc, ESphCollation eCollation, const ISphSchema & tSchema, CSphString & sWarning ); void ToColumnarFilters ( VecTraits_T<const CSphFilterSettings> & dFilters, std::vector<common::Filter_t> & dColumnarFilters, std::vector<int> & dFilterMap, const ISphSchema & tSchema, ESphCollation eCollation, CSphString & sWarning ); #endif // _columnarfilter_
1,312
C++
.h
17
75.941176
251
0.784663
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,118
datetime.h
manticoresoftware_manticoresearch/src/datetime.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/ // #ifndef _datetime_ #define _datetime_ #include "sphinxstd.h" #include "cctz/civil_time.h" #include "cctz/time_zone.h" enum class TimeUnit_e { SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR }; void InitTimeZones ( StrVec_t & dWarnings ); bool SetTimeZone ( const char * szTZ, CSphString & sError ); bool IsTimeZoneSet(); CSphString GetTimeZoneName(); CSphString GetLocalTimeZoneName(); cctz::civil_second ConvertTime ( time_t tTime ); // use local time zone by default; can be overridden by `timezone` setting cctz::civil_second ConvertTimeLocal ( time_t tTime ); // always use local time zone cctz::civil_second ConvertTimeUTC ( time_t tTime ); // always use UTC time zone time_t ConvertTime ( const cctz::civil_second & tCS ); time_t PackLocalTimeAsUTC ( time_t tTime ); CSphString FormatTime ( time_t tTime, const char * szFmt ); bool ParseAsLocalTime ( const char * szFmt, const CSphString & sTime, time_t & tRes ); int GetWeekDay ( const cctz::civil_second & tTime, bool bSundayFirst ); int GetYearDay ( const cctz::civil_second & tTime ); int GetQuarter ( const cctz::civil_second & tTime ); int CalcNumYearDays ( const cctz::civil_second & tTime ); bool IsLeapYear ( const cctz::civil_second & tTime ); // misc year+month+week combos. used in grouping int CalcYearMonth ( const cctz::civil_second & tTime ); int CalcYearMonthDay ( const cctz::civil_second & tTime ); int CalcYearWeek ( const cctz::civil_second & tTime ); int CalcWeekNumber ( const cctz::civil_second & tTime, uint32_t uFlags ); template<bool UTC> FORCE_INLINE cctz::civil_second ConvertGroupbyTime ( time_t tTime ) { if constexpr ( UTC ) return ConvertTimeUTC(tTime); else return ConvertTime(tTime); } #endif // _datetime_
2,128
C++
.h
56
36.553571
124
0.744299
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,119
sphinxdefs.h
manticoresoftware_manticoresearch/src/sphinxdefs.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/ // // elementary typedefs, enums and inline funcs, project-wide. // Note! No specific non-standard types here, so inclusion of a header should not make circular dependencies #pragma once #include "config.h" #include "sphinxstd.h" using RowID_t = DWORD; const RowID_t INVALID_ROWID = 0xFFFFFFFF; using DocID_t = int64_t; /// row entry (storage only, does not necessarily map 1:1 to attributes) using CSphRowitem = DWORD; #define DOCID_MIN (INT64_MIN) #define WORDID_MAX U64C(0xffffffffffffffff) STATIC_SIZE_ASSERT ( DocID_t, 8 ); STATIC_SIZE_ASSERT ( RowID_t, 4 ); #define DWSIZEOF(a) ( sizeof(a) / sizeof(DWORD) ) ////////////////////////////////////////////////////////////////////////// typedef const BYTE * CSphRowitemPtr; /// widest integer type that can be be stored as an attribute (ideally, fully decoupled from rowitem size!) typedef int64_t SphAttr_t; const CSphRowitem ROWITEM_MAX = UINT_MAX; const int ROWITEM_BITS = 8*sizeof(CSphRowitem); const int ROWITEMPTR_BITS = 8*sizeof(CSphRowitemPtr); const int ROWITEM_SHIFT = 5; STATIC_ASSERT ( ( 1 << ROWITEM_SHIFT )==ROWITEM_BITS, INVALID_ROWITEM_SHIFT ); #ifndef USE_LITTLE_ENDIAN #error Please define endianness #endif ///////////////////////////////////////////////////////////////////////////// #define SPH_MAX_WORD_LEN 42 // so that any UTF-8 word fits 127 bytes #define SPH_MAX_FILENAME_LEN 512 #define SPH_MAX_FIELDS 256 const int MAX_KEYWORD_BYTES = SPH_MAX_WORD_LEN*3+4; ///////////////////////////////////////////////////////////////////////////// int sphUTF8Len ( const char * pStr ); /// check for valid attribute name char inline int sphIsAttr ( int c ) { // different from sphIsAlpha() in that we don't allow minus return ( c>='0' && c<='9' ) || ( c>='a' && c<='z' ) || ( c>='A' && c<='Z' ) || c=='_'; } class CSphDict; using DictRefPtr_c = CSphRefcountedPtr<CSphDict>; ///////////////////////////////////////////////////////////////////////////// // DATASOURCES ///////////////////////////////////////////////////////////////////////////// using SphWordID_t = uint64_t; STATIC_SIZE_ASSERT ( SphWordID_t, 8 ); /// hit position storage type typedef DWORD Hitpos_t; /// empty hit value #define EMPTY_HIT 0 /// hit info struct CSphWordHit { RowID_t m_tRowID; ///< document ID SphWordID_t m_uWordID = WORDID_MAX; ///< word ID in current dictionary Hitpos_t m_uWordPos = EMPTY_HIT; ///< word position in current document CSphWordHit () = default; CSphWordHit ( RowID_t tRowID, SphWordID_t uWordID, Hitpos_t uWordPos ) : m_tRowID { tRowID } , m_uWordID { uWordID } , m_uWordPos { uWordPos } {} }; inline bool operator== ( const CSphWordHit& lhs, const CSphWordHit& rhs ) { return lhs.m_tRowID==rhs.m_tRowID && lhs.m_uWordID==rhs.m_uWordID && lhs.m_uWordPos == rhs.m_uWordPos; } /// hit vector interface /// because specific position type might vary (dword, qword, etc) /// but we don't want to template and instantiate everything because of that using ISphHits = CSphVector<CSphWordHit>; /// field filter class ISphFieldFilter; class ISphTokenizer; using TokenizerRefPtr_c = CSphRefcountedPtr<ISphTokenizer>; ///////////////////////////////////////////////////////////////////////////// // SEARCH QUERIES ///////////////////////////////////////////////////////////////////////////// /// search query sorting orders enum ESphSortOrder { SPH_SORT_RELEVANCE = 0, ///< sort by document relevance desc, then by date SPH_SORT_ATTR_DESC = 1, ///< sort by document date desc, then by relevance desc SPH_SORT_ATTR_ASC = 2, ///< sort by document date asc, then by relevance desc SPH_SORT_TIME_SEGMENTS = 3, ///< sort by time segments (hour/day/week/etc) desc, then by relevance desc SPH_SORT_EXTENDED = 4, ///< sort by SQL-like expression (eg. "@relevance DESC, price ASC, @id DESC") SPH_SORT_EXPR = 5, ///< sort by arithmetic expression in descending order (eg. "@id + max(@weight,1000)*boost + log(price)") SPH_SORT_TOTAL }; /// search query matching mode enum ESphMatchMode { SPH_MATCH_ALL = 0, ///< match all query words SPH_MATCH_ANY, ///< match any query word SPH_MATCH_PHRASE, ///< match this exact phrase SPH_MATCH_BOOLEAN, ///< match this boolean query SPH_MATCH_EXTENDED, ///< match this extended query SPH_MATCH_FULLSCAN, ///< match all document IDs w/o fulltext query, apply filters SPH_MATCH_EXTENDED2, ///< extended engine V2 (TEMPORARY, WILL BE REMOVED IN 0.9.8-RELEASE) SPH_MATCH_TOTAL }; /// search query relevance ranking mode enum ESphRankMode { SPH_RANK_PROXIMITY_BM25 = 0, ///< default mode, phrase proximity major factor and BM25 minor one (aka SPH03) SPH_RANK_BM25 = 1, ///< statistical mode, BM25 ranking only (faster but worse quality) SPH_RANK_NONE = 2, ///< no ranking, all matches get a weight of 1 SPH_RANK_WORDCOUNT = 3, ///< simple word-count weighting, rank is a weighted sum of per-field keyword occurence counts SPH_RANK_PROXIMITY = 4, ///< phrase proximity (aka SPH01) SPH_RANK_MATCHANY = 5, ///< emulate old match-any weighting (aka SPH02) SPH_RANK_FIELDMASK = 6, ///< sets bits where there were matches SPH_RANK_SPH04 = 7, ///< codename SPH04, phrase proximity + bm25 + head/exact boost SPH_RANK_EXPR = 8, ///< rank by user expression (eg. "sum(lcs*user_weight)*1000+bm25") SPH_RANK_EXPORT = 9, ///< rank by BM25, but compute and export all user expression factors SPH_RANK_PLUGIN = 10, ///< user-defined ranker SPH_RANK_TOTAL, SPH_RANK_DEFAULT = SPH_RANK_PROXIMITY_BM25 }; /// known multi-valued attr sources enum ESphAttrSrc { SPH_ATTRSRC_NONE = 0, ///< not multi-valued SPH_ATTRSRC_FIELD = 1, ///< get attr values from text field SPH_ATTRSRC_QUERY = 2, ///< get attr values from SQL query SPH_ATTRSRC_RANGEDQUERY = 3, ///< get attr values from ranged SQL query SPH_ATTRSRC_RANGEDMAINQUERY = 4 ///< get attr values from main ranged SQL query, used for MVA query }; /// aggregate function to apply enum ESphAggrFunc { SPH_AGGR_NONE, SPH_AGGR_AVG, SPH_AGGR_MIN, SPH_AGGR_MAX, SPH_AGGR_SUM, SPH_AGGR_CAT }; /// search query grouping mode enum ESphGroupBy { SPH_GROUPBY_DAY = 0, ///< group by day SPH_GROUPBY_WEEK = 1, ///< group by week SPH_GROUPBY_MONTH = 2, ///< group by month SPH_GROUPBY_YEAR = 3, ///< group by year SPH_GROUPBY_ATTR = 4, ///< group by attribute value SPH_GROUPBY_ATTRPAIR= 5, ///< group by sequential attrs pair (rendered redundant by 64bit attrs support; removed) SPH_GROUPBY_MULTIPLE= 6 ///< group by on multiple attribute values }; /// search query filter types enum ESphFilter { SPH_FILTER_VALUES = 0, ///< filter by integer values set SPH_FILTER_RANGE = 1, ///< filter by integer range SPH_FILTER_FLOATRANGE = 2, ///< filter by float range SPH_FILTER_STRING = 3, ///< filter by string value SPH_FILTER_NULL = 4, ///< filter by NULL SPH_FILTER_USERVAR = 5, ///< filter by @uservar SPH_FILTER_STRING_LIST = 6, ///< filter by string list SPH_FILTER_EXPRESSION = 7 ///< filter by expression }; /// MVA folding function /// (currently used in filters, eg WHERE ALL(mymva) BETWEEN 1 AND 3) enum ESphMvaFunc { SPH_MVAFUNC_NONE = 0, SPH_MVAFUNC_ANY, SPH_MVAFUNC_ALL }; enum QueryType_e { QUERY_API, QUERY_SQL, QUERY_JSON }; enum QueryOption_e { QUERY_OPT_DEFAULT = 0, QUERY_OPT_DISABLED, QUERY_OPT_ENABLED, QUERY_OPT_MORPH_NONE }; /// match sorting functions enum ESphSortFunc { FUNC_REL_DESC, FUNC_TIMESEGS, FUNC_GENERIC1, FUNC_GENERIC2, FUNC_GENERIC3, FUNC_GENERIC4, FUNC_GENERIC5, FUNC_EXPR }; /// match sorting clause parsing outcomes enum ESortClauseParseResult { SORT_CLAUSE_OK, SORT_CLAUSE_ERROR, SORT_CLAUSE_RANDOM }; /// sorting key part types enum ESphSortKeyPart { SPH_KEYPART_ROWID, SPH_KEYPART_WEIGHT, SPH_KEYPART_INT, SPH_KEYPART_FLOAT, SPH_KEYPART_DOUBLE, SPH_KEYPART_STRING, SPH_KEYPART_STRINGPTR }; enum KeywordExpansion_e { KWE_DISABLED = 0, KWE_EXACT = ( 1UL << 0 ), KWE_STAR = ( 1UL << 1 ), KWE_MORPH_NONE = ( 1UL << 2 ), KWE_ENABLED = ( KWE_EXACT | KWE_STAR ), }; enum TypeConversion_e { CONVERSION_NONE, CONVERSION_BIGINT2FLOAT, CONVERSION_FLOAT2BIGINT, }; enum DocstoreDataType_e { DOCSTORE_TEXT, DOCSTORE_BIN, DOCSTORE_ATTR, DOCSTORE_TOTAL }; /// wordpart processing type enum ESphWordpart { SPH_WORDPART_WHOLE = 0, ///< whole-word SPH_WORDPART_PREFIX = 1, ///< prefix SPH_WORDPART_INFIX = 2 ///< infix }; enum class AttrEngine_e { DEFAULT, ROWWISE, COLUMNAR }; using Bson_t = CSphVector<BYTE>; #if UNALIGNED_RAM_ACCESS /// pass-through wrapper template<typename T> inline T sphUnalignedRead ( const T& tRef ) { return tRef; } /// pass-through wrapper template<typename T> void sphUnalignedWrite ( void* pPtr, const T& tVal ) { *(T*)pPtr = tVal; } #else /// unaligned read wrapper for some architectures (eg. SPARC) template<typename T> inline T sphUnalignedRead ( const T& tRef ) { T uTmp; BYTE* pSrc = (BYTE*)&tRef; BYTE* pDst = (BYTE*)&uTmp; for ( int i = 0; i < (int)sizeof ( T ); i++ ) *pDst++ = *pSrc++; return uTmp; } /// unaligned write wrapper for some architectures (eg. SPARC) template<typename T> void sphUnalignedWrite ( void* pPtr, const T& tVal ) { BYTE* pDst = (BYTE*)pPtr; BYTE* pSrc = (BYTE*)&tVal; for ( int i = 0; i < (int)sizeof ( T ); i++ ) *pDst++ = *pSrc++; } #endif // unalgined #if UNALIGNED_RAM_ACCESS && USE_LITTLE_ENDIAN /// get a dword from memory, intel version inline DWORD sphGetDword ( const BYTE* p ) { return *(const DWORD*)p; } #else /// get a dword from memory, non-intel version inline DWORD sphGetDword ( const BYTE* p ) { return p[0] + ( p[1] << 8 ) + ( p[2] << 16 ) + ( p[3] << 24 ); } #endif
10,149
C++
.h
304
31.723684
127
0.678568
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,120
grouper.h
manticoresoftware_manticoresearch/src/grouper.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 _grouper_ #define _grouper_ #include "sortsetup.h" namespace columnar { class Columnar_i; } class BlobPool_c { public: virtual ~BlobPool_c() = default; virtual void SetBlobPool ( const BYTE * pBlobPool ) { m_pBlobPool = pBlobPool; } const BYTE * GetBlobPool () const { return m_pBlobPool; } protected: const BYTE * m_pBlobPool {nullptr}; }; /// groupby key type typedef int64_t SphGroupKey_t; /// base grouper (class that computes groupby key) class CSphGrouper : public BlobPool_c, public ISphRefcountedMT { public: virtual SphGroupKey_t KeyFromValue ( SphAttr_t uValue ) const = 0; virtual SphGroupKey_t KeyFromMatch ( const CSphMatch & tMatch ) const = 0; virtual void MultipleKeysFromMatch ( const CSphMatch & tMatch, CSphVector<SphGroupKey_t> & dKeys ) const = 0; virtual void GetLocator ( CSphAttrLocator & tOut ) const = 0; virtual ESphAttr GetResultType () const = 0; virtual CSphGrouper * Clone() const = 0; virtual bool IsMultiValue() const { return false; } virtual void SetColumnar ( const columnar::Columnar_i * ) {} protected: ~CSphGrouper () override {} // =default causes bunch of errors building on wheezy }; class DistinctFetcher_i : public ISphRefcountedMT { public: virtual SphAttr_t GetKey ( const CSphMatch & tMatch ) const = 0; virtual void GetKeys ( const CSphMatch & tMatch, CSphVector<SphAttr_t> & dKeys ) const = 0; virtual void SetBlobPool ( const BYTE * pBlobPool ) = 0; virtual void SetColumnar ( const columnar::Columnar_i * pColumnar ) = 0; virtual void FixupLocators ( const ISphSchema * pOldSchema, const ISphSchema * pNewSchema ) = 0; virtual bool IsMultiValue() const = 0; virtual DistinctFetcher_i * Clone() const = 0; }; CSphGrouper * CreateGrouperDay ( const CSphAttrLocator & tLoc ); CSphGrouper * CreateGrouperWeek ( const CSphAttrLocator & tLoc ); CSphGrouper * CreateGrouperMonth ( const CSphAttrLocator & tLoc ); CSphGrouper * CreateGrouperYear ( const CSphAttrLocator & tLoc ); CSphGrouper * CreateGrouperJsonField ( const CSphAttrLocator & tLoc, ISphExpr * pExpr ); CSphGrouper * CreateGrouperMVA32 ( const CSphAttrLocator & tLoc ); CSphGrouper * CreateGrouperMVA64 ( const CSphAttrLocator & tLoc ); CSphGrouper * CreateGrouperAttr ( const CSphAttrLocator & tLoc ); CSphGrouper * CreateGrouperString ( const CSphAttrLocator & tLoc, ESphCollation eCollation ); CSphGrouper * CreateGrouperStringExpr ( ISphExpr * pExpr, ESphCollation eCollation ); CSphGrouper * CreateGrouperMulti ( const CSphVector<CSphColumnInfo> & dAttrs, VecRefPtrs_t<ISphExpr *> dJsonKeys, ESphCollation eCollation ); DistinctFetcher_i * CreateDistinctFetcher ( const CSphString & sName, const CSphAttrLocator & tLocator, ESphAttr eType ); #endif // _grouper_
3,222
C++
.h
68
45.794118
141
0.762496
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,121
fileio.h
manticoresoftware_manticoresearch/src/fileio.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 _fileio_ #define _fileio_ #include "queryprofile.h" #include "sphinxstd.h" #include "sphinxdefs.h" // set to 1 in order to collect overall histogram of VLB values (displayed in 'show status' output) // e.g. how many 1-byte, 2-bytes, 3... 10 bytes vlb encoded values happened in real stream. #ifndef TRACE_UNZIP #define TRACE_UNZIP 0 #endif /// file which closes automatically when going out of scope class CSphAutofile : ISphNoncopyable { public: CSphAutofile() = default; CSphAutofile ( const CSphString & sName, int iMode, CSphString & sError, bool bTemp=false ); ~CSphAutofile(); int Open ( const CSphString & sName, int iMode, CSphString & sError, bool bTemp=false ); void Close (); int LeakID (); void SetPersistent(); ///< would unset 'temporary' flag, if any - so that file will not be unlinked int GetFD () const { return m_iFD; } const char * GetFilename () const; SphOffset_t GetSize ( SphOffset_t iMinSize, bool bCheckSizeT, CSphString & sError ); SphOffset_t GetSize (); bool Read ( void * pBuf, int64_t iCount, CSphString & sError ); protected: int m_iFD = -1; ///< my file descriptor CSphString m_sFilename; ///< my file name bool m_bTemporary = false; ///< whether to unlink this file on Close() }; /// file reader with read buffering and int decoder class CSphReader { public: QueryProfile_c * m_pProfile = nullptr; ESphQueryState m_eProfileState { SPH_QSTATE_IO }; CSphReader ( BYTE * pBuf=NULL, int iSize=0 ); virtual ~CSphReader (); CSphReader & operator = ( const CSphReader & rhs ); void SetBuffers ( int iReadBuffer, int iReadUnhinted ); void SetFile ( int iFD, const char * sFilename ); void SetFile ( const CSphAutofile & tFile ); void Reset (); void SeekTo ( SphOffset_t iPos, int iSizeHint ); void SkipBytes ( int iCount ); SphOffset_t GetPos () const { return m_iPos+m_iBuffPos; } template <typename T> void Read ( T & tValue ) { GetBytes ( &tValue, sizeof(tValue) ); } void Read ( void * pData, size_t tSize ) { GetBytes ( pData, tSize ); } void GetBytes ( void * pData, int iSize ); int GetByte (); DWORD GetDword (); SphOffset_t GetOffset (); CSphString GetString (); CSphString GetZString (); int GetLine ( char * sBuffer, int iMaxLen ); bool Tag ( const char * sTag ); DWORD UnzipInt (); uint64_t UnzipOffset (); bool GetErrorFlag () const { return m_bError; } const CSphString & GetErrorMessage () const { return m_sError; } const CSphString & GetFilename() const { return m_sFilename; } int GetBufferSize() const { return m_iBufSize; } void ResetError(); inline RowID_t UnzipRowid () { return UnzipInt(); } inline SphWordID_t UnzipWordid () { return UnzipOffset(); } ///< zerocopy method; returns actual length present in buffer (upto iMax) inline int GetBytesZerocopy ( const BYTE ** ppData, int64_t iMax ) { if ( m_iBuffPos>=m_iBuffUsed ) { UpdateCache(); if ( m_iBuffPos>=m_iBuffUsed ) return 0; // unexpected io failure } int iChunk = (int)Min ( m_iBuffUsed-m_iBuffPos, iMax ); *ppData = m_pBuff + m_iBuffPos; m_iBuffPos += iChunk; return iChunk; } SphOffset_t GetFilesize() const; #if TRACE_UNZIP static std::array<std::atomic<uint64_t>, 5> m_dZip32Stats; static std::array<std::atomic<uint64_t>, 10> m_dZip64Stats; inline static std::array<std::atomic<uint64_t>, 5>& GetStat32() { return m_dZip32Stats; } inline static std::array<std::atomic<uint64_t>, 10>& GetStat64() { return m_dZip64Stats; } #endif protected: int m_iFD = -1; CSphString m_sFilename; int m_iBuffUsed = 0; ///< how many bytes in buffer are valid SphOffset_t m_iPos = 0; ///< position in the file from witch m_pBuff starts BYTE * m_pBuff; ///< the buffer int m_iBuffPos = 0; ///< position in the buffer. (so pos in file is m_iPos + m_iBuffPos) virtual void UpdateCache (); private: int m_iSizeHint = 0; ///< how much do we expect to read (>=m_iReadUnhinted) int m_iBufSize; bool m_bBufOwned = false; int m_iReadUnhinted; ///< how much to read if no hint provided. bool m_bError = false; CSphString m_sError; }; class FileReader_c: public CSphReader { public: explicit FileReader_c ( BYTE* pBuf = nullptr, int iSize = 0 ) : CSphReader ( pBuf, iSize ) {} SphOffset_t GetFilesize () const; // added for DebugCheck() int GetFD () const { return m_iFD; } }; /// scoped file reader class CSphAutoreader : public FileReader_c { public: CSphAutoreader ( BYTE * pBuf=nullptr, int iSize=0 ) : FileReader_c ( pBuf, iSize ) {} ~CSphAutoreader () override { Close(); } bool Open ( const CSphString & sFilename, CSphString & sError ); void Close (); }; class Writer_i : ISphNoncopyable { public: virtual void PutByte ( BYTE uValue ) = 0; virtual void PutBytes ( const void * pData, int64_t iSize ) = 0; virtual void PutWord ( WORD uValue ) = 0; virtual void PutDword ( DWORD uValue ) = 0; virtual void PutOffset ( SphOffset_t uValue ) = 0; virtual void PutString ( const char * szString ) = 0; virtual void PutString ( const CSphString & sString ) = 0; virtual void PutZString ( const char * szString ) = 0; virtual void PutZString ( const CSphString & sString ) = 0; virtual void ZipInt ( DWORD uValue ) = 0; virtual void ZipOffset ( uint64_t uValue ) = 0; virtual ~Writer_i() = default; template<typename BYTES_PAIR> void PutBlob ( BYTES_PAIR tData ) { PutBytes ( (const void *)tData.first, (int64_t)tData.second ); } }; /// file writer with write buffering and int encoder class CSphWriter : public Writer_i { public: virtual ~CSphWriter (); ///< if error flag is set, or if file is not closed by CloseFile, it will be automatically deleted (unlinked). void SetBufferSize ( int iBufferSize ); ///< tune write cache size; must be called before OpenFile() or SetFile() bool OpenFile ( const CSphString & sName, CSphString & sError ); bool OpenFile ( const CSphString & sName, int iOpenFlags, CSphString & sError ); void SetFile ( CSphAutofile & tAuto, SphOffset_t * pSharedOffset, CSphString & sError ); void CloseFile ( bool bTruncate = false ); ///< note: calls Flush(), ie. IsError() might get true after this call template <typename T> void Write ( const T & tValue ) { PutBytes ( &tValue, sizeof(tValue) ); } void Write ( const void * pData, int64_t iSize ) { PutBytes ( pData, iSize ); } void PutByte ( BYTE uValue ) override; void PutBytes ( const void * pData, int64_t iSize ) override; void PutWord ( WORD uValue ) override { PutBytes ( &uValue, sizeof(WORD) ); } void PutDword ( DWORD uValue ) override { PutBytes ( &uValue, sizeof(DWORD) ); } void PutOffset ( SphOffset_t uValue ) override { PutBytes ( &uValue, sizeof(SphOffset_t) ); } void PutString ( const char * szString ) override; void PutString ( const CSphString & sString ) override; void PutString ( Str_t tString ) { PutBytes ( tString.first, tString.second ); }; void PutZString ( const char * szString ) override; void PutZString ( const CSphString & sString ) override; void Tag ( const char * sTag ); void SeekTo ( SphOffset_t iPos, bool bTruncate = false ); void ZipInt ( DWORD uValue ) override; void ZipOffset ( uint64_t uValue ) override; bool IsError () const { return m_bError; } SphOffset_t GetPos () const { return m_iPos; } CSphString GetFilename() const { return m_sName; } virtual void Flush (); protected: CSphString m_sName; SphOffset_t m_iPos = -1; SphOffset_t m_iDiskPos = 0; int m_iFD = -1; int m_iPoolUsed = 0; std::unique_ptr<BYTE[]> m_pBuffer = nullptr; BYTE * m_pPool = nullptr; bool m_bOwnFile = false; SphOffset_t * m_pSharedOffset = nullptr; int m_iBufferSize = 262144; bool m_bUnlinkNonClosed = true; /// if no success CloseFile() called, file should be unlinked on destroy. bool m_bError = false; CSphString * m_pError = nullptr; private: void UpdatePoolUsed(); }; class CSphWriterNonThrottled final : public CSphWriter { public: void Flush () final; }; bool SeekAndWarn ( int iFD, SphOffset_t iPos, const char * szWarnPrefix ); // atomic seek+read wrapper int sphPread ( int iFD, void * pBuf, int iBytes, SphOffset_t iOffset ); /// set throttling options void sphSetThrottling ( int iMaxIOps, int iMaxIOSize ); /// write blob to file honoring throttling bool sphWriteThrottled ( int iFD, const void * pBuf, int64_t iCount, const char * szName, CSphString & sError ); /// write blob to file honoring iostats, but without throttling bool WriteNonThrottled ( int iFD, const void * pBuf, int64_t iCount, const char * sName, CSphString & sError ); /// read blob from file honoring throttling size_t sphReadThrottled ( int iFD, void* pBuf, size_t iCount ); #endif // _sphinxint_
9,289
C++
.h
220
40.113636
138
0.705575
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