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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16,638
|
SelectionTracker.h
|
dail8859_NotepadNext/src/NotepadNext/SelectionTracker.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef SELECTIONTRACKER_H
#define SELECTIONTRACKER_H
class ScintillaNext;
class SelectionTracker
{
public:
explicit SelectionTracker(ScintillaNext *editor);
~SelectionTracker();
void trackInsertion(int pos, int length);
void trackDeletion(int pos, int length);
private:
void saveSelection();
void restoreSelection();
ScintillaNext *editor;
int caret;
int anchor;
};
#endif // SELECTIONTRACKER_H
| 1,167
|
C++
|
.h
| 35
| 30.628571
| 73
| 0.761566
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,640
|
DebugManager.h
|
dail8859_NotepadNext/src/NotepadNext/DebugManager.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef DEBUGMANAGER_H
#define DEBUGMANAGER_H
#include <QtMessageHandler>
typedef void (*DebugOutputHandler)(const QString &str);
namespace DebugManager {
void manageDebugOutput();
void pauseDebugOutput();
void resumeDebugOutput();
void addMessageHandler(DebugOutputHandler handler);
}
#endif // DEBUGMANAGER_H
| 1,060
|
C++
|
.h
| 28
| 35.5
| 73
| 0.770955
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,641
|
SearchResultsCollector.h
|
dail8859_NotepadNext/src/NotepadNext/SearchResultsCollector.h
|
/*
* This file is part of Notepad Next.
* Copyright 2023 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "ISearchResultsHandler.h"
class SearchResultsCollector: public ISearchResultsHandler
{
public:
SearchResultsCollector(ISearchResultsHandler *child);
virtual ~SearchResultsCollector() {}
void newSearch(const QString searchTerm) override;
void newFileEntry(ScintillaNext *editor) override;
void newResultsEntry(const QString line, int lineNumber, int startPositionFromBeginning, int endPositionFromBeginning, int hitCount=1) override;
void completeSearch() override;
private:
ISearchResultsHandler *child;
int runningHitCount = 0;
QString prevLine;
int prevLineNumber;
int prevStartPositionFromBeginning;
int prevEndPositionFromBeginning;
};
| 1,446
|
C++
|
.h
| 36
| 37.138889
| 148
| 0.78444
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,642
|
Macro.h
|
dail8859_NotepadNext/src/NotepadNext/Macro.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACRO_H
#define MACRO_H
#include "MacroStep.h"
class Macro
{
public:
Macro();
~Macro();
void addMacroStep(Scintilla::Message message, Scintilla::uptr_t wParam, Scintilla::sptr_t lParam);
void addMacroStep(MacroStep step);
int size() const { return steps.size(); }
void replay(ScintillaNext *editor, int n = 1) const;
void replayTillEndOfFile(ScintillaNext *editor) const;
QString getName() const;
void setName(const QString &value);
QVector<MacroStep> &getSteps() { return steps; }
friend QDataStream &operator<<(QDataStream& stream, const Macro &Macro);
friend QDataStream &operator>>(QDataStream& stream, Macro &Macro);
private:
QVector<MacroStep> steps;
QString name;
};
Q_DECLARE_METATYPE(Macro)
Q_DECLARE_METATYPE(Macro*)
#endif // MACRO_H
| 1,549
|
C++
|
.h
| 42
| 33.857143
| 102
| 0.742972
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,643
|
RangeAllocator.h
|
dail8859_NotepadNext/src/NotepadNext/RangeAllocator.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <QBitArray>
#include <QMap>
class RangeAllocator
{
public:
explicit RangeAllocator(int total);
void disableRange(int start, int end);
int requestResource(const QString name);
private:
QBitArray resource;
QMap<QString, int> allocation;
};
| 1,016
|
C++
|
.h
| 30
| 31.366667
| 73
| 0.760491
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,644
|
ApplicationSettings.h
|
dail8859_NotepadNext/src/NotepadNext/ApplicationSettings.h
|
/*
* This file is part of Notepad Next.
* Copyright 2024 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <functional>
#include <QObject>
#include <QSettings>
#include <QString>
template<typename T>
class ApplicationSetting
{
public:
ApplicationSetting(const char * const key, T defaultValue = T())
: mKey(key)
, mDefault(defaultValue)
, mCallable(Q_NULLPTR)
{}
ApplicationSetting(const char * const key, std::function<T()> callable)
: mKey(key)
, mDefault(T())
, mCallable(callable)
{}
inline T getDefault() const { return mCallable ? mCallable() : mDefault ; }
inline const char * const key() const { return mKey; }
private:
const char * const mKey;
const T mDefault;
std::function<T()> mCallable;
};
#define DEFINE_SETTING(name, lname, type)\
public:\
type lname() const;\
public slots:\
void set##name(type lname);\
Q_SIGNAL\
void lname##Changed(type lname);\
class ApplicationSettings : public QSettings
{
Q_OBJECT
public:
explicit ApplicationSettings(QObject *parent = nullptr);
public:
template <typename T>
T get(const char *key, const T &defaultValue) const
{ return value(QLatin1String(key), defaultValue).template value<T>(); }
template <typename T>
T get(const ApplicationSetting<T> &setting) const
{ return get(setting.key(), setting.getDefault()); }
template <typename T>
void set(const ApplicationSetting<T> &setting, const T &value)
{ setValue(QLatin1String(setting.key()), value); }
public:
DEFINE_SETTING(ShowMenuBar, showMenuBar, bool)
DEFINE_SETTING(ShowToolBar, showToolBar, bool)
DEFINE_SETTING(ShowTabBar, showTabBar, bool)
DEFINE_SETTING(ShowStatusBar, showStatusBar, bool)
DEFINE_SETTING(CenterSearchDialog, centerSearchDialog, bool)
DEFINE_SETTING(TabsClosable, tabsClosable, bool)
DEFINE_SETTING(ExitOnLastTabClosed, exitOnLastTabClosed, bool)
DEFINE_SETTING(CombineSearchResults, combineSearchResults, bool)
DEFINE_SETTING(RestorePreviousSession, restorePreviousSession, bool)
DEFINE_SETTING(RestoreUnsavedFiles, restoreUnsavedFiles, bool)
DEFINE_SETTING(RestoreTempFiles, restoreTempFiles, bool)
DEFINE_SETTING(Translation, translation, QString)
DEFINE_SETTING(ShowWhitespace, showWhitespace, bool);
DEFINE_SETTING(ShowEndOfLine, showEndOfLine, bool);
DEFINE_SETTING(ShowWrapSymbol, showWrapSymbol, bool)
DEFINE_SETTING(ShowIndentGuide, showIndentGuide, bool)
DEFINE_SETTING(WordWrap, wordWrap, bool);
DEFINE_SETTING(FontName, fontName, QString);
DEFINE_SETTING(FontSize, fontSize, int);
DEFINE_SETTING(AdditionalWordChars, additionalWordChars, QString);
};
| 3,373
|
C++
|
.h
| 87
| 34.793103
| 79
| 0.744407
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,645
|
RecentFilesListManager.h
|
dail8859_NotepadNext/src/NotepadNext/RecentFilesListManager.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef RECENTFILESLISTMANAGER_H
#define RECENTFILESLISTMANAGER_H
#include <QObject>
#include <QList>
class RecentFilesListManager : public QObject
{
Q_OBJECT
public:
explicit RecentFilesListManager(QObject *parent = Q_NULLPTR);
QString mostRecentFile() const;
QStringList fileList() const;
void setFileList(const QStringList &list);
int count() const { return recentFiles.size(); }
public slots:
void addFile(const QString &filePath);
void removeFile(const QString &filePath);
void clear();
private:
QStringList recentFiles;
};
#endif // RECENTFILESLISTMANAGER_H
| 1,341
|
C++
|
.h
| 38
| 32.552632
| 73
| 0.764114
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,646
|
Finder.h
|
dail8859_NotepadNext/src/NotepadNext/Finder.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef FINDER_H
#define FINDER_H
#include "ScintillaNext.h"
class Finder
{
public:
explicit Finder(ScintillaNext *edit);
void setEditor(ScintillaNext *editor);
void setSearchFlags(int flags);
void setWrap(bool wrap);
void setSearchText(const QString &text);
Sci_CharacterRange findNext(int startPos = INVALID_POSITION);
Sci_CharacterRange findPrev();
int count();
bool didLatestSearchWrapAround() const { return did_latest_search_wrap; }
Sci_CharacterRange replaceSelectionIfMatch(const QString &replaceText);
int replaceAll(const QString &replaceText);
template<typename Func>
void forEachMatch(Func callback) { forEachMatchInRange(callback, {0, (Sci_PositionCR)editor->length()}); }
template<typename Func>
void forEachMatchInRange(Func callback, Sci_CharacterRange range);
private:
ScintillaNext *editor;
bool did_latest_search_wrap = false;
bool wrap = false;
int search_flags = 0;
QString text;
};
template<typename Func>
void Finder::forEachMatchInRange(Func callback, Sci_CharacterRange range)
{
editor->setSearchFlags(search_flags);
editor->forEachMatchInRange(text.toUtf8(), callback, range);
}
#endif // FINDER_H
| 1,954
|
C++
|
.h
| 52
| 34.288462
| 110
| 0.758347
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,647
|
QRegexSearch.h
|
dail8859_NotepadNext/src/NotepadNext/QRegexSearch.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef QREGEXSEARCH_H
#define QREGEXSEARCH_H
#include <QRegularExpressionMatch>
#include <vector>
#include <map>
#include <memory>
#include <stdexcept>
// TODO: Fix this mess. Scintilla makes you include everything...in the correct order...
// this was copied from Editor.cxx just to get it to compile
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <set>
#include <forward_list>
#include <optional>
#include <algorithm>
#include <iterator>
#include <memory>
#include <chrono>
#include "ScintillaTypes.h"
#include "ScintillaMessages.h"
#include "ScintillaStructures.h"
#include "ILoader.h"
#include "ILexer.h"
#include "Debugging.h"
#include "Geometry.h"
#include "Platform.h"
#include "CharacterType.h"
#include "CharacterCategoryMap.h"
#include "Position.h"
#include "UniqueString.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "PerLine.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "Scintilla.h"
using namespace Scintilla::Internal;
class QRegexSearch : public RegexSearchBase
{
public:
QRegexSearch();
Sci::Position FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s, bool caseSensitive, bool word, bool wordStart, Scintilla::FindOption flags, Sci::Position *length) override;
const char *SubstituteByPosition(Document *doc, const char *text, Sci::Position *length) override;
private:
QRegularExpressionMatch match;
QByteArray *substituted = Q_NULLPTR;
};
#endif // QREGEXSEARCH_H
| 2,612
|
C++
|
.h
| 84
| 29.464286
| 209
| 0.775388
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,648
|
FileDialogHelpers.h
|
dail8859_NotepadNext/src/NotepadNext/FileDialogHelpers.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef FILEDIALOGHELPERS_H
#define FILEDIALOGHELPERS_H
#include <QWidget>
#include <QFileDialog>
namespace FileDialogHelpers
{
QList<QUrl> getOpenFileUrls(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options, const QStringList &supportedSchemes);
QStringList getOpenFileNames(QWidget *parent = nullptr, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = nullptr, QFileDialog::Options options = QFileDialog::Options());
QUrl getSaveFileUrl(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options, const QStringList &supportedSchemes);
QString getSaveFileName(QWidget *parent = nullptr, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = nullptr, QFileDialog::Options options = QFileDialog::Options());
}
#endif // FILEDIALOGHELPERS_H
| 1,806
|
C++
|
.h
| 29
| 59.965517
| 253
| 0.775268
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,651
|
ScintillaNext.h
|
dail8859_NotepadNext/src/NotepadNext/ScintillaNext.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef SCINTILLANEXT_H
#define SCINTILLANEXT_H
#include "RangeAllocator.h"
#include "ScintillaEdit.h"
#include <QDateTime>
#include <QFile>
#include <QFileInfo>
class ScintillaNext : public ScintillaEdit
{
Q_OBJECT
public:
static bool isRangeValid(const Sci_CharacterRange &range)
{
return range.cpMin != INVALID_POSITION && range.cpMax != INVALID_POSITION;
}
explicit ScintillaNext(QString name, QWidget *parent = Q_NULLPTR);
virtual ~ScintillaNext();
static ScintillaNext *fromFile(const QString &filePath, bool tryToCreate=false);
int allocateIndicator(const QString &name);
template<typename Func>
void forEachMatch(const QString &text, Func callback) { forEachMatch(text.toUtf8(), callback); }
template<typename Func>
void forEachMatch(const QByteArray &byteArray, Func callback) { forEachMatchInRange(byteArray, callback, {0, (Sci_PositionCR)length()}); }
template<typename Func>
void forEachMatchInRange(const QByteArray &byteArray, Func callback, Sci_CharacterRange range);
template<typename Func>
void forEachLineInSelection(int selection, Func callback);
void goToRange(const Sci_CharacterRange &range);
QByteArray eolString() const;
bool lineIsEmpty(int line);
void deleteLine(int line);
void cutAllowLine();
void modifyFoldLevels(int level, int action);
void foldAllLevels(int level);
void unFoldAllLevels(int level);
void deleteLeadingEmptyLines();
void deleteTrailingEmptyLines();
bool isFile() const;
QFileInfo getFileInfo() const;
bool isSavedToDisk() const;
bool canSaveToDisk() const;
QString getName() const { return name; }
void setName(const QString &name);
QString getPath() const;
QString getFilePath() const;
// NOTE: this is dangerous and should only be used in very rare situations
void setFileInfo(const QString &filePath);
void detachFileInfo(const QString &newName);
enum FileStateChange {
NoChange,
Modified,
Deleted,
Restored,
};
enum BufferType {
New, // A temporary buffer, e.g. "New 1"
File, // Buffer tied to a file on the file system
FileMissing, // Buffer with a missing file on the file system
};
bool isTemporary() const { return temporary; }
void setTemporary(bool temp);
void setFoldMarkers(const QString &type);
QString languageName;
QByteArray languageSingleLineComment;
#include "ScintillaEnums.h"
public slots:
void close();
QFileDevice::FileError save();
void reload();
QFileDevice::FileError saveAs(const QString &newFilePath);
QFileDevice::FileError saveCopyAs(const QString &filePath);
bool rename(const QString &newFilePath);
ScintillaNext::FileStateChange checkFileForStateChange();
bool moveToTrash();
void toggleCommentSelection();
void commentLineSelection();
void uncommentLineSelection();
signals:
void aboutToSave();
void saved();
void closed();
void renamed();
void lexerChanged();
protected:
void dragEnterEvent(QDragEnterEvent *event) override;
void dropEvent(QDropEvent *event) override;
private:
QString name;
BufferType bufferType = BufferType::New;
QFileInfo fileInfo;
QDateTime modifiedTime;
RangeAllocator indicatorResources;
bool temporary = false; // Temporary file loaded from a session. It can either be a 'New' file or actual 'File'
bool readFromDisk(QFile &file);
QDateTime fileTimestamp();
void updateTimestamp();
};
template<typename Func>
void ScintillaNext::forEachLineInSelection(int selection, Func callback)
{
int lineStart = lineFromPosition(selectionNStart(selection));
int lineEnd = lineFromPosition(selectionNEnd(selection));
for (int curLine = lineStart; curLine <= lineEnd; ++curLine) {
callback(curLine);
}
}
// Stick this in the header file...because C++, that's why
template<typename Func>
void ScintillaNext::forEachMatchInRange(const QByteArray &text, Func callback, Sci_CharacterRange range)
{
Sci_TextToFind ttf {range, text.constData(), {-1, -1}};
int flags = searchFlags();
while (send(SCI_FINDTEXT, flags, reinterpret_cast<sptr_t>(&ttf)) != -1) {
if(ttf.chrgText.cpMin == ttf.chrgText.cpMax)
break;
ttf.chrg.cpMin = callback(ttf.chrgText.cpMin, ttf.chrgText.cpMax);
}
}
#endif // SCINTILLANEXT_H
| 5,196
|
C++
|
.h
| 136
| 33.580882
| 142
| 0.732588
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,653
|
IFaceTable.h
|
dail8859_NotepadNext/src/NotepadNext/IFaceTable.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef IFACETABLE_H
#define IFACETABLE_H
#include <string>
#include <vector>
enum IFaceType {
iface_void,
iface_int,
iface_length,
iface_position,
iface_colour,
iface_bool,
iface_keymod,
iface_string,
iface_stringresult,
iface_cells, // This and everything else below is not "scriptable"
iface_textrange,
iface_findtext,
iface_formatrange
};
struct IFaceConstant {
const char *name;
int value;
};
struct IFaceFunction {
const char *name;
int value;
IFaceType returnType;
IFaceType paramType[2];
};
struct IFaceProperty {
const char *name;
int getter;
int setter;
IFaceType valueType;
IFaceType paramType;
IFaceFunction GetterFunction() const {
IFaceFunction result = {"(property getter)",getter,valueType,{paramType,iface_void}};
return result;
}
IFaceFunction SetterFunction() const {
IFaceFunction result = {"(property setter)",setter,iface_void,{valueType, iface_void}};
if (paramType != iface_void) {
result.paramType[0] = paramType;
if (valueType == iface_stringresult)
result.paramType[1] = iface_string;
else
result.paramType[1] = valueType;
}
if ((paramType == iface_void) && ((valueType == iface_string) || (valueType == iface_stringresult))) {
result.paramType[0] = paramType;
if (valueType == iface_stringresult)
result.paramType[1] = iface_string;
else
result.paramType[1] = valueType;
}
return result;
}
};
inline bool IFaceTypeIsScriptable(IFaceType t, int index) {
return t < iface_stringresult || (index == 1 && t == iface_stringresult);
}
inline bool IFaceTypeIsNumeric(IFaceType t) {
return (t > iface_void && t < iface_bool);
}
inline bool IFaceFunctionIsScriptable(const IFaceFunction &f) {
return IFaceTypeIsScriptable(f.paramType[0], 0) && IFaceTypeIsScriptable(f.paramType[1], 1);
}
inline bool IFacePropertyIsScriptable(const IFaceProperty &p) {
return (((p.valueType > iface_void) && (p.valueType <= iface_stringresult) && (p.valueType != iface_keymod)) &&
((p.paramType < iface_colour) || (p.paramType == iface_string) || (p.paramType == iface_bool)) && (p.getter || p.setter));
}
class IFaceTableInterface {
public:
virtual const IFaceConstant *FindConstant(const char *name) const = 0;
virtual const IFaceFunction *FindFunction(const char *name) const = 0;
virtual const IFaceFunction *FindFunctionByConstantName(const char *name) const = 0;
virtual const IFaceFunction *FindFunctionByValue(int value) const = 0;
virtual const IFaceProperty *FindProperty(const char *name) const = 0;
virtual int GetConstantName(int value, char *nameOut, unsigned nameBufferLen, const char *hint) const = 0;
virtual const IFaceFunction *GetFunctionByMessage(int message) const = 0;
virtual IFaceFunction GetPropertyFuncByMessage(int message) const = 0;
};
class IFaceTable : public IFaceTableInterface {
public:
IFaceTable(const char *_prefix,
const std::vector<IFaceFunction> &_functions,
const std::vector<IFaceConstant> &_constants,
const std::vector<IFaceProperty> &_properties) :
prefix(_prefix),
functions(_functions),
constants(_constants),
properties(_properties)
{}
const char *prefix;
const std::vector<IFaceFunction> &functions;
const std::vector<IFaceConstant> &constants;
const std::vector<IFaceProperty> &properties;
// IFaceTableInterface
const IFaceConstant *FindConstant(const char *name) const;
const IFaceFunction *FindFunction(const char *name) const;
const IFaceFunction *FindFunctionByConstantName(const char *name) const;
const IFaceFunction *FindFunctionByValue(int value) const;
const IFaceProperty *FindProperty(const char *name) const;
int GetConstantName(int value, char *nameOut, unsigned nameBufferLen, const char *hint) const;
const IFaceFunction *GetFunctionByMessage(int message) const;
IFaceFunction GetPropertyFuncByMessage(int message) const;
std::vector<std::string> GetAllConstantNames() const;
std::vector<std::string> GetAllFunctionNames() const;
std::vector<std::string> GetAllPropertyNames() const;
};
#endif
| 5,107
|
C++
|
.h
| 128
| 34.734375
| 130
| 0.708552
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,654
|
NppImporter.h
|
dail8859_NotepadNext/src/NotepadNext/NppImporter.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef NPPIMPORTER_H
#define NPPIMPORTER_H
#include <QXmlStreamReader>
#include <QMap>
#include "ScintillaEdit.h"
struct LexerStyle {
int id;
int fgColor;
int bgColor;
QString fontName;
int fontStyle;
int fontSize;
int keywordClass;
};
struct LexerType {
QString description;
QVector<LexerStyle> styles;
};
struct Language {
QString name;
QString shortName;
QString longDescription;
int lexer_id;
QStringList extensions;
LexerType lexer;
QMap<int, QString> keywords;
};
class NppImporter
{
public:
NppImporter(const QString &configPath, ScintillaEdit *_editor);
QMap<QString, Language> languages;
QStringList sortedLanguageKeys;
private:
ScintillaEdit *editor;
void readLangsModel(const QString &filePath);
void readStylersModel(const QString &filePath);
void readConfigModel(const QString &filePath);
void readLexerStyles(QXmlStreamReader &xml);
void readGlobalStyles(QXmlStreamReader &xml);
void readGUIConfigs(QXmlStreamReader &xml);
int foldFgColor;
int foldBgColor;
int activeFgColor;
};
#endif // NPPIMPORTER_H
| 1,875
|
C++
|
.h
| 63
| 26.444444
| 73
| 0.75584
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,655
|
DockedEditor.h
|
dail8859_NotepadNext/src/NotepadNext/DockedEditor.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef DOCKEDEDITOR_H
#define DOCKEDEDITOR_H
#include <QObject>
#include "DockManager.h"
#include "ScintillaNext.h"
class DockedEditor : public QObject
{
Q_OBJECT
private:
ads::CDockManager* dockManager = Q_NULLPTR;
ScintillaNext *currentEditor = Q_NULLPTR;
public:
explicit DockedEditor(QWidget *parent);
ScintillaNext *getCurrentEditor() const;
ads::CDockAreaWidget *currentDockArea() const;
QVector<ScintillaNext *> editors() const;
void switchToEditor(const ScintillaNext *editor);
int count() const;
public slots:
void addEditor(ScintillaNext *editor);
private slots:
void dockWidgetCloseRequested();
void editorRenamed(ScintillaNext *editor);
signals:
void editorAdded(ScintillaNext *editor);
void editorCloseRequested(ScintillaNext *editor);
void editorClosed(ScintillaNext *editor);
void editorActivated(ScintillaNext *editor);
void editorOrderChanged();
void contextMenuRequestedForEditor(ScintillaNext *editor);
void titleBarDoubleClicked();
};
#endif // DOCKEDEDITOR_H
| 1,800
|
C++
|
.h
| 50
| 32.84
| 73
| 0.769319
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,656
|
TranslationManager.h
|
dail8859_NotepadNext/src/NotepadNext/TranslationManager.h
|
/*
* This file is part of Notepad Next.
* Copyright 2024 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <QCoreApplication>
#include <QTranslator>
#include <QObject>
#include <QLocale>
class TranslationManager : public QObject
{
Q_OBJECT
public:
TranslationManager(QObject *parent, const QString &path);
QStringList availableTranslations() const;
static QString FormatLocaleTerritoryAndLanguage(QLocale &locale);
public slots:
void loadSystemDefaultTranslation();
void loadTranslation(QLocale locale);
void loadTranslationByName(QString localeName);
private:
const QString path;
QList<QTranslator*> translators;
};
| 1,305
|
C++
|
.h
| 37
| 32.594595
| 73
| 0.775835
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,657
|
EditorPrintPreviewRenderer.h
|
dail8859_NotepadNext/src/NotepadNext/EditorPrintPreviewRenderer.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef EDITORPRINTPREVIEWRENDERER_H
#define EDITORPRINTPREVIEWRENDERER_H
#include <QObject>
class ScintillaNext;
class QPrinter;
class EditorPrintPreviewRenderer : public QObject
{
Q_OBJECT
public:
explicit EditorPrintPreviewRenderer(ScintillaNext *editor);
public slots:
void render(QPrinter *printer);
private:
ScintillaNext *editor;
};
#endif // EDITORPRINTPREVIEWRENDERER_H
| 1,132
|
C++
|
.h
| 33
| 32.030303
| 73
| 0.784206
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,658
|
QuickFindWidget.h
|
dail8859_NotepadNext/src/NotepadNext/QuickFindWidget.h
|
/*
* This file is part of Notepad Next.
* Copyright 2020 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef QUICKFINDWIDGET_H
#define QUICKFINDWIDGET_H
#include <QEvent>
#include <QFrame>
#include <QKeyEvent>
#include <QLineEdit>
#include <QObject>
#include "Finder.h"
#include "ScintillaNext.h"
namespace Ui {
class QuickFindWidget;
}
class QuickFindWidget : public QFrame
{
Q_OBJECT
public:
explicit QuickFindWidget(QWidget *parent = nullptr);
~QuickFindWidget();
void setEditor(ScintillaNext *editor);
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
private slots:
void performNewSearch();
void navigateToNextMatch(bool skipCurrent = true);
void navigateToPrevMatch();
void positionWidget();
void focusIn();
void focusOut();
void returnPressed();
private:
void highlightMatches();
void clearHighlights();
void clearCachedMatches();
void prepareSearch();
int computeSearchFlags() const;
void setSearchContextColorBad();
void setSearchContextColorGood();
void setSearchContextColor(const QString &color);
void initializeEditorIndicator();
QString searchText() const;
void goToCurrentMatch();
void showWrapIndicator();
Ui::QuickFindWidget *ui;
ScintillaNext *editor = Q_NULLPTR;
Finder *finder = Q_NULLPTR;
int indicator;
QList<QPair<int, int>> matches;
qsizetype currentMatchIndex = -1;
};
#endif // QUICKFINDWIDGET_H
| 2,105
|
C++
|
.h
| 67
| 28.089552
| 73
| 0.751116
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,659
|
LuaState.h
|
dail8859_NotepadNext/src/NotepadNext/LuaState.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef LUASTATE_H
#define LUASTATE_H
#include <QString>
#include <QStringList>
#include <QtGlobal>
#include "lua.hpp"
struct lua_State;
class LuaState
{
public:
LuaState();
~LuaState();
void execute(const char *statement, bool clear = true);
void executeFile(const QString &fileName);
template<typename T>
T executeAndReturn(const char *statement);
void clearStack();
void raiseError(const char *errorMessage = Q_NULLPTR);
lua_State *L = Q_NULLPTR;
private:
};
template<>
inline bool LuaState::executeAndReturn(const char *statement)
{
execute(statement, false);
luaL_checktype(L, 1, LUA_TBOOLEAN);
bool b = lua_toboolean(L, 1);
lua_pop(L, 1);
return b;
}
template<>
inline QString LuaState::executeAndReturn(const char *statement)
{
execute(statement, false);
luaL_checktype(L, 1, LUA_TSTRING);
QString s(lua_tostring(L, 1));
lua_pop(L, 1);
return s;
}
template<>
inline QStringList LuaState::executeAndReturn(const char *statement)
{
execute(statement, false);
luaL_checktype(L, 1, LUA_TTABLE);
QStringList list;
/* table is in the stack at index 't' */
lua_pushnil(L); /* first key */
while (lua_next(L, 1) != 0) {
list << lua_tostring(L, -1);
lua_pop(L, 1);
}
lua_pop(L, 1);
return list;
}
#endif // LUASTATE_H
| 2,095
|
C++
|
.h
| 72
| 25.777778
| 73
| 0.7085
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,660
|
MacroManager.h
|
dail8859_NotepadNext/src/NotepadNext/MacroManager.h
|
/*
* This file is part of Notepad Next.
* Copyright 2024 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACROMANAGER_H
#define MACROMANAGER_H
#include "MacroRecorder.h"
#include <QObject>
class MacroManager : public QObject
{
Q_OBJECT
public:
explicit MacroManager(QObject *parent = nullptr);
virtual ~MacroManager();
bool isRecording() const;
QVector<Macro *> &availableMacros() { return macros; };
void replayCurrentMacro(ScintillaNext *editor);
void saveCurrentMacro(const QString ¯oName);
bool hasCurrentUnsavedMacro() const;
Macro *getCurrentMacro() const { return currentMacro; }
public slots:
void startRecording(ScintillaNext *editor);
void stopRecording();
private slots:
void loadSettings();
void saveSettings() const;
signals:
void recordingStarted();
void recordingStopped();
private:
MacroRecorder recorder;
Macro *currentMacro = Q_NULLPTR;
QVector<Macro *> macros;
bool _isRecording = false;
bool isCurrentMacroSaved = false;
};
#endif // MACROMANAGER_H
| 1,696
|
C++
|
.h
| 50
| 30.74
| 73
| 0.751378
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,661
|
MacroStepTableModel.h
|
dail8859_NotepadNext/src/NotepadNext/MacroStepTableModel.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#include <QAbstractTableModel>
#include "Macro.h"
class MacroStepTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit MacroStepTableModel(Macro *m, QObject *parent = nullptr);
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
bool insertRows(int row, int count, const QModelIndex &parent) override;
bool removeRows(int row, int count, const QModelIndex &parent) override;
bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild) override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
private:
Macro *macro;
};
| 1,789
|
C++
|
.h
| 36
| 46.583333
| 146
| 0.769098
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,662
|
MacroRecorder.h
|
dail8859_NotepadNext/src/NotepadNext/MacroRecorder.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACRORECORDER_H
#define MACRORECORDER_H
#include <QObject>
#include "ScintillaNext.h"
#include "Macro.h"
class MacroRecorder : public QObject
{
Q_OBJECT
public:
MacroRecorder(QObject *parent = nullptr);
void startRecording(ScintillaNext *editor);
Macro *stopRecording();
public slots:
void recordMacroStep(Scintilla::Message message, Scintilla::uptr_t wParam, Scintilla::sptr_t lParam);
private:
ScintillaNext *editor = Q_NULLPTR;
Macro *macro = Q_NULLPTR;
};
#endif // MACRORECORDER_H
| 1,261
|
C++
|
.h
| 36
| 32.472222
| 105
| 0.760923
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,663
|
MacroListModel.h
|
dail8859_NotepadNext/src/NotepadNext/MacroListModel.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACROLISTMODEL_H
#define MACROLISTMODEL_H
#include <QAbstractItemModel>
#include "MacroManager.h"
class MacroListModel : public QAbstractListModel
{
Q_OBJECT
public :
MacroListModel(QObject * parent, MacroManager *mm);
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
bool removeRows(int row, int count, const QModelIndex &parent) override;
bool insertRows(int row, int count, const QModelIndex &parent=QModelIndex()) override;
Macro *macro(const QModelIndex &index);
private:
MacroManager *macroManager;
};
#endif // MACROLISTMODEL_H
| 1,403
|
C++
|
.h
| 35
| 37.371429
| 90
| 0.769004
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,664
|
HtmlConverter.h
|
dail8859_NotepadNext/src/NotepadNext/HtmlConverter.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "Converter.h"
class HtmlConverter : public Converter
{
using Converter::Converter;
public:
void convertRange(QTextStream &stream, int start, int end) override;
};
| 926
|
C++
|
.h
| 25
| 34.84
| 73
| 0.763128
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,665
|
EditorManager.h
|
dail8859_NotepadNext/src/NotepadNext/EditorManager.h
|
/*
* This file is part of Notepad Next.
* Copyright 2021 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef EDITORMANAGER_H
#define EDITORMANAGER_H
#include <QObject>
#include <QPointer>
class ApplicationSettings;
class ScintillaNext;
class EditorManager : public QObject
{
Q_OBJECT
public:
explicit EditorManager(ApplicationSettings *settings, QObject *parent = nullptr);
ScintillaNext *createEditor(const QString &name);
ScintillaNext *createEditorFromFile(const QString &filePath, bool tryToCreate=false);
ScintillaNext *getEditorByFilePath(const QString &filePath);
void manageEditor(ScintillaNext *editor);
signals:
void editorCreated(ScintillaNext *editor);
void editorClosed(ScintillaNext *editor);
private:
void setupEditor(ScintillaNext *editor);
void purgeOldEditorPointers();
QList<QPointer<ScintillaNext>> getEditors();
QList<QPointer<ScintillaNext>> editors;
ApplicationSettings *settings;
};
#endif // EDITORMANAGER_H
| 1,625
|
C++
|
.h
| 43
| 34.883721
| 89
| 0.779974
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,666
|
LuaExtension.h
|
dail8859_NotepadNext/src/NotepadNext/LuaExtension.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef LUAEXTENSION_H
#define LUAEXTENSION_H
#include "ScintillaNext.h"
#include <vector>
class ScintillaNext;
struct lua_State;
class LuaExtension final {
private:
LuaExtension(); // Singleton
LuaExtension(const LuaExtension &); // Disable copy ctor
void operator=(const LuaExtension &); // Disable operator=
public:
static LuaExtension &Instance();
~LuaExtension();
bool Initialise(lua_State *L, ScintillaNext *editor_);
void setEditor(ScintillaEdit *editor_);
bool Finalise();
// Helper methods
bool RunString(const char *s);
bool OnExecute(const char *s);
void CallShortcut(int id);
// Scintilla callbacks
//bool OnStyle(unsigned int startPos, int lengthDoc, int initStyle, StyleWriter *styler);
//bool OnChar(const SCNotification *sc);
//bool OnSavePointReached(const SCNotification *sc);
//bool OnSavePointLeft(const SCNotification *sc);
//bool OnModifyAttemptRO(const SCNotification *sc);
//bool OnDoubleClick(const SCNotification *sc);
//bool OnUpdateUI(const SCNotification *sc);
//bool OnModification(const SCNotification *sc);
//bool OnMacroRecord(const SCNotification *sc);
//bool OnMarginClick(const SCNotification *sc);
//bool OnNeedShown(const SCNotification *sc);
//bool OnPainted(const SCNotification *sc);
//bool OnUserListSelection(const SCNotification *sc);
//bool OnDwellStart(const SCNotification *sc);
//bool OnDwellEnd(const SCNotification *sc);
//bool OnZoom(const SCNotification *sc);
//bool OnHotSpotClick(const SCNotification *sc);
//bool OnHotSpotDoubleClick(const SCNotification *sc);
//bool OnHotSpotReleaseClick(const SCNotification *sc);
//bool OnIndicatorClick(const SCNotification *sc);
//bool OnIndicatorRelease(const SCNotification *sc);
//bool OnCallTipClick(const SCNotification *sc);
//bool OnAutoCSelection(const SCNotification *sc);
//bool OnAutoCCancelled(const SCNotification *sc);
//bool OnAutoCCharDeleted(const SCNotification *sc);
//bool OnFocusIn(const SCNotification *sc);
//bool OnFocusOut(const SCNotification *sc);
//// Notepad++ callbacks
//bool OnReady();
//bool OnToolBarModification();
//bool OnBeforeClose(const char *filename, uptr_t bufferid);
//bool OnOpen(const char *filename, uptr_t bufferid);
//bool OnClose();
//bool OnBeforeOpen(const char *filename, uptr_t bufferid);
//bool OnBeforeSave(const char *filename, uptr_t bufferid);
//bool OnSave(const char *filename, uptr_t bufferid);
//bool OnShutdown();
//bool OnSwitchFile(const char *filename, uptr_t bufferid);
//bool OnLangChange();
//bool OnFileBeforeLoad();
//bool OnFileLoadFailed();
//bool OnReadOnlyChanged(const char *filename, uptr_t bufferid, int status);
//bool OnDocOrderChanged(const char *filename, uptr_t bufferid, int newIndex);
//bool OnSnapshotDirtyFileLoaded(const char *filename, uptr_t bufferid);
//bool OnBeforeShutdown();
//bool OnCancelShutdown();
//bool OnFileBeforeRename(const char *filename, uptr_t bufferid);
//bool OnFileRenameCancel(const char *filename, uptr_t bufferid);
//bool OnFileRenamed(const char *filename, uptr_t bufferid);
//bool OnFileBeforeDelete(const char *filename, uptr_t bufferid);
//bool OnFileDeleteFailed(const char *filename, uptr_t bufferid);
//bool OnFileDeleted();
};
#endif
| 4,152
|
C++
|
.h
| 93
| 40.548387
| 93
| 0.737336
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,667
|
NotepadNextApplication.h
|
dail8859_NotepadNext/src/NotepadNext/NotepadNextApplication.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef NOTEPADNEXTAPPLICATION_H
#define NOTEPADNEXTAPPLICATION_H
#include "ApplicationSettings.h"
#include "SingleApplication"
#include <QCommandLineParser>
#include <QPointer>
class MainWindow;
class LuaState;
class EditorManager;
class RecentFilesListManager;
class ScintillaNext;
class SessionManager;
class TranslationManager;
class NotepadNextApplication : public SingleApplication
{
Q_OBJECT
public:
NotepadNextApplication(int &argc, char **argv);
bool init();
RecentFilesListManager *getRecentFilesListManager() const { return recentFilesListManager; }
EditorManager *getEditorManager() const { return editorManager; }
SessionManager *getSessionManager() const;
TranslationManager *getTranslationManager() const { return translationManager; };
LuaState *getLuaState() const { return luaState; }
QString getFileDialogFilter() const;
QString getFileDialogFilterForLanguage(const QString &language) const;
ApplicationSettings *getSettings() const { return settings; }
QStringList getLanguages() const;
void setEditorLanguage(ScintillaNext *editor, const QString &languageName) const;
QString detectLanguage(ScintillaNext *editor) const;
QString detectLanguageFromExtension(const QString &extension) const;
QString detectLanguageFromContents(ScintillaNext *editor) const;
void sendInfoToPrimaryInstance();
bool isRunningAsAdmin() const;
protected:
bool event(QEvent *event) override;
private slots:
void saveSettings();
void receiveInfoFromSecondaryInstance(quint32 instanceId, QByteArray message);
private:
void openFiles(const QStringList &files);
void loadSettings();
EditorManager *editorManager;
RecentFilesListManager *recentFilesListManager;
ApplicationSettings *settings;
SessionManager *sessionManager;
TranslationManager *translationManager;
LuaState *luaState = Q_NULLPTR;
MainWindow *window = Q_NULLPTR;
QPointer<QWidget> currentlyFocusedWidget; // Keep a weak pointer to the QWidget since we don't own it
MainWindow *createNewWindow();
QCommandLineParser parser;
};
#endif // NOTEPADNEXTAPPLICATION_H
| 2,904
|
C++
|
.h
| 71
| 37.43662
| 105
| 0.790449
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,668
|
SciIFaceTable.h
|
dail8859_NotepadNext/src/NotepadNext/SciIFaceTable.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef SCIIFACETABLE_H
#define SCIIFACETABLE_H
#include "IFaceTable.h"
extern IFaceTable SciIFaceTable;
#endif
| 844
|
C++
|
.h
| 22
| 36.409091
| 73
| 0.772338
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,669
|
RtfConverter.h
|
dail8859_NotepadNext/src/NotepadNext/RtfConverter.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "Converter.h"
class RtfConverter : public Converter
{
using Converter::Converter;
public:
void convertRange(QTextStream &stream, int start, int end) override;
};
| 925
|
C++
|
.h
| 25
| 34.8
| 73
| 0.762864
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,670
|
UndoAction.h
|
dail8859_NotepadNext/src/NotepadNext/UndoAction.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef UNDOACTION_H
#define UNDOACTION_H
class ScintillaNext;
class UndoAction
{
public:
explicit UndoAction(ScintillaNext *editor);
~UndoAction();
private:
ScintillaNext *editor;
};
#endif // UNDOACTION_H
| 952
|
C++
|
.h
| 29
| 30.655172
| 73
| 0.764449
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,672
|
IFaceTableMixer.h
|
dail8859_NotepadNext/src/NotepadNext/IFaceTableMixer.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef IFACETABLEMIXER_H
#define IFACETABLEMIXER_H
#include "IFaceTable.h"
#include <vector>
class IFaceTableMixer : public IFaceTableInterface {
private:
std::vector<IFaceTableInterface *> ifaces;
public:
void AddIFaceTable(IFaceTableInterface *iface) { ifaces.push_back(iface); }
// IFaceTableInterface
const IFaceConstant *FindConstant(const char *name) const;
const IFaceFunction *FindFunction(const char *name) const;
const IFaceFunction *FindFunctionByConstantName(const char *name) const;
const IFaceFunction *FindFunctionByValue(int value) const;
const IFaceProperty *FindProperty(const char *name) const;
int GetConstantName(int value, char *nameOut, unsigned nameBufferLen, const char *hint) const;
const IFaceFunction *GetFunctionByMessage(int message) const;
IFaceFunction GetPropertyFuncByMessage(int message) const;
};
#endif
| 1,586
|
C++
|
.h
| 37
| 40.945946
| 95
| 0.79572
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,673
|
SessionManager.h
|
dail8859_NotepadNext/src/NotepadNext/SessionManager.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef SESSIONMANAGER_H
#define SESSIONMANAGER_H
#include <QDir>
#include <QSettings>
class ScintillaNext;
class MainWindow;
class NotepadNextApplication;
class SessionManager
{
public:
enum SessionFileType {
None = 0,
SavedFile = 1,
UnsavedFile = 2,
TempFile = 4,
};
Q_DECLARE_FLAGS(SessionFileTypes, SessionFileType)
SessionManager(NotepadNextApplication *app, SessionFileTypes types = SessionFileTypes());
void setSessionFileTypes(SessionFileTypes types);
void clear() const;
void saveSession(MainWindow *window);
void loadSession(MainWindow *window);
bool willFileGetStoredInSession(ScintillaNext *editor) const;
private:
QDir sessionDirectory() const;
void saveIntoSessionDirectory(ScintillaNext *editor, const QString &sessionFileName) const;
SessionFileType determineType(ScintillaNext *editor) const;
void clearSettings() const;
void clearDirectory() const;
void storeFileDetails(ScintillaNext *editor, QSettings &settings);
ScintillaNext *loadFileDetails(QSettings &settings);
void storeUnsavedFileDetails(ScintillaNext *editor, QSettings &settings);
ScintillaNext *loadUnsavedFileDetails(QSettings &settings);
void storeTempFile(ScintillaNext *editor, QSettings &settings);
ScintillaNext *loadTempFile(QSettings &settings);
void storeEditorViewDetails(ScintillaNext *editor, QSettings &settings);
void loadEditorViewDetails(ScintillaNext *editor, QSettings &settings);
NotepadNextApplication *app;
SessionFileTypes fileTypes;
};
Q_DECLARE_OPERATORS_FOR_FLAGS(SessionManager::SessionFileTypes)
#endif // SESSIONMANAGER_H
| 2,410
|
C++
|
.h
| 59
| 37
| 95
| 0.777396
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,674
|
MacroStep.h
|
dail8859_NotepadNext/src/NotepadNext/MacroStep.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACROSTEP_H
#define MACROSTEP_H
#include "ScintillaNext.h"
class MacroStep {
public:
MacroStep() {}
MacroStep(Scintilla::Message message, uptr_t wParam, sptr_t lParam);
~MacroStep();
QString toString() const;
QString getName() const;
void replay(ScintillaNext *editor) const;
friend QDataStream &operator<<(QDataStream& stream, const MacroStep ¯oStep);
friend QDataStream &operator>>(QDataStream& stream, MacroStep ¯oStep);
static bool MessageHasString(Scintilla::Message message);
static QString NameOfMessage(Scintilla::Message message);
static QList<Scintilla::Message> RecordableMacroMessages();
Scintilla::Message message;
uptr_t wParam;
sptr_t lParam;
QByteArray str;
};
Q_DECLARE_METATYPE(MacroStep)
#endif // MACROSTEP_H
| 1,543
|
C++
|
.h
| 40
| 35.425
| 84
| 0.755526
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,675
|
LanguageInspectorDock.h
|
dail8859_NotepadNext/src/NotepadNext/docks/LanguageInspectorDock.h
|
/*
* This file is part of Notepad Next.
* Copyright 2021 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef LANGUAGEINSPECTORDOCK_H
#define LANGUAGEINSPECTORDOCK_H
#include <QDockWidget>
#include "ScintillaTypes.h"
class MainWindow;
class ScintillaNext;
namespace Ui {
class LanguageInspectorDock;
}
class LanguageInspectorDock : public QDockWidget
{
Q_OBJECT
public:
explicit LanguageInspectorDock(MainWindow *parent);
~LanguageInspectorDock();
private slots:
void connectToEditor(ScintillaNext *editor);
void updatePositionInfo(Scintilla::Update updated);
void updateLexerInfo(ScintillaNext *editor);
private:
Ui::LanguageInspectorDock *ui;
QMetaObject::Connection editorConnection;
QMetaObject::Connection documentConnection;
void disconnectFromEditor();
void updateLanguageName(ScintillaNext *editor);
void updatePropertyInfo(ScintillaNext *editor);
void updateKeywordInfo(ScintillaNext *editor);
void updateStyleInfo(ScintillaNext *editor);
};
#endif // LANGUAGEINSPECTORDOCK_H
| 1,678
|
C++
|
.h
| 47
| 32.914894
| 73
| 0.789376
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,676
|
LuaConsoleDock.h
|
dail8859_NotepadNext/src/NotepadNext/docks/LuaConsoleDock.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef LUACONSOLEDOCK_H
#define LUACONSOLEDOCK_H
#include <QDockWidget>
class ScintillaNext;
class LuaState;
namespace Ui {
class LuaConsoleDock;
}
class LuaConsoleDock : public QDockWidget
{
Q_OBJECT
public:
explicit LuaConsoleDock(LuaState *l, QWidget *parent = 0);
~LuaConsoleDock();
void writeToOutput(const char *s);
void writeErrorToOutput(const char *s);
LuaState *L = Q_NULLPTR;
public slots:
void runCurrentCommand(void);
protected:
bool eventFilter(QObject *obj, QEvent *event);
private:
Ui::LuaConsoleDock *ui;
ScintillaNext *output;
ScintillaNext *input;
void setupStyle(ScintillaNext *editor);
};
#endif // LUACONSOLEDOCK_H
| 1,428
|
C++
|
.h
| 45
| 28.977778
| 73
| 0.760234
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,677
|
SearchResultsDock.h
|
dail8859_NotepadNext/src/NotepadNext/docks/SearchResultsDock.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef SEARCHRESULTSDOCK_H
#define SEARCHRESULTSDOCK_H
#include <QDockWidget>
#include "ISearchResultsHandler.h"
namespace Ui {
class SearchResultsDock;
}
class QTreeWidgetItem;
class ScintillaNext;
class SearchResultsDock : public QDockWidget, public ISearchResultsHandler
{
Q_OBJECT
public:
explicit SearchResultsDock(QWidget *parent = nullptr);
~SearchResultsDock();
void newSearch(const QString searchTerm) override;
void newFileEntry(ScintillaNext *editor) override;
void newResultsEntry(const QString line, int lineNumber, int startPositionFromBeginning, int endPositionFromBeginning, int hitCount=1) override;
void completeSearch() override;
public slots:
void collapseAll() const;
void expandAll() const;
void deleteEntry(QTreeWidgetItem *item);
void deleteAll();
private slots:
void itemActivated(QTreeWidgetItem *item, int column);
void itemExpanded(QTreeWidgetItem *item);
void copySearchResultsToClipboard() ;
signals:
void searchResultActivated(ScintillaNext *editor, int lineNumber, int startPositionFromBeginning, int endPositionFromBeginning);
private:
void updateSearchStatus();
Ui::SearchResultsDock *ui;
QString searchTerm;
QString currentFilePath;
int currentFileCount = 0;
int totalFileHitCount = 0;
int totalHitCount = 0;
QTreeWidgetItem *currentSearch = Q_NULLPTR;
QTreeWidgetItem *currentFile = Q_NULLPTR;
};
#endif // SEARCHRESULTSDOCK_H
| 2,205
|
C++
|
.h
| 59
| 34.169492
| 148
| 0.781015
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,678
|
FolderAsWorkspaceDock.h
|
dail8859_NotepadNext/src/NotepadNext/docks/FolderAsWorkspaceDock.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef FOLDERASWORKSPACEDOCK_H
#define FOLDERASWORKSPACEDOCK_H
#include <QDockWidget>
namespace Ui {
class FolderAsWorkspaceDock;
}
class QFileSystemModel;
class FolderAsWorkspaceDock : public QDockWidget
{
Q_OBJECT
public:
explicit FolderAsWorkspaceDock(QWidget *parent = nullptr);
~FolderAsWorkspaceDock();
void setRootPath(const QString dir);
QString rootPath() const;
signals:
void fileDoubleClicked(const QString &filePath);
private:
Ui::FolderAsWorkspaceDock *ui;
QFileSystemModel *model;
};
#endif // FOLDERASWORKSPACEDOCK_H
| 1,304
|
C++
|
.h
| 39
| 30.897436
| 73
| 0.778132
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,679
|
FileListDock.h
|
dail8859_NotepadNext/src/NotepadNext/docks/FileListDock.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef FILELISTDOCK_H
#define FILELISTDOCK_H
#include "ScintillaNext.h"
#include <QDockWidget>
#include <QListWidgetItem>
namespace Ui {
class FileList;
}
class MainWindow;
class FileListDock : public QDockWidget
{
Q_OBJECT
public:
explicit FileListDock(MainWindow *parent);
~FileListDock();
private slots:
void refreshList();
void addEditor(ScintillaNext *editor);
void removeEditor(ScintillaNext *editor);
void selectCurrentEditor();
void itemClicked(QListWidgetItem *item);
void editorSavePointChanged(bool dirty);
void editorRenamed();
private:
QListWidgetItem *lookupItemByEditor(ScintillaNext *editor);
Ui::FileList *ui;
MainWindow *window;
};
#endif // FILELISTDOCK_H
| 1,470
|
C++
|
.h
| 46
| 29.152174
| 73
| 0.766501
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,680
|
DebugLogDock.h
|
dail8859_NotepadNext/src/NotepadNext/docks/DebugLogDock.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef DEBUGLOGDOCK_H
#define DEBUGLOGDOCK_H
#include <QDockWidget>
#include <QStringListModel>
namespace Ui {
class DebugLogDock;
}
class DebugLogDock : public QDockWidget
{
Q_OBJECT
public:
explicit DebugLogDock(QWidget *parent = nullptr);
~DebugLogDock();
private:
Ui::DebugLogDock *ui;
};
#endif // DEBUGLOGDOCK_H
| 1,070
|
C++
|
.h
| 34
| 29.294118
| 73
| 0.764591
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,681
|
EditorInspectorDock.h
|
dail8859_NotepadNext/src/NotepadNext/docks/EditorInspectorDock.h
|
/*
* This file is part of Notepad Next.
* Copyright 2021 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef EDITORINSPECTORDOCK_H
#define EDITORINSPECTORDOCK_H
#include <QDockWidget>
#include <QTreeWidgetItem>
#include "ScintillaTypes.h"
class MainWindow;
class ScintillaNext;
typedef std::function<QString(ScintillaNext *)> EditorFunction;
namespace Ui {
class EditorInspectorDock;
}
class EditorInspectorDock : public QDockWidget
{
Q_OBJECT
public:
explicit EditorInspectorDock(MainWindow *parent);
~EditorInspectorDock();
private slots:
void connectToEditor(ScintillaNext *editor);
void editorUIUpdated(Scintilla::Update updated);
void updateEditorInfo(ScintillaNext *editor);
private:
void newItem(QTreeWidgetItem *parent, const QString &label, EditorFunction func);
void disconnectFromEditor();
Ui::EditorInspectorDock *ui;
QTreeWidgetItem *selectionsInfo;
QMetaObject::Connection editorConnection;
QVector<QPair<QTreeWidgetItem *, EditorFunction>> items;
};
#endif // EDITORINSPECTORDOCK_H
| 1,685
|
C++
|
.h
| 47
| 33.191489
| 85
| 0.78633
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,682
|
HexViewerDock.h
|
dail8859_NotepadNext/src/NotepadNext/docks/HexViewerDock.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef HEXVIEWERDOCK_H
#define HEXVIEWERDOCK_H
#include <QDockWidget>
namespace Ui {
class HexViewerDock;
}
class MainWindow;
class ScintillaNext;
class HexViewerDock : public QDockWidget
{
Q_OBJECT
public:
explicit HexViewerDock(MainWindow *parent);
~HexViewerDock();
private slots:
void connectToEditor(ScintillaNext *editor);
private:
Ui::HexViewerDock *ui;
};
#endif // HEXVIEWERDOCK_H
| 1,148
|
C++
|
.h
| 37
| 28.783784
| 73
| 0.772025
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,683
|
PreferencesDialog.h
|
dail8859_NotepadNext/src/NotepadNext/dialogs/PreferencesDialog.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PREFERENCESDIALOG_H
#define PREFERENCESDIALOG_H
#include "ApplicationSettings.h"
#include <QDialog>
#include <QCheckBox>
#include <QGroupBox>
namespace Ui {
class PreferencesDialog;
}
class Settings;
class PreferencesDialog : public QDialog
{
Q_OBJECT
public:
PreferencesDialog(ApplicationSettings *settings, QWidget *parent = 0);
~PreferencesDialog();
void showApplicationRestartRequired() const;
private:
Ui::PreferencesDialog *ui;
ApplicationSettings *settings;
template <typename Func1, typename Func2, typename Func3>
void MapSettingToCheckBox(QCheckBox *checkBox, Func1 getter, Func2 setter, Func3 notifier) const;
template <typename Func1, typename Func2, typename Func3>
void MapSettingToGroupBox(QGroupBox *groupBox, Func1 getter, Func2 setter, Func3 notifier) const;
void populateTranslationComboBox();
};
#endif // PREFERENCESDIALOG_H
| 1,639
|
C++
|
.h
| 44
| 34.568182
| 101
| 0.779886
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,684
|
FindReplaceDialog.h
|
dail8859_NotepadNext/src/NotepadNext/dialogs/FindReplaceDialog.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef FINDREPLACEDIALOG_H
#define FINDREPLACEDIALOG_H
#include <QDialog>
#include <QEvent>
#include <QStatusBar>
#include <QTabBar>
#include "Finder.h"
#include "ISearchResultsHandler.h"
class ScintillaNext;
class MainWindow;
namespace Ui {
class FindReplaceDialog;
}
class FindReplaceDialog : public QDialog
{
Q_OBJECT
public:
enum {
FIND_TAB = 0,
REPLACE_TAB = 1,
FIND_IN_FILES_TAB = 2,
MARK_TAB = 3
};
explicit FindReplaceDialog(ISearchResultsHandler *searchResults, MainWindow *window = nullptr);
~FindReplaceDialog() override;
void setFindString(const QString &string);
void setTab(int tab);
QString replaceString();
void setSearchResultsHandler(ISearchResultsHandler *searchResultsHandler);
protected:
bool event(QEvent *event) override;
void showEvent(QShowEvent *event) override;
signals:
void windowActivated();
void windowDeactivated();
public slots:
void performLastSearch();
void find();
void findAllInCurrentDocument();
void findAllInDocuments();
void count();
void replace();
void replaceAll();
private slots:
void setEditor(ScintillaNext *edit);
void adjustOpacity(int value);
void transparencyToggled(bool on);
void adjustOpacityWhenLosingFocus(bool checked);
void adjustOpacityAlways(bool on);
void changeTab(int index);
private:
QString findString();
void prepareToPerformSearch(bool replace=false);
void loadSettings();
void saveSettings();
void savePosition();
void restorePosition();
int computeSearchFlags();
void showMessage(const QString &message, const QString &color);
void updateFindList(const QString &text);
void updateReplaceList(const QString &text);
bool isFirstTime = true;
QPoint lastClosedPosition;
Ui::FindReplaceDialog *ui;
ScintillaNext *editor;
QStatusBar *statusBar;
QTabBar *tabBar;
ISearchResultsHandler *searchResultsHandler;
Finder *finder;
};
#endif // FINDREPLACEDIALOG_H
| 2,782
|
C++
|
.h
| 88
| 27.761364
| 99
| 0.747657
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,685
|
ColumnEditorDialog.h
|
dail8859_NotepadNext/src/NotepadNext/dialogs/ColumnEditorDialog.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef COLUMNEDITORDIALOG_H
#define COLUMNEDITORDIALOG_H
#include "MainWindow.h"
#include <QDialog>
namespace Ui {
class ColumnEditorDialog;
}
class ColumnEditorDialog : public QDialog
{
Q_OBJECT
public:
explicit ColumnEditorDialog(MainWindow *parent);
~ColumnEditorDialog();
void insertTextStartingAtCurrentColumn(const std::function <QString (void)>& f);
void insertTextAtColumn(ScintillaNext *editor, int line, int column, const QString &str);
private:
Ui::ColumnEditorDialog *ui;
MainWindow *parent;
};
#endif // COLUMNEDITORDIALOG_H
| 1,303
|
C++
|
.h
| 37
| 32.783784
| 93
| 0.771679
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,686
|
MacroEditorDialog.h
|
dail8859_NotepadNext/src/NotepadNext/dialogs/MacroEditorDialog.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACROEDITORDIALOG_H
#define MACROEDITORDIALOG_H
#include <QDialog>
#include "MacroListModel.h"
#include "MacroStepTableModel.h"
#include "MacroManager.h"
namespace Ui {
class MacroEditorDialog;
}
class MacroEditorDialog : public QDialog
{
Q_OBJECT
public:
explicit MacroEditorDialog(QWidget *parent, MacroManager *mm);
~MacroEditorDialog();
private slots:
void rowChanged(const QModelIndex ¤t, const QModelIndex &previous);
void macroNameChanged(const QString &text);
void deleteCurrentMacro();
void copyCurrentMacro();
void insertMacroStep();
void deleteMacroStep();
void moveMacroStepUp();
void moveMacroStepDown();
private:
Ui::MacroEditorDialog *ui;
MacroManager *macroManager;
MacroListModel *model;
};
#endif // MACROEDITORDIALOG_H
| 1,547
|
C++
|
.h
| 47
| 30.12766
| 77
| 0.768145
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,687
|
MacroRunDialog.h
|
dail8859_NotepadNext/src/NotepadNext/dialogs/MacroRunDialog.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACRORUNDIALOG_H
#define MACRORUNDIALOG_H
#include <QDialog>
class Macro;
class MacroManager;
namespace Ui {
class MacroRunDialog;
}
class MacroRunDialog : public QDialog
{
Q_OBJECT
public:
MacroRunDialog(QWidget *parent, MacroManager *mm);
~MacroRunDialog();
protected:
void showEvent(QShowEvent *event) override;
signals:
void execute(Macro *macro, int times);
private:
Ui::MacroRunDialog *ui;
MacroManager *macroManager;
};
#endif // MACRORUNDIALOG_H
| 1,229
|
C++
|
.h
| 40
| 28.325
| 73
| 0.766355
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,688
|
MainWindow.h
|
dail8859_NotepadNext/src/NotepadNext/dialogs/MainWindow.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QActionGroup>
#include "DockedEditor.h"
#include "MacroManager.h"
#include "ScintillaNext.h"
#include "NppImporter.h"
#include "SearchResultsCollector.h"
namespace Ui {
class MainWindow;
}
class NotepadNextApplication;
class Macro;
class Settings;
class QuickFindWidget;
class ZoomEventWatcher;
class Converter;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(NotepadNextApplication *app);
~MainWindow() override;
bool isAnyUnsaved() const;
void setupLanguageMenu();
ScintillaNext *currentEditor() const;
int editorCount() const;
QVector<ScintillaNext *> editors() const;
DockedEditor *getDockedEditor() const { return dockedEditor; }
public slots:
void newFile();
void openFileDialog();
void openFile(const QString &filePath);
void openFolderAsWorkspaceDialog();
void reloadFile();
void closeCurrentFile();
void closeFile(ScintillaNext *editor);
void closeAllFiles();
void closeAllExceptActive();
void closeAllToLeft();
void closeAllToRight();
bool saveCurrentFile();
bool saveFile(ScintillaNext *editor);
bool saveCurrentFileAsDialog();
bool saveCurrentFileAs(const QString &fileName);
bool saveFileAs(ScintillaNext *editor, const QString &fileName);
bool saveCopyAsDialog();
bool saveCopyAs(const QString &fileName);
void saveAll();
void exportAsFormat(Converter *converter, const QString &filter);
void copyAsFormat(Converter *converter, const QString &mimeType);
void renameFile();
void moveCurrentFileToTrash();
void moveFileToTrash(ScintillaNext *editor);
void print();
void convertEOLs(int eolMode);
void showFindReplaceDialog(int index);
void updateFileStatusBasedUi(ScintillaNext *editor);
void updateEOLBasedUi(ScintillaNext *editor);
void updateDocumentBasedUi(Scintilla::Update updated);
void updateSelectionBasedUi(ScintillaNext *editor);
void updateContentBasedUi(ScintillaNext *editor);
void updateSaveStatusBasedUi(ScintillaNext *editor);
void updateEditorPositionBasedUi();
void updateLanguageBasedUi(ScintillaNext *editor);
void updateGui(ScintillaNext *editor);
void detectLanguage(ScintillaNext *editor);
void setLanguage(ScintillaNext *editor, const QString &languageName);
void bringWindowToForeground();
void focusIn();
void addEditor(ScintillaNext *editor);
void checkForUpdates(bool silent = false);
void restoreWindowState();
void switchToEditor(const ScintillaNext *editor);
signals:
void editorActivated(ScintillaNext *editor);
void aboutToClose();
protected:
void closeEvent(QCloseEvent *event) override;
void dragEnterEvent(QDragEnterEvent *event) override;
void dropEvent(QDropEvent *event) override;
private slots:
void tabBarRightClicked(ScintillaNext *editor);
void languageMenuTriggered();
void checkForUpdatesFinished(QString url);
void activateEditor(ScintillaNext *editor);
private:
Ui::MainWindow *ui = Q_NULLPTR;
NotepadNextApplication *app = Q_NULLPTR;
DockedEditor *dockedEditor = Q_NULLPTR;
QScopedPointer<SearchResultsCollector> searchResults;
void applyStyleSheet();
void applyCustomShortcuts();
void initUpdateCheck();
ScintillaNext *getInitialEditor();
void openFileList(const QStringList &fileNames);
bool checkEditorsBeforeClose(const QVector<ScintillaNext *> &editors);
bool checkFileForModification(ScintillaNext *editor);
void showSaveErrorMessage(ScintillaNext *editor, QFileDevice::FileError error);
void showEditorZoomLevelIndicator();
void saveSettings() const;
void restoreSettings();
ISearchResultsHandler *determineSearchResultsHandler();
QActionGroup *languageActionGroup;
//NppImporter *npp;
MacroManager macroManager;
ZoomEventWatcher *zoomEventWatcher;
int zoomLevel = 0;
int contextMenuPos = 0;
};
#endif // MAINWINDOW_H
| 4,817
|
C++
|
.h
| 130
| 32.992308
| 83
| 0.770739
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,689
|
MacroSaveDialog.h
|
dail8859_NotepadNext/src/NotepadNext/dialogs/MacroSaveDialog.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MACROSAVEDIALOG_H
#define MACROSAVEDIALOG_H
#include <QDialog>
namespace Ui {
class MacroSaveDialog;
}
class MacroSaveDialog : public QDialog
{
Q_OBJECT
public:
explicit MacroSaveDialog(QWidget *parent = 0);
~MacroSaveDialog();
QString getName() const;
QKeySequence getShortcut() const;
private:
Ui::MacroSaveDialog *ui;
};
#endif // MACROSAVEDIALOG_H
| 1,120
|
C++
|
.h
| 35
| 29.6
| 73
| 0.762082
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,690
|
EditorInfoStatusBar.h
|
dail8859_NotepadNext/src/NotepadNext/widgets/EditorInfoStatusBar.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef EDITORINFOSTATUSBAR_H
#define EDITORINFOSTATUSBAR_H
#include <QStatusBar>
#include "ScintillaTypes.h"
class QLabel;
class QMainWindow;
class ScintillaNext;
class EditorInfoStatusBar : public QStatusBar
{
Q_OBJECT
public:
explicit EditorInfoStatusBar(QMainWindow *window);
void refresh(ScintillaNext *editor);
private slots:
void connectToEditor(ScintillaNext *editor);
void editorUpdated(Scintilla::Update updated);
void updateDocumentSize(ScintillaNext *editor);
void updateSelectionInfo(ScintillaNext *editor);
void updateLanguage(ScintillaNext *editor);
void updateEol(ScintillaNext *editor);
void updateEncoding(ScintillaNext *editor);
void updateOverType(ScintillaNext *editor);
private:
QLabel *docType;
QLabel *docSize;
QLabel *docPos;
QLabel *unicodeType;
QLabel *eolFormat;
QLabel *overType;
QMetaObject::Connection editorUiUpdated;
QMetaObject::Connection documentLexerChanged;
};
#endif // EDITORINFOSTATUSBAR_H
| 1,749
|
C++
|
.h
| 50
| 31.84
| 73
| 0.77791
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,691
|
StatusLabel.h
|
dail8859_NotepadNext/src/NotepadNext/widgets/StatusLabel.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef STATUSLABEL_H
#define STATUSLABEL_H
#include <QLabel>
#include <QMouseEvent>
class ClickableLabel : public QLabel
{
Q_OBJECT
public:
explicit ClickableLabel(QWidget *parent=Q_NULLPTR, Qt::WindowFlags f=Qt::WindowFlags()) : QLabel(parent, f) {}
explicit ClickableLabel(const QString &text, QWidget *parent=Q_NULLPTR, Qt::WindowFlags f=Qt::WindowFlags()) : QLabel(text, parent, f) {}
signals:
void clicked();
protected:
void mouseReleaseEvent(QMouseEvent *event) override { Q_UNUSED(event); emit clicked(); }
void mouseDoubleClickEvent(QMouseEvent *event) override { emit customContextMenuRequested(event->pos()); }
};
class StatusLabel : public ClickableLabel
{
Q_OBJECT
public:
explicit StatusLabel(int size = 200, QWidget *parent = 0) : ClickableLabel(parent), preferredSize(size) {
// Since these get set a lot and plain text is always used go ahead and set the format
setTextFormat(Qt::PlainText);
}
protected:
QSize sizeHint() const override {
QSize size = ClickableLabel::sizeHint();
size.setWidth(preferredSize);
return size;
}
QSize minimumSizeHint() const override { return QSize(); }
private:
int preferredSize;
};
#endif // STATUSLABEL_H
| 1,990
|
C++
|
.h
| 52
| 34.903846
| 141
| 0.73947
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,692
|
HighlightedScrollBar.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/HighlightedScrollBar.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef HIGHLIGHTEDSCROLLBAR_H
#define HIGHLIGHTEDSCROLLBAR_H
#include <QScrollBar>
#include <QPointer>
#include "EditorDecorator.h"
class HighlightedScrollBar;
class HighlightedScrollBarDecorator : public EditorDecorator
{
Q_OBJECT
public:
explicit HighlightedScrollBarDecorator(ScintillaNext *editor);
~HighlightedScrollBarDecorator() override;
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
private:
HighlightedScrollBar *scrollBar;
};
class HighlightedScrollBar : public QScrollBar
{
Q_OBJECT
public:
explicit HighlightedScrollBar(ScintillaNext *editor, Qt::Orientation orientation, QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
private:
void drawMarker(QPainter &p, int marker);
void drawIndicator(QPainter &p, int indicator);
void drawCursors(QPainter &p);
void drawTickMark(QPainter &p, int y, int height, QColor color);
int posToScrollBarY(int pos) const;
int lineToScrollBarY(int line) const;
int scrollbarArrowHeight() const;
ScintillaNext *editor;
int smartHighlighterIndicator;
};
#endif // HIGHLIGHTEDSCROLLBAR_H
| 1,909
|
C++
|
.h
| 53
| 33.075472
| 113
| 0.781709
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,693
|
AutoCompletion.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/AutoCompletion.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef AUTOCOMPLETION_H
#define AUTOCOMPLETION_H
#include "EditorDecorator.h"
class AutoCompletion : public EditorDecorator
{
Q_OBJECT
public:
explicit AutoCompletion(ScintillaNext *editor);
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
void showAutoCompletion();
};
#endif // AUTOCOMPLETION_H
| 1,077
|
C++
|
.h
| 30
| 33.566667
| 73
| 0.772859
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,694
|
ApplicationDecorator.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/ApplicationDecorator.h
|
/*
* This file is part of Notepad Next.
* Copyright 2021 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef APPLICATIONDECORATOR_H
#define APPLICATIONDECORATOR_H
#include <QObject>
#include "NotepadNextApplication.h"
class ApplicationDecorator : public QObject
{
Q_OBJECT
Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY stateChanged)
public:
explicit ApplicationDecorator(NotepadNextApplication *app) : QObject(app), app(app) {}
bool isEnabled() const { return enabled; }
public slots:
void setEnabled(bool b);
signals:
void stateChanged(bool b);
protected:
NotepadNextApplication *app;
bool enabled = false;
};
#endif // APPLICATIONDECORATOR_H
| 1,330
|
C++
|
.h
| 37
| 33.351351
| 90
| 0.770671
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,695
|
EditorDecorator.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/EditorDecorator.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef EDITORDECORATOR_H
#define EDITORDECORATOR_H
#include <QObject>
#include "ScintillaNext.h"
class EditorDecorator : public QObject
{
Q_OBJECT
Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY stateChanged)
public:
explicit EditorDecorator(ScintillaNext *editor) : QObject(editor), editor(editor) {}
virtual ~EditorDecorator() {}
bool isEnabled() const { return enabled; }
ScintillaNext *getEditor() const { return editor; }
public slots:
void setEnabled(bool b);
virtual void notify(const Scintilla::NotificationData *pscn) = 0;
signals:
void stateChanged(bool b);
protected:
ScintillaNext *editor;
bool enabled = false;
};
#endif // EDITORDECORATOR_H
| 1,453
|
C++
|
.h
| 40
| 33.55
| 88
| 0.758916
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,696
|
EditorConfigAppDecorator.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/EditorConfigAppDecorator.h
|
/*
* This file is part of Notepad Next.
* Copyright 2021 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef EDITORCONFIGAPPDECORATOR_H
#define EDITORCONFIGAPPDECORATOR_H
#include "ApplicationDecorator.h"
class ScintillaNext;
class EditorConfigAppDecorator : public ApplicationDecorator
{
Q_OBJECT
public:
explicit EditorConfigAppDecorator(NotepadNextApplication *app);
private slots:
void doEditorConfig(ScintillaNext *editor);
void trimTrailingWhitespace();
void ensureFinalNewline();
void ensureNoFinalNewline();
};
#endif // EDITORCONFIGAPPDECORATOR_H
| 1,214
|
C++
|
.h
| 33
| 34.333333
| 73
| 0.786871
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,697
|
SmartHighlighter.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/SmartHighlighter.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef SMARTHIGHLIGHTER_H
#define SMARTHIGHLIGHTER_H
#include "EditorDecorator.h"
class SmartHighlighter : public EditorDecorator
{
Q_OBJECT
public:
SmartHighlighter(ScintillaNext *editor);
private:
void highlightCurrentView();
int indicator;
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
};
#endif // SMARTHIGHLIGHTER_H
| 1,109
|
C++
|
.h
| 32
| 32.25
| 73
| 0.773408
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,698
|
BraceMatch.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/BraceMatch.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef BRACEMATCH_H
#define BRACEMATCH_H
#include "EditorDecorator.h"
class BraceMatch : public EditorDecorator
{
Q_OBJECT
public:
BraceMatch(ScintillaNext *editor);
private:
void doHighlighting();
void clearHighlighting();
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
};
#endif // BRACEMATCH_H
| 1,084
|
C++
|
.h
| 32
| 31.46875
| 73
| 0.766059
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,699
|
SurroundSelection.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/SurroundSelection.h
|
/*
* This file is part of Notepad Next.
* Copyright 2020 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef SURROUNDSELECTION_H
#define SURROUNDSELECTION_H
#include <QObject>
#include <QWidget>
#include "EditorDecorator.h"
class SurroundSelection : public EditorDecorator
{
Q_OBJECT
public:
SurroundSelection(ScintillaNext *editor);
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
private:
void surroundSelections(const char ch1, const char ch2);
};
#endif // SURROUNDSELECTION_H
| 1,234
|
C++
|
.h
| 35
| 32.914286
| 73
| 0.776094
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,700
|
URLFinder.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/URLFinder.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef URLFINDER_H
#define URLFINDER_H
#include "EditorDecorator.h"
class URLFinder : public EditorDecorator
{
Q_OBJECT
public:
URLFinder(ScintillaNext *editor);
bool isURL(int position) const;
void copyURLToClipboard(int position) const;
private slots:
void findURLs();
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
private:
QTimer *timer;
int indicator;
};
#endif // URLFINDER_H
| 1,181
|
C++
|
.h
| 36
| 30.222222
| 73
| 0.761444
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,701
|
BookMarkDecorator.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/BookMarkDecorator.h
|
/*
* This file is part of Notepad Next.
* Copyright 2022 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "EditorDecorator.h"
class BookMarkDecorator : public EditorDecorator
{
Q_OBJECT
public:
BookMarkDecorator(ScintillaNext *editor);
void toggleBookmark(int line);
int nextBookmarkAfter(int line);
int previousBookMarkBefore(int line);
void clearBookmarks();
QList<int> bookMarkedLines() const;
void setBookMarkedLines(QList<int> &lines);
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
};
| 1,208
|
C++
|
.h
| 33
| 33.787879
| 73
| 0.764353
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,702
|
LineNumbers.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/LineNumbers.h
|
/*
* This file is part of Notepad Next.
* Copyright 2019 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef LINENUMBERS_H
#define LINENUMBERS_H
#include <QObject>
#include "EditorDecorator.h"
class LineNumbers : public EditorDecorator
{
Q_OBJECT
public:
LineNumbers(ScintillaNext *editor);
private:
void adjustMarginWidth();
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
};
#endif // LINENUMBERS_H
| 1,081
|
C++
|
.h
| 32
| 31.5
| 73
| 0.769231
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,703
|
AutoIndentation.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/AutoIndentation.h
|
/*
* This file is part of Notepad Next.
* Copyright 2021 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef AUTOINDENTATION_H
#define AUTOINDENTATION_H
#include "EditorDecorator.h"
class AutoIndentation : public EditorDecorator
{
Q_OBJECT
public:
AutoIndentation(ScintillaNext *editor);
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
private:
void autoIndentLine(int line) const;
};
#endif // AUTOINDENTATION_H
| 1,093
|
C++
|
.h
| 31
| 32.935484
| 73
| 0.773979
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,704
|
BetterMultiSelection.h
|
dail8859_NotepadNext/src/NotepadNext/decorators/BetterMultiSelection.h
|
/*
* This file is part of Notepad Next.
* Copyright 2021 Justin Dailey
*
* Notepad Next is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Notepad Next is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Notepad Next. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef BETTERMULTISELECTION_H
#define BETTERMULTISELECTION_H
#include <QObject>
#include <QWidget>
#include "EditorDecorator.h"
struct Selection;
class BetterMultiSelection : public EditorDecorator
{
Q_OBJECT
public:
BetterMultiSelection(ScintillaNext *editor);
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
public slots:
void notify(const Scintilla::NotificationData *pscn) override;
private:
QVector<Selection> GetSelections();
void SetSelections(const QVector<Selection> &selections);
void EditSelections(std::function<void(Selection &selection)> edit);
std::function<void(Selection &selection)> SimpleEdit(int message);
};
#endif // BETTERMULTISELECTION_H
| 1,454
|
C++
|
.h
| 39
| 34.717949
| 73
| 0.778174
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,731
|
scintilla-marshal.h
|
dail8859_NotepadNext/src/scintilla/gtk/scintilla-marshal.h
|
/* This file is generated, all changes will be lost */
#ifndef __SCINTILLA_MARSHAL_MARSHAL_H__
#define __SCINTILLA_MARSHAL_MARSHAL_H__
#include <glib-object.h>
G_BEGIN_DECLS
/* VOID:INT,OBJECT (scintilla-marshal.list:1) */
extern
void scintilla_marshal_VOID__INT_OBJECT (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data);
/* VOID:INT,BOXED (scintilla-marshal.list:2) */
extern
void scintilla_marshal_VOID__INT_BOXED (GClosure *closure,
GValue *return_value,
guint n_param_values,
const GValue *param_values,
gpointer invocation_hint,
gpointer marshal_data);
G_END_DECLS
#endif /* __SCINTILLA_MARSHAL_MARSHAL_H__ */
| 1,173
|
C++
|
.h
| 23
| 32.086957
| 71
| 0.467192
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
16,733
|
Wrappers.h
|
dail8859_NotepadNext/src/scintilla/gtk/Wrappers.h
|
// Scintilla source code edit control
// Wrappers.h - Encapsulation of GLib, GObject, Pango, Cairo, GTK, and GDK types
// Copyright 2022 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef WRAPPERS_H
#define WRAPPERS_H
namespace Scintilla::Internal {
// GLib
struct GFreeReleaser {
template <class T>
void operator()(T *object) noexcept {
g_free(object);
}
};
using UniqueStr = std::unique_ptr<gchar, GFreeReleaser>;
// GObject
struct GObjectReleaser {
// Called by unique_ptr to destroy/free the object
template <class T>
void operator()(T *object) noexcept {
g_object_unref(object);
}
};
// Pango
using UniquePangoContext = std::unique_ptr<PangoContext, GObjectReleaser>;
using UniquePangoLayout = std::unique_ptr<PangoLayout, GObjectReleaser>;
using UniquePangoFontMap = std::unique_ptr<PangoFontMap, GObjectReleaser>;
struct FontDescriptionReleaser {
void operator()(PangoFontDescription *fontDescription) noexcept {
pango_font_description_free(fontDescription);
}
};
using UniquePangoFontDescription = std::unique_ptr<PangoFontDescription, FontDescriptionReleaser>;
struct FontMetricsReleaser {
void operator()(PangoFontMetrics *metrics) noexcept {
pango_font_metrics_unref(metrics);
}
};
using UniquePangoFontMetrics = std::unique_ptr<PangoFontMetrics, FontMetricsReleaser>;
struct LayoutIterReleaser {
// Called by unique_ptr to destroy/free the object
void operator()(PangoLayoutIter *iter) noexcept {
pango_layout_iter_free(iter);
}
};
using UniquePangoLayoutIter = std::unique_ptr<PangoLayoutIter, LayoutIterReleaser>;
// Cairo
struct CairoReleaser {
void operator()(cairo_t *context) noexcept {
cairo_destroy(context);
}
};
using UniqueCairo = std::unique_ptr<cairo_t, CairoReleaser>;
struct CairoSurfaceReleaser {
void operator()(cairo_surface_t *psurf) noexcept {
cairo_surface_destroy(psurf);
}
};
using UniqueCairoSurface = std::unique_ptr<cairo_surface_t, CairoSurfaceReleaser>;
// GTK
using UniqueIMContext = std::unique_ptr<GtkIMContext, GObjectReleaser>;
// GDK
struct GdkEventReleaser {
void operator()(GdkEvent *ev) noexcept {
gdk_event_free(ev);
}
};
using UniqueGdkEvent = std::unique_ptr<GdkEvent, GdkEventReleaser>;
inline void UnRefCursor(GdkCursor *cursor) noexcept {
#if GTK_CHECK_VERSION(3,0,0)
g_object_unref(cursor);
#else
gdk_cursor_unref(cursor);
#endif
}
[[nodiscard]] inline GdkWindow *WindowFromWidget(GtkWidget *w) noexcept {
return gtk_widget_get_window(w);
}
}
#endif
| 2,564
|
C++
|
.h
| 80
| 30.2
| 98
| 0.789409
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,738
|
Sci_Position.h
|
dail8859_NotepadNext/src/scintilla/include/Sci_Position.h
|
// Scintilla source code edit control
/** @file Sci_Position.h
** Define the Sci_Position type used in Scintilla's external interfaces.
** These need to be available to clients written in C so are not in a C++ namespace.
**/
// Copyright 2015 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef SCI_POSITION_H
#define SCI_POSITION_H
#include <stddef.h>
// Basic signed type used throughout interface
typedef ptrdiff_t Sci_Position;
// Unsigned variant used for ILexer::Lex and ILexer::Fold
typedef size_t Sci_PositionU;
// For Sci_CharacterRange which is defined as long to be compatible with Win32 CHARRANGE
typedef long Sci_PositionCR;
#ifdef _WIN32
#define SCI_METHOD __stdcall
#else
#define SCI_METHOD
#endif
#endif
| 822
|
C++
|
.h
| 22
| 35.818182
| 94
| 0.788146
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
16,739
|
ILoader.h
|
dail8859_NotepadNext/src/scintilla/include/ILoader.h
|
// Scintilla source code edit control
/** @file ILoader.h
** Interface for loading into a Scintilla document from a background thread.
** Interface for manipulating a document without a view.
**/
// Copyright 1998-2017 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef ILOADER_H
#define ILOADER_H
#include "Sci_Position.h"
namespace Scintilla {
class ILoader {
public:
virtual int SCI_METHOD Release() = 0;
// Returns a status code from SC_STATUS_*
virtual int SCI_METHOD AddData(const char *data, Sci_Position length) = 0;
virtual void * SCI_METHOD ConvertToDocument() = 0;
};
static constexpr int deRelease0 = 0;
class IDocumentEditable {
public:
// Allow this interface to add methods over time and discover whether new methods available.
virtual int SCI_METHOD DEVersion() const noexcept = 0;
// Lifetime control
virtual int SCI_METHOD AddRef() noexcept = 0;
virtual int SCI_METHOD Release() = 0;
};
}
#endif
| 1,025
|
C++
|
.h
| 29
| 33.62069
| 94
| 0.77305
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,744
|
ScintillaWidget.h
|
dail8859_NotepadNext/src/scintilla/include/ScintillaWidget.h
|
/* Scintilla source code edit control */
/* @file ScintillaWidget.h
* Definition of Scintilla widget for GTK+.
* Only needed by GTK+ code but is harmless on other platforms.
* This comment is not a doc-comment as that causes warnings from g-ir-scanner.
*/
/* Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
* The License.txt file describes the conditions under which this software may be distributed. */
#ifndef SCINTILLAWIDGET_H
#define SCINTILLAWIDGET_H
#if defined(GTK)
#ifdef __cplusplus
extern "C" {
#endif
#define SCINTILLA(obj) G_TYPE_CHECK_INSTANCE_CAST (obj, scintilla_get_type (), ScintillaObject)
#define SCINTILLA_CLASS(klass) G_TYPE_CHECK_CLASS_CAST (klass, scintilla_get_type (), ScintillaClass)
#define IS_SCINTILLA(obj) G_TYPE_CHECK_INSTANCE_TYPE (obj, scintilla_get_type ())
#define SCINTILLA_TYPE_OBJECT (scintilla_object_get_type())
#define SCINTILLA_OBJECT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), SCINTILLA_TYPE_OBJECT, ScintillaObject))
#define SCINTILLA_IS_OBJECT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), SCINTILLA_TYPE_OBJECT))
#define SCINTILLA_OBJECT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), SCINTILLA_TYPE_OBJECT, ScintillaObjectClass))
#define SCINTILLA_IS_OBJECT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), SCINTILLA_TYPE_OBJECT))
#define SCINTILLA_OBJECT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), SCINTILLA_TYPE_OBJECT, ScintillaObjectClass))
typedef struct _ScintillaObject ScintillaObject;
typedef struct _ScintillaClass ScintillaObjectClass;
struct _ScintillaObject {
GtkContainer cont;
void *pscin;
};
struct _ScintillaClass {
GtkContainerClass parent_class;
void (* command) (ScintillaObject *sci, int cmd, GtkWidget *window);
void (* notify) (ScintillaObject *sci, int id, SCNotification *scn);
};
GType scintilla_object_get_type (void);
GtkWidget* scintilla_object_new (void);
gintptr scintilla_object_send_message (ScintillaObject *sci, unsigned int iMessage, guintptr wParam, gintptr lParam);
GType scnotification_get_type (void);
#define SCINTILLA_TYPE_NOTIFICATION (scnotification_get_type())
#ifndef G_IR_SCANNING
/* The legacy names confuse the g-ir-scanner program */
typedef struct _ScintillaClass ScintillaClass;
GType scintilla_get_type (void);
GtkWidget* scintilla_new (void);
void scintilla_set_id (ScintillaObject *sci, uptr_t id);
sptr_t scintilla_send_message (ScintillaObject *sci,unsigned int iMessage, uptr_t wParam, sptr_t lParam);
void scintilla_release_resources(void);
#endif
#define SCINTILLA_NOTIFY "sci-notify"
#ifdef __cplusplus
}
#endif
#endif
#endif
| 2,646
|
C++
|
.h
| 54
| 47.481481
| 121
| 0.767288
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
16,746
|
HanjaDic.h
|
dail8859_NotepadNext/src/scintilla/win32/HanjaDic.h
|
// Scintilla source code edit control
/** @file HanjaDic.h
** Korean Hanja Dictionary
** Convert between Korean Hanja and Hangul by COM interface.
**/
// Copyright 2015 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef HANJADIC_H
#define HANJADIC_H
namespace Scintilla::Internal {
namespace HanjaDict {
bool GetHangulOfHanja(std::wstring &inout) noexcept;
}
}
#endif
| 468
|
C++
|
.h
| 15
| 29.533333
| 94
| 0.793722
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,747
|
ScintillaWin.h
|
dail8859_NotepadNext/src/scintilla/win32/ScintillaWin.h
|
// Scintilla source code edit control
/** @file ScintillaWin.h
** Define functions from ScintillaWin.cxx that can be called from ScintillaDLL.cxx.
**/
// Copyright 1998-2018 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef SCINTILLAWIN_H
#define SCINTILLAWIN_H
namespace Scintilla::Internal {
class ScintillaWin;
int ResourcesRelease(bool fromDllMain) noexcept;
int RegisterClasses(void *hInstance) noexcept;
Scintilla::sptr_t DirectFunction(ScintillaWin *sci, UINT iMessage, Scintilla::uptr_t wParam, Scintilla::sptr_t lParam);
}
#endif
| 638
|
C++
|
.h
| 15
| 41
| 119
| 0.811994
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,750
|
QuartzTextStyleAttribute.h
|
dail8859_NotepadNext/src/scintilla/cocoa/QuartzTextStyleAttribute.h
|
/**
* QuartzTextStyleAttribute.h
*
* Original Code by Evan Jones on Wed Oct 02 2002.
* Contributors:
* Shane Caraveo, ActiveState
* Bernd Paradies, Adobe
*
*/
#ifndef QUARTZTEXTSTYLEATTRIBUTE_H
#define QUARTZTEXTSTYLEATTRIBUTE_H
// Convert from a FontWeight value to a floating point value to pass to CoreText.
// This was defined based on Cocoa's NSFontWeight* values, discussion by other open
// source projects then tweaked until most values produced visibly different results.
inline double WeightFromEnumeration(Scintilla::FontWeight weight) {
switch (static_cast<int>(weight)/100) {
case 0: return -1.0;
case 1: return -0.7;
case 2: return -0.5;
case 3: return -0.23;
case 4: return 0.0;
case 5: return 0.2;
case 6: return 0.3;
case 7: return 0.4;
case 8: return 0.6;
case 9: return 0.8;
}
return 0.0;
}
// Convert from a FontStretch value to a floating point value to pass to CoreText.
// This was defined based on values used by other open source projects then tweaked
// until most values produced reasonable results.
inline double StretchFromEnumeration(Scintilla::FontStretch stretch) {
switch (stretch) {
case Scintilla::FontStretch::UltraCondensed: return -0.8;
case Scintilla::FontStretch::ExtraCondensed: return -0.3;
case Scintilla::FontStretch::Condensed: return -0.23;
case Scintilla::FontStretch::SemiCondensed: return -0.1;
case Scintilla::FontStretch::Normal: return 0.0;
case Scintilla::FontStretch::SemiExpanded: return 0.1;
case Scintilla::FontStretch::Expanded: return 0.2;
case Scintilla::FontStretch::ExtraExpanded: return 0.3;
case Scintilla::FontStretch::UltraExpanded: return 0.7;
}
}
class QuartzFont {
public:
/** Create a font style from a name. */
QuartzFont(const char *name, size_t length, float size, Scintilla::FontWeight weight, Scintilla::FontStretch stretch, bool italic) {
assert(name != NULL && length > 0 && name[length] == '\0');
CFStringRef fontName = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingMacRoman);
assert(fontName != NULL);
// Specify the weight, stretch, and italics
DictionaryForCF traits;
const double weightValue = WeightFromEnumeration(weight);
traits.SetItem(kCTFontWeightTrait, kCFNumberCGFloatType, &weightValue);
const double stretchValue = StretchFromEnumeration(stretch);
traits.SetItem(kCTFontWidthTrait, kCFNumberCGFloatType, &stretchValue);
if (italic) {
const int italicValue = kCTFontTraitItalic;
traits.SetItem(kCTFontSymbolicTrait, kCFNumberIntType, &italicValue);
}
// create a font decriptor and then a font with that descriptor
DictionaryForCF attributes;
attributes.SetValue(kCTFontTraitsAttribute, traits.get());
attributes.SetValue(kCTFontNameAttribute, fontName);
CTFontDescriptorRef desc = ::CTFontDescriptorCreateWithAttributes(attributes.get());
fontid = ::CTFontCreateWithFontDescriptor(desc, size, NULL);
CFRelease(desc);
if (!fontid) {
// Traits failed so use base font
fontid = ::CTFontCreateWithName(fontName, size, NULL);
}
if (!fontid) {
// Failed to create requested font so use font always present
fontid = ::CTFontCreateWithName((CFStringRef)@"Monaco", size, NULL);
}
CFRelease(fontName);
}
CTFontRef getFontID() {
return fontid;
}
private:
CTFontRef fontid;
};
#endif
| 3,331
|
C++
|
.h
| 86
| 36.127907
| 133
| 0.766873
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,751
|
InfoBarCommunicator.h
|
dail8859_NotepadNext/src/scintilla/cocoa/InfoBarCommunicator.h
|
/*
* InfoBarCommunicator.h - Definitions of a communication protocol and other data types used for
* the info bar implementation.
*
* Mike Lischke <mlischke@sun.com>
*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* This file is dual licensed under LGPL v2.1 and the Scintilla license (http://www.scintilla.org/License.txt).
*/
typedef NS_OPTIONS(NSUInteger, IBDisplay) {
IBShowZoom = 0x01,
IBShowCaretPosition = 0x02,
IBShowStatusText = 0x04,
IBShowAll = 0xFF
};
/**
* The info bar communicator protocol is used for communication between ScintillaView and its
* information bar component. Using this protocol decouples any potential info target from the main
* ScintillaView implementation. The protocol is used two-way.
*/
typedef NS_ENUM(NSInteger, NotificationType) {
IBNZoomChanged, // The user selected another zoom value.
IBNCaretChanged, // The caret in the editor changed.
IBNStatusChanged, // The application set a new status message.
};
@protocol InfoBarCommunicator
- (void) notify: (NotificationType) type message: (NSString *) message location: (NSPoint) location
value: (float) value;
- (void) setCallback: (id <InfoBarCommunicator>) callback;
@end
| 1,258
|
C++
|
.h
| 30
| 40.033333
| 111
| 0.747343
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
16,752
|
DictionaryForCF.h
|
dail8859_NotepadNext/src/scintilla/cocoa/DictionaryForCF.h
|
/**
* Scintilla source code edit control
* @file DictionaryForCF.h - Wrapper for CFMutableDictionary
*
* Copyright 2024 Neil Hodgson.
* This file is dual licensed under LGPL v2.1 and the Scintilla license (http://www.scintilla.org/License.txt).
*/
#ifndef DICTIONARYFORCF_H
#define DICTIONARYFORCF_H
class DictionaryForCF {
CFMutableDictionaryRef dict;
public:
DictionaryForCF() noexcept :
dict(::CFDictionaryCreateMutable(kCFAllocatorDefault, 2,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks)) {
}
~DictionaryForCF() {
::CFRelease(dict);
}
CFMutableDictionaryRef get() const noexcept {
return dict;
}
void SetValue(const void *key, const void *value) noexcept {
::CFDictionarySetValue(dict, key, value);
}
void SetItem(const void *key, CFNumberType theType, const void *valuePtr) noexcept {
CFNumberRef number = ::CFNumberCreate(kCFAllocatorDefault, theType, valuePtr);
::CFDictionarySetValue(dict, key, number);
::CFRelease(number);
}
};
#endif
| 1,011
|
C++
|
.h
| 33
| 28.272727
| 111
| 0.774359
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,753
|
ScintillaView.h
|
dail8859_NotepadNext/src/scintilla/cocoa/ScintillaView.h
|
/**
* Declaration of the native Cocoa View that serves as container for the scintilla parts.
* @file ScintillaView.h
*
* Created by Mike Lischke.
*
* Copyright 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright 2009, 2011 Sun Microsystems, Inc. All rights reserved.
* This file is dual licensed under LGPL v2.1 and the Scintilla license (http://www.scintilla.org/License.txt).
*/
#import <Cocoa/Cocoa.h>
#import "Scintilla.h"
#import "InfoBarCommunicator.h"
/**
* Scintilla sends these two messages to the notify handler. Please refer
* to the Windows API doc for details about the message format.
*/
#define WM_COMMAND 1001
#define WM_NOTIFY 1002
/**
* On the Mac, there is no WM_COMMAND or WM_NOTIFY message that can be sent
* back to the parent. Therefore, there must be a callback handler that acts
* like a Windows WndProc, where Scintilla can send notifications to. Use
* ScintillaView registerNotifyCallback() to register such a handler.
* Message format is:
* <br>
* WM_COMMAND: HIWORD (wParam) = notification code, LOWORD (wParam) = control ID, lParam = ScintillaCocoa*
* <br>
* WM_NOTIFY: wParam = control ID, lParam = ptr to SCNotification structure, with hwndFrom set to ScintillaCocoa*
*/
typedef void(*SciNotifyFunc)(intptr_t windowid, unsigned int iMessage, uintptr_t wParam, uintptr_t lParam);
extern NSString *const SCIUpdateUINotification;
@protocol ScintillaNotificationProtocol
- (void) notification: (SCNotification *) notification;
@end
/**
* SCIScrollView provides pre-macOS 10.14 tiling behavior.
*/
@interface SCIScrollView : NSScrollView;
@end
/**
* SCIMarginView draws line numbers and other margins next to the text view.
*/
@interface SCIMarginView : NSRulerView;
@end
/**
* SCIContentView is the Cocoa interface to the Scintilla backend. It handles text input and
* provides a canvas for painting the output.
*/
@interface SCIContentView : NSView <
NSTextInputClient,
NSUserInterfaceValidations,
NSDraggingSource,
NSDraggingDestination,
NSAccessibilityStaticText>;
- (void) setCursor: (int) cursor; // Needed by ScintillaCocoa
@end
/**
* ScintillaView is the class instantiated by client code.
* It contains an NSScrollView which contains a SCIMarginView and a SCIContentView.
* It is responsible for providing an API and communicating to a delegate.
*/
@interface ScintillaView : NSView <InfoBarCommunicator, ScintillaNotificationProtocol>;
@property(nonatomic, unsafe_unretained) id<ScintillaNotificationProtocol> delegate;
@property(nonatomic, readonly) NSScrollView *scrollView;
+ (Class) contentViewClass;
- (void) notify: (NotificationType) type message: (NSString *) message location: (NSPoint) location
value: (float) value;
- (void) setCallback: (id <InfoBarCommunicator>) callback;
- (void) suspendDrawing: (BOOL) suspend;
- (void) notification: (SCNotification *) notification;
- (void) updateIndicatorIME;
// Scroller handling
- (void) setMarginWidth: (int) width;
- (SCIContentView *) content;
- (void) updateMarginCursors;
// NSTextView compatibility layer.
- (NSString *) string;
- (void) setString: (NSString *) aString;
- (void) insertText: (id) aString;
- (void) setEditable: (BOOL) editable;
- (BOOL) isEditable;
- (NSRange) selectedRange;
- (NSRange) selectedRangePositions;
- (NSString *) selectedString;
- (void) deleteRange: (NSRange) range;
- (void) setFontName: (NSString *) font
size: (int) size
bold: (BOOL) bold
italic: (BOOL) italic;
// Native call through to the backend.
+ (sptr_t) directCall: (ScintillaView *) sender message: (unsigned int) message wParam: (uptr_t) wParam
lParam: (sptr_t) lParam;
- (sptr_t) message: (unsigned int) message wParam: (uptr_t) wParam lParam: (sptr_t) lParam;
- (sptr_t) message: (unsigned int) message wParam: (uptr_t) wParam;
- (sptr_t) message: (unsigned int) message;
// Back end properties getters and setters.
- (void) setGeneralProperty: (int) property parameter: (long) parameter value: (long) value;
- (void) setGeneralProperty: (int) property value: (long) value;
- (long) getGeneralProperty: (int) property;
- (long) getGeneralProperty: (int) property parameter: (long) parameter;
- (long) getGeneralProperty: (int) property parameter: (long) parameter extra: (long) extra;
- (long) getGeneralProperty: (int) property ref: (const void *) ref;
- (void) setColorProperty: (int) property parameter: (long) parameter value: (NSColor *) value;
- (void) setColorProperty: (int) property parameter: (long) parameter fromHTML: (NSString *) fromHTML;
- (NSColor *) getColorProperty: (int) property parameter: (long) parameter;
- (void) setReferenceProperty: (int) property parameter: (long) parameter value: (const void *) value;
- (const void *) getReferenceProperty: (int) property parameter: (long) parameter;
- (void) setStringProperty: (int) property parameter: (long) parameter value: (NSString *) value;
- (NSString *) getStringProperty: (int) property parameter: (long) parameter;
- (void) setLexerProperty: (NSString *) name value: (NSString *) value;
- (NSString *) getLexerProperty: (NSString *) name;
// The delegate property should be used instead of registerNotifyCallback which is deprecated.
- (void) registerNotifyCallback: (intptr_t) windowid value: (SciNotifyFunc) callback __attribute__ ( (deprecated)) ;
- (void) setInfoBar: (NSView <InfoBarCommunicator> *) aView top: (BOOL) top;
- (void) setStatusText: (NSString *) text;
- (BOOL) findAndHighlightText: (NSString *) searchText
matchCase: (BOOL) matchCase
wholeWord: (BOOL) wholeWord
scrollTo: (BOOL) scrollTo
wrap: (BOOL) wrap;
- (BOOL) findAndHighlightText: (NSString *) searchText
matchCase: (BOOL) matchCase
wholeWord: (BOOL) wholeWord
scrollTo: (BOOL) scrollTo
wrap: (BOOL) wrap
backwards: (BOOL) backwards;
- (int) findAndReplaceText: (NSString *) searchText
byText: (NSString *) newText
matchCase: (BOOL) matchCase
wholeWord: (BOOL) wholeWord
doAll: (BOOL) doAll;
@end
| 6,033
|
C++
|
.h
| 133
| 43.112782
| 116
| 0.751918
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
16,754
|
PlatCocoa.h
|
dail8859_NotepadNext/src/scintilla/cocoa/PlatCocoa.h
|
/**
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* This file is dual licensed under LGPL v2.1 and the Scintilla license (http://www.scintilla.org/License.txt).
* @file PlatCocoa.h
*/
#ifndef PLATCOCOA_H
#define PLATCOCOA_H
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <Cocoa/Cocoa.h>
#include "ScintillaTypes.h"
#include "ScintillaMessages.h"
#include "Debugging.h"
#include "Geometry.h"
#include "Platform.h"
#include "DictionaryForCF.h"
#include "QuartzTextLayout.h"
NSRect PRectangleToNSRect(const Scintilla::Internal::PRectangle &rc);
Scintilla::Internal::PRectangle NSRectToPRectangle(const NSRect &rc);
CFStringEncoding EncodingFromCharacterSet(bool unicode, Scintilla::CharacterSet characterSet);
@interface ScintillaContextMenu : NSMenu {
Scintilla::Internal::ScintillaCocoa *owner;
}
- (void) handleCommand: (NSMenuItem *) sender;
- (void) setOwner: (Scintilla::Internal::ScintillaCocoa *) newOwner;
@end
namespace Scintilla::Internal {
// A class to do the actual text rendering for us using Quartz 2D.
class SurfaceImpl : public Surface {
private:
SurfaceMode mode;
CGContextRef gc;
/** If the surface is a bitmap context, contains a reference to the bitmap data. */
std::unique_ptr<uint8_t[]> bitmapData;
/** If the surface is a bitmap context, stores the dimensions of the bitmap. */
int bitmapWidth;
int bitmapHeight;
/** Set the CGContext's fill colour to the specified desired colour. */
void FillColour(ColourRGBA fill);
void PenColourAlpha(ColourRGBA fore);
void SetFillStroke(FillStroke fillStroke);
// 24-bit RGB+A bitmap data constants
static const int BITS_PER_COMPONENT = 8;
static const int BITS_PER_PIXEL = BITS_PER_COMPONENT * 4;
static const int BYTES_PER_PIXEL = BITS_PER_PIXEL / 8;
bool UnicodeMode() const noexcept;
void Clear();
public:
SurfaceImpl();
SurfaceImpl(const SurfaceImpl *surface, int width, int height);
~SurfaceImpl() override;
void Init(WindowID wid) override;
void Init(SurfaceID sid, WindowID wid) override;
std::unique_ptr<Surface> AllocatePixMap(int width, int height) override;
std::unique_ptr<SurfaceImpl> AllocatePixMapImplementation(int width, int height);
CGContextRef GetContext() { return gc; }
void SetMode(SurfaceMode mode) override;
void Release() noexcept override;
int SupportsFeature(Scintilla::Supports feature) noexcept override;
bool Initialised() override;
/** Returns a CGImageRef that represents the surface. Returns NULL if this is not possible. */
CGImageRef CreateImage();
void CopyImageRectangle(SurfaceImpl *source, PRectangle srcRect, PRectangle dstRect);
int LogPixelsY() override;
int PixelDivisions() override;
int DeviceHeightFont(int points) override;
void LineDraw(Point start, Point end, Stroke stroke) override;
void PolyLine(const Point *pts, size_t npts, Stroke stroke) override;
void Polygon(const Scintilla::Internal::Point *pts, size_t npts, FillStroke fillStroke) override;
void RectangleDraw(PRectangle rc, FillStroke fillStroke) override;
void RectangleFrame(PRectangle rc, Stroke stroke) override;
void FillRectangle(PRectangle rc, Fill fill) override;
void FillRectangleAligned(PRectangle rc, Fill fill) override;
void FillRectangle(PRectangle rc, Surface &surfacePattern) override;
void RoundedRectangle(PRectangle rc, FillStroke fillStroke) override;
void AlphaRectangle(PRectangle rc, XYPOSITION cornerSize, FillStroke fillStroke) override;
void GradientRectangle(PRectangle rc, const std::vector<ColourStop> &stops, GradientOptions options) override;
void DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) override;
void Ellipse(PRectangle rc, FillStroke fillStroke) override;
void Stadium(PRectangle rc, FillStroke fillStroke, Ends ends) override;
void Copy(PRectangle rc, Scintilla::Internal::Point from, Surface &surfaceSource) override;
std::unique_ptr<IScreenLineLayout> Layout(const IScreenLine *screenLine) override;
void DrawTextNoClip(PRectangle rc, const Font *font_, XYPOSITION ybase, std::string_view text, ColourRGBA fore,
ColourRGBA back) override;
void DrawTextClipped(PRectangle rc, const Font *font_, XYPOSITION ybase, std::string_view text, ColourRGBA fore,
ColourRGBA back) override;
void DrawTextTransparent(PRectangle rc, const Font *font_, XYPOSITION ybase, std::string_view text, ColourRGBA fore) override;
void MeasureWidths(const Font *font_, std::string_view text, XYPOSITION *positions) override;
XYPOSITION WidthText(const Font *font_, std::string_view text) override;
void DrawTextNoClipUTF8(PRectangle rc, const Font *font_, XYPOSITION ybase, std::string_view text, ColourRGBA fore,
ColourRGBA back) override;
void DrawTextClippedUTF8(PRectangle rc, const Font *font_, XYPOSITION ybase, std::string_view text, ColourRGBA fore,
ColourRGBA back) override;
void DrawTextTransparentUTF8(PRectangle rc, const Font *font_, XYPOSITION ybase, std::string_view text, ColourRGBA fore) override;
void MeasureWidthsUTF8(const Font *font_, std::string_view text, XYPOSITION *positions) override;
XYPOSITION WidthTextUTF8(const Font *font_, std::string_view text) override;
XYPOSITION Ascent(const Font *font_) override;
XYPOSITION Descent(const Font *font_) override;
XYPOSITION InternalLeading(const Font *font_) override;
XYPOSITION Height(const Font *font_) override;
XYPOSITION AverageCharWidth(const Font *font_) override;
void SetClip(PRectangle rc) override;
void PopClip() override;
void FlushCachedState() override;
void FlushDrawing() override;
}; // SurfaceImpl class
} // Scintilla namespace
#endif
| 5,652
|
C++
|
.h
| 110
| 49.136364
| 131
| 0.795826
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,755
|
ScintillaCocoa.h
|
dail8859_NotepadNext/src/scintilla/cocoa/ScintillaCocoa.h
|
/*
* ScintillaCocoa.h
*
* Mike Lischke <mlischke@sun.com>
*
* Based on ScintillaMacOSX.h
* Original code by Evan Jones on Sun Sep 01 2002.
* Contributors:
* Shane Caraveo, ActiveState
* Bernd Paradies, Adobe
*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* This file is dual licensed under LGPL v2.1 and the Scintilla license (http://www.scintilla.org/License.txt).
*/
#include <cstddef>
#include <cstdlib>
#include <cstdint>
#include <cstdio>
#include <ctime>
#include <stdexcept>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <memory>
#include "ILoader.h"
#include "ILexer.h"
#include "CharacterCategoryMap.h"
#include "Position.h"
#include "UniqueString.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "CaseConvert.h"
#include "UniConversion.h"
#include "DBCS.h"
#include "Selection.h"
#include "PositionCache.h"
#include "EditModel.h"
#include "MarginView.h"
#include "EditView.h"
#include "Editor.h"
#include "AutoComplete.h"
#include "ScintillaBase.h"
extern "C" NSString *ScintillaRecPboardType;
@class SCIContentView;
@class SCIMarginView;
@class ScintillaView;
@class FindHighlightLayer;
/**
* Helper class to be used as timer target (NSTimer).
*/
@interface TimerTarget : NSObject {
void *mTarget;
NSNotificationQueue *notificationQueue;
}
- (id) init: (void *) target;
- (void) timerFired: (NSTimer *) timer;
- (void) idleTimerFired: (NSTimer *) timer;
- (void) idleTriggered: (NSNotification *) notification;
@end
namespace Scintilla::Internal {
CGContextRef CGContextCurrent();
/**
* Main scintilla class, implemented for macOS (Cocoa).
*/
class ScintillaCocoa : public ScintillaBase {
private:
__weak ScintillaView *sciView;
TimerTarget *timerTarget;
NSEvent *lastMouseEvent;
__weak id<ScintillaNotificationProtocol> delegate;
SciNotifyFunc notifyProc;
intptr_t notifyObj;
bool capturedMouse;
bool isFirstResponder;
bool isActive;
Point sizeClient;
bool enteredSetScrollingSize;
bool GetPasteboardData(NSPasteboard *board, SelectionText *selectedText);
void SetPasteboardData(NSPasteboard *board, const SelectionText &selectedText);
Sci::Position TargetAsUTF8(char *text) const;
Sci::Position EncodedFromUTF8(const char *utf8, char *encoded) const;
int scrollSpeed;
int scrollTicks;
CFRunLoopObserverRef observer;
FindHighlightLayer *layerFindIndicator;
protected:
Point GetVisibleOriginInMain() const override;
Point ClientSize() const override;
PRectangle GetClientRectangle() const override;
PRectangle GetClientDrawingRectangle() override;
Point ConvertPoint(NSPoint point);
void RedrawRect(PRectangle rc) override;
void DiscardOverdraw() override;
void Redraw() override;
void Init();
std::unique_ptr<CaseFolder> CaseFolderForEncoding() override;
std::string CaseMapString(const std::string &s, CaseMapping caseMapping) override;
void CancelModes() override;
public:
ScintillaCocoa(ScintillaView *sciView_, SCIContentView *viewContent, SCIMarginView *viewMargin);
// Deleted so ScintillaCocoa objects can not be copied.
ScintillaCocoa(const ScintillaCocoa &) = delete;
ScintillaCocoa &operator=(const ScintillaCocoa &) = delete;
~ScintillaCocoa() override;
void Finalise() override;
void SetDelegate(id<ScintillaNotificationProtocol> delegate_);
void RegisterNotifyCallback(intptr_t windowid, SciNotifyFunc callback);
sptr_t WndProc(Scintilla::Message iMessage, uptr_t wParam, sptr_t lParam) override;
NSScrollView *ScrollContainer() const;
SCIContentView *ContentView();
bool SyncPaint(void *gc, PRectangle rc);
bool Draw(NSRect rect, CGContextRef gc);
void PaintMargin(NSRect aRect);
sptr_t DefWndProc(Scintilla::Message iMessage, uptr_t wParam, sptr_t lParam) override;
void TickFor(TickReason reason) override;
bool FineTickerRunning(TickReason reason) override;
void FineTickerStart(TickReason reason, int millis, int tolerance) override;
void FineTickerCancel(TickReason reason) override;
bool SetIdle(bool on) override;
void SetMouseCapture(bool on) override;
bool HaveMouseCapture() override;
void WillDraw(NSRect rect);
void ScrollText(Sci::Line linesToMove) override;
void SetVerticalScrollPos() override;
void SetHorizontalScrollPos() override;
bool ModifyScrollBars(Sci::Line nMax, Sci::Line nPage) override;
bool SetScrollingSize();
void Resize();
void UpdateForScroll();
// Notifications for the owner.
void NotifyChange() override;
void NotifyFocus(bool focus) override;
void NotifyParent(Scintilla::NotificationData scn) override;
void NotifyURIDropped(const char *uri);
bool HasSelection();
bool CanUndo();
bool CanRedo();
void CopyToClipboard(const SelectionText &selectedText) override;
void Copy() override;
bool CanPaste() override;
void Paste() override;
void Paste(bool rectangular);
void CTPaint(void *gc, NSRect rc);
void CallTipMouseDown(NSPoint pt);
void CreateCallTipWindow(PRectangle rc) override;
void AddToPopUp(const char *label, int cmd = 0, bool enabled = true) override;
void ClaimSelection() override;
NSPoint GetCaretPosition();
std::string UTF8FromEncoded(std::string_view encoded) const override;
std::string EncodedFromUTF8(std::string_view utf8) const override;
static sptr_t DirectFunction(sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam);
static sptr_t DirectStatusFunction(sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam, int *pStatus);
NSTimer *timers[static_cast<size_t>(TickReason::platform)+1];
void TimerFired(NSTimer *timer);
void IdleTimerFired();
static void UpdateObserver(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *sci);
void ObserverAdd();
void ObserverRemove();
void IdleWork() override;
void QueueIdleWork(WorkItems items, Sci::Position upTo) override;
ptrdiff_t InsertText(NSString *input, Scintilla::CharacterSource charSource);
NSRange PositionsFromCharacters(NSRange rangeCharacters) const;
NSRange CharactersFromPositions(NSRange rangePositions) const;
NSString *RangeTextAsString(NSRange rangePositions) const;
NSInteger VisibleLineForIndex(NSInteger index);
NSRange RangeForVisibleLine(NSInteger lineVisible);
NSRect FrameForRange(NSRange rangeCharacters);
NSRect GetBounds() const;
void SelectOnlyMainSelection();
void ConvertSelectionVirtualSpace();
bool ClearAllSelections();
void CompositionStart();
void CompositionCommit();
void CompositionUndo();
void SetDocPointer(Document *document) override;
bool KeyboardInput(NSEvent *event);
void MouseDown(NSEvent *event);
void RightMouseDown(NSEvent *event);
void MouseMove(NSEvent *event);
void MouseUp(NSEvent *event);
void MouseEntered(NSEvent *event);
void MouseExited(NSEvent *event);
void MouseWheel(NSEvent *event);
// Drag and drop
void StartDrag() override;
bool GetDragData(id <NSDraggingInfo> info, NSPasteboard &pasteBoard, SelectionText *selectedText);
NSDragOperation DraggingEntered(id <NSDraggingInfo> info);
NSDragOperation DraggingUpdated(id <NSDraggingInfo> info);
void DraggingExited(id <NSDraggingInfo> info);
bool PerformDragOperation(id <NSDraggingInfo> info);
void DragScroll();
// Promote some methods needed for NSResponder actions.
void SelectAll() override;
void DeleteBackward();
void Cut() override;
void Undo() override;
void Redo() override;
bool ShouldDisplayPopupOnMargin();
bool ShouldDisplayPopupOnText();
NSMenu *CreateContextMenu(NSEvent *event);
void HandleCommand(NSInteger command);
void SetFirstResponder(bool isFirstResponder_);
void ActiveStateChanged(bool isActive_);
void SetFocusActiveState();
void UpdateBaseElements() override;
void WindowWillMove();
// Find indicator
void ShowFindIndicatorForRange(NSRange charRange, BOOL retaining);
void MoveFindIndicatorWithBounce(BOOL bounce);
void HideFindIndicator();
};
}
| 8,120
|
C++
|
.h
| 226
| 34.022124
| 115
| 0.804586
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,756
|
InfoBar.h
|
dail8859_NotepadNext/src/scintilla/cocoa/InfoBar.h
|
/**
* Scintilla source code edit control
* @file InfoBar.h - Implements special info bar with zoom info, caret position etc. to be used with
* ScintillaView.
*
* Mike Lischke <mlischke@sun.com>
*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* This file is dual licensed under LGPL v2.1 and the Scintilla license (http://www.scintilla.org/License.txt).
*/
#import <Cocoa/Cocoa.h>
#import "InfoBarCommunicator.h"
/**
* Extended text cell for vertically aligned text.
*/
@interface VerticallyCenteredTextFieldCell : NSTextFieldCell {
BOOL mIsEditingOrSelecting;
}
@end
@interface InfoBar : NSView <InfoBarCommunicator> {
@private
NSImage *mBackground;
IBDisplay mDisplayMask;
float mScaleFactor;
NSPopUpButton *mZoomPopup;
int mCurrentCaretX;
int mCurrentCaretY;
NSTextField *mCaretPositionLabel;
NSTextField *mStatusTextLabel;
id <InfoBarCommunicator> mCallback;
}
- (void) notify: (NotificationType) type message: (NSString *) message location: (NSPoint) location
value: (float) value;
- (void) setCallback: (id <InfoBarCommunicator>) callback;
- (void) createItems;
- (void) positionSubViews;
- (void) setDisplay: (IBDisplay) display;
- (void) zoomItemAction: (id) sender;
- (void) setScaleFactor: (float) newScaleFactor adjustPopup: (BOOL) flag;
- (void) setCaretPosition: (NSPoint) position;
- (void) sizeToFit;
@end
| 1,382
|
C++
|
.h
| 42
| 31.071429
| 111
| 0.769752
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
16,757
|
QuartzTextLayout.h
|
dail8859_NotepadNext/src/scintilla/cocoa/QuartzTextLayout.h
|
/*
* QuartzTextLayout.h
*
* Original Code by Evan Jones on Wed Oct 02 2002.
* Contributors:
* Shane Caraveo, ActiveState
* Bernd Paradies, Adobe
*
*/
#ifndef QUARTZTEXTLAYOUT_H
#define QUARTZTEXTLAYOUT_H
#include <Cocoa/Cocoa.h>
#include "QuartzTextStyle.h"
class QuartzTextLayout {
public:
/** Create a text layout for drawing. */
QuartzTextLayout(std::string_view sv, CFStringEncoding encoding, const QuartzTextStyle *r) {
encodingUsed = encoding;
const UInt8 *puiBuffer = reinterpret_cast<const UInt8 *>(sv.data());
CFStringRef str = CFStringCreateWithBytes(NULL, puiBuffer, sv.length(), encodingUsed, false);
if (!str) {
// Failed to decode bytes into string with given encoding so try
// MacRoman which should accept any byte.
encodingUsed = kCFStringEncodingMacRoman;
str = CFStringCreateWithBytes(NULL, puiBuffer, sv.length(), encodingUsed, false);
}
if (!str) {
return;
}
stringLength = CFStringGetLength(str);
CFMutableDictionaryRef stringAttribs = r->getCTStyle();
mString = ::CFAttributedStringCreate(NULL, str, stringAttribs);
mLine = ::CTLineCreateWithAttributedString(mString);
CFRelease(str);
}
~QuartzTextLayout() {
if (mString) {
CFRelease(mString);
mString = NULL;
}
if (mLine) {
CFRelease(mLine);
mLine = NULL;
}
}
/** Draw the text layout into a CGContext at the specified position.
* @param gc The CGContext in which to draw the text.
* @param x The x axis position to draw the baseline in the current CGContext.
* @param y The y axis position to draw the baseline in the current CGContext. */
void draw(CGContextRef gc, double x, double y) {
if (!mLine)
return;
::CGContextSetTextMatrix(gc, CGAffineTransformMakeScale(1.0, -1.0));
// Set the text drawing position.
::CGContextSetTextPosition(gc, x, y);
// And finally, draw!
::CTLineDraw(mLine, gc);
}
float MeasureStringWidth() {
if (mLine == NULL)
return 0.0f;
return static_cast<float>(::CTLineGetTypographicBounds(mLine, NULL, NULL, NULL));
}
CTLineRef getCTLine() {
return mLine;
}
CFIndex getStringLength() {
return stringLength;
}
CFStringEncoding getEncoding() {
return encodingUsed;
}
private:
CFAttributedStringRef mString = NULL;
CTLineRef mLine = NULL;
CFIndex stringLength = 0;
CFStringEncoding encodingUsed = kCFStringEncodingMacRoman;
};
#endif
| 2,377
|
C++
|
.h
| 79
| 27.316456
| 95
| 0.74297
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
16,758
|
AppController.h
|
dail8859_NotepadNext/src/scintilla/cocoa/ScintillaTest/AppController.h
|
/**
* AppController.h
* SciTest
*
* Created by Mike Lischke on 01.04.09.
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* This file is dual licensed under LGPL v2.1 and the Scintilla license (http://www.scintilla.org/License.txt).
*/
#import <Cocoa/Cocoa.h>
#include <dlfcn.h>
#import "Scintilla/ILexer.h"
#import "Scintilla/ScintillaView.h"
#import "Scintilla/InfoBar.h"
#include <SciLexer.h>
#include <Lexilla.h>
@interface AppController : NSObject {
IBOutlet NSBox *mEditHost;
ScintillaView* mEditor;
ScintillaView* sciExtra; // For testing Scintilla tear-down
}
- (void) awakeFromNib;
- (void) setupEditor;
- (IBAction) searchText: (id) sender;
- (IBAction) addRemoveExtra: (id) sender;
@end
| 729
|
C++
|
.h
| 25
| 27.4
| 111
| 0.755014
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
16,778
|
Debugging.h
|
dail8859_NotepadNext/src/scintilla/src/Debugging.h
|
// Scintilla source code edit control
/** @file Debugging.h
** Assert and debug trace functions.
** Implemented in each platform layer.
**/
// Copyright 1998-2009 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef DEBUGGING_H
#define DEBUGGING_H
namespace Scintilla::Internal {
#if defined(__clang__)
# if __has_feature(attribute_analyzer_noreturn)
# define CLANG_ANALYZER_NORETURN __attribute__((analyzer_noreturn))
# else
# define CLANG_ANALYZER_NORETURN
# endif
#else
# define CLANG_ANALYZER_NORETURN
#endif
/**
* Platform namespace used to segregate debugging functions.
*/
namespace Platform {
void DebugDisplay(const char *s) noexcept;
void DebugPrintf(const char *format, ...) noexcept;
bool ShowAssertionPopUps(bool assertionPopUps_) noexcept;
void Assert(const char *c, const char *file, int line) noexcept CLANG_ANALYZER_NORETURN;
}
#ifdef NDEBUG
#define PLATFORM_ASSERT(c) ((void)0)
#else
#define PLATFORM_ASSERT(c) ((c) ? (void)(0) : Scintilla::Internal::Platform::Assert(#c, __FILE__, __LINE__))
#endif
}
#endif
| 1,132
|
C++
|
.h
| 35
| 30.942857
| 108
| 0.767463
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,780
|
UndoHistory.h
|
dail8859_NotepadNext/src/scintilla/src/UndoHistory.h
|
// Scintilla source code edit control
/** @file UndoHistory.h
** Manages undo for the document.
**/
// Copyright 1998-2024 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef UNDOHISTORY_H
#define UNDOHISTORY_H
namespace Scintilla::Internal {
// ScaledVector is a vector of unsigned integers that uses elements sized to hold the largest value.
// Thus, if an undo history only contains short insertions and deletions the lengths vector may
// only use 2 bytes or even 1 byte for each length.
// This saves much memory often reducing by 50% for 32-bit builds and 75% for 64-bit builds.
struct SizeMax {
size_t size = 1;
size_t maxValue = UINT8_MAX;
};
class ScaledVector {
SizeMax element;
std::vector<uint8_t> bytes;
public:
[[nodiscard]] size_t Size() const noexcept;
[[nodiscard]] size_t ValueAt(size_t index) const noexcept;
[[nodiscard]] intptr_t SignedValueAt(size_t index) const noexcept;
void SetValueAt(size_t index, size_t value);
void ClearValueAt(size_t index) noexcept;
void Clear() noexcept;
void Truncate(size_t length) noexcept;
void ReSize(size_t length);
void PushBack();
// For testing
[[nodiscard]] size_t SizeInBytes() const noexcept;
};
class UndoActionType {
public:
ActionType at : 4;
bool mayCoalesce : 1;
UndoActionType() noexcept;
};
struct UndoActions {
std::vector<UndoActionType> types;
ScaledVector positions;
ScaledVector lengths;
UndoActions() noexcept;
void Truncate(size_t length) noexcept;
void PushBack();
void Clear() noexcept;
[[nodiscard]] intptr_t SSize() const noexcept;
void Create(size_t index, ActionType at_, Sci::Position position_, Sci::Position lenData_, bool mayCoalesce_);
[[nodiscard]] bool AtStart(size_t index) const noexcept;
[[nodiscard]] size_t LengthTo(size_t index) const noexcept;
[[nodiscard]] Sci::Position Position(int action) const noexcept;
[[nodiscard]] Sci::Position Length(int action) const noexcept;
};
class ScrapStack {
std::string stack;
size_t current = 0;
public:
void Clear() noexcept;
const char *Push(const char *text, size_t length);
void SetCurrent(size_t position) noexcept;
void MoveForward(size_t length) noexcept;
void MoveBack(size_t length) noexcept;
[[nodiscard]] const char *CurrentText() const noexcept;
[[nodiscard]] const char *TextAt(size_t position) const noexcept;
};
constexpr int coalesceFlag = 0x100;
/**
*
*/
class UndoHistory {
UndoActions actions;
int currentAction = 0;
int undoSequenceDepth = 0;
int savePoint = 0;
int tentativePoint = -1;
std::optional<int> detach; // Never set if savePoint set (>= 0)
std::unique_ptr<ScrapStack> scraps;
struct actPos { int act; size_t position; };
std::optional<actPos> memory;
int PreviousAction() const noexcept;
public:
UndoHistory();
~UndoHistory() noexcept;
const char *AppendAction(ActionType at, Sci::Position position, const char *data, Sci::Position lengthData, bool &startSequence, bool mayCoalesce=true);
void BeginUndoAction(bool mayCoalesce=false) noexcept;
void EndUndoAction() noexcept;
int UndoSequenceDepth() const noexcept;
void DropUndoSequence() noexcept;
void DeleteUndoHistory() noexcept;
[[nodiscard]] int Actions() const noexcept;
/// The save point is a marker in the undo stack where the container has stated that
/// the buffer was saved. Undo and redo can move over the save point.
void SetSavePoint(int action) noexcept;
[[nodiscard]] int SavePoint() const noexcept;
void SetSavePoint() noexcept;
bool IsSavePoint() const noexcept;
bool BeforeSavePoint() const noexcept;
bool PreviousBeforeSavePoint() const noexcept;
bool BeforeReachableSavePoint() const noexcept;
bool AfterSavePoint() const noexcept;
/// The detach point is the last action that was before an inaccessible missing save point.
void SetDetachPoint(int action) noexcept;
[[nodiscard]] int DetachPoint() const noexcept;
bool AfterDetachPoint() const noexcept;
bool AfterOrAtDetachPoint() const noexcept;
[[nodiscard]] intptr_t Delta(int action) const noexcept;
[[nodiscard]] bool Validate(intptr_t lengthDocument) const noexcept;
void SetCurrent(int action, intptr_t lengthDocument);
[[nodiscard]] int Current() const noexcept;
[[nodiscard]] int Type(int action) const noexcept;
[[nodiscard]] Sci::Position Position(int action) const noexcept;
[[nodiscard]] Sci::Position Length(int action) const noexcept;
[[nodiscard]] std::string_view Text(int action) noexcept;
void PushUndoActionType(int type, Sci::Position position);
void ChangeLastUndoActionText(size_t length, const char *text);
// Tentative actions are used for input composition so that it can be undone cleanly
void SetTentative(int action) noexcept;
[[nodiscard]] int TentativePoint() const noexcept;
void TentativeStart() noexcept;
void TentativeCommit() noexcept;
bool TentativeActive() const noexcept;
int TentativeSteps() const noexcept;
/// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is
/// called that many times. Similarly for redo.
bool CanUndo() const noexcept;
int StartUndo() const noexcept;
Action GetUndoStep() const noexcept;
void CompletedUndoStep() noexcept;
bool CanRedo() const noexcept;
int StartRedo() const noexcept;
Action GetRedoStep() const noexcept;
void CompletedRedoStep() noexcept;
};
}
#endif
| 5,379
|
C++
|
.h
| 136
| 37.602941
| 153
| 0.776202
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,783
|
CharacterType.h
|
dail8859_NotepadNext/src/scintilla/src/CharacterType.h
|
// Scintilla source code edit control
/** @file CharacterType.h
** Tests for character type and case-insensitive comparisons.
**/
// Copyright 2007 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef CHARACTERTYPE_H
#define CHARACTERTYPE_H
namespace Scintilla::Internal {
// Functions for classifying characters
/**
* Check if a character is a space.
* This is ASCII specific but is safe with chars >= 0x80.
*/
constexpr bool IsASpace(int ch) noexcept {
return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d));
}
constexpr bool IsSpaceOrTab(int ch) noexcept {
return (ch == ' ') || (ch == '\t');
}
constexpr bool IsControl(int ch) noexcept {
return ((ch >= 0) && (ch <= 0x1F)) || (ch == 0x7F);
}
constexpr bool IsEOLCharacter(int ch) noexcept {
return ch == '\r' || ch == '\n';
}
constexpr bool IsBreakSpace(int ch) noexcept {
// used for text breaking, treat C0 control character as space.
// by default C0 control character is handled as special representation,
// so not appears in normal text. 0x7F DEL is omitted to simplify the code.
return ch >= 0 && ch <= ' ';
}
constexpr bool IsADigit(int ch) noexcept {
return (ch >= '0') && (ch <= '9');
}
constexpr bool IsADigit(int ch, int base) noexcept {
if (base <= 10) {
return (ch >= '0') && (ch < '0' + base);
} else {
return ((ch >= '0') && (ch <= '9')) ||
((ch >= 'A') && (ch < 'A' + base - 10)) ||
((ch >= 'a') && (ch < 'a' + base - 10));
}
}
constexpr bool IsASCII(int ch) noexcept {
return (ch >= 0) && (ch < 0x80);
}
constexpr bool IsLowerCase(int ch) noexcept {
return (ch >= 'a') && (ch <= 'z');
}
constexpr bool IsUpperCase(int ch) noexcept {
return (ch >= 'A') && (ch <= 'Z');
}
constexpr bool IsUpperOrLowerCase(int ch) noexcept {
return IsUpperCase(ch) || IsLowerCase(ch);
}
constexpr bool IsAlphaNumeric(int ch) noexcept {
return
((ch >= '0') && (ch <= '9')) ||
((ch >= 'a') && (ch <= 'z')) ||
((ch >= 'A') && (ch <= 'Z'));
}
constexpr bool IsPunctuation(int ch) noexcept {
switch (ch) {
case '!':
case '"':
case '#':
case '$':
case '%':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case '-':
case '.':
case '/':
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '@':
case '[':
case '\\':
case ']':
case '^':
case '_':
case '`':
case '{':
case '|':
case '}':
case '~':
return true;
default:
return false;
}
}
// Simple case functions for ASCII supersets.
template <typename T>
constexpr T MakeUpperCase(T ch) noexcept {
if (ch < 'a' || ch > 'z')
return ch;
else
return ch - 'a' + 'A';
}
template <typename T>
constexpr T MakeLowerCase(T ch) noexcept {
if (ch < 'A' || ch > 'Z')
return ch;
else
return ch - 'A' + 'a';
}
int CompareCaseInsensitive(const char *a, const char *b) noexcept;
int CompareNCaseInsensitive(const char *a, const char *b, size_t len) noexcept;
}
#endif
| 2,994
|
C++
|
.h
| 120
| 22.9
| 94
| 0.619215
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,788
|
CellBuffer.h
|
dail8859_NotepadNext/src/scintilla/src/CellBuffer.h
|
// Scintilla source code edit control
/** @file CellBuffer.h
** Manages the text of the document.
**/
// Copyright 1998-2004 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef CELLBUFFER_H
#define CELLBUFFER_H
namespace Scintilla::Internal {
// Interface to per-line data that wants to see each line insertion and deletion
class PerLine {
public:
virtual ~PerLine() {}
virtual void Init()=0;
virtual void InsertLine(Sci::Line line)=0;
virtual void InsertLines(Sci::Line line, Sci::Line lines) = 0;
virtual void RemoveLine(Sci::Line line)=0;
};
class UndoHistory;
class ChangeHistory;
/**
* The line vector contains information about each of the lines in a cell buffer.
*/
class ILineVector;
enum class ActionType : unsigned char { insert, remove, container };
/**
* Actions are used to return the information required to report one undo/redo step.
*/
struct Action {
ActionType at = ActionType::insert;
bool mayCoalesce = false;
Sci::Position position = 0;
const char *data = nullptr;
Sci::Position lenData = 0;
};
struct SplitView {
const char *segment1 = nullptr;
size_t length1 = 0;
const char *segment2 = nullptr;
size_t length = 0;
bool operator==(const SplitView &other) const noexcept {
return segment1 == other.segment1 && length1 == other.length1 &&
segment2 == other.segment2 && length == other.length;
}
bool operator!=(const SplitView &other) const noexcept {
return !(*this == other);
}
char CharAt(size_t position) const noexcept {
if (position < length1) {
return segment1[position];
}
if (position < length) {
return segment2[position];
}
return 0;
}
};
/**
* Holder for an expandable array of characters that supports undo and line markers.
* Based on article "Data Structures in a Bit-Mapped Text Editor"
* by Wilfred J. Hansen, Byte January 1987, page 183.
*/
class CellBuffer {
private:
bool hasStyles;
bool largeDocument;
SplitVector<char> substance;
SplitVector<char> style;
bool readOnly;
bool utf8Substance;
Scintilla::LineEndType utf8LineEnds;
bool collectingUndo;
std::unique_ptr<UndoHistory> uh;
std::unique_ptr<ChangeHistory> changeHistory;
std::unique_ptr<ILineVector> plv;
bool UTF8LineEndOverlaps(Sci::Position position) const noexcept;
bool UTF8IsCharacterBoundary(Sci::Position position) const;
void ResetLineEnds();
void RecalculateIndexLineStarts(Sci::Line lineFirst, Sci::Line lineLast);
bool MaintainingLineCharacterIndex() const noexcept;
/// Actions without undo
void BasicInsertString(Sci::Position position, const char *s, Sci::Position insertLength);
void BasicDeleteChars(Sci::Position position, Sci::Position deleteLength);
public:
CellBuffer(bool hasStyles_, bool largeDocument_);
// Deleted so CellBuffer objects can not be copied.
CellBuffer(const CellBuffer &) = delete;
CellBuffer(CellBuffer &&) = delete;
CellBuffer &operator=(const CellBuffer &) = delete;
CellBuffer &operator=(CellBuffer &&) = delete;
~CellBuffer() noexcept;
/// Retrieving positions outside the range of the buffer works and returns 0
char CharAt(Sci::Position position) const noexcept;
unsigned char UCharAt(Sci::Position position) const noexcept;
void GetCharRange(char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const;
char StyleAt(Sci::Position position) const noexcept;
void GetStyleRange(unsigned char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const;
const char *BufferPointer();
const char *RangePointer(Sci::Position position, Sci::Position rangeLength) noexcept;
Sci::Position GapPosition() const noexcept;
SplitView AllView() const noexcept;
Sci::Position Length() const noexcept;
void Allocate(Sci::Position newSize);
void SetUTF8Substance(bool utf8Substance_) noexcept;
Scintilla::LineEndType GetLineEndTypes() const noexcept { return utf8LineEnds; }
void SetLineEndTypes(Scintilla::LineEndType utf8LineEnds_);
bool ContainsLineEnd(const char *s, Sci::Position length) const noexcept;
void SetPerLine(PerLine *pl) noexcept;
Scintilla::LineCharacterIndexType LineCharacterIndex() const noexcept;
void AllocateLineCharacterIndex(Scintilla::LineCharacterIndexType lineCharacterIndex);
void ReleaseLineCharacterIndex(Scintilla::LineCharacterIndexType lineCharacterIndex);
Sci::Line Lines() const noexcept;
void AllocateLines(Sci::Line lines);
Sci::Position LineStart(Sci::Line line) const noexcept;
Sci::Position LineEnd(Sci::Line line) const noexcept;
Sci::Position IndexLineStart(Sci::Line line, Scintilla::LineCharacterIndexType lineCharacterIndex) const noexcept;
Sci::Line LineFromPosition(Sci::Position pos) const noexcept;
Sci::Line LineFromPositionIndex(Sci::Position pos, Scintilla::LineCharacterIndexType lineCharacterIndex) const noexcept;
void InsertLine(Sci::Line line, Sci::Position position, bool lineStart);
void RemoveLine(Sci::Line line);
const char *InsertString(Sci::Position position, const char *s, Sci::Position insertLength, bool &startSequence);
/// Setting styles for positions outside the range of the buffer is safe and has no effect.
/// @return true if the style of a character is changed.
bool SetStyleAt(Sci::Position position, char styleValue) noexcept;
bool SetStyleFor(Sci::Position position, Sci::Position lengthStyle, char styleValue) noexcept;
const char *DeleteChars(Sci::Position position, Sci::Position deleteLength, bool &startSequence);
bool IsReadOnly() const noexcept;
void SetReadOnly(bool set) noexcept;
bool IsLarge() const noexcept;
bool HasStyles() const noexcept;
/// The save point is a marker in the undo stack where the container has stated that
/// the buffer was saved. Undo and redo can move over the save point.
void SetSavePoint();
bool IsSavePoint() const noexcept;
void TentativeStart() noexcept;
void TentativeCommit() noexcept;
bool TentativeActive() const noexcept;
int TentativeSteps() noexcept;
bool SetUndoCollection(bool collectUndo) noexcept;
bool IsCollectingUndo() const noexcept;
void BeginUndoAction(bool mayCoalesce=false) noexcept;
void EndUndoAction() noexcept;
int UndoSequenceDepth() const noexcept;
void AddUndoAction(Sci::Position token, bool mayCoalesce);
void DeleteUndoHistory() noexcept;
/// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is
/// called that many times. Similarly for redo.
bool CanUndo() const noexcept;
int StartUndo() noexcept;
Action GetUndoStep() const noexcept;
void PerformUndoStep();
bool CanRedo() const noexcept;
int StartRedo() noexcept;
Action GetRedoStep() const noexcept;
void PerformRedoStep();
int UndoActions() const noexcept;
void SetUndoSavePoint(int action) noexcept;
int UndoSavePoint() const noexcept;
void SetUndoDetach(int action) noexcept;
int UndoDetach() const noexcept;
void SetUndoTentative(int action) noexcept;
int UndoTentative() const noexcept;
void SetUndoCurrent(int action);
int UndoCurrent() const noexcept;
int UndoActionType(int action) const noexcept;
Sci::Position UndoActionPosition(int action) const noexcept;
std::string_view UndoActionText(int action) const noexcept;
void PushUndoActionType(int type, Sci::Position position);
void ChangeLastUndoActionText(size_t length, const char *text);
void ChangeHistorySet(bool set);
[[nodiscard]] int EditionAt(Sci::Position pos) const noexcept;
[[nodiscard]] Sci::Position EditionEndRun(Sci::Position pos) const noexcept;
[[nodiscard]] unsigned int EditionDeletesAt(Sci::Position pos) const noexcept;
[[nodiscard]] Sci::Position EditionNextDelete(Sci::Position pos) const noexcept;
};
}
#endif
| 7,673
|
C++
|
.h
| 177
| 41.259887
| 121
| 0.790757
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,795
|
PositionCache.h
|
dail8859_NotepadNext/src/scintilla/src/PositionCache.h
|
// Scintilla source code edit control
/** @file PositionCache.h
** Classes for caching layout information.
**/
// Copyright 1998-2009 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef POSITIONCACHE_H
#define POSITIONCACHE_H
namespace Scintilla::Internal {
/**
* A point in document space.
* Uses double for sufficient resolution in large (>20,000,000 line) documents.
*/
class PointDocument {
public:
double x;
double y;
explicit PointDocument(double x_ = 0, double y_ = 0) noexcept : x(x_), y(y_) {
}
// Conversion from Point.
explicit PointDocument(Point pt) noexcept : x(pt.x), y(pt.y) {
}
};
// There are two points for some positions and this enumeration
// can choose between the end of the first line or subline
// and the start of the next line or subline.
enum class PointEnd {
start = 0x0,
lineEnd = 0x1,
subLineEnd = 0x2,
endEither = lineEnd | subLineEnd,
};
class BidiData {
public:
std::vector<std::shared_ptr<Font>> stylesFonts;
std::vector<XYPOSITION> widthReprs;
void Resize(size_t maxLineLength_);
};
/**
*/
class LineLayout {
private:
std::unique_ptr<int []>lineStarts;
int lenLineStarts;
/// Drawing is only performed for @a maxLineLength characters on each line.
Sci::Line lineNumber;
public:
enum { wrapWidthInfinite = 0x7ffffff };
int maxLineLength;
int numCharsInLine;
int numCharsBeforeEOL;
enum class ValidLevel { invalid, checkTextAndStyle, positions, lines } validity;
int xHighlightGuide;
bool highlightColumn;
bool containsCaret;
int edgeColumn;
std::unique_ptr<char[]> chars;
std::unique_ptr<unsigned char[]> styles;
std::unique_ptr<XYPOSITION[]> positions;
unsigned char bracePreviousStyles[2];
std::unique_ptr<BidiData> bidiData;
// Wrapped line support
int widthLine;
int lines;
XYPOSITION wrapIndent; // In pixels
LineLayout(Sci::Line lineNumber_, int maxLineLength_);
// Deleted so LineLayout objects can not be copied.
LineLayout(const LineLayout &) = delete;
LineLayout(LineLayout &&) = delete;
void operator=(const LineLayout &) = delete;
void operator=(LineLayout &&) = delete;
virtual ~LineLayout();
void Resize(int maxLineLength_);
void ReSet(Sci::Line lineNumber_, Sci::Position maxLineLength_);
void EnsureBidiData();
void Free() noexcept;
void ClearPositions();
void Invalidate(ValidLevel validity_) noexcept;
Sci::Line LineNumber() const noexcept;
bool CanHold(Sci::Line lineDoc, int lineLength_) const noexcept;
int LineStart(int line) const noexcept;
int LineLength(int line) const noexcept;
enum class Scope { visibleOnly, includeEnd };
int LineLastVisible(int line, Scope scope) const noexcept;
Range SubLineRange(int subLine, Scope scope) const noexcept;
bool InLine(int offset, int line) const noexcept;
int SubLineFromPosition(int posInLine, PointEnd pe) const noexcept;
void AddLineStart(Sci::Position start);
void SetBracesHighlight(Range rangeLine, const Sci::Position braces[],
char bracesMatchStyle, int xHighlight, bool ignoreStyle);
void RestoreBracesHighlight(Range rangeLine, const Sci::Position braces[], bool ignoreStyle);
int FindBefore(XYPOSITION x, Range range) const noexcept;
int FindPositionFromX(XYPOSITION x, Range range, bool charPosition) const noexcept;
Point PointFromPosition(int posInLine, int lineHeight, PointEnd pe) const noexcept;
XYPOSITION XInLine(Sci::Position index) const noexcept;
Interval Span(int start, int end) const noexcept;
Interval SpanByte(int index) const noexcept;
int EndLineStyle() const noexcept;
void WrapLine(const Document *pdoc, Sci::Position posLineStart, Wrap wrapState, XYPOSITION wrapWidth);
};
struct ScreenLine : public IScreenLine {
const LineLayout *ll;
size_t start;
size_t len;
XYPOSITION width;
XYPOSITION height;
int ctrlCharPadding;
XYPOSITION tabWidth;
int tabWidthMinimumPixels;
ScreenLine(const LineLayout *ll_, int subLine, const ViewStyle &vs, XYPOSITION width_, int tabWidthMinimumPixels_);
// Deleted so ScreenLine objects can not be copied.
ScreenLine(const ScreenLine &) = delete;
ScreenLine(ScreenLine &&) = delete;
void operator=(const ScreenLine &) = delete;
void operator=(ScreenLine &&) = delete;
virtual ~ScreenLine();
std::string_view Text() const override;
size_t Length() const override;
size_t RepresentationCount() const override;
XYPOSITION Width() const override;
XYPOSITION Height() const override;
XYPOSITION TabWidth() const override;
XYPOSITION TabWidthMinimumPixels() const override;
const Font *FontOfPosition(size_t position) const override;
XYPOSITION RepresentationWidth(size_t position) const override;
XYPOSITION TabPositionAfter(XYPOSITION xPosition) const override;
};
struct SignificantLines {
Sci::Line lineCaret;
Sci::Line lineTop;
Sci::Line linesOnScreen;
Scintilla::LineCache level;
bool LineMayCache(Sci::Line line) const noexcept;
};
/**
*/
class LineLayoutCache {
public:
private:
Scintilla::LineCache level;
std::vector<std::shared_ptr<LineLayout>>cache;
LineLayout::ValidLevel maxValidity;
int styleClock;
size_t EntryForLine(Sci::Line line) const noexcept;
void AllocateForLevel(Sci::Line linesOnScreen, Sci::Line linesInDoc);
public:
LineLayoutCache();
// Deleted so LineLayoutCache objects can not be copied.
LineLayoutCache(const LineLayoutCache &) = delete;
LineLayoutCache(LineLayoutCache &&) = delete;
void operator=(const LineLayoutCache &) = delete;
void operator=(LineLayoutCache &&) = delete;
virtual ~LineLayoutCache();
void Deallocate() noexcept;
void Invalidate(LineLayout::ValidLevel validity_) noexcept;
void SetLevel(Scintilla::LineCache level_) noexcept;
Scintilla::LineCache GetLevel() const noexcept { return level; }
std::shared_ptr<LineLayout> Retrieve(Sci::Line lineNumber, Sci::Line lineCaret, int maxChars, int styleClock_,
Sci::Line linesOnScreen, Sci::Line linesInDoc);
};
class Representation {
public:
static constexpr size_t maxLength = 200;
std::string stringRep;
RepresentationAppearance appearance;
ColourRGBA colour;
explicit Representation(std::string_view value="", RepresentationAppearance appearance_= RepresentationAppearance::Blob) :
stringRep(value), appearance(appearance_) {
}
};
typedef std::map<unsigned int, Representation> MapRepresentation;
const char *ControlCharacterString(unsigned char ch) noexcept;
void Hexits(char *hexits, int ch) noexcept;
class SpecialRepresentations {
MapRepresentation mapReprs;
unsigned short startByteHasReprs[0x100] {};
unsigned int maxKey = 0;
bool crlf = false;
public:
void SetRepresentation(std::string_view charBytes, std::string_view value);
void SetRepresentationAppearance(std::string_view charBytes, RepresentationAppearance appearance);
void SetRepresentationColour(std::string_view charBytes, ColourRGBA colour);
void ClearRepresentation(std::string_view charBytes);
const Representation *GetRepresentation(std::string_view charBytes) const;
const Representation *RepresentationFromCharacter(std::string_view charBytes) const;
bool ContainsCrLf() const noexcept {
return crlf;
}
bool MayContain(unsigned char ch) const noexcept {
return startByteHasReprs[ch] != 0;
}
void Clear();
void SetDefaultRepresentations(int dbcsCodePage);
};
struct TextSegment {
int start;
int length;
const Representation *representation;
TextSegment(int start_=0, int length_=0, const Representation *representation_=nullptr) noexcept :
start(start_), length(length_), representation(representation_) {
}
int end() const noexcept {
return start + length;
}
};
// Class to break a line of text into shorter runs at sensible places.
class BreakFinder {
const LineLayout *ll;
const Range lineRange;
int nextBreak;
std::vector<int> selAndEdge;
unsigned int saeCurrentPos;
int saeNext;
int subBreak;
const Document *pdoc;
const EncodingFamily encodingFamily;
const SpecialRepresentations *preprs;
void Insert(Sci::Position val);
public:
// If a whole run is longer than lengthStartSubdivision then subdivide
// into smaller runs at spaces or punctuation.
enum { lengthStartSubdivision = 300 };
// Try to make each subdivided run lengthEachSubdivision or shorter.
enum { lengthEachSubdivision = 100 };
enum class BreakFor {
Text = 0,
Selection = 1,
Foreground = 2,
ForegroundAndSelection = 3,
};
BreakFinder(const LineLayout *ll_, const Selection *psel, Range lineRange_, Sci::Position posLineStart,
XYPOSITION xStart, BreakFor breakFor, const Document *pdoc_, const SpecialRepresentations *preprs_, const ViewStyle *pvsDraw);
// Deleted so BreakFinder objects can not be copied.
BreakFinder(const BreakFinder &) = delete;
BreakFinder(BreakFinder &&) = delete;
void operator=(const BreakFinder &) = delete;
void operator=(BreakFinder &&) = delete;
~BreakFinder() noexcept;
TextSegment Next();
bool More() const noexcept;
};
class IPositionCache {
public:
virtual ~IPositionCache() = default;
virtual void Clear() noexcept = 0;
virtual void SetSize(size_t size_) = 0;
virtual size_t GetSize() const noexcept = 0;
virtual void MeasureWidths(Surface *surface, const ViewStyle &vstyle, unsigned int styleNumber,
bool unicode, std::string_view sv, XYPOSITION *positions, bool needsLocking) = 0;
};
std::unique_ptr<IPositionCache> CreatePositionCache();
}
#endif
| 9,308
|
C++
|
.h
| 253
| 34.86166
| 128
| 0.787218
|
dail8859/NotepadNext
| 9,006
| 547
| 57
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
16,804
|
coroutine.cpp
|
manticoresoftware_manticoresearch/src/coroutine.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 "coroutine.h"
#include "sphinxstd.h"
#include "task_info.h"
#include "coro_stack.h"
#include <atomic>
#include <boost/context/detail/fcontext.hpp>
#define LOG_LEVEL_DIAG false
#define LOG_LEVEL_DEBUGV false
namespace Threads {
#define LOG_COMPONENT_CORO "Stack: " << m_tStack.first.size << " (" << m_eState << ") "
bool StackMockingAllowed()
{
#if __has_include( <valgrind/valgrind.h>)
if (!!RUNNING_ON_VALGRIND)
{
sphWarning ( "Running under valgrind, so stack mocking is not allowed");
return false;
}
#endif
return !val_from_env ( "NO_STACK_CALCULATION", false );
}
//////////////////////////////////////////////////////////////
/// Coroutine - uses boost::context to switch between jobs
using namespace boost::context::detail;
class CoRoutine_c
{
enum class State_e
{
Paused, Running, Finished,
};
State_e m_eState = State_e::Paused;
Handler m_fnHandler;
CoroStack_t m_tStack;
using Ctx_t = fcontext_t;
Ctx_t m_tCoroutineContext;
Ctx_t m_tExternalContext;
friend StringBuilder_c & operator<< ( StringBuilder_c &, CoRoutine_c::State_e);
private:
void WorkerLowest ( Ctx_t tCtx )
{
m_tExternalContext = tCtx;
m_eState = State_e::Running;
m_fnHandler ();
m_eState = State_e::Finished;
YieldLowest ();
}
// goto back to external context
void YieldLowest ()
{
m_tExternalContext = jump_fcontext ( m_tExternalContext, nullptr ).fctx;
}
void CreateContext ( Handler fnHandler, CoroStack_t tStack )
{
m_fnHandler = std::move ( fnHandler );
m_tStack = tStack;
m_tCoroutineContext = make_fcontext ( m_tStack.first.sp, m_tStack.first.size, [] ( transfer_t pT ) {
static_cast<CoRoutine_c *>(pT.data)->WorkerLowest ( pT.fctx );
} );
}
public:
CoRoutine_c ( Handler fnHandler, CoroStack_t tStack )
{
CreateContext ( std::move ( fnHandler ), tStack );
}
~CoRoutine_c()
{
DeallocateStack ( m_tStack );
}
void Run ()
{
LOG( DEBUGV, CORO ) << "Run";
assert ( m_eState==State_e::Paused );
m_tCoroutineContext = jump_fcontext ( m_tCoroutineContext, static_cast<void*>(this) ).fctx;
}
bool IsFinished () const
{
return m_eState==State_e::Finished;
}
// yield to external context
void Yield_ ()
{
LOG( DEBUGV, CORO ) << "Yield_";
assert ( m_eState==State_e::Running );
m_eState = State_e::Paused;
YieldLowest ();
m_eState = State_e::Running;
}
const BYTE* GetTopOfStack() const noexcept
{
return static_cast<const BYTE*> ( m_tStack.first.sp );
}
int GetStackSize() const noexcept
{
return m_tStack.first.size;
}
};
StringBuilder_c & operator<< ( StringBuilder_c & dOut, CoRoutine_c::State_e eData )
{
switch (eData) {
case CoRoutine_c::State_e::Paused: return dOut << "Paused";
case CoRoutine_c::State_e::Running: return dOut << "Running";
case CoRoutine_c::State_e::Finished: return dOut << "Finished";
}
return dOut;
}
struct CoroState_t
{
enum ESTATE : DWORD
{
Running_e = 1, // if coro scheduled (and m.b. running) or not.
Paused_e = 2, // if set, will auto schedule again after yield
};
std::atomic<DWORD> m_uState { Running_e };
// reset some flags and return previous state
DWORD ResetFlags( DWORD uFlags )
{
return m_uState.fetch_and ( ~uFlags, std::memory_order_relaxed );
}
// set some flags and return previous state
DWORD SetFlags ( DWORD uFlags )
{
return m_uState.fetch_or ( uFlags, std::memory_order_relaxed );
}
};
#define LOG_COMPONENT_COROW "(" << m_tState.m_uState << ") "
namespace Coro {
class Worker_c final: public details::SchedulerOperation_t
{
// our executor (thread pool, etc. which provides Schedule(handler) method)
Scheduler_i * m_pScheduler = nullptr;
Keeper_t m_tKeepSchedulerAlive;
Waiter_t m_tTracer; // may be set to trace this worker lifetime
// our main execution coroutine
CoRoutine_c m_tCoroutine;
CoroState_t m_tState;
Handler m_fnYieldWithProceeder = nullptr;
// chain nested workers via TLS
void * m_pPreviousWorker = nullptr;
// operative stuff to be as near as possible
void * m_pCurrentTaskInfo = nullptr;
int64_t m_tmCpuTimeBase = 0; // add sphCpuTime() to this value to get truly cpu time ticks
uint64_t m_uId { InitWorkerID() };
std::atomic<size_t> m_iWakerEpoch { 0 };
// support for periodical checks/throttling
MiniTimer_c m_tInternalTimer {"Worker"};
int64_t m_tmNextTimePointUS = 0;
int64_t m_tmRuntimePeriodUS = 0;
int m_iNumOfRestarts = 0;
// task-local msg
StringBuilder_c m_sTlsMsg;
StringBuilder_c* m_pPrevTlsMsg = nullptr;
static uint64_t InitWorkerID()
{
static std::atomic<uint64_t> uWorker { 0ULL };
return uWorker.fetch_add ( 1, std::memory_order_relaxed );
}
enum class TimePoint_e : bool { fromresume, realtime };
inline void CheckEngageTimer ( TimePoint_e eKind )
{
if ( !m_tmRuntimePeriodUS )
return;
int64_t tmStartPointUS = ( eKind == TimePoint_e::realtime ) ? sph::MicroTimer() : MyThd().m_tmLastJobStartTimeUS;
m_tmNextTimePointUS = tmStartPointUS + m_tmRuntimePeriodUS;
m_tInternalTimer.EngageAt ( m_tmNextTimePointUS );
}
inline void CoroGuardEnter() noexcept
{
auto& tMyThd = MyThd();
m_pPreviousWorker = std::exchange ( tMyThd.m_pWorker, this );
m_pPrevTlsMsg = tMyThd.m_pTlsMsg.exchange ( &m_sTlsMsg, std::memory_order_relaxed );
m_pCurrentTaskInfo = tMyThd.m_pTaskInfo.exchange ( m_pCurrentTaskInfo, std::memory_order_relaxed );
m_tmCpuTimeBase -= sphThreadCpuTimer();
++m_iNumOfRestarts;
CheckEngageTimer( TimePoint_e::fromresume );
}
inline void CoroGuardExit()
{
if ( m_tmRuntimePeriodUS )
m_tInternalTimer.UnEngage();
m_tmCpuTimeBase += sphThreadCpuTimer();
auto& tMyThd = MyThd();
m_pCurrentTaskInfo = tMyThd.m_pTaskInfo.exchange ( m_pCurrentTaskInfo, std::memory_order_relaxed );
tMyThd.m_pTlsMsg.store ( m_pPrevTlsMsg, std::memory_order_relaxed );
std::exchange ( tMyThd.m_pWorker, m_pPreviousWorker );
}
// RAII worker's keeper
class CoroGuard_c
{
Worker_c* m_pWorker;
public:
explicit CoroGuard_c ( Worker_c* pWorker ) : m_pWorker { pWorker } { m_pWorker->CoroGuardEnter(); }
~CoroGuard_c() { m_pWorker->CoroGuardExit(); }
};
static void DoComplete ( void* pOwner, SchedulerOperation_t* pBase )
{
if ( !pOwner )
return;
Threads::JobTracker_t dTrack;
auto* pThis = static_cast<Worker_c*> ( pBase );
pThis->Run();
}
private:
// called from StartPrimary from Coro::Go - Multiserve, Sphinxql, replication recv
Worker_c ( Handler fnHandler, Scheduler_i* pScheduler )
: SchedulerOperation_t ( &Worker_c::DoComplete )
, m_pScheduler ( pScheduler )
, m_tKeepSchedulerAlive { pScheduler->KeepWorking () }
, m_tCoroutine { std::move (fnHandler), AllocateStack(0) }
{
assert ( m_pScheduler );
}
// from CallCoroutine - StartCall (blocking run);
// from Coro::Co - StartOther - all secondary parallel things in non-vip queue
// from Coro::Continue - StartContinuation - same context, another stack, run as fast as possible
Worker_c ( Handler fnHandler, Scheduler_i* pScheduler, Waiter_t tTracer, size_t iStack=0 )
: SchedulerOperation_t ( &Worker_c::DoComplete )
, m_pScheduler ( pScheduler )
, m_tKeepSchedulerAlive { pScheduler->KeepWorking () }
, m_tTracer ( std::move(tTracer))
, m_tCoroutine { std::move (fnHandler), AllocateStack(iStack) }
{
assert ( m_pScheduler );
}
// called solely for mocking - no scheduler, not possible to yield. Just provided stack and executor
Worker_c ( Handler fnHandler, VecTraits_T<BYTE> dStack )
: SchedulerOperation_t ( &Worker_c::DoComplete )
, m_tCoroutine { std::move ( fnHandler ), MockedStack ( dStack ) }
{
assert ( !m_pScheduler );
}
inline void ResetRunningAndReschedule () noexcept
{
auto uPrevState = m_tState.m_uState.load ( std::memory_order_relaxed );
do
if ( uPrevState & CoroState_t::Paused_e )
{
LOG ( DIAG, COROW ) << "ResetRunningAndReschedule schedule because done";
Schedule();
return;
}
while ( !m_tState.m_uState.compare_exchange_weak ( uPrevState, uPrevState & ~CoroState_t::Running_e, std::memory_order_relaxed ) );
if ( m_fnYieldWithProceeder )
std::exchange ( m_fnYieldWithProceeder, nullptr )();
}
inline void Run() noexcept
{
if ( !Resume() ) // Resume() returns true when coro is finished
ResetRunningAndReschedule();
}
inline void Schedule(bool bVip=false) noexcept
{
LOG ( DEBUGV, COROW ) << "Coro::Worker_c::Schedule (" << bVip << ", " << m_pScheduler << ")";
assert ( m_pScheduler );
m_pScheduler->ScheduleOp ( this, bVip ); // true means 'vip', false - 'secondary'
}
// continuation means, task is already started, and, if possible, should not be scheduled/paused.
// That means, it might be call immediately, without placing it to queue. In recurrent call it may cause stack overflow by recursion -
// that is Run(..Run(..Run..(... chain
inline void ScheduleContinuation () noexcept
{
LOG ( DEBUGV, COROW ) << "Coro::Worker_c::ScheduleContinuation (" << m_pScheduler << ")";
assert ( m_pScheduler );
m_pScheduler->ScheduleContinuationOp (this);
}
public:
// invoked from Coro::Go - Multiserve, Sphinxql, replication recv. Schedule by default into primary queue.
// Agnostic to parent's task info (if any). Should create and use it's own.
static void StartPrimary ( Handler fnHandler, Scheduler_i* pScheduler, bool bPrimary=true )
{
( new Worker_c ( std::move ( fnHandler ), pScheduler ) )->Schedule ( bPrimary );
}
// from Coro::Co -> all parallel tasks (snippets, local searches, pq, disk chunks). Schedule into secondary queue.
// May refer to parent's task info as read-only. For changes has dedicated mini info, also can create and use it's own local.
static void StartOther ( Handler fnHandler, Scheduler_i * pScheduler, size_t iStack, Waiter_t tWait )
{
( new Worker_c ( myinfo::OwnMini ( std::move ( fnHandler ) ), pScheduler, std::move ( tWait ), iStack ) )->Schedule ();
}
// invoked from CallCoroutine -> ReplicationServiceStart on daemon startup. Schedule into primary queue.
// Adopt parent's task info (if any), and may change it exclusively.
// Parent thread at the moment blocked and may display info about it
static void StartCall ( Handler fnHandler, Scheduler_i* pScheduler, Waiter_t tWait )
{
( new Worker_c ( myinfo::StickParent ( std::move ( fnHandler ) ), pScheduler, std::move ( tWait ) ) )->Schedule ( true );
}
// from Coro::Continue -> all continuations (main purpose - continue with extended stack).
// Adopt parent's task info (if any), and may change it exclusively.
// Parent thread is not blocked and may freely switch to another tasks
static void StartContinuation ( Handler fnHandler, Scheduler_i * pScheduler, size_t iStack, Waiter_t tWait )
{
( new Worker_c ( myinfo::StickParent ( std::move ( fnHandler ) ), pScheduler, std::move ( tWait ), iStack ) )->ScheduleContinuation ();
}
static void MockRun ( Handler fnHandler, VecTraits_T<BYTE> dStack )
{
Worker_c tAction ( std::move ( fnHandler ), dStack );
auto pOldStack = Threads::TopOfStack ();
Threads::SetTopStack ( &dStack.Last() );
{
CoroGuard_c pThis ( &tAction );
tAction.m_tCoroutine.Run ();
}
Threads::SetTopStack ( pOldStack );
}
// secondary context worker.
Worker_c* MakeWorker ( Handler fnHandler ) const
{
return new Worker_c ( myinfo::StickParent ( std::move ( fnHandler ) ), CurrentScheduler () );
}
inline void Restart ( bool bVip = true ) noexcept
{
if (( m_tState.SetFlags ( CoroState_t::Running_e ) & CoroState_t::Running_e )==0 )
Schedule ( bVip );
}
inline void Continue () noexcept // continue previously run task. As continue calculation with extended stack
{
if ( ( m_tState.SetFlags ( CoroState_t::Running_e ) & CoroState_t::Running_e )==0 )
ScheduleContinuation();
}
inline void Pause ( bool bVip = true ) noexcept
{
if ( ( m_tState.SetFlags ( CoroState_t::Running_e | CoroState_t::Paused_e ) & CoroState_t::Running_e ) == 0 )
Schedule ( bVip );
}
inline void Reschedule ( bool bVip = true ) noexcept
{
Pause ( bVip );
Yield_();
m_tState.ResetFlags ( CoroState_t::Paused_e );
}
inline void Yield_ () noexcept
{
m_tCoroutine.Yield_ ();
}
inline void YieldWith ( Handler fnHandler ) noexcept
{
m_fnYieldWithProceeder = std::move (fnHandler);
Yield_ ();
}
inline void MoveTo ( Scheduler_i * pScheduler ) noexcept
{
if ( m_pScheduler == pScheduler )
return; // nothing to do
m_pScheduler = pScheduler;
Reschedule();
}
inline bool Resume () noexcept
{
{
CoroGuard_c pThis (this);
m_tCoroutine.Run();
}
if ( m_tCoroutine.IsFinished () )
{
delete this;
return true;
}
return false;
}
inline Handler Restarter ( bool bVip = true ) noexcept
{
return [this, bVip] { Restart ( bVip ); };
}
inline Handler Continuator () noexcept
{
return [this] { Continue(); };
}
const BYTE * GetTopOfStack () const noexcept
{
return m_tCoroutine.GetTopOfStack();
}
int GetStackSize () const noexcept
{
return m_tCoroutine.GetStackSize ();
}
inline Scheduler_i * CurrentScheduler() const noexcept
{
return m_pScheduler;
}
inline int64_t GetCurrentCpuTimeBase() const noexcept
{
return m_tmCpuTimeBase;
}
inline uint64_t UID() const noexcept
{
return m_uId;
}
inline int ID() const noexcept
{
return (int)m_uId;
}
inline static Worker_c* CurrentWorker() noexcept
{
return (Worker_c*)Threads::MyThd().m_pWorker;
}
inline bool Wake ( size_t iExpectedEpoch, bool bVip ) noexcept
{
bool bLastWaker = m_iWakerEpoch.compare_exchange_strong ( iExpectedEpoch, iExpectedEpoch + 1, std::memory_order_acq_rel );
if ( !bLastWaker ) {
// m_iWakerEpoch doesn't match expected epoch, op outdated
return false;
}
assert ( CurrentWorker() != this );
Restart ( bVip );
return true;
}
inline Waker_c CreateWaker() noexcept
{
// this operation makes all previously created wakers to be outdated
return { this, ++m_iWakerEpoch };
}
inline void SetTimePeriodUS ( int64_t tmTimePointPeriodUS )
{
m_tmRuntimePeriodUS = tmTimePointPeriodUS;
CheckEngageTimer ( TimePoint_e::fromresume );
}
inline int64_t GetTimePeriodUS() const noexcept
{
return m_tmRuntimePeriodUS;
}
inline bool RuntimeExceeded() const
{
return sph::TimeExceeded ( m_tmNextTimePointUS );
}
inline const int64_t& GetNextTimePointUS() const noexcept
{
return m_tmNextTimePointUS;
}
inline int64_t GetRestPeriodUS() const noexcept
{
return m_tmNextTimePointUS - sph::MicroTimer();
}
inline void RestartRuntime() noexcept
{
CheckEngageTimer ( TimePoint_e::realtime );
}
inline int NumOfRestarts() const noexcept
{
return m_iNumOfRestarts;
}
};
Worker_c* CurrentWorker() noexcept
{
return Worker_c::CurrentWorker();
}
Worker_c* Worker() noexcept
{
auto pWorker = CurrentWorker();
assert ( pWorker && "function must be called from inside coroutine" );
return pWorker;
}
// start primary task
void Go ( Handler&& fnHandler, Scheduler_i * pScheduler )
{
if ( !pScheduler )
return;
assert ( pScheduler );
Worker_c::StartPrimary ( std::move(fnHandler), pScheduler );
}
// start secondary subtasks (parallel search, pq processing, etc)
void Co ( Handler&& fnHandler, Waiter_t tSignaller )
{
auto pScheduler = CurrentScheduler ();
if ( !pScheduler )
pScheduler = GlobalWorkPool ();
assert ( pScheduler );
Worker_c::StartOther ( std::move ( fnHandler ), pScheduler, 0, std::move ( tSignaller ) );
}
// resize stack and continue as fast as possible (continuation task in same thread, or post to vip queue)
void Continue ( Handler&& fnHandler, int iStack )
{
auto pScheduler = CurrentScheduler();
if ( !pScheduler )
pScheduler = GlobalWorkPool ();
assert ( pScheduler );
auto dWaiter = DefferedContinuator ();
Worker_c::StartContinuation( std::move ( fnHandler ), pScheduler, iStack, dWaiter );
WaitForDeffered ( std::move ( dWaiter ));
}
void YieldWith ( Handler fnHandler ) noexcept
{
Worker ()->YieldWith ( std::move(fnHandler) );
}
// Move current task to another scheduler. Say, from netloop to worker, or from plain worker to vip, etc.
void MoveTo ( Scheduler_i * pScheduler ) noexcept
{
Worker ()->MoveTo ( pScheduler );
}
void Yield_ () noexcept
{
Worker ()->Yield_();
}
void Reschedule() noexcept
{
auto pWorker = CurrentWorker();
if ( pWorker )
pWorker->Reschedule();
}
int ID() noexcept
{
return Worker()->ID();
}
bool RuntimeExceeded() noexcept
{
return Worker()->RuntimeExceeded();
}
const int64_t& GetNextTimePointUS() noexcept
{
return Worker()->GetNextTimePointUS();
}
void RestartRuntime() noexcept
{
Worker()->RestartRuntime();
}
int NumOfRestarts() noexcept
{
return Worker()->NumOfRestarts();
}
} // namespace Coro
Resumer_fn MakeCoroExecutor ( Handler fnHandler )
{
auto* pWorker = Coro::Worker ()->MakeWorker ( std::move ( fnHandler ) );
return [pWorker] () -> bool { return pWorker->Resume(); };
}
void CallPlainCoroutine ( Handler fnHandler, Scheduler_i* pScheduler )
{
if ( !pScheduler )
pScheduler = GlobalWorkPool();
CSphAutoEvent tEvent;
auto dWaiter = Waiter_t ( nullptr, [&tEvent] ( void * ) { tEvent.SetEvent (); } );
Coro::Worker_c::StartCall ( std::move ( fnHandler ), pScheduler, std::move(dWaiter) );
tEvent.WaitEvent ();
}
void MockCallCoroutine ( VecTraits_T<BYTE> dStack, Handler fnHandler )
{
Coro::Worker_c::MockRun ( std::move ( fnHandler ), dStack );
}
// if called from coroutine - just makes continuation.
// if called from plain thread (non-contexted) - creates coro, run and wait until it finished.
void CallCoroutine ( Handler fnHandler )
{
if ( !Coro::Worker_c::CurrentWorker () )
{
CallPlainCoroutine ( std::move ( fnHandler ) );
return;
}
auto pScheduler = Coro::CurrentScheduler ();
if ( !pScheduler )
pScheduler = GlobalWorkPool ();
assert ( pScheduler );
auto dWaiter = DefferedContinuator ();
Coro::Worker_c::StartContinuation ( std::move ( fnHandler ), pScheduler, 0, dWaiter );
WaitForDeffered ( std::move ( dWaiter ) );
}
bool CallCoroutineRes ( Predicate fnHandler )
{
bool bResult;
CallCoroutine ( [&bResult, &fnHandler] { bResult = fnHandler(); } );
return bResult;
}
// start secondary subtasks (parallel search, pq processing, etc)
void StartJob ( Handler fnHandler, Scheduler_i * pScheduler )
{
assert ( pScheduler );
Coro::Worker_c::StartPrimary ( std::move ( fnHandler ), pScheduler, false );
}
// Async schedule continuation.
// Invoking handler will schedule continuation of yielded coroutine and return immediately.
// Scheduled task ('goto continue...') will be pefromed by scheduler's worker (threadpool, etc.)
// this pushes to primary queue
Handler CurrentRestarter ( bool bVip ) noexcept
{
return Coro::Worker()->Restarter ( bVip );
}
Coro::Waker_c CreateWaker ( Coro::Worker_c* pWorker ) noexcept
{
return pWorker ? pWorker->CreateWaker() : Coro::Worker()->CreateWaker();
}
Waiter_t DefferedRestarter () noexcept
{
return { nullptr, [fnProceed = CurrentRestarter ( false )] ( void* ) { fnProceed(); } };
}
Waiter_t DefferedContinuator () noexcept
{
return { nullptr, [fnProceed = Coro::Worker ()->Continuator ()] ( void * ) { fnProceed (); }};
}
void WaitForDeffered ( Waiter_t&& dWaiter ) noexcept
{
// do nothing. Moved dWaiter will be released outside the coro after yield.
Coro::YieldWith ( [capturedWaiter = std::move ( dWaiter ) ] {} );
}
int WaitForN ( DWORD uN, std::initializer_list<Handler> dTasks )
{
assert ( uN > 0 && "trigger N must be >0" );
assert ( dTasks.size() > 0 && dTasks.size() >= uN && "num of tasks to wait must be non-zero, and not greater than trigger" );
int iRes = -1;
// need to store parentSched, since Coro::YieldWith executed _outside_ coroutine, so it has _no_ scheduler!
auto pParentSched = Coro::CurrentScheduler();
Coro::YieldWith ( [&iRes, &dTasks, uN, pParentSched, fnResumer = CurrentRestarter()] {
SharedPtr_t<std::atomic<DWORD>> pCounter { new std::atomic<DWORD> };
pCounter->store ( 0, std::memory_order_release );
int i = 0;
for ( const auto& fnHandler : dTasks )
{
Coro::Go ( [pCounter, fnResumer, &fnHandler, i, uN, &iRes] {
fnHandler();
if ( pCounter->fetch_add ( 1, std::memory_order_acq_rel ) == uN - 1 )
{
iRes = i;
fnResumer();
}
},
pParentSched );
++i;
}
} );
return iRes;
}
}
int64_t sphTaskCpuTimer()
{
auto pWorker = Threads::Coro::Worker_c::CurrentWorker();
if ( pWorker )
return pWorker->GetCurrentCpuTimeBase() + sphThreadCpuTimer();
return sphThreadCpuTimer();
}
namespace Threads {
const void* MyStack()
{
auto pWorker = Threads::Coro::Worker_c::CurrentWorker();
if ( pWorker )
return pWorker->GetTopOfStack();
return Threads::TopOfStack();
}
int MyStackSize()
{
auto pWorker = Threads::Coro::Worker_c::CurrentWorker();
if ( pWorker )
return pWorker->GetStackSize();
return Threads::STACK_SIZE;
}
int64_t GetStackUsed()
{
BYTE cStack;
auto* pStackTop = (const BYTE*)MyStack();
if ( !pStackTop )
return 0;
int64_t iHeight = pStackTop - &cStack;
return ( iHeight >= 0 ) ? iHeight : -iHeight; // on different arch stack may grow in different directions
}
bool IsInsideCoroutine()
{
// need safe function to call without coroutunes setup like in indexer
return ( Coro::Worker_c::CurrentWorker() != nullptr );
}
Scheduler_i* Coro::CurrentScheduler()
{
auto pWorker = Coro::Worker_c::CurrentWorker();
if ( !pWorker )
return nullptr;
return pWorker->CurrentScheduler();
}
int NThreads()
{
Scheduler_i* pScheduler = Coro::CurrentScheduler();
if ( !pScheduler )
pScheduler = GlobalWorkPool();
return pScheduler->WorkingThreads();
}
namespace Coro
{
void ExecuteN ( int iConcurrency, Threads::Handler&& fnWorker )
{
if ( iConcurrency==1 )
{
myinfo::OwnMiniNoCount ( fnWorker ) ();
return;
}
assert ( iConcurrency ); // must be positive
if ( !iConcurrency ) // however don't crash even there, just do nothing.
return;
auto dWaiter = DefferedRestarter ();
for ( int i = 1; i<iConcurrency; ++i )
Coro::Co ( Threads::WithCopiedCrashQuery ( fnWorker ), dWaiter );
myinfo::OwnMiniNoCount ( fnWorker ) ();
WaitForDeffered ( std::move ( dWaiter ));
}
int tmThrotleTimeQuantumMs = tmDefaultThrotleTimeQuantumMs; // how long task may work before rescheduling (in milliseconds)
void SetDefaultThrottlingPeriodMS ( int tmPeriodMs )
{
tmThrotleTimeQuantumMs = tmPeriodMs < 0 ? tmDefaultThrotleTimeQuantumMs : tmPeriodMs;
}
void SetThrottlingPeriodMS ( int tmPeriodMs )
{
if ( tmPeriodMs < 0 )
tmPeriodMs = tmThrotleTimeQuantumMs;
SetThrottlingPeriodUS ( tmPeriodMs * 1000 );
}
void SetThrottlingPeriodUS ( int64_t tmPeriodUs )
{
assert ( tmPeriodUs>=0 );
Worker()->SetTimePeriodUS ( tmPeriodUs );
}
int64_t GetThrottlingPeriodUS ()
{
return Worker()->GetTimePeriodUS ();
}
void RescheduleAndKeepCrashQuery ( bool bVip ) noexcept
{
CrashQueryKeeper_c _;
Coro::Worker()->Reschedule ( bVip ); // timer will be automatically re-engaged on resume
}
inline void fnResume ( volatile Worker_c* pCtx )
{
if ( pCtx )
( (Worker_c*)pCtx )->Restart ( false );
}
// yield and reschedule after given period of time (in milliseconds)
void SleepMsec ( int iMsec )
{
if ( iMsec < 0 )
return;
MiniTimer_c tWait { "SleepMsec", [tWaker = Worker()->CreateWaker()] { tWaker.Wake(); } };
// suspend this fiber
Coro::YieldWith ( [&tWait, iMsec](){ tWait.Engage ( iMsec ); });
}
Event_c::~Event_c ()
{
// edge case: event destroyed being in wait state.
// Let's resume then.
if ( m_pCtx && (m_uState.load() & Waited_e)!=0 )
fnResume ( m_pCtx );
}
// If 'waited' state detected, resume waiter.
// else atomically set flag 'signaled'
void Event_c::SetEvent()
{
BYTE uState = m_uState.load ( std::memory_order_relaxed );
do
{
if ( uState & Waited_e )
{
m_uState.store ( Signaled_e ); // memory_order_sec_cst - to ensure that next call will not resume again
return fnResume ( m_pCtx );
}
} while ( !m_uState.compare_exchange_weak ( uState, uState | Signaled_e, std::memory_order_relaxed ) );
}
// if 'signaled' state detected, clean all flags and return.
// else yield, then (out of coro) atomically set 'waited' flag, checking also 'signaled' flag again.
// on resume clean all flags.
void Event_c::WaitEvent()
{
if ( !( m_uState.load ( std::memory_order_relaxed ) & Signaled_e ) )
{
if ( m_pCtx != Worker() )
m_pCtx = Worker();
YieldWith ( [this] {
BYTE uState = m_uState.load ( std::memory_order_relaxed );
do
{
if ( uState & Signaled_e )
return fnResume ( m_pCtx );
} while ( !m_uState.compare_exchange_weak ( uState, uState | Waited_e, std::memory_order_relaxed ) );
} );
}
m_uState.store ( 0, std::memory_order_relaxed );
std::atomic_thread_fence ( std::memory_order_release );
}
bool Waker_c::Wake ( bool bVip ) const noexcept
{
assert ( m_iEpoch > 0 );
assert ( m_pCtx );
return m_pCtx->Wake ( m_iEpoch, bVip );
}
bool AtomicWaker_c::WakeOnce ( bool bVip ) noexcept
{
auto pCtx = m_pCtx.exchange ( nullptr, std::memory_order_relaxed );
if ( !pCtx )
return false;
assert ( m_iEpoch > 0 );
return pCtx->Wake ( m_iEpoch, bVip );
}
void WaitQueue_c::SuspendAndWait ( sph::Spinlock_lock& tLock, Worker_c* pActive ) NO_THREAD_SAFETY_ANALYSIS
{
WakerInQueue_c w { pActive->CreateWaker() };
m_Slist.push_back ( w );
// suspend this fiber
pActive->YieldWith ( [&tLock]() NO_THREAD_SAFETY_ANALYSIS { tLock.unlock(); } );
assert ( !w.is_linked() );
}
// returns true if signalled, false if timed-out
bool WaitQueue_c::SuspendAndWaitUntil ( sph::Spinlock_lock& tLock, Worker_c* pActive, int64_t iTimestamp ) NO_THREAD_SAFETY_ANALYSIS
{
WakerInQueue_c w { pActive->CreateWaker() };
m_Slist.push_back ( w );
MiniTimer_c tWait ( "SuspendAndWait", [&w] { w.Wake(); } );
// suspend this fiber
pActive->YieldWith ( [&tLock, &tWait, iTimestamp]() NO_THREAD_SAFETY_ANALYSIS {
tLock.unlock();
tWait.EngageAt ( iTimestamp );
});
// resumed. Check if deadline is reached
if ( sph::TimeExceeded ( iTimestamp ) || sphInterrupted () )
{
tLock.lock();
// remove from waiting-queue
if ( w.is_linked() )
m_Slist.remove ( w );
tLock.unlock();
return false;
}
assert ( !w.is_linked () );
return true;
}
bool WaitQueue_c::SuspendAndWaitForMS ( sph::Spinlock_lock& tLock, Worker_c* pActive, int64_t iTimePeriodMS )
{
return SuspendAndWaitUntil ( tLock, pActive, sphMicroTimer() + iTimePeriodMS * 1000 );
}
void WaitQueue_c::NotifyOne()
{
while ( !m_Slist.empty() ) {
Waker_c& w = m_Slist.front();
m_Slist.pop_front();
if ( w.Wake() ) {
break;
}
}
}
void WaitQueue_c::NotifyAll()
{
while ( !m_Slist.empty() ) {
Waker_c& w = m_Slist.front();
m_Slist.pop_front();
w.Wake();
}
}
bool WaitQueue_c::Empty() const
{
return m_Slist.empty();
}
// the mutex
void Mutex_c::Lock()
{
while ( true ) {
auto* pActiveWorker = Worker();
// store this fiber in order to be notified later
sph::Spinlock_lock tLock { m_tWaitQueueSpinlock };
assert ( pActiveWorker != m_pOwner );
if ( !m_pOwner ) {
m_pOwner = pActiveWorker;
return;
}
m_tWaitQueue.SuspendAndWait( tLock, pActiveWorker );
}
}
void Mutex_c::Unlock()
{
Debug (auto* pActiveWorker = Worker();)
sph::Spinlock_lock tLock { m_tWaitQueueSpinlock };
assert ( pActiveWorker == m_pOwner );
m_pOwner = nullptr;
m_tWaitQueue.NotifyOne();
}
// conditional variable
void ConditionVariableAny_c::NotifyOne() noexcept
{
sph::Spinlock_lock tLock { m_tWaitQueueSpinlock };
m_tWaitQueue.NotifyOne();
}
void ConditionVariableAny_c::NotifyAll() noexcept
{
sph::Spinlock_lock tLock { m_tWaitQueueSpinlock };
m_tWaitQueue.NotifyAll();
}
// the shared mutex
// practice shows few numbers are more expressive than symbolic names in that case
static constexpr DWORD ux01 = 1; // w-lock acquired
static constexpr DWORD ux02 = 2; // r-lock bias
Debug (static constexpr DWORD uxFE = ~ux01;) // mask for w-lock flag (0xFFFFFFFE)
// prefer w-lock: acquire only if w-lock queue is empty
void RWLock_c::ReadLock()
{
while ( true ) {
sph::Spinlock_lock tLock { m_tInternalMutex };
if ( !( m_uState & ux01 ) && m_tWaitWQueue.Empty() )
{
m_uState += ux02;
assert ( ( m_uState & uxFE ) != uxFE ); // hope, 31 bits is enough to count all acquired r-locks.
return;
}
m_tWaitRQueue.SuspendAndWait ( tLock, Worker() );
}
}
void RWLock_c::WriteLock()
{
while ( true ) {
sph::Spinlock_lock tLock { m_tInternalMutex };
if ( !m_uState )
{
m_uState = ux01;
return;
}
m_tWaitWQueue.SuspendAndWait ( tLock, Worker() );
}
}
void RWLock_c::Unlock()
{
sph::Spinlock_lock tLock { m_tInternalMutex };
assert ( m_uState >= ux01 && "attempt to unlock not locked coro mutex");
m_uState = ( m_uState == ux01 ) ? 0 : ( m_uState - ux02 );
if ( m_uState )
return;
// fixme! point of priority decision: on unlock, do we need to wake up next w-locker, or all r-lockers?
if ( !m_tWaitWQueue.Empty() )
m_tWaitWQueue.NotifyOne();
else
m_tWaitRQueue.NotifyAll();
}
// returns true if there are single read-lock, and pending write-lock
bool RWLock_c::TestNextWlock () const noexcept
{
sph::Spinlock_lock tLock { m_tInternalMutex };
if ( m_uState != ux02 )
return false;
return !m_tWaitWQueue.Empty ();
}
} // namespace Coro
} // namespace Threads
| 29,529
|
C++
|
.cpp
| 935
| 29.305882
| 137
| 0.709152
|
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
|
16,805
|
task_dispatcher.cpp
|
manticoresoftware_manticoresearch/src/task_dispatcher.cpp
|
//
// 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
//
#include "task_dispatcher.h"
#include "coroutine.h"
#include "client_task_info.h"
#include <atomic>
#include <cassert>
// artificial race right after source creation.
// That is, quite seldom race between 'make source' and 'clone context' will surely happen in debug build
#ifndef NDEBUG
#define MAKE_RACE 1
#else
#define MAKE_RACE 0
#endif
namespace {
inline int CalcConcurrency ( int iConcurrency )
{
if ( iConcurrency )
return iConcurrency;
iConcurrency = GetEffectiveDistThreads();
if ( iConcurrency )
return iConcurrency;
return Threads::NThreads();
}
}
/////////////////////////////////////////////////////////////////////////////
/// trivial concurrent task dispatcher
/////////////////////////////////////////////////////////////////////////////
class ConcurrentTaskDispatcher_c;
class SingleTaskSource_c final : public Dispatcher::TaskSource_i
{
ConcurrentTaskDispatcher_c& m_tParent;
const int m_iMaxJob;
public:
SingleTaskSource_c ( ConcurrentTaskDispatcher_c& tParent, int iJobs );
bool FetchTask ( int& iTask ) final;
};
class ConcurrentTaskDispatcher_c final: public Dispatcher::TaskDispatcher_i
{
const int m_iJobs;
const int m_iConcurrency;
std::atomic<int32_t> m_iCurrentJob;
public:
ConcurrentTaskDispatcher_c ( int iJobs, int iConcurrency );
int GetConcurrency() const final;
std::unique_ptr<Dispatcher::TaskSource_i> MakeSource() final;
int GetNextConcurrentTask();
};
SingleTaskSource_c::SingleTaskSource_c ( ConcurrentTaskDispatcher_c& tParent, int iJobs )
: m_tParent ( tParent )
, m_iMaxJob ( iJobs - 1 )
{}
bool SingleTaskSource_c::FetchTask ( int& iTask )
{
if ( iTask>=0 )
return true; // previous value wasn't yet consumed
auto iNextTask = m_tParent.GetNextConcurrentTask();
if ( iNextTask < 0 )
return false;
iTask = m_iMaxJob - iNextTask;
return true;
}
ConcurrentTaskDispatcher_c::ConcurrentTaskDispatcher_c ( int iJobs, int iConcurrency )
: m_iJobs ( iJobs )
, m_iConcurrency ( CalcConcurrency ( iConcurrency ) )
, m_iCurrentJob { iJobs - 1 }
{}
int ConcurrentTaskDispatcher_c::GetConcurrency() const
{
return m_iConcurrency;
}
std::unique_ptr<Dispatcher::TaskSource_i> ConcurrentTaskDispatcher_c::MakeSource()
{
auto pSource = std::make_unique<SingleTaskSource_c> ( *this, m_iJobs );
#if MAKE_RACE
Threads::Coro::Reschedule();
#endif
return pSource;
}
int ConcurrentTaskDispatcher_c::GetNextConcurrentTask()
{
return m_iCurrentJob.fetch_sub ( 1, std::memory_order_relaxed );
}
/////////////////////////////////////////////////////////////////////////////
/// round-robin task dispatcher
/////////////////////////////////////////////////////////////////////////////
class RRTaskSource_c final: public Dispatcher::TaskSource_i
{
const int m_iJobs;
const int m_iBatch;
const int m_iStride;
const int m_iOffset;
const bool m_bIdle;
int m_iMySerie = 0;
int m_iJobInSerie = 0;
public:
RRTaskSource_c ( int iJobs, int iFiber, int iBatch, int iFibers );
bool FetchTask ( int& iTask ) final;
};
RRTaskSource_c::RRTaskSource_c ( int iJobs, int iFiber, int iBatch, int iFibers )
: m_iJobs ( iJobs )
, m_iBatch ( iBatch )
, m_iStride ( iFibers * iBatch )
, m_iOffset ( iFiber * iBatch )
, m_bIdle ( iFiber >= iFibers )
{}
bool RRTaskSource_c::FetchTask ( int& iTask )
{
if ( iTask >= 0 )
return true; // previous value wasn't yet consumed
if ( m_bIdle )
return false;
auto iJob = m_iMySerie * m_iStride + m_iOffset + m_iJobInSerie;
if ( iJob >= m_iJobs )
return false;
iTask = iJob;
++m_iJobInSerie;
if ( m_iJobInSerie >= m_iBatch )
{
m_iJobInSerie = 0;
++m_iMySerie;
}
return true;
}
class NullTaskSource_c final: public Dispatcher::TaskSource_i
{
public:
bool FetchTask ( int& iTask ) final;
};
bool NullTaskSource_c::FetchTask ( int& iTask )
{
return iTask >= 0;
}
class RRTaskDispatcher_c final: public Dispatcher::TaskDispatcher_i
{
const int m_iJobs;
const int m_iConcurrency;
const int m_iBatch;
std::atomic<int32_t> m_iNextFiber {0};
public:
RRTaskDispatcher_c ( int iJobs, int iConcurrency, int iBatch );
int GetConcurrency() const final;
std::unique_ptr<Dispatcher::TaskSource_i> MakeSource() final;
};
RRTaskDispatcher_c::RRTaskDispatcher_c ( int iJobs, int iConcurrency, int iBatch )
: m_iJobs ( iJobs )
, m_iConcurrency ( CalcConcurrency ( iConcurrency ) )
, m_iBatch ( iBatch )
{}
int RRTaskDispatcher_c::GetConcurrency() const
{
return m_iConcurrency;
}
std::unique_ptr<Dispatcher::TaskSource_i> RRTaskDispatcher_c::MakeSource()
{
int iFiber = m_iNextFiber.fetch_add ( 1, std::memory_order_relaxed );
if ( iFiber >= m_iConcurrency )
return std::make_unique<NullTaskSource_c>();
auto pSource = std::make_unique<RRTaskSource_c> ( m_iJobs, iFiber, m_iBatch, m_iConcurrency );
#if MAKE_RACE
Threads::Coro::Reschedule();
#endif
return pSource;
}
namespace Dispatcher {
std::unique_ptr<TaskDispatcher_i> MakeTrivial ( int iJobs, int iConcurrency )
{
return std::make_unique<ConcurrentTaskDispatcher_c> ( iJobs, iConcurrency );
}
std::unique_ptr<TaskDispatcher_i> MakeRoundRobin ( int iJobs, int iConcurrency, int iBatch )
{
return std::make_unique<RRTaskDispatcher_c> ( iJobs, iConcurrency, iBatch );
}
std::unique_ptr<Dispatcher::TaskDispatcher_i> Make ( int iJobs, int iDefaultConcurrency, Dispatcher::Template_t tWhat, bool bSingle )
{
if ( bSingle )
iDefaultConcurrency = 1;
else if ( tWhat.concurrency )
iDefaultConcurrency = tWhat.concurrency;
if ( tWhat.batch )
return MakeRoundRobin ( iJobs, iDefaultConcurrency, tWhat.batch );
return MakeTrivial ( iJobs, iDefaultConcurrency );
}
Template_t ParseTemplate ( Str_t sTemplate )
{
StrtVec_t dStr;
sph::Split ( dStr, sTemplate.first, sTemplate.second, "/" );
dStr.for_each ( [] ( auto& tVal ) { tVal = sph::Trim ( tVal ); } );
while ( dStr.GetLength()<2 )
dStr.Add ( dEmptyStr );
auto fnParseValue = [] ( Str_t tVal ) -> int
{
if ( IsEmpty ( tVal ) )
return 0;
if ( tVal.second == 1 && ( *tVal.first == '0' || *tVal.first == '*' ) )
return 0;
return atoi ( CSphString ( tVal ).cstr() );
};
assert ( dStr.GetLength() >= 2 );
return { fnParseValue ( dStr[0] ), fnParseValue ( dStr[1] ) };
}
Template_t ParseTemplate ( const char* szTemplate )
{
return ParseTemplate ( FromSz ( szTemplate ) );
}
std::pair<Template_t, Template_t> ParseTemplates ( Str_t sTemplates )
{
sTemplates = sph::Trim ( sTemplates, '\'' ); // unquote, if necessary.
StrtVec_t dStr;
sph::Split ( dStr, sTemplates.first, sTemplates.second, "+" );
while ( dStr.GetLength() < 2 )
dStr.Add ( dEmptyStr );
assert ( dStr.GetLength() >= 2 );
return { ParseTemplate ( dStr[0] ), ParseTemplate ( dStr[1] ) };
}
std::pair<Template_t, Template_t> ParseTemplates ( const char* szTemplates )
{
return ParseTemplates ( FromSz ( szTemplates ) );
}
namespace {
std::pair<Template_t, Template_t> g_GlobalDispatcherTemplates = ParseTemplates ( getenv ( "MANTICORE_THREADS_EX" ) );
}
void SetGlobalDispatchers ( const char* szTemplates )
{
g_GlobalDispatcherTemplates = ParseTemplates ( szTemplates );
}
// return stored global dispatchers
Template_t GetGlobalBaseDispatcherTemplate()
{
return g_GlobalDispatcherTemplates.first;
}
Template_t GetGlobalPseudoShardingDispatcherTemplate()
{
return g_GlobalDispatcherTemplates.second;
}
void Unify ( Template_t& tBase, const Template_t tNew )
{
if ( tNew.concurrency )
tBase.concurrency = tNew.concurrency;
if ( tNew.batch )
tBase.batch = tNew.batch;
}
CSphString RenderTemplate ( Template_t tTemplate )
{
if ( tTemplate.concurrency && tTemplate.batch )
return SphSprintf ("%d/%d", tTemplate.concurrency, tTemplate.batch );
if ( tTemplate.concurrency )
return SphSprintf ( "%d", tTemplate.concurrency );
if ( tTemplate.batch )
return SphSprintf ( "/%d", tTemplate.batch );
return "";
}
void RenderTemplates ( StringBuilder_c& tOut, std::pair<Template_t, Template_t> dTemplates )
{
auto sFirst = RenderTemplate ( dTemplates.first );
auto sSecond = RenderTemplate ( dTemplates.second );
if ( !sFirst.IsEmpty() && !sSecond.IsEmpty() )
return (void)tOut.Sprint ( sFirst, '+', sSecond );
if ( !sFirst.IsEmpty() )
return (void)tOut.Sprint ( sFirst );
if ( !sSecond.IsEmpty() )
return (void)tOut.Sprint ( '+', sSecond );
}
} // namespace Dispatcher
| 8,645
|
C++
|
.cpp
| 271
| 30.04428
| 133
| 0.709988
|
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
|
16,806
|
libutils.cpp
|
manticoresoftware_manticoresearch/src/libutils.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 "libutils.h"
#include "fileutils.h"
#include <optional>
#if _WIN32
void * dlsym ( void * lib, const char * name )
{
return (void*)GetProcAddress ( (HMODULE)lib, name );
}
void * dlopen ( const char * libname, int )
{
return LoadLibraryEx ( libname, NULL, 0 );
}
int dlclose ( void * lib )
{
return FreeLibrary ( (HMODULE)lib )
? 0
: GetLastError();
}
const char * dlerror()
{
static char sError[256];
DWORD uError = GetLastError();
FormatMessage ( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, uError, LANG_SYSTEM_DEFAULT, (LPTSTR)sError, sizeof(sError), NULL );
return sError;
}
#endif // _WIN32
std::optional<CSphString> TryPath ( const CSphString& sFullpath, int iVersion )
{
// first try versioned variant. So, that non-versioned libs from 'ancient age' doesn't suppress new one one
auto sVersionedFullPath = SphSprintf ( "%s.%i", sFullpath.cstr(), iVersion );
if ( sphFileExists ( sVersionedFullPath.cstr() ) )
return sVersionedFullPath;
if ( sphFileExists ( sFullpath.cstr() ) )
return sFullpath;
return std::nullopt;
}
CSphString TryDifferentPaths ( const CSphString & sLibfile, const CSphString & sFullpath, int iVersion )
{
auto sAnyPath = TryPath ( sFullpath, iVersion );
if ( sAnyPath )
return sAnyPath.value();
#if _WIN32
CSphString sPathToExe = GetPathOnly ( GetExecutablePath() );
CSphString sPath;
sPath.SetSprintf ( "%s%s", sPathToExe.cstr(), sLibfile.cstr() );
sAnyPath = TryPath ( sPath, iVersion );
#endif
return sAnyPath.value_or("");
}
| 2,007
|
C++
|
.cpp
| 60
| 31.7
| 151
| 0.736406
|
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
|
16,807
|
config_reloader.cpp
|
manticoresoftware_manticoresearch/src/config_reloader.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 "config_reloader.h"
#include "searchdaemon.h"
#include "searchdha.h"
#include "index_rotator.h"
#include "detail/indexlink.h"
static auto& g_bSeamlessRotate = sphGetSeamlessRotate();
// Reloading called always from same thread (so, for now not need to be th-safe for itself)
// ServiceMain() -> TickHead() -> CheckRotate() -> ReloadConfigAndRotateIndexes().
class ConfigReloader_c::Impl_c final
{
ReadOnlyServedHash_c::Snapshot_t m_hLocalSnapshot;
ReadOnlyDistrHash_c::Snapshot_t m_hDistrSnapshot;
WriteableServedHash_c m_hNewLocalIndexes { *g_pLocalIndexes };
WriteableDistrHash_c m_hNewDistrIndexes { *g_pDistIndexes };
HashOfServed_c& m_hDeferred;
sph::StringSet m_hProcessed;
sph::StringSet m_hLocals;
private:
bool ExistsLocal ( const CSphString& sIndex ) const
{
assert ( m_hLocalSnapshot.first );
return m_hLocalSnapshot.first->Exists ( sIndex );
}
bool ExistsDistr ( const CSphString& sIndex ) const
{
assert ( m_hDistrSnapshot.first );
return m_hDistrSnapshot.first->Exists ( sIndex );
}
inline cServedIndexRefPtr_c GetSnapServed ( const CSphString& sName ) const
{
assert ( m_hLocalSnapshot.first );
auto* pEntry = ( *m_hLocalSnapshot.first ) ( sName );
assert ( pEntry );
return *pEntry;
}
bool CopyExistingLocal ( const CSphString& sIndex )
{
assert ( m_hLocalSnapshot.first );
auto* pExisting = ( *m_hLocalSnapshot.first ) ( sIndex );
if ( !pExisting )
return false;
sphLogDebug ( "Keep existing before local table %s", sIndex.cstr() );
return m_hNewLocalIndexes.Add ( *pExisting, sIndex );
}
bool CopyExistingDistr ( const CSphString& sIndex )
{
assert ( m_hDistrSnapshot.first );
auto* pExisting = ( *m_hDistrSnapshot.first ) ( sIndex );
if ( !pExisting )
return false;
sphLogDebug ( "Keep existing before distr table %s", sIndex.cstr() );
return m_hNewDistrIndexes.Add ( *pExisting, sIndex );
}
void KeepExisting ( const CSphString& sIndex )
{
sphLogDebug ( "keep existing table %s", sIndex.cstr() );
CopyExistingLocal ( sIndex );
m_hLocals.Add ( sIndex );
}
void AddDeferred ( const CSphString& sIndex, ServedIndexRefPtr_c&& pServed )
{
sphLogDebug ( "add deferred table %s", sIndex.cstr() );
KeepExisting ( sIndex );
CopyExistingDistr ( sIndex ); // keep for now; will be removed when deferred processed.
m_hDeferred.Add ( pServed, sIndex );
}
void LoadDistrFromConfig ( const CSphString& sIndex, const CSphConfigSection& hIndex )
{
CSphString sError;
DistributedIndexRefPtr_t pNewDistr ( new DistributedIndex_t );
bool bOk = ConfigureDistributedIndex ( [this] ( const auto& sIdx ) { return m_hLocals[sIdx]; }, *pNewDistr, sIndex.cstr(), hIndex, sError );
if ( !bOk || pNewDistr->IsEmpty() )
{
if ( CopyExistingDistr ( sIndex ) || CopyExistingLocal ( sIndex ) )
sphWarning ( "table '%s': no valid local/remote tables in distributed table; using last valid definition; error: %s", sIndex.cstr(), sError.cstr() );
} else
m_hNewDistrIndexes.Add ( pNewDistr, sIndex );
}
// load fresh local index
void LoadNewLocalFromConfig ( const CSphString& sIndex, const CSphConfigSection& hIndex )
{
CSphString sError;
auto [ eAdd, pFreshLocal ] = AddIndex ( sIndex.cstr(), hIndex, false, false, nullptr, sError );
assert ( eAdd != ADD_DISTR && "internal error: distr table should not be here!" );
switch ( eAdd )
{
case ADD_ERROR:
sphWarning ( "table '%s': failed to load with error %s", sIndex.cstr(), sError.cstr() );
break;
case ADD_NEEDLOAD:
assert ( ServedDesc_t::IsLocal ( pFreshLocal ) ); // that is: PLAIN, RT, or PERCOLATE
if ( pFreshLocal->m_eType == IndexType_e::PLAIN && !PreloadKlistTarget ( RedirectToRealPath ( pFreshLocal->m_sIndexPath ), CheckIndexRotate_c ( *pFreshLocal, CheckIndexRotate_c::CheckLink ), pFreshLocal->m_dKilllistTargets ) )
pFreshLocal->m_dKilllistTargets.Reset();
AddDeferred ( sIndex, std::move ( pFreshLocal ) );
break;
case ADD_SERVED:
sphLogDebug ( "add template table %s", sIndex.cstr() );
assert ( pFreshLocal->m_eType == IndexType_e::TEMPLATE ); // only templates are immediately ready
m_hLocals.Add ( sIndex );
m_hNewLocalIndexes.Add ( pFreshLocal, sIndex );
default:
break;
}
}
// special pass for 'simple' rotation (i.e. *.new to current)
void PreparePlainRotationIfNeed ( const CSphString& sIndex, const cServedIndexRefPtr_c& pAlreadyServed )
{
assert ( pAlreadyServed->m_eType == IndexType_e::PLAIN );
if ( !CheckIndexRotate_c ( *pAlreadyServed, CheckIndexRotate_c::CheckLink ).RotateFromNew() )
return KeepExisting ( sIndex ); // no .new, no need to rotate, just keep existing
ServedIndexRefPtr_c pIndex = MakeCloneForRotation ( pAlreadyServed, sIndex );
// reinit klist targets for rotating index
pIndex->m_dKilllistTargets.Reset();
if ( !PreloadKlistTarget ( RedirectToRealPath ( pIndex->m_sIndexPath ), RotateFrom_e::NEW, pIndex->m_dKilllistTargets ) )
pIndex->m_dKilllistTargets.Reset();
AddDeferred ( sIndex, std::move ( pIndex ) );
}
void ReconfigureIndex ( const CSphString& sIndex, const CSphConfigSection& hIndex )
{
cServedIndexRefPtr_c pAlreadyServed = GetSnapServed ( sIndex );
assert ( pAlreadyServed );
ServedIndexRefPtr_c pClone = MakeFullClone ( pAlreadyServed );
ConfigureLocalIndex ( pClone, hIndex, false, nullptr );
m_hNewLocalIndexes.Add ( pClone, sIndex );
// need w-lock of already served (exposed) idx, since we change settings.
// fixme! what about another probably changed settings?
WIdx_c pIdx { pAlreadyServed };
pIdx->SetMutableSettings ( pClone->m_tSettings );
pIdx->SetGlobalIDFPath ( pClone->m_sGlobalIDFPath );
}
void LoadLocalFromConfig ( const CSphString& sIndex, IndexType_e eType, const CSphConfigSection& hIndex )
{
if ( !ExistsLocal ( sIndex ) )
return LoadNewLocalFromConfig ( sIndex, hIndex );
cServedIndexRefPtr_c pAlreadyServed = GetSnapServed ( sIndex );
assert ( pAlreadyServed );
if ( eType != pAlreadyServed->m_eType )
{
if ( !g_bSeamlessRotate && ServedDesc_t::IsLocal ( pAlreadyServed ) && ( eType == IndexType_e::RT || eType == IndexType_e::PERCOLATE || eType == IndexType_e::PLAIN ) )
{
sphWarning ( "table '%s': changing table role plain<>rt<>percolate is possible only with seamless rotation - skip", sIndex.cstr() );
return;
}
return LoadNewLocalFromConfig ( sIndex, hIndex );
}
// reload/reconfigure already existing local index of the same type
bool bPathChanged =
pAlreadyServed->m_eType != IndexType_e::TEMPLATE
&& hIndex.Exists ( "path" )
&& hIndex["path"].strval() != pAlreadyServed->m_sIndexPath;
if ( bPathChanged )
return LoadNewLocalFromConfig ( sIndex, hIndex );
ServedDesc_t tNewDesc;
ConfigureLocalIndex ( &tNewDesc, hIndex, false, nullptr );
bool bReconfigured =
tNewDesc.m_tSettings.m_iExpandKeywords != pAlreadyServed->m_tSettings.m_iExpandKeywords
|| tNewDesc.m_tSettings.m_tFileAccess != pAlreadyServed->m_tSettings.m_tFileAccess
|| tNewDesc.m_tSettings.m_bPreopen != pAlreadyServed->m_tSettings.m_bPreopen
|| tNewDesc.m_sGlobalIDFPath != pAlreadyServed->m_sGlobalIDFPath;
if ( bReconfigured )
return ReconfigureIndex ( sIndex, hIndex );
if ( pAlreadyServed->m_eType == IndexType_e::PLAIN )
PreparePlainRotationIfNeed ( sIndex, pAlreadyServed );
else
KeepExisting ( sIndex );
}
public:
explicit Impl_c ( HashOfServed_c& hDeferred )
: m_hLocalSnapshot { g_pLocalIndexes->GetSnapshot() }
, m_hDistrSnapshot { g_pDistIndexes->GetSnapshot() }
, m_hNewLocalIndexes { *g_pLocalIndexes }
, m_hNewDistrIndexes { *g_pDistIndexes }
, m_hDeferred ( hDeferred )
{
m_hNewLocalIndexes.InitEmptyHash();
m_hNewDistrIndexes.InitEmptyHash();
}
void LoadIndexFromConfig ( const CSphString& sIndex, IndexType_e eType, const CSphConfigSection& hIndex ) noexcept
{
sphLogDebug ( "Load from config table %s with type %s", sIndex.cstr(), szIndexType ( eType ) );
assert ( eType != IndexType_e::ERROR_ );
if ( m_hProcessed[sIndex] )
{
sphWarning ( "table '%s': duplicate name - NOT SERVING", sIndex.cstr() );
return;
}
if ( eType == IndexType_e::DISTR )
LoadDistrFromConfig ( sIndex, hIndex );
else
LoadLocalFromConfig ( sIndex, eType, hIndex );
m_hProcessed.Add ( sIndex );
}
void IssuePlainOldRotation() noexcept
{
m_hNewLocalIndexes.CopyOwnerHash();
m_hNewDistrIndexes.CopyOwnerHash();
for ( auto& tServed : *m_hLocalSnapshot.first )
{
cServedIndexRefPtr_c pAlreadyServed = tServed.second;
assert ( pAlreadyServed );
if ( pAlreadyServed->m_eType == IndexType_e::PLAIN )
PreparePlainRotationIfNeed ( tServed.first, pAlreadyServed );
}
}
};
/// public iface
ConfigReloader_c::ConfigReloader_c ( HashOfServed_c& hDeferred )
: m_pImpl { std::make_unique<ConfigReloader_c::Impl_c> ( hDeferred ) }
{}
ConfigReloader_c::~ConfigReloader_c() = default;
void ConfigReloader_c::LoadIndexFromConfig ( const CSphString& sIndex, IndexType_e eType, const CSphConfigSection& hIndex ) noexcept
{
m_pImpl->LoadIndexFromConfig ( sIndex, eType, hIndex );
}
void ConfigReloader_c::IssuePlainOldRotation() noexcept
{
m_pImpl->IssuePlainOldRotation();
}
| 9,635
|
C++
|
.cpp
| 228
| 39.416667
| 229
| 0.732231
|
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
|
16,808
|
queryfilter.cpp
|
manticoresoftware_manticoresearch/src/queryfilter.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 "queryfilter.h"
#include "sphinxsearch.h"
void ISphQueryFilter::GetKeywords ( CSphVector<CSphKeywordInfo> & dKeywords, ExpansionContext_t & tCtx )
{
assert ( m_pTokenizer && m_pDict && m_pSettings );
BYTE sDstWord[3 * SPH_MAX_WORD_LEN + 4];
BYTE sTokenized[3 * SPH_MAX_WORD_LEN + 4];
BYTE* sWord;
int iQpos = 1;
int iExactQpos = -1;
CSphVector<int> dQposWildcards;
// FIXME!!! got rid of duplicated term stat and qword setup
while ( ( sWord = m_pTokenizer->GetToken() ) != NULL )
{
if ( tCtx.m_iCutoff!=-1 && dKeywords.GetLength()>=tCtx.m_iCutoff )
{
dKeywords.Add(); // fake keyword to let code know we're past cutoff
return;
}
if ( m_pTokenizer->WasTokenSpecial() )
{
if ( sWord[0]=='=' )
iExactQpos = iQpos;
continue;
}
if ( iExactQpos==iQpos )
{
snprintf ( (char *)sDstWord, sizeof(sDstWord)-1, "=%s", sWord );
sWord = sDstWord;
}
const BYTE* sMultiform = m_pTokenizer->GetTokenizedMultiform();
strncpy ( (char*)sTokenized, sMultiform ? (const char*)sMultiform : (const char*)sWord, sizeof ( sTokenized ) - 1 );
if ( tCtx.m_bAllowExpansion && ( !m_tFoldSettings.m_bFoldWildcards || m_tFoldSettings.m_bStats ) && sphHasExpandableWildcards ( (const char*)sWord ) )
{
dQposWildcards.Add ( iQpos );
ISphWordlist::Args_t tWordlist ( false, tCtx );
bool bExpanded = sphExpandGetWords ( (const char*)sWord, tCtx, tWordlist );
tCtx.m_bHasWildcards |= bExpanded;
int iDocs = 0;
int iHits = 0;
// might fold wildcards but still want to sum up stats
if ( m_tFoldSettings.m_bFoldWildcards && m_tFoldSettings.m_bStats )
{
ARRAY_FOREACH ( i, tWordlist.m_dExpanded )
{
iDocs += tWordlist.m_dExpanded[i].m_iDocs;
iHits += tWordlist.m_dExpanded[i].m_iHits;
}
bExpanded = false;
} else
{
ARRAY_FOREACH ( i, tWordlist.m_dExpanded )
{
CSphKeywordInfo& tInfo = dKeywords.Add();
tInfo.m_sTokenized = (const char*)sWord;
tInfo.m_sNormalized = tWordlist.GetWordExpanded ( i );
tInfo.m_iDocs = tWordlist.m_dExpanded[i].m_iDocs;
tInfo.m_iHits = tWordlist.m_dExpanded[i].m_iHits;
tInfo.m_iQpos = iQpos;
RemoveDictSpecials ( tInfo.m_sNormalized, ( m_pSettings->m_eBigramIndex!=SPH_BIGRAM_NONE ) );
}
}
if ( !bExpanded || !tWordlist.m_dExpanded.GetLength() )
{
CSphKeywordInfo& tInfo = dKeywords.Add();
tInfo.m_sTokenized = (const char*)sWord;
tInfo.m_sNormalized = (const char*)sWord;
tInfo.m_iDocs = iDocs;
tInfo.m_iHits = iHits;
tInfo.m_iQpos = iQpos;
}
} else
{
AddKeywordStats ( sWord, sTokenized, iQpos, dKeywords );
}
// FIXME!!! handle consecutive blended wo blended parts
bool bBlended = m_pTokenizer->TokenIsBlended();
if ( bBlended )
{
if ( m_tFoldSettings.m_bFoldBlended )
iQpos += m_pTokenizer->SkipBlended();
} else
{
iQpos++;
}
}
if ( !m_pSettings->m_uAotFilterMask )
return;
XQLimitSpec_t tSpec;
BYTE sTmp[3 * SPH_MAX_WORD_LEN + 4];
BYTE sTmp2[3 * SPH_MAX_WORD_LEN + 4];
CSphVector<XQNode_t*> dChildren ( 64 );
CSphBitvec tSkipTransform;
if ( dQposWildcards.GetLength() )
{
tSkipTransform.Init ( iQpos + 1 );
ARRAY_FOREACH ( i, dQposWildcards )
tSkipTransform.BitSet ( dQposWildcards[i] );
}
int iTokenizedTotal = dKeywords.GetLength();
for ( int iTokenized = 0; iTokenized < iTokenizedTotal; iTokenized++ )
{
int iKeywordQpos = dKeywords[iTokenized].m_iQpos;
// do not transform expanded wild-cards
if ( tSkipTransform.BitGetOr ( iKeywordQpos ) )
continue;
// MUST copy as Dict::GetWordID changes word and might add symbols
strncpy ( (char*)sTokenized, dKeywords[iTokenized].m_sNormalized.scstr(), sizeof ( sTokenized ) - 1 );
int iPreAotCount = dKeywords.GetLength();
XQNode_t tAotNode ( tSpec );
tAotNode.m_dWords.Resize ( 1 );
tAotNode.m_dWords.Begin()->m_sWord = (char*)sTokenized;
TransformAotFilter ( &tAotNode, m_pDict->GetWordforms(), *m_pSettings );
dChildren.Resize ( 0 );
dChildren.Add ( &tAotNode );
// recursion unfolded
ARRAY_FOREACH ( iChild, dChildren )
{
// process all words at node
ARRAY_FOREACH ( iAotKeyword, dChildren[iChild]->m_dWords )
{
// MUST copy as Dict::GetWordID changes word and might add symbols
strncpy ( (char*)sTmp, dChildren[iChild]->m_dWords[iAotKeyword].m_sWord.scstr(), sizeof ( sTmp ) - 1 );
// prevent use-after-free-bug due to vector grow: AddKeywordsStats() calls dKeywords.Add()
strncpy ( (char*)sTmp2, dKeywords[iTokenized].m_sTokenized.scstr(), sizeof ( sTmp2 ) - 1 );
AddKeywordStats ( sTmp, sTmp2, iKeywordQpos, dKeywords );
}
// push all child nodes at node to process list
const XQNode_t* pChild = dChildren[iChild];
ARRAY_FOREACH ( iRec, pChild->m_dChildren )
dChildren.Add ( pChild->m_dChildren[iRec] );
}
bool bGotLemmas = ( iPreAotCount != dKeywords.GetLength() );
// remove (replace) original word in case of AOT taken place
if ( bGotLemmas )
{
if ( !m_tFoldSettings.m_bFoldLemmas )
{
::Swap ( dKeywords[iTokenized], dKeywords.Last() );
dKeywords.Resize ( dKeywords.GetLength() - 1 );
} else
{
int iKeywordWithMaxHits = iPreAotCount;
for ( int i = iPreAotCount + 1; i < dKeywords.GetLength(); i++ )
if ( dKeywords[i].m_iHits > dKeywords[iKeywordWithMaxHits].m_iHits )
iKeywordWithMaxHits = i;
CSphString sNormalizedWithMaxHits = dKeywords[iKeywordWithMaxHits].m_sNormalized;
int iDocs = 0;
int iHits = 0;
if ( m_tFoldSettings.m_bStats )
{
for ( int i = iPreAotCount; i < dKeywords.GetLength(); i++ )
{
iDocs += dKeywords[i].m_iDocs;
iHits += dKeywords[i].m_iHits;
}
}
::Swap ( dKeywords[iTokenized], dKeywords[iPreAotCount] );
dKeywords.Resize ( iPreAotCount );
dKeywords[iTokenized].m_iDocs = iDocs;
dKeywords[iTokenized].m_iHits = iHits;
dKeywords[iTokenized].m_sNormalized = sNormalizedWithMaxHits;
RemoveDictSpecials ( dKeywords[iTokenized].m_sNormalized, ( m_pSettings->m_eBigramIndex!=SPH_BIGRAM_NONE ) );
}
}
}
// sort by qpos
if ( dKeywords.GetLength() != iTokenizedTotal )
sphSort ( dKeywords.Begin(), dKeywords.GetLength(), bind ( &CSphKeywordInfo::m_iQpos ) );
}
void CSphTemplateQueryFilter::AddKeywordStats ( BYTE* sWord, const BYTE* sTokenized, int iQpos, CSphVector<CSphKeywordInfo>& dKeywords )
{
SphWordID_t iWord = m_pDict->GetWordID ( sWord );
if ( !iWord )
return;
CSphKeywordInfo& tInfo = dKeywords.Add();
tInfo.m_sTokenized = (const char*)sTokenized;
tInfo.m_sNormalized = (const char*)sWord;
tInfo.m_iDocs = 0;
tInfo.m_iHits = 0;
tInfo.m_iQpos = iQpos;
RemoveDictSpecials ( tInfo.m_sNormalized, ( m_pSettings->m_eBigramIndex!=SPH_BIGRAM_NONE ) );
}
void CSphPlainQueryFilter::AddKeywordStats ( BYTE * sWord, const BYTE * sTokenized, int iQpos, CSphVector <CSphKeywordInfo> & dKeywords )
{
assert ( !m_tFoldSettings.m_bStats || ( m_pTermSetup && m_pQueryWord ) );
SphWordID_t iWord = m_pDict->GetWordID ( sWord );
if ( !iWord )
return;
if ( m_tFoldSettings.m_bStats )
{
m_pQueryWord->Reset ();
m_pQueryWord->m_sWord = (const char*)sWord;
m_pQueryWord->m_sDictWord = (const char*)sWord;
m_pQueryWord->m_uWordID = iWord;
m_pTermSetup->QwordSetup ( m_pQueryWord );
}
CSphKeywordInfo & tInfo = dKeywords.Add();
tInfo.m_sTokenized = (const char *)sTokenized;
tInfo.m_sNormalized = (const char*)sWord;
tInfo.m_iDocs = m_tFoldSettings.m_bStats ? m_pQueryWord->m_iDocs : 0;
tInfo.m_iHits = m_tFoldSettings.m_bStats ? m_pQueryWord->m_iHits : 0;
tInfo.m_iQpos = iQpos;
RemoveDictSpecials ( tInfo.m_sNormalized, ( m_pSettings->m_eBigramIndex!=SPH_BIGRAM_NONE ) );
}
void UniqKeywords ( CSphVector<CSphKeywordInfo> & dSrc )
{
CSphOrderedHash < CSphKeywordInfo, uint64_t, IdentityHash_fn, 256 > hWords;
ARRAY_FOREACH ( i, dSrc )
{
const CSphKeywordInfo & tInfo = dSrc[i];
uint64_t uKey = sphFNV64 ( &tInfo.m_iQpos, sizeof(tInfo.m_iQpos) );
uKey = sphFNV64 ( tInfo.m_sNormalized.cstr(), tInfo.m_sNormalized.Length(), uKey );
CSphKeywordInfo & tVal = hWords.AddUnique ( uKey );
if ( !tVal.m_iQpos )
{
tVal = tInfo;
} else
{
tVal.m_iDocs += tInfo.m_iDocs;
tVal.m_iHits += tInfo.m_iHits;
}
}
dSrc.Resize ( 0 );
for ( const auto& tWord : hWords )
dSrc.Add ( tWord.second );
sphSort ( dSrc.Begin(), dSrc.GetLength(), KeywordSorter_fn() );
}
| 8,860
|
C++
|
.cpp
| 239
| 33.631799
| 152
| 0.694334
|
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
|
16,809
|
sphinxfilter.cpp
|
manticoresoftware_manticoresearch/src/sphinxfilter.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 "sphinxfilter.h"
#include "columnarfilter.h"
#include "sphinxint.h"
#include "sphinxjson.h"
#include "attribute.h"
#include "histogram.h"
#include "coroutine.h"
#include "stackmock.h"
#include "conversion.h"
#include "geodist.h"
#include "joinsorter.h"
#include "secondaryindex.h"
#include "jsonsi.h"
#include <boost/icl/interval.hpp>
#if _WIN32
#pragma warning(disable:4250) // inheritance via dominance is our intent
#endif
/// attribute-based
struct IFilter_Attr: virtual ISphFilter
{
CSphAttrLocator m_tLocator;
void SetLocator ( const CSphAttrLocator & tLocator ) override
{
m_tLocator = tLocator;
}
};
/// values
struct IFilter_Values : virtual ISphFilter
{
VecTraits_T<SphAttr_t> m_tValues;
void SetValues ( const VecTraits_T<SphAttr_t>& tValues ) final
{
assert ( !tValues.IsEmpty() );
#ifndef NDEBUG // values must be sorted
for ( int i = 1; i < tValues.GetLength(); ++i )
assert ( tValues[i - 1] <= tValues[i] );
#endif
m_tValues = tValues;
}
inline SphAttr_t GetValue ( int iIndex ) const
{
return m_tValues[iIndex];
}
inline bool EvalValues ( SphAttr_t uValue ) const;
inline bool EvalBlockValues ( SphAttr_t uBlockMin, SphAttr_t uBlockMax ) const;
};
bool IFilter_Values::EvalValues ( SphAttr_t uValue ) const
{
if ( m_tValues.IsEmpty() )
return true;
const SphAttr_t * pA = m_tValues.Begin();
const SphAttr_t * pB = &m_tValues.Last();
if ( uValue==*pA || uValue==*pB ) return true;
if ( uValue<(*pA) || uValue>(*pB) ) return false;
while ( pB-pA>1 )
{
const SphAttr_t * pM = pA + ((pB-pA)/2);
if ( uValue==(*pM) )
return true;
if ( uValue<(*pM) )
pB = pM;
else
pA = pM;
}
return false;
}
// OPTIMIZE: use binary search
bool IFilter_Values::EvalBlockValues ( SphAttr_t uBlockMin, SphAttr_t uBlockMax ) const
{
return !!m_tValues.BinarySearch ( [uBlockMin, uBlockMax] ( auto i ) { return ( i < uBlockMin ) ? -1 : ( i > uBlockMax ) ? 1 : 0; }, 0 );
}
/// range
struct IFilter_Range: virtual ISphFilter
{
SphAttr_t m_iMinValue;
SphAttr_t m_iMaxValue;
void SetRange ( SphAttr_t tMin, SphAttr_t tMax ) override
{
m_iMinValue = tMin;
m_iMaxValue = tMax;
}
};
/// filters
// attr
class Filter_Values : public IFilter_Attr, public IFilter_Values
{
public:
bool Eval ( const CSphMatch & tMatch ) const final
{
return EvalValues ( tMatch.GetAttr ( m_tLocator ) );
}
bool EvalBlock ( const DWORD * pMinDocinfo, const DWORD * pMaxDocinfo ) const final
{
if ( m_tLocator.m_bDynamic )
return true; // ignore computed attributes
SphAttr_t uBlockMin = sphGetRowAttr ( pMinDocinfo, m_tLocator );
SphAttr_t uBlockMax = sphGetRowAttr ( pMaxDocinfo, m_tLocator );
return EvalBlockValues ( uBlockMin, uBlockMax );
}
};
class Filter_SingleValue : public IFilter_Attr
{
public:
void SetValues ( const VecTraits_T<SphAttr_t>& tValues ) final
{
assert ( tValues.GetLength()==1 );
m_RefValue = tValues[0];
}
bool Eval ( const CSphMatch & tMatch ) const override
{
return tMatch.GetAttr ( m_tLocator )==m_RefValue;
}
bool EvalBlock ( const DWORD * pMinDocinfo, const DWORD * pMaxDocinfo ) const final
{
if ( m_tLocator.m_bDynamic )
return true; // ignore computed attributes
SphAttr_t uBlockMin = sphGetRowAttr ( pMinDocinfo, m_tLocator );
SphAttr_t uBlockMax = sphGetRowAttr ( pMaxDocinfo, m_tLocator );
return ( uBlockMin<=m_RefValue && m_RefValue<=uBlockMax );
}
protected:
SphAttr_t m_RefValue;
};
class Filter_SingleValueStatic32 : public Filter_SingleValue
{
public:
Filter_SingleValueStatic32() = default;
void SetLocator ( const CSphAttrLocator & tLoc ) final
{
assert ( tLoc.m_iBitCount==32 );
assert ( ( tLoc.m_iBitOffset % 32 )==0 );
assert ( !tLoc.m_bDynamic );
m_tLocator = tLoc;
m_iIndex = tLoc.m_iBitOffset / 32;
}
bool Eval ( const CSphMatch & tMatch ) const final
{
return tMatch.m_pStatic [ m_iIndex ]==m_RefValue;
}
private:
int m_iIndex;
};
template < bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX, bool OPEN_LEFT, bool OPEN_RIGHT >
struct Filter_Range : public IFilter_Attr, public IFilter_Range
{
bool Eval ( const CSphMatch & tMatch ) const final
{
return EvalRange<HAS_EQUAL_MIN,HAS_EQUAL_MAX,OPEN_LEFT,OPEN_RIGHT> ( tMatch.GetAttr ( m_tLocator ), m_iMinValue, m_iMaxValue );
}
bool EvalBlock ( const DWORD * pMinDocinfo, const DWORD * pMaxDocinfo ) const final
{
if ( m_tLocator.m_bDynamic )
return true; // ignore computed attributes
auto uBlockMin = sphGetRowAttr ( pMinDocinfo, m_tLocator );
auto uBlockMax = sphGetRowAttr ( pMaxDocinfo, m_tLocator );
// not-reject
return EvalBlockRangeAny<HAS_EQUAL_MIN,HAS_EQUAL_MAX,OPEN_LEFT,OPEN_RIGHT> ( uBlockMin, uBlockMax, m_iMinValue, m_iMaxValue );
}
};
// float
template < bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX >
struct Filter_FloatRange : public IFilter_Attr
{
float m_fMinValue;
float m_fMaxValue;
void SetRangeFloat ( float fMin, float fMax ) final
{
m_fMinValue = fMin;
m_fMaxValue = fMax;
}
bool Eval ( const CSphMatch & tMatch ) const final
{
return EvalRange<HAS_EQUAL_MIN,HAS_EQUAL_MAX> ( tMatch.GetAttrFloat ( m_tLocator ), m_fMinValue, m_fMaxValue );
}
bool EvalBlock ( const DWORD * pMinDocinfo, const DWORD * pMaxDocinfo ) const final
{
if ( m_tLocator.m_bDynamic )
return true; // ignore computed attributes
float fBlockMin = sphDW2F ( (DWORD)sphGetRowAttr ( pMinDocinfo, m_tLocator ) );
float fBlockMax = sphDW2F ( (DWORD)sphGetRowAttr ( pMaxDocinfo, m_tLocator ) );
// not-reject
return EvalBlockRangeAny<HAS_EQUAL_MIN,HAS_EQUAL_MAX> ( fBlockMin, fBlockMax, m_fMinValue, m_fMaxValue );
}
};
struct Filter_WeightValues: public IFilter_Values
{
bool Eval ( const CSphMatch & tMatch ) const final
{
return EvalValues ( tMatch.m_iWeight );
}
};
template < bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX >
struct Filter_WeightRange: public IFilter_Range
{
virtual bool IsEarly () { return false; }
bool Eval ( const CSphMatch & tMatch ) const final
{
return EvalRange<HAS_EQUAL_MIN, HAS_EQUAL_MAX> ( (SphAttr_t)tMatch.m_iWeight, m_iMinValue, m_iMaxValue );
}
};
RowIdBoundaries_t GetFilterRowIdBoundaries ( const CSphFilterSettings & tFilter, RowID_t tTotalDocs )
{
assert ( tFilter.m_eType==SPH_FILTER_RANGE );
assert ( tFilter.m_sAttrName=="@rowid" );
RowID_t tMin = tFilter.m_iMinValue;
RowID_t tMax = tFilter.m_iMaxValue;
double fDelta = (double)tTotalDocs / tMax;
RowID_t tMinRowID = RowID_t ( fDelta*tMin );
RowID_t tMaxRowID;
if ( tMin==tMax-1 )
tMaxRowID = tTotalDocs-1;
else
{
tMaxRowID = RowID_t ( fDelta*(tMin+1) );
if ( tMaxRowID>tMinRowID )
tMaxRowID--;
}
return { tMinRowID, tMaxRowID };
}
//////////////////////////////////////////////////////////////////////////
// MVA
//////////////////////////////////////////////////////////////////////////
class Filter_MVA_c: public virtual IFilter_Attr
{
public:
void SetBlobStorage ( const BYTE * pBlobPool ) override
{
m_pBlobPool = pBlobPool;
}
protected:
const BYTE * m_pBlobPool {nullptr};
};
template < typename T >
class Filter_MVAValues_Any_c : public Filter_MVA_c, public IFilter_Values
{
public:
bool Eval ( const CSphMatch & tMatch ) const final
{
auto dMva = tMatch.FetchAttrData ( m_tLocator, m_pBlobPool );
return MvaEval_Any<T> ( dMva, m_tValues );
}
};
template < typename T >
class Filter_MVAValues_All_c : public Filter_MVA_c, IFilter_Values
{
public:
bool Eval ( const CSphMatch & tMatch ) const final
{
auto dMva = tMatch.FetchAttrData ( m_tLocator, m_pBlobPool );
return MvaEval_All<T> ( dMva, m_tValues );
}
};
template < typename T, bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX >
class Filter_MVARange_Any_c : public Filter_MVA_c, IFilter_Range
{
public:
bool Eval ( const CSphMatch & tMatch ) const final
{
auto dMva = tMatch.FetchAttrData ( m_tLocator, m_pBlobPool );
return MvaEval_RangeAny<T, HAS_EQUAL_MIN, HAS_EQUAL_MAX> ( (const T*)dMva.first, dMva.second/sizeof(T),
m_iMinValue, m_iMaxValue );
}
};
template < typename T, bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX >
class Filter_MVARange_All_c : public Filter_MVA_c, IFilter_Range
{
public:
bool Eval ( const CSphMatch & tMatch ) const final
{
auto dMva = tMatch.FetchAttrData ( m_tLocator, m_pBlobPool );
return MvaEval_RangeAll<T, HAS_EQUAL_MIN, HAS_EQUAL_MAX> ( (const T*)dMva.first, dMva.second/sizeof(T),
m_iMinValue, m_iMaxValue );
}
};
class IFilter_Str : public IFilter_Attr
{
protected:
const BYTE * m_pBlobPool = nullptr;
public:
void SetBlobStorage ( const BYTE * pBlobPool ) final
{
m_pBlobPool = pBlobPool;
}
};
class FilterString_c : public IFilter_Str
{
public:
FilterString_c ( ESphCollation eCollation, bool bExclude )
: m_fnStrCmp { GetStringCmpFunc ( eCollation ) }
, m_bExclude { bExclude }
{}
void SetRefString ( const CSphString * pRef, int iCount ) override
{
assert ( iCount<2 );
const char * sVal = pRef ? pRef->cstr() : nullptr;
int iLen = pRef ? pRef->Length() : 0;
m_dVal.Reset ( iLen );
memcpy ( m_dVal.Begin(), sVal, iLen );
}
bool Eval ( const CSphMatch & tMatch ) const override
{
auto dStr = tMatch.FetchAttrData ( m_tLocator, m_pBlobPool );
bool bNeq = m_fnStrCmp ( dStr, m_dVal, false )!=0;
return m_bExclude == bNeq;
}
bool CanExclude() const override { return true; }
protected:
CSphFixedVector<BYTE> m_dVal { 0 };
SphStringCmp_fn m_fnStrCmp;
bool m_bExclude;
};
class FilterStringCmp_c : public FilterString_c
{
public:
FilterStringCmp_c ( ESphCollation eCollation, bool bExclude, EStrCmpDir eStrCmpDir )
: FilterString_c ( eCollation, bExclude )
, m_eStrCmpDir ( eStrCmpDir )
{}
bool Eval ( const CSphMatch & tMatch ) const override
{
auto dStr = tMatch.FetchAttrData ( m_tLocator, m_pBlobPool );
int iCmpResult = m_fnStrCmp ( dStr, m_dVal, false );
switch ( m_eStrCmpDir )
{
case EStrCmpDir::LT: return m_bExclude ? iCmpResult>=0 : iCmpResult<0;
case EStrCmpDir::GT: return m_bExclude ? iCmpResult<=0 : iCmpResult>0;
case EStrCmpDir::EQ:
default:
assert (false && "unexpected: EStrCmpDir::EQ should not be here!");
return false;
}
}
private:
EStrCmpDir m_eStrCmpDir;
};
static void CollectStrings ( const CSphString * pRef, int iCount, StrVec_t & dVals )
{
dVals.Resize ( iCount );
for ( int i=0; i<iCount; ++i )
dVals[i] = *( pRef + i );
}
class Filter_StringValues_c : public IFilter_Str
{
public:
Filter_StringValues_c ( ESphCollation eCollation )
: m_fnStrCmp ( GetStringCmpFunc ( eCollation ) )
{}
void SetRefString ( const CSphString * pRef, int iCount ) final
{
assert ( pRef );
assert ( iCount>0 );
CollectStrings ( pRef, iCount, m_dValues );
}
bool Eval ( const CSphMatch & tMatch ) const final
{
ByteBlob_t sRef = tMatch.FetchAttrData ( m_tLocator, m_pBlobPool );
return m_dValues.any_of( [this, &sRef] ( const CSphString & sVal )
{
return m_fnStrCmp ( sRef, ByteBlob_t ( sVal ), false )==0;
});
}
private:
SphStringCmp_fn m_fnStrCmp;
StrVec_t m_dValues;
};
struct Filter_StringTags_c : IFilter_Str
{
protected:
CSphVector<uint64_t> m_dTags;
mutable CSphVector<uint64_t> m_dMatchTags;
public:
void SetRefString ( const CSphString * pRef, int iCount ) final
{
assert ( pRef );
assert ( iCount>0 );
m_dTags.Resize ( iCount );
for ( int i = 0; i<iCount; ++i )
m_dTags[i] = sphFNV64 ( pRef[i].cstr () );
m_dTags.Uniq ();
}
protected:
inline void GetMatchTags ( const CSphMatch &tMatch ) const
{
auto dStr = tMatch.FetchAttrData ( m_tLocator, m_pBlobPool );
m_dMatchTags.Resize ( 0 );
sphSplitApply ( ( const char * ) dStr.first, dStr.second, [this] ( const char * pTag, int iLen ) {
m_dMatchTags.Add ( sphFNV64 ( pTag, iLen, SPH_FNV64_SEED ) );
} );
m_dMatchTags.Uniq ();
}
};
struct Filter_StringTagsAny_c : Filter_StringTags_c
{
public:
bool Eval ( const CSphMatch &tMatch ) const final
{
GetMatchTags ( tMatch );
auto pFilter = m_dMatchTags.begin ();
auto pQueryTags = m_dTags.begin ();
auto pFilterEnd = m_dMatchTags.end ();
auto pTagsEnd = m_dTags.end ();
while ( pFilter<pFilterEnd && pQueryTags<pTagsEnd )
{
if ( *pQueryTags<*pFilter )
++pQueryTags;
else if ( *pFilter<*pQueryTags )
++pFilter;
else if ( *pQueryTags==*pFilter )
return true;
}
return false;
}
};
struct Filter_StringTagsAll_c : Filter_StringTags_c
{
public:
bool Eval ( const CSphMatch &tMatch ) const final
{
GetMatchTags ( tMatch );
auto pFilter = m_dMatchTags.begin ();
auto pQueryTags = m_dTags.begin ();
auto pFilterEnd = m_dMatchTags.end ();
auto pTagsEnd = m_dTags.end ();
int iExpectedTags = m_dTags.GetLength();
while ( pFilter<pFilterEnd && pQueryTags<pTagsEnd && iExpectedTags>0 )
{
if ( *pQueryTags<*pFilter )
++pQueryTags;
else if ( *pFilter<*pQueryTags )
++pFilter;
else if ( *pQueryTags==*pFilter )
{
--iExpectedTags;
++pQueryTags;
++pFilter;
}
}
return !iExpectedTags;
}
};
struct Filter_And2 final : public ISphFilter
{
std::unique_ptr<ISphFilter> m_pArg1;
std::unique_ptr<ISphFilter> m_pArg2;
explicit Filter_And2 ( std::unique_ptr<ISphFilter> pArg1, std::unique_ptr<ISphFilter> pArg2 )
: m_pArg1 ( std::move ( pArg1 ) )
, m_pArg2 ( std::move ( pArg2 ) )
{}
bool Eval ( const CSphMatch & tMatch ) const final
{
return m_pArg1->Eval ( tMatch ) && m_pArg2->Eval ( tMatch );
}
bool EvalBlock ( const DWORD * pMin, const DWORD * pMax ) const final
{
return m_pArg1->EvalBlock ( pMin, pMax ) && m_pArg2->EvalBlock ( pMin, pMax );
}
bool Test ( const columnar::MinMaxVec_t & dMinMax ) const final
{
return m_pArg1->Test(dMinMax) && m_pArg2->Test(dMinMax);
}
void SetColumnar ( const columnar::Columnar_i * pColumnar ) final
{
m_pArg1->SetColumnar(pColumnar);
m_pArg2->SetColumnar(pColumnar);
}
std::unique_ptr<ISphFilter> Join ( std::unique_ptr<ISphFilter> pFilter ) final
{
m_pArg2 = std::make_unique<Filter_And2> ( std::move ( m_pArg2 ), std::move ( pFilter ) );
return std::unique_ptr<ISphFilter>(this);
}
void SetBlobStorage ( const BYTE * pBlobPool ) final
{
m_pArg1->SetBlobStorage ( pBlobPool );
m_pArg2->SetBlobStorage ( pBlobPool );
}
};
struct Filter_And3 final : public ISphFilter
{
std::unique_ptr<ISphFilter> m_pArg1;
std::unique_ptr<ISphFilter> m_pArg2;
std::unique_ptr<ISphFilter> m_pArg3;
explicit Filter_And3 ( std::unique_ptr<ISphFilter> pArg1, std::unique_ptr<ISphFilter> pArg2, std::unique_ptr<ISphFilter> pArg3 )
: m_pArg1 ( std::move ( pArg1 ) )
, m_pArg2 ( std::move ( pArg2 ) )
, m_pArg3 ( std::move ( pArg3 ) )
{}
bool Eval ( const CSphMatch & tMatch ) const final
{
return m_pArg1->Eval ( tMatch ) && m_pArg2->Eval ( tMatch ) && m_pArg3->Eval ( tMatch );
}
bool EvalBlock ( const DWORD * pMin, const DWORD * pMax ) const final
{
return m_pArg1->EvalBlock ( pMin, pMax ) && m_pArg2->EvalBlock ( pMin, pMax ) && m_pArg3->EvalBlock ( pMin, pMax );
}
bool Test ( const columnar::MinMaxVec_t & dMinMax ) const final
{
return m_pArg1->Test(dMinMax) && m_pArg2->Test(dMinMax) && m_pArg3->Test(dMinMax);
}
void SetColumnar ( const columnar::Columnar_i * pColumnar ) final
{
m_pArg1->SetColumnar(pColumnar);
m_pArg2->SetColumnar(pColumnar);
m_pArg3->SetColumnar(pColumnar);
}
std::unique_ptr<ISphFilter> Join ( std::unique_ptr<ISphFilter> pFilter ) final
{
m_pArg3 = std::make_unique<Filter_And2> ( std::move ( m_pArg3 ), std::move ( pFilter ) );
return std::unique_ptr<ISphFilter>(this);
}
void SetBlobStorage ( const BYTE * pBlobPool ) final
{
m_pArg1->SetBlobStorage ( pBlobPool );
m_pArg2->SetBlobStorage ( pBlobPool );
m_pArg3->SetBlobStorage ( pBlobPool );
}
};
struct Filter_And final : public ISphFilter
{
CSphVector<std::unique_ptr<ISphFilter>> m_dFilters;
void Add ( std::unique_ptr<ISphFilter> pFilter )
{
m_dFilters.Add ( std::move ( pFilter ) );
}
bool Eval ( const CSphMatch & tMatch ) const final
{
for ( auto& pFilter: m_dFilters )
if ( !pFilter->Eval ( tMatch ) )
return false;
return true;
}
bool EvalBlock ( const DWORD * pMinDocinfo, const DWORD * pMaxDocinfo ) const final
{
for ( auto& pFilter : m_dFilters )
if ( !pFilter->EvalBlock ( pMinDocinfo, pMaxDocinfo ) )
return false;
return true;
}
bool Test ( const columnar::MinMaxVec_t & dMinMax ) const final { return m_dFilters.all_of ( [&dMinMax]( auto& pFilter ){ return pFilter->Test(dMinMax); } ); }
void SetColumnar ( const columnar::Columnar_i * pColumnar ) final { m_dFilters.for_each ( [pColumnar]( auto& pFilter ){ pFilter->SetColumnar(pColumnar); } ); }
std::unique_ptr<ISphFilter> Join ( std::unique_ptr<ISphFilter> pFilter ) final
{
Add ( std::move (pFilter) );
return std::unique_ptr<ISphFilter>(this);
}
void SetBlobStorage ( const BYTE * pBlobPool ) final
{
for ( auto &pFilter : m_dFilters )
pFilter->SetBlobStorage ( pBlobPool );
}
std::unique_ptr<ISphFilter> Optimize() final
{
if ( m_dFilters.GetLength()==2 )
{
auto pOpt = std::make_unique<Filter_And2> ( std::move ( m_dFilters[0] ), std::move ( m_dFilters[1] ) );
m_dFilters.Reset();
delete this;
return pOpt;
}
if ( m_dFilters.GetLength()==3 )
{
auto pOpt = std::make_unique<Filter_And3> ( std::move ( m_dFilters[0] ), std::move ( m_dFilters[1] ), std::move ( m_dFilters[2] ) );
m_dFilters.Reset();
delete this;
return pOpt;
}
return std::unique_ptr<ISphFilter>(this);
}
};
struct Filter_Or final : public ISphFilter
{
std::unique_ptr<ISphFilter> m_pLeft;
std::unique_ptr<ISphFilter> m_pRight;
Filter_Or ( std::unique_ptr<ISphFilter> pLeft, std::unique_ptr<ISphFilter> pRight )
: m_pLeft ( std::move ( pLeft ) )
, m_pRight ( std::move ( pRight ) )
{}
bool Eval ( const CSphMatch & tMatch ) const final
{
return ( m_pLeft->Eval ( tMatch ) || m_pRight->Eval ( tMatch ) );
}
bool EvalBlock ( const DWORD * pMinDocinfo, const DWORD * pMaxDocinfo ) const final
{
return ( m_pLeft->EvalBlock ( pMinDocinfo, pMaxDocinfo ) || m_pRight->EvalBlock ( pMinDocinfo, pMaxDocinfo ) );
}
bool Test ( const columnar::MinMaxVec_t & dMinMax ) const final
{
return ( m_pLeft->Test(dMinMax) || m_pRight->Test(dMinMax) );
}
void SetColumnar ( const columnar::Columnar_i * pColumnar ) final
{
m_pLeft->SetColumnar(pColumnar);
m_pRight->SetColumnar(pColumnar);
}
void SetBlobStorage ( const BYTE * pBlobPool ) final
{
m_pLeft->SetBlobStorage ( pBlobPool );
m_pRight->SetBlobStorage ( pBlobPool );
}
std::unique_ptr<ISphFilter> Optimize() final
{
m_pLeft->Optimize();
m_pRight->Optimize();
return std::unique_ptr<ISphFilter>(this);
}
};
// not
struct Filter_Not final : public ISphFilter
{
std::unique_ptr<ISphFilter> m_pFilter;
explicit Filter_Not ( std::unique_ptr<ISphFilter> pFilter )
: m_pFilter ( std::move ( pFilter ) )
{
assert ( m_pFilter );
}
bool Eval ( const CSphMatch & tMatch ) const final
{
return !m_pFilter->Eval ( tMatch );
}
bool EvalBlock ( const DWORD *, const DWORD * ) const final
{
// if block passes through the filter we can't just negate the
// result since it's imprecise at this point
return true;
}
void SetBlobStorage ( const BYTE * pBlobPool ) final
{
m_pFilter->SetBlobStorage ( pBlobPool );
}
void SetColumnar ( const columnar::Columnar_i * pColumnar ) final
{
m_pFilter->SetColumnar(pColumnar);
}
};
/// impl
std::unique_ptr<ISphFilter> ISphFilter::Join ( std::unique_ptr<ISphFilter> pFilter )
{
auto pAnd = std::make_unique<Filter_And>();
pAnd->Add ( std::unique_ptr<ISphFilter> ( this ) );
pAnd->Add ( std::move ( pFilter ) );
return pAnd;
}
/// helper functions
CSphString FilterType2Str ( ESphFilter eFilterType )
{
CSphString sFilterName;
switch ( eFilterType )
{
case SPH_FILTER_VALUES: sFilterName = "intvalues"; break;
case SPH_FILTER_RANGE: sFilterName = "intrange"; break;
case SPH_FILTER_FLOATRANGE: sFilterName = "floatrange"; break;
case SPH_FILTER_STRING: sFilterName = "string"; break;
case SPH_FILTER_STRING_LIST: sFilterName = "stringlist"; break;
case SPH_FILTER_NULL: sFilterName = "null"; break;
default: sFilterName.SetSprintf ( "(filter-type-%d)", eFilterType ); break;
}
return sFilterName;
}
static inline std::unique_ptr<ISphFilter> ReportError ( CSphString & sError, const char * sMessage, ESphFilter eFilterType )
{
sError.SetSprintf ( sMessage, FilterType2Str(eFilterType).cstr() );
return nullptr;
}
#define CREATE_RANGE_FILTER(FILTER,SETTINGS) \
{ \
if ( SETTINGS.m_bHasEqualMin ) \
{ \
if ( SETTINGS.m_bHasEqualMax ) \
return std::make_unique<FILTER<true,true>>(); \
else \
return std::make_unique<FILTER<true,false>>(); \
} else \
{ \
if ( SETTINGS.m_bHasEqualMax ) \
return std::make_unique<FILTER<false,true>>(); \
else \
return std::make_unique<FILTER<false,false>>(); \
} \
}
#define CREATE_RANGE_FILTER_WITH_OPEN(FILTER,SETTINGS) \
{ \
if ( SETTINGS.m_bOpenLeft ) \
{ \
if ( SETTINGS.m_bHasEqualMax ) \
return std::make_unique <FILTER<true,true,true,false>>(); \
else \
return std::make_unique <FILTER<true,false,true,false>>(); \
} else if ( SETTINGS.m_bOpenRight ) \
{ \
if ( SETTINGS.m_bHasEqualMin ) \
return std::make_unique <FILTER<true,true,false,true>>(); \
else \
return std::make_unique <FILTER<false,true,false,true>>(); \
} \
assert ( !SETTINGS.m_bOpenLeft && !SETTINGS.m_bOpenRight ); \
if ( SETTINGS.m_bHasEqualMin ) \
{ \
if ( SETTINGS.m_bHasEqualMax ) \
return std::make_unique <FILTER<true,true,false,false>>(); \
else \
return std::make_unique <FILTER<true,false,false,false>>(); \
} else \
{ \
if ( SETTINGS.m_bHasEqualMax ) \
return std::make_unique <FILTER<false,true,false,false>>(); \
else \
return std::make_unique <FILTER<false,false,false,false>>(); \
} \
}
#define CREATE_MVA_RANGE_FILTER(FILTER,T,SETTINGS) \
{ \
if ( SETTINGS.m_bHasEqualMin ) \
{ \
if ( SETTINGS.m_bHasEqualMax ) \
return std::make_unique<FILTER<T,true,true>>(); \
else \
return std::make_unique<FILTER<T,true,false>>(); \
} else \
{ \
if ( SETTINGS.m_bHasEqualMax ) \
return std::make_unique<FILTER<T,false,true>>(); \
else \
return std::make_unique<FILTER<T,false,false>>(); \
} \
}
#define CREATE_EXPR_RANGE_FILTER(FILTER,EXPR,bHasEqualMin,bHasEqualMax) \
{ \
if ( bHasEqualMin ) \
{ \
if ( bHasEqualMax ) \
return std::make_unique<FILTER<true,true>>(EXPR); \
else \
return std::make_unique<FILTER<true,false>>(EXPR); \
} else \
{ \
if ( bHasEqualMax ) \
return std::make_unique<FILTER<false,true>>(EXPR); \
else \
return std::make_unique<FILTER<false,false>>(EXPR); \
} \
}
static std::unique_ptr<ISphFilter> CreateSpecialFilter ( const CSphString & sName, const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx, CSphString & sError )
{
if ( sName=="@weight" )
{
switch ( tSettings.m_eType )
{
case SPH_FILTER_VALUES: return std::make_unique<Filter_WeightValues>();
case SPH_FILTER_RANGE: CREATE_RANGE_FILTER ( Filter_WeightRange, tSettings );
default:
return ReportError ( sError, "unsupported filter type '%s' on @weight", tSettings.m_eType );
}
}
return nullptr;
}
static std::unique_ptr<ISphFilter> CreateFilter ( const CSphFilterSettings & tSettings, ESphFilter eFilterType,ESphAttr eAttrType, const CSphAttrLocator & tLoc, ESphCollation eCollation, CSphString & sError, CSphString & sWarning )
{
if ( IsMvaAttr(eAttrType) )
{
if (!( eFilterType==SPH_FILTER_VALUES || eFilterType==SPH_FILTER_RANGE ))
return ReportError ( sError, "unsupported filter type '%s' on MVA column", eFilterType );
if ( tSettings.m_eMvaFunc==SPH_MVAFUNC_NONE )
sWarning.SetSprintf ( "use an explicit ANY()/ALL() around a filter on MVA column" );
bool bWide = eAttrType==SPH_ATTR_INT64SET || eAttrType==SPH_ATTR_INT64SET_PTR;
bool bRange = ( eFilterType==SPH_FILTER_RANGE );
bool bAll = ( tSettings.m_eMvaFunc==SPH_MVAFUNC_ALL );
int iIndex = bWide*4 + bRange*2 + bAll;
switch ( iIndex )
{
case 0: return std::make_unique<Filter_MVAValues_Any_c<DWORD>>();
case 1: return std::make_unique<Filter_MVAValues_All_c<DWORD>>();
case 2: CREATE_MVA_RANGE_FILTER ( Filter_MVARange_Any_c, DWORD, tSettings );
case 3: CREATE_MVA_RANGE_FILTER ( Filter_MVARange_All_c, DWORD, tSettings );
case 4: return std::make_unique<Filter_MVAValues_Any_c<int64_t>>();
case 5: return std::make_unique<Filter_MVAValues_All_c<int64_t>>();
case 6: CREATE_MVA_RANGE_FILTER ( Filter_MVARange_Any_c, int64_t, tSettings );
case 7: CREATE_MVA_RANGE_FILTER ( Filter_MVARange_All_c, int64_t, tSettings );
default:
assert (false && "UB in CreateFilter");
}
}
// float
if ( eAttrType==SPH_ATTR_FLOAT )
{
if ( eFilterType==SPH_FILTER_FLOATRANGE || eFilterType==SPH_FILTER_RANGE )
CREATE_RANGE_FILTER ( Filter_FloatRange, tSettings );
return ReportError ( sError, "unsupported filter type '%s' on float column", eFilterType );
}
if ( eAttrType==SPH_ATTR_STRING || eAttrType==SPH_ATTR_STRINGPTR )
{
if ( eFilterType==SPH_FILTER_STRING_LIST )
{
if ( tSettings.m_eMvaFunc==SPH_MVAFUNC_NONE )
return std::make_unique<Filter_StringValues_c> ( eCollation );
else if ( tSettings.m_eMvaFunc==SPH_MVAFUNC_ANY )
return std::make_unique<Filter_StringTagsAny_c>();
else if ( tSettings.m_eMvaFunc==SPH_MVAFUNC_ALL )
return std::make_unique<Filter_StringTagsAll_c>();
}
else if ( tSettings.m_eStrCmpDir==EStrCmpDir::EQ )
return std::make_unique<FilterString_c> ( eCollation, tSettings.m_bExclude );
else
return std::make_unique<FilterStringCmp_c> ( eCollation, tSettings.m_bExclude, tSettings.m_eStrCmpDir );
}
// non-float, non-MVA
switch ( eFilterType )
{
case SPH_FILTER_VALUES:
if ( tSettings.GetNumValues()==1 && ( eAttrType==SPH_ATTR_INTEGER || eAttrType==SPH_ATTR_BIGINT || eAttrType==SPH_ATTR_TOKENCOUNT ) )
{
if ( ( eAttrType==SPH_ATTR_INTEGER || eAttrType==SPH_ATTR_TOKENCOUNT ) && !tLoc.m_bDynamic && tLoc.m_iBitCount==32 && ( tLoc.m_iBitOffset % 32 )==0 )
return std::make_unique<Filter_SingleValueStatic32>();
else
return std::make_unique<Filter_SingleValue>();
} else
return std::make_unique<Filter_Values>();
case SPH_FILTER_RANGE: CREATE_RANGE_FILTER_WITH_OPEN ( Filter_Range, tSettings );
default: return ReportError ( sError, "unsupported filter type '%s' on int column", eFilterType );
}
}
//////////////////////////////////////////////////////////////////////////
// EXPRESSION STUFF
//////////////////////////////////////////////////////////////////////////
template<typename BASE>
class ExprFilter_c : public BASE
{
public:
explicit ExprFilter_c ( ISphExpr * pExpr )
: m_pExpr ( pExpr )
{
SafeAddRef ( pExpr );
}
void SetBlobStorage ( const BYTE * pBlobPool ) final
{
m_pBlobPool = pBlobPool;
if ( m_pExpr )
m_pExpr->Command ( SPH_EXPR_SET_BLOB_POOL, (void*)pBlobPool );
}
void SetColumnar ( const columnar::Columnar_i * pColumnar ) final
{
if ( !m_pExpr )
return;
m_pExpr->Command ( SPH_EXPR_SET_COLUMNAR, (void*)pColumnar );
}
protected:
const BYTE * m_pBlobPool {nullptr};
CSphRefcountedPtr<ISphExpr> m_pExpr;
};
template < bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX >
class ExprFilterFloatRange_c : public ExprFilter_c<IFilter_Range>
{
public:
explicit ExprFilterFloatRange_c ( ISphExpr * pExpr )
: ExprFilter_c<IFilter_Range> ( pExpr )
{}
float m_fMinValue = 0.0f;
float m_fMaxValue = 0.0f;
void SetRangeFloat ( float fMin, float fMax ) override
{
m_fMinValue = fMin;
m_fMaxValue = fMax;
}
bool Eval ( const CSphMatch & tMatch ) const final
{
return EvalRange<HAS_EQUAL_MIN, HAS_EQUAL_MAX,false,false,float> ( m_pExpr->Eval ( tMatch ), m_fMinValue, m_fMaxValue );
}
};
template < bool HAS_EQUAL_MIN, bool HAS_EQUAL_MAX >
class ExprFilterRange_c : public ExprFilter_c<IFilter_Range>
{
public:
explicit ExprFilterRange_c ( ISphExpr * pExpr )
: ExprFilter_c<IFilter_Range> ( pExpr )
{}
bool Eval ( const CSphMatch & tMatch ) const final
{
return EvalRange<HAS_EQUAL_MIN, HAS_EQUAL_MAX> ( m_pExpr->Int64Eval(tMatch), m_iMinValue, m_iMaxValue );
}
};
class ExprFilterValues_c : public ExprFilter_c<IFilter_Values>
{
public:
explicit ExprFilterValues_c ( ISphExpr * pExpr )
: ExprFilter_c<IFilter_Values> ( pExpr )
{}
bool Eval ( const CSphMatch & tMatch ) const final
{
assert ( this->m_pExpr );
return EvalValues ( m_pExpr->Int64Eval ( tMatch ) );
}
};
class ExprFilterString_c : public ExprFilter_c<ISphFilter>
{
protected:
CSphString m_sVal;
int m_iValLength = 0;
SphStringCmp_fn m_fnStrCmp;
bool m_bEq;
public:
explicit ExprFilterString_c ( ISphExpr * pExpr, ESphCollation eCollation, bool bEq )
: ExprFilter_c<ISphFilter> ( pExpr )
, m_fnStrCmp ( GetStringCmpFunc ( eCollation ) )
, m_bEq ( bEq )
{}
void SetRefString ( const CSphString * pRef, int iCount )
{
assert ( iCount<2 );
if ( pRef )
{
m_sVal = *pRef;
m_iValLength = m_sVal.Length();
}
}
bool Eval ( const CSphMatch & tMatch ) const
{
// attribute storages can fetch string length without reading the string itself
int iLen = m_pExpr->StringLenEval ( tMatch );
// StringLenEval returns -1 if not supported by expression
if ( iLen!=-1 && m_iValLength!=iLen )
return false;
const BYTE * pVal = nullptr;
iLen = m_pExpr->StringEval ( tMatch, &pVal );
bool bEq = m_fnStrCmp ( {pVal, iLen}, {(const BYTE *) m_sVal.cstr (), m_iValLength}, false )==0;
return ( m_bEq==bEq );
}
};
class ExprFilterStringValues_c : public ExprFilterString_c
{
private:
StrVec_t m_dValues;
public:
ExprFilterStringValues_c ( ISphExpr * pExpr, ESphCollation eCollation, bool bEq )
: ExprFilterString_c ( pExpr, eCollation, bEq )
{}
void SetRefString ( const CSphString * pRef, int iCount )
{
CollectStrings ( pRef, iCount, m_dValues );
}
bool Eval ( const CSphMatch & tMatch ) const
{
const BYTE * pVal = nullptr;
int iLen = m_pExpr->StringEval ( tMatch, &pVal );
ByteBlob_t sRef ( pVal, iLen );
return m_dValues.any_of( [this, &sRef] ( const CSphString & sVal )
{
bool bEq = m_fnStrCmp ( sRef, ByteBlob_t ( sVal ), false )==0;
return ( m_bEq==bEq );
});
}
};
class ExprFilterNull_c : public ExprFilter_c<ISphFilter>
{
public:
ExprFilterNull_c ( ISphExpr * pExpr, bool bEquals, bool bCheckOnlyKey )
: ExprFilter_c<ISphFilter> ( pExpr )
, m_bEquals ( bEquals )
, m_bCheckOnlyKey ( bCheckOnlyKey )
{}
void SetLocator ( const CSphAttrLocator & tLocator ) final
{
m_tLoc = tLocator;
}
ESphJsonType GetKey ( const CSphMatch & tMatch ) const
{
if ( !m_pExpr )
return JSON_EOF;
uint64_t uValue = m_pExpr->Int64Eval ( tMatch );
if ( uValue==0 ) // either no data or invalid path
return JSON_EOF;
return sphJsonUnpackType ( uValue );
}
bool Eval ( const CSphMatch & tMatch ) const final
{
if ( !m_pExpr ) // regular attribute? return true if blob size is null
{
int iLen = sphGetBlobAttrLen ( tMatch, m_tLoc, m_pBlobPool );
return m_bEquals ^ ( iLen!=0 );
}
// possibly json
ESphJsonType eRes = GetKey ( tMatch );
if ( m_bCheckOnlyKey )
return ( eRes!=JSON_EOF );
return m_bEquals ^ ( eRes!=JSON_EOF && eRes!=JSON_NULL );
}
protected:
CSphAttrLocator m_tLoc;
const bool m_bEquals;
const bool m_bCheckOnlyKey;
};
// TODO: implement expression -> filter tree optimization to extract filters from general expression and got rid of all filters wo block-level optimizer
// wrapper for whole expression that evaluates to 0 and 1 on filtering
class ExprFilterProxy_c : public ExprFilter_c<ISphFilter>
{
protected:
ESphAttr m_eAttrType = SPH_ATTR_NONE;
public:
ExprFilterProxy_c ( ISphExpr * pExpr, ESphAttr eAttrType )
: ExprFilter_c<ISphFilter> ( pExpr )
, m_eAttrType ( eAttrType )
{}
bool Eval ( const CSphMatch & tMatch ) const final
{
switch ( m_eAttrType )
{
case SPH_ATTR_INTEGER:
return ( m_pExpr->IntEval ( tMatch )>0 );
case SPH_ATTR_BIGINT:
case SPH_ATTR_JSON_FIELD:
return ( m_pExpr->Int64Eval ( tMatch )>0 );
case SPH_ATTR_INT64SET:
case SPH_ATTR_UINT32SET:
return ( m_pExpr->IntEval ( tMatch )>0 );
default:
return ( m_pExpr->Eval ( tMatch )>0.0f );
}
}
};
static std::unique_ptr<ISphFilter> SetupJsonExpr ( CSphRefcountedPtr<ISphExpr> & pExpr, const CSphFilterSettings & tSettings, const CommonFilterSettings_t & tFixedSettings, ESphCollation eCollation )
{
// auto-convert all JSON types except SPH_FILTER_NULL, it needs more info
bool bAutoConvert = false;
bool bJsonExpr = false;
if ( pExpr && tFixedSettings.m_eType!=SPH_FILTER_NULL )
bJsonExpr = pExpr->IsJson ( bAutoConvert );
if ( !bJsonExpr )
return nullptr;
if ( tFixedSettings.m_eType==SPH_FILTER_STRING_LIST || tFixedSettings.m_eType==SPH_FILTER_STRING )
return std::make_unique<ExprFilterProxy_c> ( ExprJsonIn ( tSettings.m_dStrings, pExpr, eCollation ), SPH_ATTR_INTEGER );
if ( tSettings.m_eMvaFunc==SPH_MVAFUNC_ANY )
{
switch ( tFixedSettings.m_eType )
{
case SPH_FILTER_VALUES:
return std::make_unique<ExprFilterProxy_c> ( ExprJsonIn ( tSettings.m_dValues, pExpr, eCollation ), SPH_ATTR_INTEGER );
case SPH_FILTER_RANGE:
case SPH_FILTER_FLOATRANGE:
return std::make_unique<ExprFilterProxy_c> ( ExprJsonRange ( tFixedSettings, pExpr ), SPH_ATTR_INTEGER );
default:
break;
}
}
if ( !bAutoConvert )
pExpr = sphJsonFieldConv(pExpr);
return nullptr;
}
static std::unique_ptr<ISphFilter> CreateFilterExpr ( ISphExpr * _pExpr, const CSphFilterSettings & tSettings, const CommonFilterSettings_t & tFixedSettings, CSphString & sError, ESphCollation eCollation, ESphAttr eAttrType )
{
CSphRefcountedPtr<ISphExpr> pExpr { _pExpr };
SafeAddRef ( _pExpr );
std::unique_ptr<ISphFilter> pRes = SetupJsonExpr ( pExpr, tSettings, tFixedSettings, eCollation );
if ( pRes )
return pRes;
switch ( tFixedSettings.m_eType )
{
case SPH_FILTER_VALUES: return std::make_unique<ExprFilterValues_c> ( pExpr );
case SPH_FILTER_FLOATRANGE: CREATE_EXPR_RANGE_FILTER ( ExprFilterFloatRange_c, pExpr, tSettings.m_bHasEqualMin, tSettings.m_bHasEqualMax );
case SPH_FILTER_RANGE: CREATE_EXPR_RANGE_FILTER ( ExprFilterRange_c, pExpr, tSettings.m_bHasEqualMin, tSettings.m_bHasEqualMax );
case SPH_FILTER_STRING: return std::make_unique<ExprFilterString_c> ( pExpr, eCollation, tSettings.m_bHasEqualMin || tSettings.m_bHasEqualMax );
case SPH_FILTER_STRING_LIST: return std::make_unique<ExprFilterStringValues_c> ( pExpr, eCollation, tSettings.m_bHasEqualMin || tSettings.m_bHasEqualMax );
case SPH_FILTER_NULL: return std::make_unique<ExprFilterNull_c> ( pExpr, tSettings.m_bIsNull, false );
case SPH_FILTER_EXPRESSION:
{
if ( eAttrType!=SPH_ATTR_INTEGER && eAttrType!=SPH_ATTR_BIGINT && eAttrType!=SPH_ATTR_JSON_FIELD && eAttrType!=SPH_ATTR_FLOAT
&& eAttrType!=SPH_ATTR_INT64SET && eAttrType!=SPH_ATTR_UINT32SET )
{
sError = "filter expression must evaluate to integer or float";
return nullptr;
} else
{
return std::make_unique<ExprFilterProxy_c> ( pExpr, eAttrType );
}
}
default:
sError = "this filter type on expressions is not implemented yet";
return nullptr;
}
}
static std::unique_ptr<ISphFilter> TryToCreateExpressionFilter ( CSphRefcountedPtr<ISphExpr> & pExpr, const CSphString & sAttrName, const ISphSchema & tSchema, const CSphFilterSettings & tSettings, const CommonFilterSettings_t & tFixedSettings, ExprParseArgs_t & tExprArgs, const CSphString * pJoinIdx, CSphString & sError )
{
pExpr = sphExprParse ( sAttrName.cstr(), tSchema, pJoinIdx, sError, tExprArgs );
if ( pExpr && pExpr->UsesDocstore() )
{
sError.SetSprintf ( "unsupported filter on field '%s' (filters are supported only on attributes, not stored fields)", sAttrName.cstr() );
pExpr = nullptr;
return nullptr;
}
if ( pExpr )
return CreateFilterExpr ( pExpr, tSettings, tFixedSettings, sError, tExprArgs.m_eCollation, *tExprArgs.m_pAttrType );
if ( sError.IsEmpty() )
sError.SetSprintf ( "no such filter attribute '%s'", sAttrName.cstr() );
return nullptr;
}
static void SetFilterLocator ( const std::unique_ptr<ISphFilter>& pFilter, const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx, const CSphString & sAttrName )
{
if ( !pFilter )
return;
assert ( tCtx.m_pMatchSchema );
const ISphSchema & tSchema = *tCtx.m_pMatchSchema;
int iAttr = ( tSettings.m_eType!=SPH_FILTER_EXPRESSION ? tSchema.GetAttrIndex ( sAttrName.cstr() ) : -1 );
if ( iAttr==-1 )
return;
const CSphColumnInfo & tAttr = tSchema.GetAttr(iAttr);
pFilter->SetLocator ( tAttr.m_tLocator );
}
static void SetFilterSettings ( const std::unique_ptr<ISphFilter>& pFilter, const CSphFilterSettings & tSettings, const CommonFilterSettings_t & tFixedSettings, const CreateFilterContext_t & tCtx )
{
if ( !pFilter )
return;
pFilter->SetBlobStorage ( tCtx.m_pBlobPool );
pFilter->SetColumnar ( tCtx.m_pColumnar );
pFilter->SetRange ( tSettings.m_iMinValue, tSettings.m_iMaxValue );
if ( tFixedSettings.m_eType==SPH_FILTER_FLOATRANGE )
pFilter->SetRangeFloat ( (float)tFixedSettings.m_fMinValue, (float)tFixedSettings.m_fMaxValue );
pFilter->SetRefString ( tSettings.m_dStrings.Begin(), tSettings.m_dStrings.GetLength() );
if ( tSettings.GetNumValues() > 0 )
{
pFilter->SetValues ( tSettings.GetValues() );
#ifndef NDEBUG
// check that the values are actually sorted
const auto& tValues = tSettings.GetValues();
for ( int i = 1; i < tValues.GetLength(); ++i )
assert ( tValues[i] >= tValues[i - 1] );
#endif
}
}
static void TryToCreateExcludeFilter ( std::unique_ptr<ISphFilter>& pFilter, const CSphFilterSettings & tSettings )
{
if ( !pFilter || pFilter->CanExclude() ) // some filters can handle exclude flag themselves
return;
if ( tSettings.m_bExclude )
pFilter = std::make_unique<Filter_Not> ( std::move ( pFilter ) );
}
static void TryToCreateJsonNullFilter ( std::unique_ptr<ISphFilter>& pFilter, const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx, ESphAttr eAttrType, ISphExpr * pExpr )
{
if ( !pFilter || !pExpr )
return;
// filter for json || json.field needs to check that key exists
if ( ( eAttrType==SPH_ATTR_JSON || eAttrType==SPH_ATTR_JSON_FIELD ) && tSettings.m_eType!=SPH_FILTER_NULL )
{
auto pNotNull = std::make_unique<ExprFilterNull_c> ( pExpr, false, true );
pNotNull->SetBlobStorage ( tCtx.m_pBlobPool );
pFilter = std::make_unique<Filter_And2> ( std::move ( pFilter ), std::move ( pNotNull ) );
}
}
static bool TryToCreateSpecialFilter ( std::unique_ptr<ISphFilter> & pFilter, const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx, bool bHaving, const CSphString & sAttrName, CSphString & sError )
{
assert ( !pFilter );
// try to create a filter on a special attribute
if ( sAttrName.Begins("@") && !bHaving && ( sAttrName=="@groupby" || sAttrName=="@count" || sAttrName=="@distinct" ) )
{
sError.SetSprintf ( "unsupported filter column '%s'", sAttrName.cstr() );
return false;
}
if ( sAttrName.Begins("@") )
{
pFilter = CreateSpecialFilter ( sAttrName, tSettings, tCtx, sError );
if ( !pFilter && !sError.IsEmpty() )
return false;
}
return true;
}
static bool CanSpawnColumnarFilter ( int iAttr, const ISphSchema & tSchema )
{
if ( iAttr<0 )
return false;
const CSphColumnInfo & tCol = tSchema.GetAttr(iAttr);
if ( tCol.IsColumnar() )
return true;
// spawn special filter even if we have an expression in the column
// because the filter is (usually) faster
if ( tCol.IsColumnarExpr() && tCol.m_eStage>SPH_EVAL_PREFILTER )
{
// columnar expression for aggregate should be filtered by plain filter
return ( tCol.m_eAggrFunc==SPH_AGGR_NONE );
}
// we had a columnar expression in the select list that we wanted to evaluate at the final stage
// we replaced it with a stored expression
// now we want to create a columnar filter based on the original columnar attribute
if ( tCol.IsStoredExpr() )
return true;
return false;
}
static void TryToCreateJoinNullFilter ( std::unique_ptr<ISphFilter> & pFilter, const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx, const CSphString & sAttrName, CommonFilterSettings_t & tFixedSettings )
{
if ( pFilter )
return;
assert ( tCtx.m_pMatchSchema );
const ISphSchema & tSchema = *tCtx.m_pMatchSchema;
int iAttr = tSchema.GetAttrIndex ( sAttrName.cstr() );
if ( iAttr<0 )
return;
const CSphColumnInfo * pAttrMask = tSchema.GetAttr ( GetNullMaskAttrName() );
const CSphColumnInfo & tAttr = tSchema.GetAttr(iAttr);
if ( ( tAttr.m_uAttrFlags & CSphColumnInfo::ATTR_JOINED ) && pAttrMask && tFixedSettings.m_eType==SPH_FILTER_NULL )
pFilter = CreateJoinNullFilter ( tSettings, pAttrMask->m_tLocator );
}
static void TryToCreateExpressionFilter ( std::unique_ptr<ISphFilter> & pFilter, const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx, const CSphString & sAttrName, const CommonFilterSettings_t & tFixedSettings, ESphAttr & eAttrType, CSphRefcountedPtr<ISphExpr> & pExpr, const CSphString * pJoinIdx, CSphString & sError, CSphString & sWarning )
{
if ( pFilter )
return;
assert ( tCtx.m_pMatchSchema );
const ISphSchema & tSchema = *tCtx.m_pMatchSchema;
int iAttr = ( tFixedSettings.m_eType!=SPH_FILTER_EXPRESSION ? tSchema.GetAttrIndex ( sAttrName.cstr() ) : -1 );
bool bColumnar = CanSpawnColumnarFilter ( iAttr, tSchema );
if ( iAttr>=0 && !bColumnar )
{
pFilter = nullptr;
return;
}
pFilter = TryToCreateColumnarFilter ( iAttr, tSchema, tSettings, tFixedSettings, tCtx.m_eCollation, sError, sWarning );
if ( pFilter )
return;
ExprParseArgs_t tExprArgs;
tExprArgs.m_pAttrType = &eAttrType;
tExprArgs.m_eCollation = tCtx.m_eCollation;
pFilter = TryToCreateExpressionFilter ( pExpr, sAttrName, tSchema, tSettings, tFixedSettings, tExprArgs, pJoinIdx, sError );
}
static void TryToCreatePlainAttrFilter ( std::unique_ptr<ISphFilter>& pFilter, const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx, bool bHaving, const CSphString & sAttrName, CommonFilterSettings_t & tFixedSettings, ESphAttr & eAttrType, CSphRefcountedPtr<ISphExpr> & pExpr, CSphString & sError, CSphString & sWarning )
{
if ( pFilter )
return;
assert ( tCtx.m_pMatchSchema );
const ISphSchema & tSchema = *tCtx.m_pMatchSchema;
int iAttr = ( tSettings.m_eType!=SPH_FILTER_EXPRESSION ? tSchema.GetAttrIndex ( sAttrName.cstr() ) : -1 );
bool bColumnar = iAttr>=0 && tSchema.GetAttr(iAttr).IsColumnar();
if ( iAttr<0 || bColumnar )
return;
const CSphColumnInfo & tAttr = tSchema.GetAttr(iAttr);
if ( !bHaving && tAttr.m_eAggrFunc!=SPH_AGGR_NONE )
{
sError.SetSprintf ( "unsupported filter '%s' on aggregate column", sAttrName.cstr() );
return;
}
if ( IsNotRealAttribute(tAttr) )
{
sError.SetSprintf ( "unsupported column '%s' (stored field, NOT attribute)", sAttrName.cstr ());
return;
}
if ( tAttr.m_eAttrType==SPH_ATTR_JSON || tAttr.m_eAttrType==SPH_ATTR_JSON_FIELD )
{
pExpr = tAttr.m_pExpr;
eAttrType = tAttr.m_eAttrType;
if ( tAttr.m_eAttrType==SPH_ATTR_JSON && !pExpr && tSettings.m_eType!=SPH_FILTER_NULL )
{
ExprParseArgs_t tExprArgs;
tExprArgs.m_pAttrType = &eAttrType;
tExprArgs.m_eCollation = tCtx.m_eCollation;
pExpr = sphExprParse ( sAttrName.cstr(), tSchema, nullptr, sError, tExprArgs );
}
pFilter = CreateFilterExpr ( pExpr, tSettings, tFixedSettings, sError, tCtx.m_eCollation, tAttr.m_eAttrType );
} else
pFilter = CreateFilter ( tSettings, tFixedSettings.m_eType, tAttr.m_eAttrType, tAttr.m_tLocator, tCtx.m_eCollation, sError, sWarning );
}
bool FixupFilterSettings ( const CSphFilterSettings & tSettings, CommonFilterSettings_t & tFixedSettings, const CreateFilterContext_t & tCtx, const CSphString & sAttrName, CSphString & sError )
{
assert ( tCtx.m_pMatchSchema );
const ISphSchema & tSchema = *tCtx.m_pMatchSchema;
int iAttr = ( tSettings.m_eType!=SPH_FILTER_EXPRESSION ? tSchema.GetAttrIndex ( sAttrName.cstr() ) : -1 );
if ( iAttr<0 )
return true;
const CSphColumnInfo & tAttr = tSchema.GetAttr(iAttr);
bool bIntFilter = tSettings.m_eType==SPH_FILTER_VALUES || tSettings.m_eType==SPH_FILTER_RANGE || tSettings.m_eType==SPH_FILTER_FLOATRANGE;
if ( bIntFilter && ( tAttr.m_eAttrType==SPH_ATTR_STRING || tAttr.m_eAttrType==SPH_ATTR_STRINGPTR ) )
{
sError.SetSprintf ( "unsupported filter on a '%s' string column", tAttr.m_sName.cstr() );
return false;
}
bool bStrFilter = tSettings.m_eType==SPH_FILTER_STRING || tSettings.m_eType==SPH_FILTER_STRING_LIST;
if ( bStrFilter && ( tAttr.m_eAttrType!=SPH_ATTR_STRING && tAttr.m_eAttrType!=SPH_ATTR_STRINGPTR && tAttr.m_eAttrType!=SPH_ATTR_JSON && tAttr.m_eAttrType!=SPH_ATTR_JSON_FIELD ) )
{
sError.SetSprintf ( "unsupported filter type '%s' on attribute '%s'", FilterType2Str(tSettings.m_eType).cstr(), tAttr.m_sName.cstr() );
return false;
}
FixupFilterSettings ( tSettings, tAttr.m_eAttrType, tFixedSettings );
return true;
}
void FixupFilterSettings ( const CSphFilterSettings & tSettings, ESphAttr eAttrType, CommonFilterSettings_t & tFixedSettings )
{
switch ( eAttrType )
{
case SPH_ATTR_INTEGER: // fixup negative values vs unsigned data
if ( tSettings.m_eType==SPH_FILTER_RANGE )
{
if ( !tSettings.m_bOpenLeft && tFixedSettings.m_iMinValue < 0 )
{
tFixedSettings.m_bOpenLeft = true;
tFixedSettings.m_bHasEqualMin = false;
tFixedSettings.m_iMinValue = INT64_MIN;
}
if ( !tSettings.m_bOpenRight && tFixedSettings.m_iMaxValue < 0 )
{
tFixedSettings.m_bHasEqualMax = true;
tFixedSettings.m_iMaxValue = 0;
}
}
break;
case SPH_ATTR_FLOAT: // fixup "fltcol=intval" conditions
if ( tSettings.m_eType==SPH_FILTER_VALUES && tSettings.GetNumValues()==1 )
{
tFixedSettings.m_eType = SPH_FILTER_FLOATRANGE;
tFixedSettings.m_fMinValue = tFixedSettings.m_fMaxValue = (float)tSettings.GetValues()[0];
}
if ( tSettings.m_eType==SPH_FILTER_RANGE )
{
tFixedSettings.m_eType = SPH_FILTER_FLOATRANGE;
tFixedSettings.m_fMinValue = (float)tSettings.m_iMinValue;
tFixedSettings.m_fMaxValue = (float)tSettings.m_iMaxValue;
}
break;
default:
break;
}
}
static bool CanAddGeodist ( const CSphColumnInfo & tAttr, const CreateFilterContext_t & tCtx )
{
if ( !tCtx.m_pIndexSchema )
return false;
const CSphColumnInfo * pAttr = tCtx.m_pIndexSchema->GetAttr ( tAttr.m_sName.cstr() );
if ( !pAttr )
return false;
return pAttr->IsColumnar() || ( tCtx.m_pSI && tCtx.m_pSI->IsEnabled ( pAttr->m_sName ) );
}
static void TryToAddGeodistFilters ( const CreateFilterContext_t & tCtx, const CSphFilterSettings & tFilter, CSphVector<CSphFilterSettings> & dModified )
{
assert ( tCtx.m_pMatchSchema );
const CSphColumnInfo * pFilterColumn = tCtx.m_pMatchSchema->GetAttr ( tFilter.m_sAttrName.cstr() );
if ( !pFilterColumn || !pFilterColumn->m_pExpr.Ptr() )
return;
if ( tFilter.m_bOpenRight )
return;
std::pair<GeoDistSettings_t *, bool> tSettingsPair { nullptr, false };
pFilterColumn->m_pExpr->Command ( SPH_EXPR_GET_GEODIST_SETTINGS, &tSettingsPair );
if ( !tSettingsPair.second )
return;
assert ( tSettingsPair.first );
const GeoDistSettings_t & tSettings = *tSettingsPair.first;
const CSphColumnInfo * pLat = tCtx.m_pMatchSchema->GetAttr ( tSettings.m_sAttrLat.cstr() );
const CSphColumnInfo * pLon = tCtx.m_pMatchSchema->GetAttr ( tSettings.m_sAttrLon.cstr() );
assert ( pLat && pLon );
if ( pLat->m_eAttrType!=SPH_ATTR_FLOAT || pLon->m_eAttrType!=SPH_ATTR_FLOAT )
return;
CSphFilterSettings tFilterLat;
tFilterLat.m_eType = SPH_FILTER_FLOATRANGE;
tFilterLat.m_sAttrName = pLat->m_sName;
tFilterLat.m_bHasEqualMin = tFilter.m_bHasEqualMax;
tFilterLat.m_bHasEqualMax = tFilter.m_bHasEqualMax;
tFilterLat.m_bOptional = true;
CSphFilterSettings tFilterLon;
tFilterLon.m_eType = SPH_FILTER_FLOATRANGE;
tFilterLon.m_sAttrName = pLon->m_sName;
tFilterLon.m_bHasEqualMin = tFilter.m_bHasEqualMax;
tFilterLon.m_bHasEqualMax = tFilter.m_bHasEqualMax;
tFilterLon.m_bOptional = true;
float fDist = tFilter.m_fMaxValue / tSettings.m_fScale;
if ( !GeodistGetSphereBBox ( tSettings.m_pFunc, tSettings.m_fAnchorLat, tSettings.m_fAnchorLon, fDist, tFilterLat.m_fMinValue, tFilterLat.m_fMaxValue, tFilterLon.m_fMinValue, tFilterLon.m_fMaxValue ) )
return;
if ( CanAddGeodist ( *pLat, tCtx ) )
dModified.Add ( tFilterLat );
if ( CanAddGeodist ( *pLon, tCtx ) )
dModified.Add ( tFilterLon );
}
static void TryToAddPoly2dFilters ( const CreateFilterContext_t & tCtx, const CSphFilterSettings & tFilter, CSphVector<CSphFilterSettings> & dModified )
{
assert ( tCtx.m_pMatchSchema );
const CSphColumnInfo * pFilterColumn = tCtx.m_pMatchSchema->GetAttr ( tFilter.m_sAttrName.cstr() );
if ( !pFilterColumn || !pFilterColumn->m_pExpr.Ptr() )
return;
bool bExclude = false;
if ( !CanAliasedExprSetupAsFilter ( tFilter, bExclude ) )
return;
if ( bExclude )
return;
std::pair<Poly2dBBox_t *, bool> tSettingsPair { nullptr, false };
pFilterColumn->m_pExpr->Command ( SPH_EXPR_GET_POLY2D_BBOX, &tSettingsPair );
if ( !tSettingsPair.second )
return;
assert ( tSettingsPair.first );
const Poly2dBBox_t & tBBox = *tSettingsPair.first;
const CSphColumnInfo * pLat = tCtx.m_pMatchSchema->GetAttr ( tBBox.m_sAttrLat.cstr() );
if ( pLat && ( pLat->m_eAttrType==SPH_ATTR_FLOAT || pLat->m_eAttrType==SPH_ATTR_INTEGER || pLat->m_eAttrType==SPH_ATTR_BIGINT ) )
{
bool bFloat = pLat->m_eAttrType==SPH_ATTR_FLOAT;
CSphFilterSettings tFilterLat;
tFilterLat.m_eType = bFloat ? SPH_FILTER_FLOATRANGE : SPH_FILTER_RANGE;
tFilterLat.m_sAttrName = pLat->m_sName;
tFilterLat.m_bHasEqualMin = true;
tFilterLat.m_bHasEqualMax = true;
tFilterLat.m_bOptional = true;
if ( bFloat )
{
tFilterLat.m_fMinValue = tBBox.m_fMinX;
tFilterLat.m_fMaxValue = tBBox.m_fMaxX;
}
else
{
tFilterLat.m_iMinValue = (SphAttr_t)tBBox.m_fMinX;
tFilterLat.m_iMaxValue = (SphAttr_t)tBBox.m_fMaxX;
}
if ( CanAddGeodist ( *pLat, tCtx ) )
dModified.Add ( tFilterLat );
}
const CSphColumnInfo * pLon = tCtx.m_pMatchSchema->GetAttr ( tBBox.m_sAttrLon.cstr() );
if ( pLon && ( pLon->m_eAttrType==SPH_ATTR_FLOAT || pLon->m_eAttrType==SPH_ATTR_INTEGER || pLon->m_eAttrType==SPH_ATTR_BIGINT ) )
{
bool bFloat = pLon->m_eAttrType==SPH_ATTR_FLOAT;
CSphFilterSettings tFilterLon;
tFilterLon.m_eType = bFloat ? SPH_FILTER_FLOATRANGE : SPH_FILTER_RANGE;
tFilterLon.m_sAttrName = pLon->m_sName;
tFilterLon.m_bHasEqualMin = true;
tFilterLon.m_bHasEqualMax = true;
tFilterLon.m_bOptional = true;
if ( bFloat )
{
tFilterLon.m_fMinValue = tBBox.m_fMinY;
tFilterLon.m_fMaxValue = tBBox.m_fMaxY;
}
else
{
tFilterLon.m_iMinValue = (SphAttr_t)tBBox.m_fMinY;
tFilterLon.m_iMaxValue = (SphAttr_t)tBBox.m_fMaxY;
}
if ( CanAddGeodist ( *pLon, tCtx ) )
dModified.Add ( tFilterLon );
}
}
static void RemoveJoinFilters ( const CreateFilterContext_t & tCtx, CSphVector<CSphFilterSettings> & dModified, CSphVector<FilterTreeItem_t> & dModifiedTree )
{
if ( tCtx.m_sJoinIdx.IsEmpty() )
return;
CSphVector<std::pair<int,bool>> dRightFilters = FetchJoinRightTableFilters ( dModified, *tCtx.m_pMatchSchema, tCtx.m_sJoinIdx.cstr() );
bool bHaveNullFilters = false;
for ( const auto & i : dRightFilters )
bHaveNullFilters |= dModified[i.first].m_eType==SPH_FILTER_NULL;
if ( tCtx.m_pFilterTree && tCtx.m_pFilterTree->GetLength() && dRightFilters.GetLength() && ( bHaveNullFilters || dRightFilters.GetLength()!=dModified.GetLength() ) )
{
// mixed joined and non-joined filters; they will be handled in join sorter
// remove all filters from the query (keep the @rowid/pseudo_sharding filter)
bool bHaveRowIdFilter = false;
CSphFilterSettings tRowIdFilter;
for ( auto & i : dModified )
if ( i.m_sAttrName=="@rowid" )
{
bHaveRowIdFilter = true;
tRowIdFilter = i;
}
dModified.Resize(0);
dModifiedTree.Resize(0);
if ( bHaveRowIdFilter )
dModified.Add(tRowIdFilter);
return;
}
CSphString sPrefix;
sPrefix.SetSprintf ( "%s.", tCtx.m_sJoinIdx.cstr() );
for ( int i = dModified.GetLength()-1; i>=0; i-- )
{
const CSphColumnInfo * pAttr = tCtx.m_pMatchSchema->GetAttr ( dModified[i].m_sAttrName.cstr() );
bool bRemove = pAttr ? pAttr->IsJoined() : dModified[i].m_sAttrName.Begins ( sPrefix.cstr() );
if ( bRemove )
dModified.Remove(i);
}
}
static void TransformForJsonSI ( const CreateFilterContext_t & tCtx, CSphVector<CSphFilterSettings> & dFilters, std::unique_ptr<ISphSchema> & pModifiedMatchSchema, const CSphVector<CSphQueryItem> & dItems )
{
if ( !tCtx.m_pSI )
return;
// check if we need to modify the schema
bool bNeedToCloneSchema = false;
for ( auto i : dFilters )
{
const CSphColumnInfo * pAttr = tCtx.m_pMatchSchema->GetAttr ( i.m_sAttrName.cstr() );
if ( pAttr && pAttr->m_pExpr && pAttr->m_pExpr->SetupAsFilter ( i, *tCtx.m_pMatchSchema, *tCtx.m_pSI ) )
{
// we transformed an attribute from an expression filter into a plain filter
// we may no longer need to calculate that expression at PREFILTER stage
StrVec_t dAttrNames;
dAttrNames.Add ( pAttr->m_sName );
FetchAttrDependencies ( dAttrNames, *tCtx.m_pMatchSchema );
for ( const auto & sAttr : dAttrNames )
{
const CSphColumnInfo * pDependentAttr = tCtx.m_pMatchSchema->GetAttr ( sAttr.cstr() );
assert(pDependentAttr);
if ( pDependentAttr->m_eStage!=SPH_EVAL_STATIC && pDependentAttr->m_eStage < SPH_EVAL_FINAL )
{
bNeedToCloneSchema = true;
break;
}
}
}
}
if ( bNeedToCloneSchema )
pModifiedMatchSchema = std::unique_ptr<ISphSchema> ( tCtx.m_pMatchSchema->CloneMe() );
const ISphSchema & tMatchSchema = pModifiedMatchSchema ? *pModifiedMatchSchema : *tCtx.m_pMatchSchema;
// now modify the schema
for ( auto & i : dFilters )
{
const CSphColumnInfo * pAttr = tMatchSchema.GetAttr ( i.m_sAttrName.cstr() );
if ( bNeedToCloneSchema && pAttr && pAttr->m_pExpr && pAttr->m_pExpr->SetupAsFilter ( i, tMatchSchema, *tCtx.m_pSI ) )
{
// we transformed an attribute from an expression filter into a plain filter
// we may no longer need to calculate that expression at PREFILTER stage
StrVec_t dAttrNames;
dAttrNames.Add ( pAttr->m_sName );
FetchAttrDependencies ( dAttrNames, tMatchSchema );
for ( const auto & sAttr : dAttrNames )
{
const CSphColumnInfo * pDependentAttr = tMatchSchema.GetAttr ( sAttr.cstr() );
assert(pDependentAttr);
if ( pDependentAttr->m_eStage!=SPH_EVAL_STATIC )
(const_cast<CSphColumnInfo *>(pDependentAttr))->m_eStage = Max ( pDependentAttr->m_eStage, SPH_EVAL_FINAL );
}
continue;
}
if ( !pAttr || pAttr->m_tLocator.m_bDynamic )
{
CSphString sTransformed = UnifyJsonFieldName ( i.m_sAttrName );
for ( const auto & tItem : dItems )
if ( tItem.m_sAlias==i.m_sAttrName && tItem.m_eAggrFunc==SPH_AGGR_NONE )
{
sTransformed = tItem.m_sExpr;
if ( sphJsonNameSplit ( sTransformed.cstr() ) )
sTransformed = UnifyJsonFieldName ( sTransformed );
break;
}
if ( tCtx.m_pSI->IsEnabled(sTransformed) )
i.m_sAttrName = sTransformed;
}
}
}
bool TransformFilters ( const CreateFilterContext_t & tCtx, CSphVector<CSphFilterSettings> & dModified, CSphVector<FilterTreeItem_t> & dModifiedTree, std::unique_ptr<ISphSchema> & pModifiedMatchSchema, const CSphVector<CSphQueryItem> & dItems, CSphString & sError )
{
assert(tCtx.m_pFilters);
const VecTraits_T<CSphFilterSettings> & dFilters = *tCtx.m_pFilters;
dModified.Resize ( dFilters.GetLength() );
ARRAY_FOREACH ( i, dFilters )
{
dModified[i] = dFilters[i];
if ( !FixupFilterSettings ( dFilters[i], dModified[i], tCtx, dFilters[i].m_sAttrName, sError ) )
return false;
}
if ( tCtx.m_pFilterTree )
{
dModifiedTree.Resize ( tCtx.m_pFilterTree->GetLength() );
ARRAY_FOREACH ( i, (*tCtx.m_pFilterTree) )
dModifiedTree[i] = (*tCtx.m_pFilterTree)[i];
}
RemoveJoinFilters ( tCtx, dModified, dModifiedTree );
TransformForJsonSI ( tCtx, dModified, pModifiedMatchSchema, dItems );
// FIXME: no further transformations if we have a filter tree
if ( tCtx.m_pFilterTree && tCtx.m_pFilterTree->GetLength() )
return true;
int iNumModified = dModified.GetLength();
for ( int i = 0; i < iNumModified; i++ )
{
TryToAddGeodistFilters ( tCtx, dModified[i], dModified );
TryToAddPoly2dFilters ( tCtx, dModified[i], dModified );
}
return true;
}
int64_t EstimateFilterSelectivity ( const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx )
{
if ( !tCtx.m_pHistograms )
return tCtx.m_iTotalDocs;
Histogram_i * pHistogram = tCtx.m_pHistograms->Get ( tSettings.m_sAttrName );
if ( !pHistogram || pHistogram->IsOutdated() )
return tCtx.m_iTotalDocs;
HistogramRset_t tEstimate;
if ( !pHistogram->EstimateRsetSize ( tSettings, tEstimate ) )
return tCtx.m_iTotalDocs;
return tEstimate.m_iTotal;
}
static bool ValuesAreSame ( const CSphVector<SphAttr_t> & dLeft, const CSphVector<SphAttr_t> & dRight )
{
if ( dLeft.GetLength()!=dRight.GetLength() )
return false;
return !memcmp ( dLeft.Begin(), dRight.Begin(), dLeft.GetLengthBytes() );
}
using namespace boost::icl;
template <typename T, typename RET>
RET ConstructInterval ( const CSphFilterSettings & tFilter )
{
assert ( !tFilter.m_bExclude );
int64_t iMin = tFilter.m_iMinValue;
int64_t iMax = tFilter.m_iMaxValue;
bool bHasEqualMin = tFilter.m_bHasEqualMin;
bool bHasEqualMax = tFilter.m_bHasEqualMax;
float fMin = tFilter.m_fMinValue;
float fMax = tFilter.m_fMaxValue;
if ( std::is_floating_point<T>::value && tFilter.m_eType==SPH_FILTER_RANGE )
{
fMin = (float)iMin;
fMax = (float)iMax;
}
if ( tFilter.m_bOpenLeft )
{
iMin = INT64_MIN;
fMin = -FLT_MAX;
bHasEqualMin = true;
}
if ( tFilter.m_bOpenRight )
{
iMax = INT64_MAX;
fMax = FLT_MAX;
bHasEqualMax = true;
}
if ( std::is_floating_point<T>::value )
{
if ( bHasEqualMin && bHasEqualMax ) return interval<T>::closed ( fMin, fMax );
if ( bHasEqualMin ) return interval<T>::right_open ( fMin, fMax );
if ( bHasEqualMax ) return interval<T>::left_open ( fMin, fMax );
return interval<T>::open ( fMin, fMax );
} else
{
if ( bHasEqualMin && bHasEqualMax ) return interval<T>::closed ( iMin, iMax );
if ( bHasEqualMin ) return interval<T>::right_open ( iMin, iMax );
if ( bHasEqualMax ) return interval<T>::left_open ( iMin, iMax );
return interval<T>::open ( iMin, iMax );
}
}
static void DeconstructInterval ( CSphFilterSettings & tFilter, const interval<int64_t>::type & tInterval )
{
tFilter.m_iMinValue = tInterval.lower();
tFilter.m_iMaxValue = tInterval.upper();
tFilter.m_bHasEqualMin = tInterval.bounds() == interval_bounds::closed() || tInterval.bounds() == interval_bounds::right_open();
tFilter.m_bHasEqualMax = tInterval.bounds() == interval_bounds::closed() || tInterval.bounds() == interval_bounds::left_open();
tFilter.m_bOpenLeft = tInterval.lower()==INT64_MIN && tFilter.m_bHasEqualMin;
tFilter.m_bOpenRight = tInterval.upper()==INT64_MAX && tFilter.m_bHasEqualMax;
}
static void DeconstructInterval ( CSphFilterSettings & tFilter, const interval<float>::type & tInterval )
{
tFilter.m_fMinValue = tInterval.lower();
tFilter.m_fMaxValue = tInterval.upper();
tFilter.m_bHasEqualMin = tInterval.bounds() == interval_bounds::closed() || tInterval.bounds() == interval_bounds::right_open();
tFilter.m_bHasEqualMax = tInterval.bounds() == interval_bounds::closed() || tInterval.bounds() == interval_bounds::left_open();
tFilter.m_bOpenLeft = tInterval.lower()==-FLT_MAX && tFilter.m_bHasEqualMin;
tFilter.m_bOpenRight = tInterval.upper()==FLT_MAX && tFilter.m_bHasEqualMax;
}
template <typename T>
bool CalcRangeMerge ( CSphFilterSettings & tLeft, const CSphFilterSettings & tRight )
{
auto tInterval1 = ConstructInterval<T, typename interval<T>::type> ( tLeft );
auto tInterval2 = ConstructInterval<T, typename interval<T>::type> ( tRight );
auto tResult = tInterval1 & tInterval2;
if ( boost::icl::is_empty(tResult) )
return false;
DeconstructInterval ( tLeft, tResult );
if ( std::is_floating_point<T>::value && tLeft.m_eType!=tRight.m_eType )
tLeft.m_eType = SPH_FILTER_FLOATRANGE;
return true;
}
static bool CheckRangeMerge ( CSphFilterSettings & tLeft, const CSphFilterSettings & tRight )
{
if ( tLeft.m_eType==SPH_FILTER_FLOATRANGE || tRight.m_eType==SPH_FILTER_FLOATRANGE )
return CalcRangeMerge<float> ( tLeft, tRight );
else
return CalcRangeMerge<int64_t> ( tLeft, tRight );
}
static bool AllInRange ( const CSphVector<int64_t> & dValues, const CSphFilterSettings & tFilter )
{
int iIndex = 0;
iIndex += 2*( tFilter.m_bHasEqualMin ? 1 : 0 ) + ( tFilter.m_bHasEqualMax ? 1 : 0 );
switch ( iIndex )
{
case 0: return MvaEval_RangeAll<int64_t,false,false> ( dValues.Begin(), dValues.GetLength(), tFilter.m_iMinValue, tFilter.m_iMaxValue );
case 1: return MvaEval_RangeAll<int64_t,false,true> ( dValues.Begin(), dValues.GetLength(), tFilter.m_iMinValue, tFilter.m_iMaxValue );
case 2: return MvaEval_RangeAll<int64_t,true,false> ( dValues.Begin(), dValues.GetLength(), tFilter.m_iMinValue, tFilter.m_iMaxValue );
case 3: return MvaEval_RangeAll<int64_t,true,true> ( dValues.Begin(), dValues.GetLength(), tFilter.m_iMinValue, tFilter.m_iMaxValue );
default:
assert(0);
return false;
}
}
static bool AllOutsideRange ( const CSphVector<int64_t> & dValues, const CSphFilterSettings & tFilter )
{
int iIndex = 0;
iIndex += 2*( tFilter.m_bHasEqualMin ? 1 : 0 ) + ( tFilter.m_bHasEqualMax ? 1 : 0 );
switch ( iIndex )
{
case 0: return !MvaEval_RangeAny<int64_t,false,false> ( dValues.Begin(), dValues.GetLength(), tFilter.m_iMinValue, tFilter.m_iMaxValue );
case 1: return !MvaEval_RangeAny<int64_t,false,true> ( dValues.Begin(), dValues.GetLength(), tFilter.m_iMinValue, tFilter.m_iMaxValue );
case 2: return !MvaEval_RangeAny<int64_t,true,false> ( dValues.Begin(), dValues.GetLength(), tFilter.m_iMinValue, tFilter.m_iMaxValue );
case 3: return !MvaEval_RangeAny<int64_t,true,true> ( dValues.Begin(), dValues.GetLength(), tFilter.m_iMinValue, tFilter.m_iMaxValue );
default:
assert(0);
return false;
}
}
static bool IsRangeFilter ( const CSphFilterSettings & tFilter )
{
return ( tFilter.m_eType==SPH_FILTER_RANGE || tFilter.m_eType==SPH_FILTER_FLOATRANGE );
}
static bool MergeFilters ( CSphFilterSettings & tLeft, const CSphFilterSettings & tRight, bool & bRemoveLeft, bool & bRejectIndex )
{
bRemoveLeft = false;
bRejectIndex = false;
if ( tLeft.m_eType==SPH_FILTER_VALUES )
{
if ( tRight.m_eType==SPH_FILTER_VALUES )
{
if ( tLeft.m_bExclude!=tRight.m_bExclude )
{
// IN (a) and NOT IN (a) => null
if ( ValuesAreSame ( tLeft.m_dValues, tRight.m_dValues ) )
{
bRejectIndex = true;
return true;
}
}
else if ( tLeft.m_bExclude )
{
// NOT IN (a) and NOT IN(b) => NOT IN(a,b)
SphAttr_t * pValues = tLeft.m_dValues.AddN ( tRight.m_dValues.GetLength() );
memcpy ( pValues, tRight.m_dValues.Begin(), tRight.m_dValues.GetLength()*sizeof ( tRight.m_dValues[0] ) );
tLeft.m_dValues.Uniq();
return true;
}
}
if ( tRight.m_eType==SPH_FILTER_RANGE )
{
// we have "values", new filter is "range"
if ( !tLeft.m_bExclude && !tRight.m_bExclude )
{
if ( AllOutsideRange ( tLeft.m_dValues, tRight ) )
{
bRejectIndex = true;
return true;
}
if ( AllInRange ( tLeft.m_dValues, tRight ) )
return true;
}
}
}
if ( IsRangeFilter ( tLeft ) )
{
if ( IsRangeFilter ( tRight ) )
{
if ( !tLeft.m_bExclude && !tRight.m_bExclude )
{
if ( !CheckRangeMerge ( tLeft, tRight ) )
bRejectIndex = true;
return true;
}
}
if ( tLeft.m_eType==SPH_FILTER_RANGE && tRight.m_eType==SPH_FILTER_VALUES )
{
// we have "range", new filter is "values"
if ( !tLeft.m_bExclude && !tRight.m_bExclude )
{
if ( AllOutsideRange ( tRight.m_dValues, tLeft ) )
{
bRejectIndex = true;
return true;
}
if ( AllInRange ( tRight.m_dValues, tLeft ) )
{
bRemoveLeft = true;
return true;
}
}
}
}
return false;
}
void OptimizeFilters ( CSphVector<CSphFilterSettings> & dFilters )
{
bool bRejectIndex = false;
SmallStringHash_T<int> hAttrNames;
for ( auto & i : dFilters )
{
int * pFound = hAttrNames ( i.m_sAttrName );
if ( pFound )
(*pFound)++;
else
hAttrNames.Add ( 1, i.m_sAttrName );
}
for ( auto & i : hAttrNames )
{
if ( i.second<2 )
continue;
bool bOk = true;
for ( const auto & tFilter : dFilters )
if ( tFilter.m_sAttrName==i.first && ( tFilter.m_eType!=SPH_FILTER_VALUES && tFilter.m_eType!=SPH_FILTER_RANGE && tFilter.m_eType!=SPH_FILTER_FLOATRANGE ) )
{
bOk = false;
break;
}
if ( !bOk )
continue;
int iLeft = -1;
ARRAY_FOREACH ( iFilter, dFilters )
{
auto & tFilter = dFilters[iFilter];
if ( tFilter.m_sAttrName!=i.first )
continue;
if ( iLeft==-1 )
{
iLeft = iFilter;
continue;
}
bool bRemoveLeft = false;
if ( MergeFilters ( dFilters[iLeft], tFilter, bRemoveLeft, bRejectIndex ) )
{
dFilters.RemoveFast ( bRemoveLeft ? iLeft : iFilter );
iLeft = -1;
iFilter = 0;
}
}
}
if ( bRejectIndex )
{
// create a fake filter that will fail index early reject
CSphFilterSettings tFake;
tFake.m_sAttrName = sphGetDocidName();
tFake.m_eType = SPH_FILTER_VALUES;
tFake.m_dValues.Add(-1);
dFilters.Resize(0);
dFilters.Add(tFake);
}
}
static std::unique_ptr<ISphFilter> CreateFilter ( const CSphFilterSettings & tSettings, const CSphString & sAttrName, const CreateFilterContext_t & tCtx, bool bHaving, CSphString & sError, CSphString & sWarning )
{
std::unique_ptr<ISphFilter> pFilter;
if ( !TryToCreateSpecialFilter ( pFilter, tSettings, tCtx, bHaving, sAttrName, sError ) )
return nullptr;
CommonFilterSettings_t tFixedSettings = (CommonFilterSettings_t)tSettings;
ESphAttr eAttrType = SPH_ATTR_NONE;
CSphRefcountedPtr<ISphExpr> pExpr;
if ( !FixupFilterSettings ( tSettings, tFixedSettings, tCtx, sAttrName, sError ) )
return nullptr;
TryToCreateJoinNullFilter ( pFilter, tSettings, tCtx, sAttrName, tFixedSettings );
TryToCreateExpressionFilter ( pFilter, tSettings, tCtx, sAttrName, tFixedSettings, eAttrType, pExpr, tCtx.m_sJoinIdx.Length() ? &tCtx.m_sJoinIdx : nullptr, sError, sWarning );
TryToCreatePlainAttrFilter ( pFilter, tSettings, tCtx, bHaving, sAttrName, tFixedSettings, eAttrType, pExpr, sError, sWarning );
SetFilterLocator ( pFilter, tSettings, tCtx, sAttrName );
SetFilterSettings ( pFilter, tSettings, tFixedSettings, tCtx );
TryToCreateExcludeFilter ( pFilter, tSettings );
TryToCreateJsonNullFilter ( pFilter, tSettings, tCtx, eAttrType, pExpr );
return pFilter;
}
std::unique_ptr<ISphFilter> sphCreateFilter ( const CSphFilterSettings & tSettings, const CreateFilterContext_t & tCtx, CSphString & sError, CSphString & sWarning )
{
return CreateFilter ( tSettings, tSettings.m_sAttrName, tCtx, false, sError, sWarning );
}
std::unique_ptr<ISphFilter> sphCreateAggrFilter ( const CSphFilterSettings * pSettings, const CSphString & sAttrName, const ISphSchema & tSchema, CSphString & sError )
{
assert ( pSettings );
CSphString sWarning;
CreateFilterContext_t tCtx;
tCtx.m_pMatchSchema = &tSchema;
tCtx.m_eCollation = SPH_COLLATION_DEFAULT;
std::unique_ptr<ISphFilter> pRes = CreateFilter ( *pSettings, sAttrName, tCtx, true, sError, sWarning );
assert ( sWarning.IsEmpty() );
return pRes;
}
std::unique_ptr<ISphFilter> sphJoinFilters ( std::unique_ptr<ISphFilter> pA, std::unique_ptr<ISphFilter> pB )
{
if ( !pA )
return pB;
if ( !pB )
return pA;
return pA.release()->Join ( std::move ( pB ) );
}
static bool IsWeightColumn ( const CSphString & sAttr, const ISphSchema & tSchema )
{
if ( sAttr=="@weight" )
return true;
const CSphColumnInfo * pCol = tSchema.GetAttr ( sAttr.cstr() );
return ( pCol && pCol->m_bWeight );
}
static std::unique_ptr<ISphFilter> CreateFilterNode ( CreateFilterContext_t & tCtx, int iNode, CSphString & sError, CSphString & sWarning, bool & bHasWeight )
{
const FilterTreeItem_t * pCur = tCtx.m_pFilterTree->Begin() + iNode;
if ( pCur->m_iFilterItem!=-1 )
{
const CSphFilterSettings * pFilterSettings = tCtx.m_pFilters->Begin() + pCur->m_iFilterItem;
if ( pFilterSettings->m_sAttrName.IsEmpty() )
{
sError = "filter with empty name";
return nullptr;
}
bHasWeight |= IsWeightColumn ( pFilterSettings->m_sAttrName, *tCtx.m_pMatchSchema );
// bind user variable local to that daemon
CSphFilterSettings tUservar;
if ( pFilterSettings->m_eType==SPH_FILTER_USERVAR )
{
const CSphString * sVar = pFilterSettings->m_dStrings.GetLength()==1 ? pFilterSettings->m_dStrings.Begin() : nullptr;
if ( !UservarsAvailable() || !sVar )
{
sError = "no global variables found";
return nullptr;
}
const UservarIntSet_c pUservar = Uservars( *sVar );
if ( !pUservar )
{
sError.SetSprintf ( "undefined global variable '%s'", sVar->cstr() );
return nullptr;
}
// NON-obvious, legacy! Liveness of value in tCtx.m_pFilters depends from tCtx.m_dUserVals here.
tCtx.m_dUserVals.Add ( pUservar );
tUservar = *pFilterSettings;
tUservar.m_eType = SPH_FILTER_VALUES;
tUservar.SetExternalValues ( *pUservar );
pFilterSettings = &tUservar;
}
return sphCreateFilter ( *pFilterSettings, tCtx, sError, sWarning );
}
assert ( pCur->m_iLeft!=-1 && pCur->m_iRight!=-1 );
std::unique_ptr<ISphFilter> pLeft = CreateFilterNode ( tCtx, pCur->m_iLeft, sError, sWarning, bHasWeight );
std::unique_ptr<ISphFilter> pRight = CreateFilterNode ( tCtx, pCur->m_iRight, sError, sWarning, bHasWeight );
if ( !pLeft || !pRight )
return nullptr;
if ( pCur->m_bOr )
return std::make_unique<Filter_Or> ( std::move ( pLeft ), std::move ( pRight ) );
return std::make_unique<Filter_And2> ( std::move ( pLeft ), std::move ( pRight ) );
}
static bool CreateFilterTree ( CreateFilterContext_t & tCtx, CSphString & sError, CSphString & sWarning )
{
bool bWeight = false;
std::unique_ptr<ISphFilter> pFilter = CreateFilterNode ( tCtx, tCtx.m_pFilterTree->GetLength() - 1, sError, sWarning, bWeight );
if ( !pFilter )
return false;
// weight filter phase only on match path
if ( bWeight && tCtx.m_bScan )
tCtx.m_pWeightFilter = std::move ( pFilter );
else
tCtx.m_pFilter = std::move ( pFilter );
return true;
}
struct FilterInfo_t
{
ISphFilter * m_pFilter {nullptr};
int64_t m_iSelectivity {INT64_MAX};
int m_iOrder {0};
};
inline bool operator<( const FilterInfo_t& tA, const FilterInfo_t& tB )
{
if ( tA.m_iSelectivity == tB.m_iSelectivity )
return tA.m_iOrder < tB.m_iOrder;
return tA.m_iSelectivity < tB.m_iSelectivity;
}
static std::unique_ptr<ISphFilter> ReorderAndCombine ( CSphVector<FilterInfo_t> dFilters )
{
if ( dFilters.GetLength()==1 )
return std::unique_ptr<ISphFilter> { dFilters.Begin()->m_pFilter };
std::unique_ptr<ISphFilter> pCombinedFilter = nullptr;
dFilters.Sort ();
for ( const auto & i : dFilters )
pCombinedFilter = sphJoinFilters ( std::move ( pCombinedFilter ), std::unique_ptr<ISphFilter> { i.m_pFilter } );
return pCombinedFilter;
}
static int g_iFilterStackSize = 200;
static int g_iStartFilterStackSize = 6*1024;
void SetFilterStackItemSize ( std::pair<int,int> tSize )
{
if ( tSize.first>g_iFilterStackSize )
g_iFilterStackSize = tSize.first;
if ( tSize.second > g_iStartFilterStackSize )
g_iStartFilterStackSize = tSize.second;
}
int GetFilterStackItemSize()
{
return g_iFilterStackSize;
}
int GetStartFilterStackItemSize()
{
return g_iStartFilterStackSize;
}
bool sphCreateFilters ( CreateFilterContext_t & tCtx, CSphString & sError, CSphString & sWarning )
{
if ( !tCtx.m_pFilters || !tCtx.m_pFilters->GetLength() )
return true;
if ( tCtx.m_pFilterTree && tCtx.m_pFilterTree->GetLength() )
{
const int TREE_SIZE_THRESH = 200;
const StackSizeTuplet_t tFilterStack = { g_iFilterStackSize, g_iFilterStackSize }; // fixme! tune eval calc
int iStackNeeded = -1;
if ( !EvalStackForTree ( *tCtx.m_pFilterTree, tCtx.m_pFilterTree->GetLength()-1, tFilterStack,
TREE_SIZE_THRESH, iStackNeeded, "filters", sError ) )
return false;
return Threads::Coro::ContinueBool ( iStackNeeded, [&] { return CreateFilterTree ( tCtx, sError, sWarning ); } );
}
assert ( tCtx.m_pMatchSchema );
CSphVector<FilterInfo_t> dFilters, dWeightFilters;
bool bSingleFilter = tCtx.m_pFilters->GetLength()==1;
ARRAY_FOREACH ( i, (*tCtx.m_pFilters) )
{
const CSphFilterSettings * pFilterSettings = tCtx.m_pFilters->Begin() + i;
if ( pFilterSettings->m_sAttrName.IsEmpty() )
continue;
if ( pFilterSettings->m_sAttrName=="@rowid" && pFilterSettings->m_eType==SPH_FILTER_RANGE )
continue;
bool bWeight = IsWeightColumn ( pFilterSettings->m_sAttrName, *tCtx.m_pMatchSchema );
if ( tCtx.m_bScan && bWeight )
continue; // @weight is not available in fullscan mode
// bind user variable local to that daemon
CSphFilterSettings tUservar;
if ( pFilterSettings->m_eType==SPH_FILTER_USERVAR )
{
const CSphString * sVar = pFilterSettings->m_dStrings.GetLength()==1 ? pFilterSettings->m_dStrings.Begin() : nullptr;
if ( !UservarsAvailable() || !sVar )
{
sError = "no global variables found";
return false;
}
const UservarIntSet_c pUservar = Uservars ( *sVar );
if ( !pUservar )
{
sError.SetSprintf ( "undefined global variable '%s'", sVar->cstr() );
return false;
}
tCtx.m_dUserVals.Add ( pUservar );
tUservar = *pFilterSettings;
tUservar.m_eType = SPH_FILTER_VALUES;
tUservar.SetExternalValues ( *pUservar );
pFilterSettings = &tUservar;
}
auto pFilter = sphCreateFilter ( *pFilterSettings, tCtx, sError, sWarning );
if ( !pFilter )
return false;
FilterInfo_t * pFilterInfo;
if ( bWeight )
pFilterInfo = &dWeightFilters.Add();
else
pFilterInfo = &dFilters.Add();
pFilterInfo->m_pFilter = pFilter.release();
pFilterInfo->m_iOrder = i;
// no need to calculate if we only have one filter
if ( !bSingleFilter )
pFilterInfo->m_iSelectivity = EstimateFilterSelectivity ( *pFilterSettings, tCtx );
}
// sort by selectivity, preserve order if equal
tCtx.m_pFilter = ReorderAndCombine ( std::move ( dFilters ) );
tCtx.m_pWeightFilter = ReorderAndCombine ( std::move ( dWeightFilters ) );
return true;
}
void FormatFilterQL ( const CSphFilterSettings & f, StringBuilder_c & tBuf, int iCompactIN )
{
ScopedComma_c sEmpty (tBuf,nullptr); // disable outer scope separator
switch ( f.m_eType )
{
case SPH_FILTER_VALUES:
//tBuf << " " << f.m_sAttrName;
// MVA + bExclude needs function inversion as does on parsing at sphinxql.y > mva_aggr TOK_NE const_int
switch (f.m_eMvaFunc)
{
case SPH_MVAFUNC_ALL:
if ( f.m_bExclude )
tBuf << "ANY(" << f.m_sAttrName << ")";
else
tBuf << "ALL(" << f.m_sAttrName << ")";
break;
case SPH_MVAFUNC_ANY:
if ( f.m_bExclude )
tBuf << "ALL(" << f.m_sAttrName << ")";
else
tBuf << "ANY(" << f.m_sAttrName << ")";
break;
case SPH_MVAFUNC_NONE: default: tBuf << f.m_sAttrName;
}
if ( f.m_dValues.GetLength()==1 )
tBuf.Sprintf ( ( f.m_bExclude ? "!=%l" : "=%l" ), (int64_t)f.m_dValues[0] );
else
{
ScopedComma_c tInComma ( tBuf, ",", ( f.m_bExclude ? " NOT IN (" : " IN (" ),")");
if ( iCompactIN>0 && ( iCompactIN+1<f.m_dValues.GetLength() ) )
{
// for really long IN-lists optionally format them as N,N,N,N,...N,N,N, with ellipsis inside.
int iLimit = Max ( iCompactIN-3, 3 );
for ( int j=0; j<iLimit; ++j )
tBuf.Sprintf ( "%l", (int64_t)f.m_dValues[j] );
iLimit = f.m_dValues.GetLength();
ScopedComma_c tElipsis ( tBuf, ",","...");
for ( int j=iLimit-3; j<iLimit; ++j )
tBuf.Sprintf ( "%l", (int64_t)f.m_dValues[j] );
} else
for ( int64_t iValue : f.m_dValues )
tBuf.Sprintf ( "%l", iValue );
}
break;
case SPH_FILTER_RANGE:
if ( f.m_iMinValue==int64_t(INT64_MIN) || ( f.m_iMinValue==0 && f.m_sAttrName=="@id" ) )
{
// no min, thus (attr<maxval)
const char * sOps[2][2] = { { "<", "<=" }, { ">=", ">" } };
tBuf.Sprintf ( "%s%s%l", f.m_sAttrName.cstr(), sOps [ f.m_bExclude ][ f.m_bHasEqualMax ], f.m_iMaxValue );
} else if ( f.m_iMaxValue==INT64_MAX || ( f.m_iMaxValue==-1 && f.m_sAttrName=="@id" ) )
{
// mo max, thus (attr>minval)
const char * sOps[2][2] = { { ">", ">=" }, { "<", "<=" } };
tBuf.Sprintf ( "%s%s%l", f.m_sAttrName.cstr(), sOps [ f.m_bExclude ][ f.m_bHasEqualMin ], f.m_iMinValue );
} else
{
if ( f.m_bHasEqualMin!=f.m_bHasEqualMax)
{
const char * sOps[2]= { "<", "<=" };
const char * sFmt = f.m_bExclude ? "NOT %l%s%s%s%l" : "%l%s%s%s%l";
tBuf.Sprintf ( sFmt, f.m_iMinValue, sOps[f.m_bHasEqualMin], f.m_sAttrName.cstr(), sOps[f.m_bHasEqualMax], f.m_iMaxValue );
} else
{
const char * sFmt = f.m_bExclude ? "%s NOT BETWEEN %l AND %l" : "%s BETWEEN %l AND %l";
tBuf.Sprintf ( sFmt, f.m_sAttrName.cstr(), f.m_iMinValue + !f.m_bHasEqualMin, f.m_iMaxValue - !f.m_bHasEqualMax );
}
}
break;
case SPH_FILTER_FLOATRANGE:
if ( f.m_fMinValue==-FLT_MAX )
{
// no min, thus (attr<maxval)
const char * sOps[2][2] = { { "<", "<=" }, { ">=", ">" } };
tBuf.Sprintf ( "%s%s%f", f.m_sAttrName.cstr(),
sOps [ f.m_bExclude ][ f.m_bHasEqualMax ], f.m_fMaxValue );
} else if ( f.m_fMaxValue==FLT_MAX )
{
// mo max, thus (attr>minval)
const char * sOps[2][2] = { { ">", ">=" }, { "<", "<=" } };
tBuf.Sprintf ( "%s%s%f", f.m_sAttrName.cstr(),
sOps [ f.m_bExclude ][ f.m_bHasEqualMin ], f.m_fMinValue );
} else
{
if ( f.m_bHasEqualMin!=f.m_bHasEqualMax)
{
const char * sOps[2]= { "<", "<=" };
tBuf.Sprintf ( "%s%f%s%s%s%f", f.m_bExclude ? "NOT ": "", f.m_fMinValue, sOps[f.m_bHasEqualMin], f.m_sAttrName.cstr(), sOps[f.m_bHasEqualMax], f.m_fMaxValue );
} else // FIXME? need we handle m_bHasEqual here?
tBuf.Sprintf ( "%s%s BETWEEN %f AND %f", f.m_sAttrName.cstr(), f.m_bExclude ? " NOT" : "", f.m_fMinValue, f.m_fMaxValue );
}
break;
case SPH_FILTER_USERVAR:
case SPH_FILTER_STRING:
{
const char * sOp = ([&]() {
switch ( f.m_eStrCmpDir )
{
case EStrCmpDir::EQ: return f.m_bExclude ? "!=" : "=";
case EStrCmpDir::LT: return f.m_bExclude ? ">=" : "<";
case EStrCmpDir::GT: return f.m_bExclude ? "<=" : ">";
default: assert(0); return f.m_bExclude ? "!?=" : "?=";
}
})();
tBuf.Sprintf ( "%s%s'%s'", f.m_sAttrName.cstr(), sOp, ( f.m_dStrings.GetLength()==1 ? f.m_dStrings[0].scstr() : "" ) );
break;
}
case SPH_FILTER_NULL:
tBuf << f.m_sAttrName << ( f.m_bIsNull ? " IS NULL" : " IS NOT NULL" );
break;
case SPH_FILTER_STRING_LIST:
tBuf << f.m_sAttrName;// << " IN (";
if ( f.m_bExclude )
tBuf << " NOT";
if ( f.m_eMvaFunc==SPH_MVAFUNC_ANY )
tBuf.StartBlock ( "', '", " ANY ('", "')" );
else if ( f.m_eMvaFunc==SPH_MVAFUNC_ALL )
tBuf.StartBlock ( "', '", " ALL ('", "')" );
else
tBuf.StartBlock ( "', '", " IN ('", "')" );
for ( const auto &sString : f.m_dStrings )
tBuf << sString;
tBuf.FinishBlock ();
break;
case SPH_FILTER_EXPRESSION:
tBuf << f.m_sAttrName;
break;
default:
tBuf += "1 /""* oops, unknown filter type *""/";
break;
}
}
static void FormatTreeItem ( StringBuilder_c & tBuf, const FilterTreeItem_t & tItem, const VecTraits_T<CSphFilterSettings> & dFilters, int iCompactIN )
{
if ( tItem.m_iFilterItem!=-1 )
FormatFilterQL ( dFilters[tItem.m_iFilterItem], tBuf, iCompactIN );
else
tBuf << ( tItem.m_bOr ? " OR " : " AND " );
}
static CSphString LogFilterTree ( int iStartItem, const VecTraits_T<FilterTreeItem_t> & dTree, const VecTraits_T<CSphFilterSettings> & dFilters, int iCompactIN )
{
struct LogTreeNode_t
{
int m_iNode;
int m_iLeftCount;
int m_iRightCount;
};
CSphVector<LogTreeNode_t> dNodes;
StringBuilder_c tBuf;
dNodes.Reserve ( dTree.GetLength() );
LogTreeNode_t tCurNode = { iStartItem, 0, 0 };
while ( tCurNode.m_iNode!=-1 || dNodes.GetLength() )
{
if ( tCurNode.m_iNode!=-1 )
{
dNodes.Add(tCurNode);
bool bTop = tCurNode.m_iNode==iStartItem;
tCurNode.m_iNode = dTree[tCurNode.m_iNode].m_iLeft;
if ( !bTop )
tCurNode.m_iLeftCount++;
tCurNode.m_iRightCount = 0;
}
else
{
tCurNode = dNodes.Pop();
const FilterTreeItem_t & tItem = dTree[tCurNode.m_iNode];
if ( tItem.m_iLeft==-1 )
{
for ( int i = 0; i < tCurNode.m_iLeftCount; i++ )
tBuf << "(";
}
FormatTreeItem ( tBuf, tItem, dFilters, iCompactIN );
if ( tItem.m_iRight==-1 )
{
for ( int i = 0; i < tCurNode.m_iRightCount; i++ )
tBuf << ")";
}
bool bTop = tCurNode.m_iNode==iStartItem;
tCurNode.m_iNode = tItem.m_iRight;
tCurNode.m_iLeftCount = 0;
if ( !bTop )
tCurNode.m_iRightCount++;
}
}
return tBuf.cstr();
}
void FormatFiltersQL ( const VecTraits_T<CSphFilterSettings> & dFilters, const VecTraits_T<FilterTreeItem_t> & dFilterTree, StringBuilder_c & tBuf, int iCompactIN )
{
if ( dFilterTree.IsEmpty() )
{
ScopedComma_c sAND ( tBuf, " AND " );
for ( const auto& dFilter : dFilters )
FormatFilterQL ( dFilter, tBuf, iCompactIN );
}
else
tBuf << LogFilterTree ( dFilterTree.GetLength() - 1, dFilterTree, dFilters, iCompactIN );
}
| 81,961
|
C++
|
.cpp
| 2,240
| 33.75625
| 364
| 0.704106
|
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
|
16,810
|
sphinxsoundex.cpp
|
manticoresoftware_manticoresearch/src/sphinxsoundex.cpp
|
//
// 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"
void stem_soundex ( BYTE * pWord )
{
static BYTE dLetter2Code[27] = "01230120022455012623010202";
// check if the word only contains lowercase English letters
BYTE * p = pWord;
while ( *p>='a' && *p<='z' )
p++;
if ( *p )
return;
// do soundex
p = pWord+1;
BYTE * pOut = pWord+1;
while ( *p )
{
BYTE c = dLetter2Code [ (*p)-'a' ];
if ( c!='0' && pOut[-1]!=c )
*pOut++ = c;
p++;
}
while ( pOut-pWord<4 && pOut<p )
*pOut++ = '0';
*pOut++ = '\0';
}
| 898
|
C++
|
.cpp
| 34
| 24.382353
| 72
| 0.649942
|
manticoresoftware/manticoresearch
| 8,893
| 493
| 500
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
16,811
|
sphinxstemar.cpp
|
manticoresoftware_manticoresearch/src/sphinxstemar.cpp
|
//
// Copyright (c) 2010, Ammar Ali
// Copyright (c) 2012, 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/
//
//
// The extended ISRI Arabic stemmer
//
// Original algorithm as described by Kazem Taghva, Rania Elkoury, and
// Jeffery Coombs in "Arabic Stemming Without A Root Dictionary", 2005.
// DOI 10.1109/ITCC.2005.90
//
// Extensions (by Ammar Ali) include:
// - added stripping of kashida (tatweel) characters;
// - added support for matching recurring stem characters;
// - added "ef3ou3ala" verb form to the known patterns.
//
#include "sphinxstd.h"
/// characters used in affix and word form patterns
/// FIXME! not right on big-endian
#define AR_ALEF_HA 0xA3D8U // U+0623
#define AR_ALEF 0xA7D8U // U+0627
#define AR_BA 0xA8D8U // U+0628
#define AR_TA_M 0xA9D8U // U+0629
#define AR_TA 0xAAD8U // U+062A
#define AR_SEEN 0xB3D8U // U+0633
#define AR_TATWEEL 0x80D9U // U+0640
#define AR_FA 0x81D9U // U+0641
#define AR_KAF 0x83D9U // U+0643
#define AR_LAM 0x84D9U // U+0644
#define AR_MIM 0x85D9U // U+0645
#define AR_NOON 0x86D9U // U+0646
#define AR_HA 0x87D9U // U+0647
#define AR_WAW 0x88D9U // U+0648
#define AR_YA 0x8AD9U // U+064A
/// extension; used for recurring root character matching
#define MATCH_M 0xB0DBU // 0x06F0
#define MATCH_0 MATCH_M
#define MATCH_1 0xB1DBU // 0x06F1
#define MATCH_2 0xB2DBU // 0x06F2
#define MATCH_3 0xB3DBU // 0x06F3
#define MATCH_4 0xB4DBU // 0x06F4
//////////////////////////////////////////////////////////////////////////
// CHARACTER SET TESTS
//////////////////////////////////////////////////////////////////////////
typedef WORD ar_char;
// AR_HAMZA_SET (U+0621, U+0624, U+0626)
#define AR_HAMZA_SET ( c==0xA1D8U || c==0xA4D8U || c==0xA6D8U )
// ALEF_SET (U+0623, U+0625, U+0671)
#define AR_ALEF_SET ( c==0xA3D8U || c==0xA5D8U || c==0xB1D9U )
// AR_DIACRITIC (>= U+064B &&<=U+0652)
#define AR_DIACRITIC(c) \
( c==0x8BD9U || c==0x8CD9U || c==0x8DD9U \
|| c==0x8ED9U || c==0x8FD9U || c==0x90D9U \
|| c==0x91D9U || c==0x92D9U )
// AR_KASHIDA (U+0640)
#define AR_KASHIDA(c) ( c==0x80D9U )
// OPTIMIZE?
#define AR_WORD_LENGTH ((int)(strlen((char*)word) / sizeof(ar_char)))
// FIXME? can crash on misaligned reads
#define AR_CHAR_AT(i) (*((ar_char*)(&word[(i * sizeof(ar_char))])))
#define AR_CHAR_SET(i,c) \
{ \
ar_char *p = (ar_char*) &word[(i * sizeof(ar_char))]; \
*p = (ar_char) c; \
}
/// remove length chars starting from start, null-terminating to new length
static inline void ar_remove ( BYTE * word, int start, int length )
{
int remain = ((AR_WORD_LENGTH - length - start) * sizeof(ar_char));
ar_char *s = (ar_char*) &word[(start * sizeof(ar_char))];
if ( remain > 0 ) {
memmove((void*)s, (void*)(s + length), remain);
s = s + (remain / sizeof(ar_char));
}
*s = '\0';
}
/// normalize (replace) all occurrences of chars in set to to_char
#define AR_NORMALIZE(set, to_char) \
{ \
int wlen = AR_WORD_LENGTH; \
while ( wlen > 0 ) { \
int ni = wlen - 1; \
ar_char c = AR_CHAR_AT(ni); \
if ( set ) { \
AR_CHAR_SET ( ni, to_char ); \
} wlen--; \
} \
}
/// remove all occurances of chars that match the given macro (e.g. KASHIDA)
#define AR_STRIP(_what) \
{ \
int wlen = AR_WORD_LENGTH; \
while ( wlen > 0 ) { \
int si = wlen - 1; \
if ( _what ( AR_CHAR_AT(si) ) ) \
ar_remove ( word, si, 1 ); \
wlen--; \
} \
}
/// attempt to match and remove a prefix with the given character count
#define AR_PREFIX(count) \
{ \
int match = ar_match_affix ( word, prefix_##count, count, 0 ); \
if ( match>=0 ) \
ar_remove ( word, 0, count ); \
}
/// attempt to match and remove a suffix with the given character count
#define AR_SUFFIX(count) \
{ \
int match = ar_match_affix ( word, suffix_##count, count, 1 ); \
if ( match>=0 ) \
ar_remove ( word, AR_WORD_LENGTH - count, count ); \
}
//////////////////////////////////////////////////////////////////////////
// TYPES
//////////////////////////////////////////////////////////////////////////
struct ar_affix_t
{
ar_char chars[4];
};
struct ar_form_entry_t
{
int at; // index to match at
ar_char cp; // code point to match
};
struct ar_form_t
{
ar_form_entry_t entry[4];
};
//////////////////////////////////////////////////////////////////////////
// PREFIX LOOKUP TABLES
//////////////////////////////////////////////////////////////////////////
/// 3-letter prefixes
static struct ar_affix_t prefix_3[] =
{
{ { AR_WAW, AR_LAM, AR_LAM, 0 } },
{ { AR_WAW, AR_ALEF, AR_LAM, 0 } },
{ { AR_KAF, AR_ALEF, AR_LAM, 0 } },
{ { AR_BA, AR_ALEF, AR_LAM, 0 } },
// Extensions
{ { AR_ALEF, AR_SEEN, AR_TA, 0 }},
{ { AR_WAW, AR_BA, AR_MIM, 0 }},
{ { AR_WAW, AR_BA, AR_ALEF, 0 }},
{ { 0 } }
};
/// 2-letter prefixes
static struct ar_affix_t prefix_2[] =
{
{ { AR_ALEF, AR_LAM, 0 } },
{ { AR_LAM, AR_LAM, 0 } },
{ { 0 } }
};
/// 1-letter prefixes
static struct ar_affix_t prefix_1[] =
{
{ { AR_ALEF, 0 } },
{ { AR_BA, 0 } },
{ { AR_TA, 0 } },
{ { AR_SEEN, 0 } },
{ { AR_FA, 0 } },
{ { AR_LAM, 0 } },
{ { AR_NOON, 0 } },
{ { AR_WAW, 0 } },
{ { AR_YA, 0 } },
{ { 0 } }
};
//////////////////////////////////////////////////////////////////////////
// SUFFIX LOOKUP TABLES
//////////////////////////////////////////////////////////////////////////
/// 3-letter suffixes
static struct ar_affix_t suffix_3[] =
{
{ { AR_TA, AR_MIM, AR_LAM, 0 } },
{ { AR_HA, AR_MIM, AR_LAM, 0 } },
{ { AR_TA, AR_ALEF, AR_NOON, 0 } },
{ { AR_TA, AR_YA, AR_NOON, 0 } },
{ { AR_KAF, AR_MIM, AR_LAM, 0 } },
{ { 0 } }
};
/// 2-letter suffixes
static struct ar_affix_t suffix_2[] = {
{ { AR_WAW, AR_NOON, 0 } },
{ { AR_ALEF, AR_TA, 0 } },
{ { AR_ALEF, AR_NOON, 0 } },
{ { AR_YA, AR_NOON, 0 } },
{ { AR_TA, AR_NOON, 0 } },
{ { AR_KAF, AR_MIM, 0 } },
{ { AR_HA, AR_NOON, 0 } },
{ { AR_NOON, AR_ALEF, 0 } },
{ { AR_YA, AR_ALEF, 0 } },
{ { AR_HA, AR_ALEF, 0 } },
{ { AR_TA, AR_MIM, 0 } },
{ { AR_KAF, AR_NOON, 0 } },
{ { AR_NOON, AR_YA, 0 } },
{ { AR_WAW, AR_ALEF, 0 } },
{ { AR_MIM, AR_ALEF, 0 } },
{ { AR_HA, AR_MIM, 0 } },
// extensions
{ { AR_WAW, AR_HA, 0 }},
{ { 0 } }
};
/// 1-letter prefixes
static struct ar_affix_t suffix_1[] =
{
{ { AR_ALEF, 0 } },
{ { AR_TA_M, 0 } },
{ { AR_TA, 0 } },
{ { AR_KAF, 0 } },
{ { AR_NOON, 0 } },
{ { AR_HA, 0 } },
{ { AR_YA, 0 } },
{ { 0 } }
};
//////////////////////////////////////////////////////////////////////////
// FORMS
//////////////////////////////////////////////////////////////////////////
/// forms for 4 letter words that yield a 3 letter stem
static struct ar_form_t form_4_3[] =
{
{ { { 3, AR_TA_M }, { 0xFF, 0 } } },
{ { { 1, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 0xFF, 0 } } }, // originally at index 05
{ { { 2, AR_WAW }, { 0xFF, 0 } } },
{ { { 2, AR_ALEF }, { 0xFF, 0 } } },
{ { { 2, AR_YA }, { 0xFF, 0 } } },
{ { { 0xFF, 0 } } }
};
/// forms for 5 letter words that yield a 3 letter stem
static struct ar_form_t form_5_3[] =
{
{ { { 0, AR_TA }, { 2, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0, AR_ALEF }, { 2, AR_TA }, { 0xFF, 0 } } },
{ { { 0, AR_ALEF }, { 3, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0, AR_ALEF }, { 2, AR_ALEF }, { 0xFF, 0 } } },
{ { { 2, AR_ALEF }, { 4, AR_TA_M }, { 0xFF, 0 } } },
{ { { 3, AR_ALEF }, { 4, AR_NOON }, { 0xFF, 0 } } },
{ { { 2, AR_WAW }, { 4, AR_TA_M }, { 0xFF, 0 } } },
{ { { 0, AR_TA }, { 4, AR_TA_M }, { 0xFF, 0 } } },
{ { { 0, AR_TA }, { 3, AR_YA }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 4, AR_TA_M }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 2, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 3, AR_WAW }, { 0xFF, 0 } } },
{ { { 1, AR_ALEF }, { 3, AR_WAW }, { 0xFF, 0 } } },
{ { { 1, AR_WAW }, { 2, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 3, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 3, AR_YA }, { 0xFF, 0 } } },
{ { { 0, AR_ALEF }, { 4, AR_TA_M }, { 0xFF, 0 } } },
{ { { 2, AR_ALEF }, { 3, AR_NOON }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 1, AR_NOON }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 2, AR_TA }, { 0xFF, 0 } } },
{ { { 1, AR_ALEF }, { 4, AR_TA_M }, { 0xFF, 0 } } },
{ { { 0, AR_YA }, { 2, AR_TA }, { 0xFF, 0 } } },
{ { { 0, AR_TA }, { 2, AR_TA }, { 0xFF, 0 } } },
{ { { 2, AR_ALEF }, { 4, AR_YA }, { 0xFF, 0 } } },
{ { { 0, AR_ALEF }, { 1, AR_NOON }, { 0xFF, 0 } } },
// extensions
{ { { 1, AR_TA }, { 4, AR_WAW }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 1, AR_TA }, { 0xFF, 0 } } },
{ { { 0, AR_TA }, { 4, AR_TA }, { 0xFF, 0 } } },
{ { { 1, AR_ALEF }, { 3, AR_YA }, { 0xFF, 0 } } },
{ { { 0xFF, 0 } } }
};
/// forms for 5 letter words that yield a 4 letter stem
static struct ar_form_t form_5_4[] =
{
{ { { 0, AR_TA }, { 0xFF, 0 } } },
{ { { 0, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 0xFF, 0 } } },
{ { { 4, AR_TA_M }, { 0xFF, 0 } } },
{ { { 2, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0xFF, 0} }}
};
/// forms for 6 letter words that yield a 3 letter stem
static struct ar_form_t form_6_3[] =
{
{ { { 0, AR_ALEF}, { 1, AR_SEEN }, { 2, AR_TA }, { 0xFF, 0 } }},
{ { { 0, AR_MIM}, { 3, AR_ALEF }, { 5, AR_TA_M }, { 0xFF, 0 } }},
{ { { 0, AR_ALEF}, { 2, AR_TA }, { 4, AR_ALEF }, { 0xFF, 0 } }},
// extensions that match recurring 2nd root letter
{ { { 0, AR_ALEF }, { 3, AR_WAW }, { 4, MATCH_2 }, { 0xFF, 0 } }},
{ { { 0, AR_MIM }, { 1, AR_SEEN }, { 2, AR_TA }, { 0xFF, 0 } }},
// extensions
{ { { 0, AR_MIM }, { 2, AR_ALEF}, { 4, AR_YA }, { 0xFF, 0 } }},
{ { { 0xFF, 0 } }}
};
/// forms for 6 letter words that yield a 4 letter stem
static struct ar_form_t form_6_4[] =
{
{ { { 0, AR_ALEF }, { 4, AR_ALEF }, { 0xFF, 0 } } },
{ { { 0, AR_MIM }, { 1, AR_TA }, { 0xFF, 0 } } },
{ { { 0xFF, 0} }}
};
/// attempt to match the given word against one of the given affix rules
static int ar_match_affix ( BYTE * word, struct ar_affix_t * affixes, int length, int reverse )
{
int match = -1, ai = 0;
while ( affixes[ai].chars[0] && match<0 )
{
int ci = 0;
while ( affixes[ai].chars[ci] && match<0 )
{
int wi = ci;
if ( reverse )
wi = (AR_WORD_LENGTH - length) + ci;
if ( AR_CHAR_AT(wi)!=affixes[ai].chars[ci] )
break;
ci++;
if ( affixes[ai].chars[ci]==0 )
match = ai;
}
ai++;
}
return match;
}
/// attempt to match the given word against one of the given form
/// rules, and if found, extract the stem
static int ar_match_form ( BYTE * word, struct ar_form_t * forms )
{
int match = -1, fi = 0;
while ( forms[fi].entry[0].at!=0xFF && match < 0 )
{
int pi = 0;
while ( forms[fi].entry[pi].at!=0xFF && match<0 )
{
if ( forms[fi].entry[pi].cp>=MATCH_M && forms[fi].entry[pi].cp<=MATCH_4 )
{
int index = ( forms[fi].entry[pi].cp - MATCH_M ) >> 8;
if ( AR_CHAR_AT(index)!=AR_CHAR_AT(forms[fi].entry[pi].at) )
break;
} else
{
if ( forms[fi].entry[pi].cp!=AR_CHAR_AT ( forms[fi].entry[pi].at ) )
break;
}
pi++;
if ( forms[fi].entry[pi].at==0xFF )
match = fi;
}
fi++;
}
// if match found, extract the stem
if ( match>=0 )
{
int pi = 0;
while ( forms[match].entry[pi].at!=0xFF )
{
ar_remove ( word, (forms[match].entry[pi].at - pi), 1 );
pi++;
}
}
return match;
}
static void ar_word_4 ( BYTE * word )
{
if ( ar_match_form ( word, form_4_3 )>=0 )
return;
AR_SUFFIX(1);
if ( AR_WORD_LENGTH==4 )
AR_PREFIX(1);
}
static void ar_word_5 ( BYTE * word )
{
if ( ar_match_form ( word, form_5_3 )>=0 )
return;
AR_SUFFIX(1);
if ( AR_WORD_LENGTH==4 )
{
ar_word_4(word);
return;
}
AR_PREFIX(1);
if ( AR_WORD_LENGTH==4 )
ar_word_4(word);
else if ( AR_WORD_LENGTH==5 )
ar_match_form ( word, form_5_4 );
}
static void ar_word_6 ( BYTE * word )
{
if ( ar_match_form ( word, form_6_3 )>=0 )
return;
AR_SUFFIX(1);
if ( AR_WORD_LENGTH==5 )
{
ar_word_5(word);
return;
}
AR_PREFIX(1);
if ( AR_WORD_LENGTH==5 )
ar_word_5(word);
else if ( AR_WORD_LENGTH==6 )
ar_match_form ( word, form_6_4 );
}
void stem_ar_utf8 ( BYTE * word )
{
AR_STRIP ( AR_DIACRITIC );
AR_STRIP ( AR_KASHIDA ); // extension
AR_NORMALIZE ( AR_HAMZA_SET, AR_ALEF_HA );
#ifdef AR_STEM_AGGRESSIVE
// extension; does both if possible (i.e. 6 and 5, not 6 else 5)
if ( AR_WORD_LENGTH>=6 )
AR_PREFIX(3);
if ( AR_WORD_LENGTH>=5 )
AR_PREFIX(2);
if ( AR_WORD_LENGTH>=6 )
AR_SUFFIX(3);
if ( AR_WORD_LENGTH>=5 )
AR_SUFFIX(2);
#else
// original; does one only (i.e. 6 or 5, not 6 and 5)
if ( AR_WORD_LENGTH>=6 )
AR_PREFIX(3)
else if ( AR_WORD_LENGTH>=5 )
AR_PREFIX(2);
if ( AR_WORD_LENGTH>=6 )
AR_SUFFIX(3)
else if ( AR_WORD_LENGTH>=5 )
AR_SUFFIX(2);
#endif
AR_NORMALIZE ( AR_ALEF_SET, AR_ALEF );
switch ( AR_WORD_LENGTH )
{
case 4: ar_word_4 ( word ); return;
case 5: ar_word_5 ( word ); return;
case 6: ar_word_6 ( word ); return;
case 7:
AR_SUFFIX(1);
if ( AR_WORD_LENGTH==6 )
{
ar_word_6(word);
return;
}
AR_PREFIX(1);
if ( AR_WORD_LENGTH==6 )
ar_word_6(word);
return;
}
}
| 13,206
|
C++
|
.cpp
| 444
| 27.63964
| 95
| 0.517728
|
manticoresoftware/manticoresearch
| 8,893
| 493
| 500
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
16,812
|
index_rotator.cpp
|
manticoresoftware_manticoresearch/src/index_rotator.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 "index_rotator.h"
#include "searchdaemon.h"
#include "indexfiles.h"
#include "detail/indexlink.h"
namespace {
inline RotateFrom_e Check ( const CSphString& sPath ) noexcept
{
switch ( ( IndexFiles_c ( sPath ).CheckHeader() ? 1 : 0 ) + ( IndexFiles_c ( sPath ).CheckHeader ( ".new" ) ? 2 : 0 ) )
{
case 0: return RotateFrom_e::NONE;
case 1: return RotateFrom_e::REENABLE;
case 2: return RotateFrom_e::NEW;
case 3: default: return RotateFrom_e::NEW_AND_OLD;
}
}
}
CheckIndexRotate_c::CheckIndexRotate_c ( const CSphString& sPath )
{
// check order:
// current_path/idx.new.sph - rotation of current index
// current_path/idx.sph - enable back current index
m_eRotateFrom = Check ( sPath );
};
CheckIndexRotate_c::CheckIndexRotate_c ( const ServedDesc_t& tServed ) : CheckIndexRotate_c ( tServed.m_sIndexPath )
{
};
CheckIndexRotate_c::CheckIndexRotate_c ( const CSphString& sPath, eCheckLink eTag )
{
m_eRotateFrom = Check ( RedirectToRealPath ( sPath ) );
}
CheckIndexRotate_c::CheckIndexRotate_c ( const ServedDesc_t& tServed, eCheckLink eTag )
: CheckIndexRotate_c ( tServed.m_sIndexPath, eTag ) {};
bool CheckIndexRotate_c::RotateFromNew() const noexcept
{
return m_eRotateFrom == RotateFrom_e::NEW || m_eRotateFrom == RotateFrom_e::NEW_AND_OLD;
}
bool CheckIndexRotate_c::RotateReenable() const noexcept
{
return m_eRotateFrom == RotateFrom_e::REENABLE || m_eRotateFrom == RotateFrom_e::NEW_AND_OLD;
}
bool CheckIndexRotate_c::NothingToRotate() const noexcept
{
return m_eRotateFrom == RotateFrom_e::NONE;
}
class StepActionEx_c : public StepAction_c
{
CSphString m_sError;
bool m_bFatal = false;
protected:
inline bool ThrowError ( CSphString sError, bool bFatal=false )
{
m_sError = std::move ( sError );
m_bFatal = bFatal;
return false;
}
public:
std::pair<CSphString,bool> GetError() const
{
return { m_sError, m_bFatal };
}
};
//////////////////
/// stuff with moving index (in seamless)
//////////////////
class RenameIdx_c : public StepActionEx_c
{
CSphIndex* m_pIdx = nullptr;
CSphString m_sOrigPath;
CSphString m_sTargetPath;
const char* m_szTo;
private:
bool DoRename ( const char* szExt, const CSphString& sTo )
{
switch ( m_pIdx->RenameEx ( sTo ) )
{
case CSphIndex::RE_FATAL: // not just failed, but also rollback wasn't success. Source index is damaged!
return ThrowError ( SphSprintf ( "rename to '%s' failed: %s; rollback also failed, TABLE UNUSABLE", szExt, m_pIdx->GetLastError().cstr() ), true );
case CSphIndex::RE_FAIL:
return ThrowError ( SphSprintf ( "rename to '%s' failed: %s", szExt, m_pIdx->GetLastError().cstr() ) );
default:
return true;
}
}
public:
void SetIdx ( CSphIndex* pIdx )
{
m_pIdx = pIdx;
assert ( m_pIdx );
m_sOrigPath = m_pIdx->GetFilebase();
m_sTargetPath = IndexFiles_c::MakePath ( m_szTo, m_sOrigPath );
}
void SetTargetPath ( const CSphString& sTo )
{
m_sTargetPath = sTo;
}
public:
explicit RenameIdx_c ( const char* szTo, CSphIndex* pIdx=nullptr )
: m_szTo ( szTo )
{
if ( pIdx )
SetIdx ( pIdx );
}
bool Action() final
{
return DoRename ( m_szTo, m_sTargetPath );
}
bool Rollback() final
{
return DoRename ( "cur", m_sOrigPath );
}
};
StepActionPtr_c RenameIdx ( CSphIndex* pIdx, const CSphString& sTo )
{
auto pAction = std::make_unique<RenameIdx_c> ( ".new", pIdx );
pAction->SetTargetPath ( sTo );
return pAction;
}
class RenameServedIdx_c: public RenameIdx_c
{
RWIdx_c m_pIdx;
public:
RenameServedIdx_c ( const char* szTo, const cServedIndexRefPtr_c& pIdx )
: RenameIdx_c ( szTo )
, m_pIdx ( pIdx )
{
SetIdx ( m_pIdx );
}
};
StepActionPtr_c RenameIdxSuffix ( const cServedIndexRefPtr_c& pIdx, const char* szToExt )
{
sphInfo ( "RW-idx for rename to %s, acquiring...", szToExt);
auto pResult = std::make_unique<RenameServedIdx_c> ( szToExt, pIdx );
sphInfo ( "RW-idx for rename to %s, acquired...", szToExt );
return pResult;
}
//////////////////
/// stuff with moving files (in greedy)
//////////////////
class RenameFiles_c: public StepActionEx_c
{
IndexFiles_c& m_tFiles;
const char* m_szFromExt;
const char* m_szToExt;
private:
bool DoRename ( const char* szFromExt, const char* szToExt )
{
if ( m_tFiles.TryRenameSuffix ( szFromExt, szToExt ) )
return true;
// backup failed.
if ( m_tFiles.IsFatal() )
return ThrowError ( SphSprintf ( "'%s' to '%s' rename failed: %s; rollback also failed, TABLE UNUSABLE", szFromExt, szToExt, m_tFiles.FatalMsg ( "rotating" ).cstr() ), true );
return ThrowError ( SphSprintf ( "'%s' to '%s' rename failed: %s", szFromExt, szToExt, m_tFiles.ErrorMsg() ) );
}
public:
explicit RenameFiles_c ( const char* szFromExt, const char* szToExt, IndexFiles_c& tFiles )
: m_tFiles { tFiles }
, m_szFromExt { szFromExt }
, m_szToExt { szToExt }
{}
bool Action() final
{
return DoRename ( m_szFromExt, m_szToExt );
}
bool Rollback() final
{
return DoRename ( m_szToExt, m_szFromExt );
}
};
StepActionPtr_c RenameFiles ( IndexFiles_c& tFiles, const char* szFromExt, const char* szToExt )
{
return std::make_unique<RenameFiles_c> ( szFromExt, szToExt, tFiles );
}
void ActionSequence_c::Defer ( StepActionPtr_c&& pAction )
{
m_dActions.Add ( std::move ( pAction ) );
}
bool ActionSequence_c::UnRunDefers()
{
for ( auto i=m_iRun-1; i>=0; --i )
{
auto pStep = (StepActionEx_c*)m_dActions[i].get();
if ( !pStep->Rollback() )
{
m_tError = pStep->GetError();
return false;
}
}
return true;
}
bool ActionSequence_c::RunDefers ()
{
m_iRun = 0;
for ( int i = 0, iEnd = m_dActions.GetLength(); i < iEnd; ++i )
{
auto pStep = (StepActionEx_c*)m_dActions[i].get();
if ( !pStep->Action() )
{
m_tError = pStep->GetError();
if ( !UnRunDefers() )
{
auto tError = pStep->GetError();
m_tError.second = m_tError.second || tError.second;
m_tError.first = SphSprintf ( "%s; than %s", tError.first.cstr(), m_tError.first.cstr() );
}
return false;
} else
++m_iRun;
}
return true;
}
std::pair<CSphString, bool> ActionSequence_c::GetError() const
{
return m_tError;
}
| 6,556
|
C++
|
.cpp
| 224
| 27.142857
| 178
| 0.698014
|
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
|
16,813
|
sphinxjson.cpp
|
manticoresoftware_manticoresearch/src/sphinxjson.cpp
|
//
// 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/
//
#include "sphinxjson.h"
#include "sphinxint.h"
#include "conversion.h"
#include "json/cJSON.h"
#if _WIN32
#include <io.h> // for isatty() in sphinxjson.c
#endif
//////////////////////////////////////////////////////////////////////////
// helpers
// cache result of system ::tolower into table for fast access
struct LowerTable
{
char m_cLowerTable[256];
LowerTable() { for ( int i = 0; i<256; ++i ) m_cLowerTable[i] = ( char ) tolower (i); }
};
inline char Mytolower ( char c )
{
static LowerTable tbl;
// return (char) tolower (c);
return tbl.m_cLowerTable [ (int) c ];
}
// how match bytes need to store packed v
inline int PackedLen ( DWORD v )
{
if ( v<0x000000FC ) // 251
return 1;
else if ( v<0x00010000 ) // 65536
return 3;
else if ( v<0x1000000 ) // 16777216
return 4;
else
return 5;
}
// parse hex word (4 digits)
inline bool parse_hex ( const char * s, WORD* pRes )
{
assert (pRes);
*pRes=0;
for ( int i=0; i<4; ++i)
{
switch (s[i])
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
*pRes += s[i] - '0'; break;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
*pRes += s[i] - 'a' + 10; break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
*pRes += s[i] - 'A' + 10; break;
default:
return false;
}
if ( i<3 )
*pRes <<= 4;
}
return true;
}
// shortcut return or parseUTF16 below
inline int parse_fail ( char *&pTarget )
{
*pTarget++ = 'u';
return 0;
}
// parse UTF-16 sequence (one or two codes)
// push result to target; return num of bytes to advance source
inline int parseUTF16 ( char* &pTarget, const char * s, const char* sMax )
{
WORD uCode1;
if ( s + 6<=sMax && parse_hex ( s+2, &uCode1 ) )
{
if ( ( uCode1>=0xDC00 ) && ( uCode1<0xE000 ) )
return parse_fail ( pTarget );
if ( ( uCode1>=0xD800 ) && ( uCode1<0xDC00 ) )
{
// it is surrogate pair; expect second code;
s+=6;
WORD uCode2;
if ( s[0]=='\\' && s[1]=='u' && s + 6<=sMax && parse_hex ( s + 2, &uCode2 ) )
{
if ( ( uCode2<0xDC00 ) || ( uCode2>0xDFFF ) )
return parse_fail ( pTarget );
int iCodepoint = 0x10000 + ( ( ( uCode1 & 0x3FF ) << 10 ) | ( uCode2 & 0x3FF ) );
pTarget += sphUTF8Encode ( ( BYTE * ) pTarget, iCodepoint );
return 10;
} else
return parse_fail ( pTarget );
}
pTarget += sphUTF8Encode ( ( BYTE * ) pTarget, uCode1 );
return 4;
}
return parse_fail ( pTarget );
}
// unescaped pEscaped, modify pEscaped to unescaped chain, return the length of unescaped
int JsonUnescape ( char * pTarget, const char * pEscaped, int iLen )
{
assert ( pEscaped );
const char * s = pEscaped;
// skip heading and trailing quotes
if ( ( s[0]=='\'' && s[iLen - 1]=='\'' ) || ( s[0]=='\"' && s[iLen - 1]=='\"' ) )
{
++s;
iLen -= 2;
}
auto * sMax = s + iLen;
auto * d = pTarget;
const char * sEscape = nullptr;
while ( s<sMax )
{
if ( s[0]=='\\' )
{
++s;
if ( s<sMax )
{
switch ( s[0] )
{
case 'b': *d++ = '\b';
break;
case 'n': *d++ = '\n';
break;
case 'r': *d++ = '\r';
break;
case 't': *d++ = '\t';
break;
case 'f': *d++ = '\f';
break; // formfeed (rfc 4627)
case 'u': s += parseUTF16 ( d, s-1, sMax ); break;
default: *d++ = *s;
}
++s;
}
continue;
}
assert ( s<sMax );
// this snippet replaces a line '*d++=*s++'. On typical string (10% escapes) it provides total time about
// 50% better then byte-by-byte copying.
sEscape = (const char *) memchr ( s, '\\', sMax - s );
if ( !sEscape )
sEscape = sMax;
auto iChunk = sEscape - s;
memmove ( d, s, iChunk ); // consider also if ((d+iChunk)<s) memcpy (d, s, iChunk); else memmove...
d += iChunk;
s += iChunk;
}
return int ( d - pTarget );
}
CSphString FormatJsonAsSortStr ( const BYTE * pVal, ESphJsonType eJson )
{
if ( !pVal )
return "";
CSphString sVal;
// FIXME!!! make string length configurable for STRING and STRING_VECTOR to compare and allocate only Min(String.Length, CMP_LENGTH)
switch ( eJson )
{
case JSON_INT32:
sVal.SetSprintf ( "%d", sphJsonLoadInt ( &pVal ) );
break;
case JSON_INT64:
sVal.SetSprintf ( INT64_FMT, sphJsonLoadBigint ( &pVal ) );
break;
case JSON_DOUBLE:
sVal.SetSprintf ( "%f", sphQW2D ( sphJsonLoadBigint ( &pVal ) ) );
break;
case JSON_STRING:
{
int iLen = sphJsonUnpackInt ( &pVal );
sVal.SetBinary ( (const char *)pVal, iLen );
break;
}
case JSON_STRING_VECTOR:
{
int iTotalLen = sphJsonUnpackInt ( &pVal );
int iCount = sphJsonUnpackInt ( &pVal );
CSphFixedVector<BYTE> dBuf ( iTotalLen + 4 + iCount ); // data and tail GAP and space count
BYTE * pDst = dBuf.Begin();
// head element
if ( iCount )
{
int iElemLen = sphJsonUnpackInt ( &pVal );
memcpy ( pDst, pVal, iElemLen );
pDst += iElemLen;
pVal += iElemLen;
}
// tail elements separated by space
for ( int i=1; i<iCount; i++ )
{
*pDst++ = ' ';
int iElemLen = sphJsonUnpackInt ( &pVal );
memcpy ( pDst, pVal, iElemLen );
pDst += iElemLen;
pVal += iElemLen;
}
// filling junk space
while ( pDst<dBuf.Begin()+dBuf.GetLength() )
*pDst++ = '\0';
auto szValue = (char*)dBuf.LeakData();
sVal.Adopt ( &szValue );
break;
}
default:
break;
}
return sVal;
}
//////////////////////////////////////////////////////////////////////////
// just a pair of numbers (std::pair is not suitable since assumes non-trivial ctrs)
struct BlobLocator_t
{
int m_iStart;
int m_iLen;
};
/// parser view on a generic node
struct JsonNode_t
{
union {
int64_t m_iValue; ///< integer value (only JSON_INT32 and JSON_INT64 )
double m_fValue; ///< floating point (only JSON_DOUBLE )
BlobLocator_t m_sValue; ///< string locator (value of JSON_STRING)
BlobLocator_t m_dChildren; ///< children locator (first, len) for obj/mix arrays
INIT_WITH_0 ( int64_t, double, BlobLocator_t );
};
union {
BlobLocator_t m_sName; ///< node name locator
INIT_WITH_0 ( int64_t, BlobLocator_t );
};
int m_iNext = -1; ///< idx of next sibling
ESphJsonType m_eType { JSON_TOTAL }; ///< node type
inline int GetLength() const { return m_dChildren.m_iLen; }
JsonNode_t() = default;
explicit JsonNode_t ( ESphJsonType eType )
{
m_eType = eType;
m_sName.m_iLen = 0;
m_sValue.m_iLen = 0;
}
};
#define YYSTYPE JsonNode_t
namespace // static unnamed
{
void StoreInt ( CSphVector<BYTE> & dBsonBuffer, int v )
{
StoreNUM32LE ( dBsonBuffer.AddN ( sizeof ( DWORD ) ), v );
}
void StoreBigint ( CSphVector<BYTE> & dBsonBuffer, int64_t v )
{
StoreBigintLE ( dBsonBuffer.AddN ( sizeof ( int64_t ) ), v );
}
void PackInt ( CSphVector<BYTE> & dBsonBuffer, DWORD v )
{
// assert ( v<16777216 ); // strings over 16M bytes and arrays over 16M entries are not supported
if ( v<0x000000FC )
{
dBsonBuffer.Add ( BYTE ( v ) );
} else if ( v<0x00010000 )
{
dBsonBuffer.Add ( 252 );
dBsonBuffer.Add ( BYTE ( v & 255 ) );
dBsonBuffer.Add ( BYTE ( v >> 8 ) );
} else if ( v<0x1000000 )
{
dBsonBuffer.Add ( 253 );
dBsonBuffer.Add ( BYTE ( v & 255 ) );
dBsonBuffer.Add ( BYTE ( ( v >> 8 ) & 255 ) );
dBsonBuffer.Add ( BYTE ( v >> 16 ) );
} else
{
dBsonBuffer.Add ( 254 );
StoreInt ( dBsonBuffer, v );
}
}
inline void PackStr ( CSphVector<BYTE> & dBsonBuffer, const char * s, int iLen )
{
assert ( iLen<=0x00FFFFFF );
iLen = Min ( iLen, 0x00ffffff );
PackInt ( dBsonBuffer, iLen );
auto * pOut = dBsonBuffer.AddN ( iLen );
if ( iLen )
memmove ( pOut, s, iLen );
}
inline void PackStr ( CSphVector<BYTE> & dBsonBuffer, const char * s )
{
PackStr ( dBsonBuffer, s, (int) strlen(s));
}
BYTE * PackStrUnescaped ( CSphVector<BYTE> & dBsonBuffer, const char * s, int iLen )
{
iLen = Min ( iLen, 0x00ffffff );
auto iLenSize = PackedLen ( iLen );
int iOfs = dBsonBuffer.GetLength ();
auto * pOut = dBsonBuffer.AddN ( iLen + iLenSize ) + iLenSize;
if ( iLen )
iLen = JsonUnescape ( ( char * ) pOut, s, iLen );
iLenSize -= PackedLen ( iLen ); // difference between place for original and unescaped len
if ( iLenSize )
{
assert ( iLenSize>0 && "Strange, unescaped json need more place than escaped" );
memmove ( pOut - iLenSize, pOut, iLen );
}
dBsonBuffer.Resize ( iOfs );
PackInt ( dBsonBuffer, iLen );
return dBsonBuffer.AddN ( iLen );
}
inline DWORD JsonKeyMask ( CSphVector<BYTE> & dBsonBuffer, const BlobLocator_t &sKey )
{
return sphJsonKeyMask ( ( const char * ) &dBsonBuffer[sKey.m_iStart], sKey.m_iLen );
}
void StoreMask ( CSphVector<BYTE> & dBsonBuffer, int iOfs, DWORD uMask )
{
#if UNALIGNED_RAM_ACCESS && USE_LITTLE_ENDIAN
*( DWORD * ) ( dBsonBuffer.begin () + iOfs ) = uMask;
#else
for ( int i=0; i<4; ++i )
{
dBsonBuffer[iOfs+i] = BYTE ( uMask & 0xff );
uMask >>= 8;
}
#endif
}
/// reserve a single byte for a yet-unknown length, to be written later with PackSize()
/// returns its offset, to be used by PackSize() to both calculate and stored the length
int ReserveSize ( CSphVector<BYTE> & dBsonBuffer )
{
int iOfs = dBsonBuffer.GetLength ();
dBsonBuffer.Resize ( iOfs + 1 );
return iOfs;
}
/// compute current length from the offset reserved with ReserveSize(), and pack the value back there
/// in most cases that single byte is enough; if not, we make room by memmove()ing the data
void PackSize ( CSphVector<BYTE> & dBsonBuffer, int iOfs )
{
int iSize = dBsonBuffer.GetLength () - iOfs - 1;
int iPackLen = PackedLen ( iSize );
if ( iPackLen!=1 )
{
dBsonBuffer.Resize ( iOfs + iPackLen + iSize );
memmove ( dBsonBuffer.Begin () + iOfs + iPackLen, dBsonBuffer.Begin () + iOfs + 1, iSize );
}
dBsonBuffer.Resize ( iOfs );
PackInt ( dBsonBuffer, iSize );
dBsonBuffer.AddN ( iSize );
}
void Finalize ( CSphVector<BYTE> & dBsonBuffer )
{
dBsonBuffer.Add ( JSON_EOF );
}
void DebugIndent ( int iLevel )
{
for ( int i = 0; i<iLevel; ++i )
printf ( " " );
}
void DebugDump ( ESphJsonType eType, const BYTE ** ppData, int iLevel )
{
DebugIndent ( iLevel );
const BYTE * p = *ppData;
switch ( eType )
{
case JSON_INT32: printf ( "JSON_INT32 %d\n", sphJsonLoadInt ( &p ) );
break;
case JSON_INT64: printf ( "JSON_INT64 " INT64_FMT "\n", sphJsonLoadBigint ( &p ) );
break;
case JSON_DOUBLE: printf ( "JSON_DOUBLE %lf\n", sphQW2D ( sphJsonLoadBigint ( &p ) ) );
break;
case JSON_STRING:
{
int iLen = sphJsonUnpackInt ( &p );
CSphString sVal;
sVal.SetBinary ( ( const char * ) p, iLen );
printf ( "JSON_STRING \"%s\"\n", sVal.cstr () );
p += iLen;
break;
}
case JSON_TRUE: printf ( "JSON_TRUE\n" );
break;
case JSON_FALSE: printf ( "JSON_FALSE\n" );
break;
case JSON_NULL: printf ( "JSON_NULL\n" );
break;
case JSON_EOF: printf ( "JSON_EOF\n" );
break;
// associative arrays
case JSON_ROOT:
case JSON_OBJECT:
{
if ( eType==JSON_OBJECT )
sphJsonUnpackInt ( &p );
DWORD uMask = sphGetDword ( p );
printf ( "%s (bloom mask: 0x%08x)\n", eType==JSON_OBJECT ? "JSON_OBJECT" : "JSON_ROOT", (uint32_t)uMask );
p += 4; // skip bloom table
while ( true )
{
auto eInnerType = ( ESphJsonType ) *p++;
if ( eInnerType==JSON_EOF )
break;
const int iStrLen = sphJsonUnpackInt ( &p );
CSphString sVal;
sVal.SetBinary ( ( const char * ) p, iStrLen );
DebugIndent ( iLevel + 1 );
printf ( "\"%s\"", sVal.cstr () );
p += iStrLen;
DebugDump ( eInnerType, &p, iLevel + 1 );
}
break;
}
case JSON_MIXED_VECTOR:
{
int iTotalLen = sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
printf ( "JSON_MIXED_VECTOR [%d] (%d bytes)\n", iLen, iTotalLen );
for ( int i = 0; i<iLen; ++i )
{
auto eInnerType = ( ESphJsonType ) *p++;
DebugDump ( eInnerType, &p, iLevel + 1 );
}
break;
}
// optimized arrays ( note they can't be empty )
case JSON_STRING_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
printf ( "JSON_STRING_VECTOR (%d) [", iLen );
for ( int i = 0; i<iLen; ++i )
{
int iStrLen = sphJsonUnpackInt ( &p );
CSphString sVal;
sVal.SetBinary ( ( const char * ) p, iStrLen );
printf ( "\"%s\"%s", sVal.cstr (), i<iLen - 1 ? "," : "]\n" );
p += iStrLen;
}
break;
}
case JSON_INT32_VECTOR:
{
int iLen = sphJsonUnpackInt ( &p );
printf ( "JSON_INT32_VECTOR (%d) [", iLen );
for ( int i = 0; i<iLen; ++i )
printf ( "%d%s", sphJsonLoadInt ( &p ), i<iLen - 1 ? "," : "]\n" );
break;
}
case JSON_INT64_VECTOR:
{
int iLen = sphJsonUnpackInt ( &p );
printf ( "JSON_INT64_VECTOR (%d) [", iLen );
for ( int i = 0; i<iLen; ++i )
printf ( INT64_FMT"%s", sphJsonLoadBigint ( &p ), i<iLen - 1 ? "," : "]\n" );
break;
}
case JSON_DOUBLE_VECTOR:
{
int iLen = sphJsonUnpackInt ( &p );
printf ( "JSON_DOUBLE_VECTOR (%d) [", iLen );
for ( int i = 0; i<iLen; ++i )
printf ( "%lf%s", sphQW2D ( sphJsonLoadBigint ( &p ) ), i<iLen - 1 ? "," : "]\n" );
break;
}
default: printf ( "UNKNOWN\n" );
break;
}
*ppData = p;
}
void DebugDump ( CSphVector<BYTE> & dBsonBuffer, const BYTE * p )
{
JsonEscapedBuilder dOut;
sphJsonFormat ( dOut, dBsonBuffer.Begin () );
printf ( "sphJsonFormat: %s\n", dOut.cstr () );
printf ( "Blob size: %d bytes\n", dBsonBuffer.GetLength () );
ESphJsonType eType = sphJsonFindFirst ( &p );
DebugDump ( eType, &p, 0 );
printf ( "\n" );
}
void AddStringData ( CSphVector<BYTE> & dBson, const VecTraits_T<CSphString> & dData )
{
auto iStartPos = ReserveSize ( dBson );
PackInt ( dBson, dData.GetLength () );
dData.Apply ( [&dBson] ( const CSphString & s ) { PackStr ( dBson, s.cstr () ); } );
PackSize ( dBson, iStartPos );
}
void AddStringData ( CSphVector<BYTE> & dBson, const VecTraits_T<const char *> & dData )
{
auto iStartPos = ReserveSize ( dBson );
PackInt ( dBson, dData.GetLength () );
dData.Apply ( [&dBson] ( const char * sz ) { PackStr ( dBson, sz ); } );
PackSize ( dBson, iStartPos );
}
void AddIntData ( CSphVector<BYTE> & dBson, const VecTraits_T<int> & dData )
{
PackInt ( dBson, dData.GetLength () );
dData.Apply ( [&dBson] ( int i ) { StoreInt ( dBson, i ); } );
}
void AddIntData ( CSphVector<BYTE> & dBson, const VecTraits_T<int64_t> & dData )
{
PackInt ( dBson, dData.GetLength () );
dData.Apply ( [&dBson] ( int64_t i ) { StoreInt ( dBson, int ( i ) ); } );
}
void AddBigintData ( CSphVector<BYTE> & dBson, const VecTraits_T<int64_t> & dData )
{
PackInt ( dBson, dData.GetLength () );
dData.Apply ( [&dBson] ( int64_t i ) { StoreBigint ( dBson, i ); } );
}
void AddDoubleData ( CSphVector<BYTE> & dBson, const VecTraits_T<double> & dData )
{
PackInt ( dBson, dData.GetLength () );
dData.Apply ( [&dBson] ( double f ) { StoreBigint ( dBson, sphD2QW ( f ) ); } );
}
}
// store, pack, unpack, bloom, etc.
class BsonHelper : ISphNoncopyable
{
public:
CSphVector<BYTE> &m_dBsonBuffer;
BsonHelper ( CSphVector<BYTE> & dBuffer )
: m_dBsonBuffer ( dBuffer )
{
// reserve 4 bytes for Bloom mask
StoreInt ( 0 );
}
inline void StoreInt ( int v )
{
::StoreInt ( m_dBsonBuffer, v );
}
inline void StoreBigint ( int64_t v )
{
::StoreBigint ( m_dBsonBuffer, v );
}
inline void Add ( BYTE b )
{
m_dBsonBuffer.Add ( b );
}
inline void PackStr ( const char * s, int iLen )
{
::PackStr ( m_dBsonBuffer, s, iLen );
}
inline void PackStr ( const char * s )
{
::PackStr ( m_dBsonBuffer, s );
}
inline void PackInt ( DWORD v )
{
::PackInt ( m_dBsonBuffer, v );
}
inline BYTE * PackStrUnescaped ( const char * s, int iLen )
{
return ::PackStrUnescaped ( m_dBsonBuffer, s, iLen );
}
inline DWORD JsonKeyMask ( const BlobLocator_t &sKey )
{
return ::JsonKeyMask ( m_dBsonBuffer, sKey );
}
inline void StoreMask ( int iOfs, DWORD uMask )
{
::StoreMask ( m_dBsonBuffer, iOfs, uMask );
}
inline int ReserveSize ()
{
return ::ReserveSize ( m_dBsonBuffer );
}
inline void PackSize ( int iOfs )
{
::PackSize ( m_dBsonBuffer, iOfs );
}
inline void Finalize ()
{
::Finalize ( m_dBsonBuffer );
}
inline void DebugDump ( const BYTE * p )
{
::DebugDump ( m_dBsonBuffer, p );
}
};
/// actually, JSON-to-SphinxBSON converter helper, but who cares
class JsonParser_c : public BsonHelper
{
bool m_bAutoconv;
bool m_bToLowercase;
public:
void * m_pScanner = nullptr;
const char * m_pLastToken = nullptr;
StringBuilder_c &m_sError;
const char * m_pSource = nullptr;
CSphVector<JsonNode_t> m_dNodes;
public:
JsonParser_c ( CSphVector<BYTE> &dBuffer, bool bAutoconv, bool bToLowercase, StringBuilder_c &sError )
: BsonHelper (dBuffer)
, m_bAutoconv ( bAutoconv )
, m_bToLowercase ( bToLowercase )
, m_sError ( sError )
{}
private:
void PackNodeStr ( const JsonNode_t &tNode )
{
PackStrUnescaped ( m_pSource + tNode.m_sValue.m_iStart, tNode.m_sValue.m_iLen );
}
// take string from source locator, write packed/unescaped string to output and return it's locator
void WriteKeyUnescaped ( BlobLocator_t &sKey )
{
auto sPacked = PackStrUnescaped ( m_pSource + sKey.m_iStart, sKey.m_iLen );
sKey.m_iStart = m_dBsonBuffer.Idx ( sPacked );
sKey.m_iLen = m_dBsonBuffer.GetLength () - sKey.m_iStart;
if ( m_bToLowercase )
for ( auto &c : VecTraits_T<char> ( ( char * ) sPacked, sKey.m_iLen ) )
c = ( char ) Mytolower ( c ); // OPTIMIZE! not sure if significant, but known to be hell slow
}
public:
#define JSON_FOREACH( _index, _node ) \
for ( auto i=0, _index=_node.m_dChildren.m_iStart; i<_node.GetLength(); ++i, _index = m_dNodes[_index].m_iNext )
void NumericFixup ( JsonNode_t &tNode )
{
// auto-convert string values, if necessary
if ( m_bAutoconv && tNode.m_eType==JSON_STRING )
if ( !sphJsonStringToNumber ( m_pSource + tNode.m_sValue.m_iStart + 1, tNode.m_sValue.m_iLen - 2
, tNode.m_eType, tNode.m_iValue, tNode.m_fValue ) )
return;
// parser and converter emits int64 values, fix them up to int32 if possible
if ( tNode.m_eType==JSON_INT64 && tNode.m_iValue==int64_t ( int ( tNode.m_iValue ) ) )
tNode.m_eType = JSON_INT32;
}
ESphJsonType OptimizeMixedVector ( JsonNode_t &tNode )
{
assert ( tNode.m_eType==JSON_MIXED_VECTOR );
if ( !tNode.m_dChildren.m_iLen )
return JSON_MIXED_VECTOR;
JSON_FOREACH ( j, tNode )
NumericFixup ( m_dNodes[j] );
ESphJsonType eBase = m_dNodes[tNode.m_dChildren.m_iStart].m_eType;
bool bAllSame = true;
JSON_FOREACH ( j, tNode )
if ( eBase!=m_dNodes[j].m_eType )
bAllSame = false;
if ( bAllSame )
switch ( eBase )
{
case JSON_INT32: return JSON_INT32_VECTOR;
case JSON_INT64: return JSON_INT64_VECTOR;
case JSON_DOUBLE: return JSON_DOUBLE_VECTOR;
case JSON_STRING: return JSON_STRING_VECTOR;
default: break; // type matches across all entries, but we do not have a special format for that type
}
return JSON_MIXED_VECTOR;
}
bool WriteRoot ( JsonNode_t &tNode ) // called in case of tompost obj enclosed in {}.
{
DWORD uMask = 0;
JSON_FOREACH ( j, tNode )
{
auto &dNode = m_dNodes[j];
WriteNode ( dNode, true );
uMask |= JsonKeyMask ( dNode.m_sName );
}
m_dBsonBuffer.Add ( JSON_EOF );
StoreMask ( 0, uMask );
return true;
}
// main proc which do whole magic over the topmost obj/array
bool WriteNode ( JsonNode_t &tNode, bool bNamed=false )
{
// convert int64 to int32, strings to numbers if needed
NumericFixup ( tNode );
auto eType = tNode.m_eType;
// process mixed vector, convert to generic vector if possible
if ( eType==JSON_MIXED_VECTOR )
eType = OptimizeMixedVector ( tNode );
// write type
m_dBsonBuffer.Add ( eType );
// write key name if exists
if ( bNamed && tNode.m_sName.m_iLen )
WriteKeyUnescaped ( tNode.m_sName );
// write nodes
switch ( eType )
{
// basic types
case JSON_INT32: StoreInt ( ( int ) tNode.m_iValue );
break;
case JSON_INT64: StoreBigint ( tNode.m_iValue );
break;
case JSON_DOUBLE: StoreBigint ( sphD2QW ( tNode.m_fValue ) );
break;
case JSON_STRING: PackNodeStr ( tNode );
break;
// literals
case JSON_TRUE:
case JSON_FALSE:
case JSON_NULL:
// no content
break;
// associative arrays
case JSON_OBJECT:
{
DWORD uMask = 0;
int iOfs = ReserveSize ();
StoreInt ( 0 );
JSON_FOREACH ( j, tNode )
{
auto &dNode = m_dNodes[j];
WriteNode ( dNode, true );
uMask |= JsonKeyMask ( dNode.m_sName );
}
m_dBsonBuffer.Add ( JSON_EOF );
StoreMask ( iOfs + 1, uMask );
PackSize ( iOfs ); // MUST be in this order, because PackSize() might move the data!
break;
}
// mixed array
case JSON_MIXED_VECTOR:
{
int iOfs = ReserveSize ();
PackInt ( tNode.GetLength () );
JSON_FOREACH ( j, tNode )
WriteNode ( m_dNodes[j] );
PackSize ( iOfs );
break;
}
// optimized (generic) arrays
case JSON_INT32_VECTOR: PackInt ( tNode.GetLength () );
JSON_FOREACH ( j, tNode )
StoreInt ( ( int ) m_dNodes[j].m_iValue );
break;
case JSON_INT64_VECTOR: PackInt ( tNode.GetLength () );
JSON_FOREACH ( j, tNode )
StoreBigint ( m_dNodes[j].m_iValue );
break;
case JSON_DOUBLE_VECTOR: PackInt ( tNode.GetLength () );
JSON_FOREACH ( j, tNode )
StoreBigint ( sphD2QW ( m_dNodes[j].m_fValue ) );
break;
case JSON_STRING_VECTOR:
{
int iOfs = ReserveSize ();
PackInt ( tNode.GetLength () );
JSON_FOREACH ( j, tNode )
PackNodeStr ( m_dNodes[j] );
PackSize ( iOfs );
break;
}
default: assert ( 0 && "internal error: unhandled type" );
return false;
}
return true;
}
void AddNode ( const JsonNode_t & tNode )
{
m_dNodes.Add ( tNode );
}
};
// unused parameter, simply to avoid type clash between all my yylex() functions
#define YY_NO_UNISTD_H 1
#define YY_DECL inline static int my_lex ( YYSTYPE * lvalp, void * yyscanner, JsonParser_c * pParser )
#include "flexsphinxjson.c"
static void yyerror ( JsonParser_c * pParser, const char * sMessage )
{
yy2lex_unhold ( pParser->m_pScanner );
pParser->m_sError.Sprintf ( "P10: %s near '%s'", sMessage, pParser->m_pLastToken );
}
#ifndef NDEBUG
// using a proxy to be possible to debug inside yylex
static int yylex ( YYSTYPE * lvalp, JsonParser_c * pParser )
{
int res = my_lex ( lvalp, pParser->m_pScanner, pParser );
return res;
}
#else
inline static int yylex ( YYSTYPE * lvalp, JsonParser_c * pParser )
{
return my_lex ( lvalp, pParser->m_pScanner, pParser );
}
#endif
#include "bissphinxjson.c"
#include "sphinxutils.h"
bool sphJsonParse ( CSphVector<BYTE>& dData, const CSphString& sFileName, CSphString& sError )
{
auto iFileSize = sphGetFileSize ( sFileName, &sError );
if ( iFileSize<0 )
return false;
CSphAutofile tFile;
if ( tFile.Open ( sFileName, SPH_O_READ, sError )<0 )
return false;
CSphFixedVector<char> dJsonText { iFileSize + 2 }; // +4 for zero-gap at the end
auto iRead = (int64_t)sphReadThrottled ( tFile.GetFD (), dJsonText.begin (), iFileSize );
if ( iRead!=iFileSize )
return false;
decltype ( dJsonText )::POLICY_T::Zero ( dJsonText.begin() + iFileSize, 2 );
return sphJsonParse ( dData, dJsonText.begin(), false, false, false, sError );
}
bool sphJsonParse ( CSphVector<BYTE> & dData, char * sData, bool bAutoconv, bool bToLowercase, bool bCheckSize, CSphString & sError )
{
StringBuilder_c sMsg;
auto bResult = sphJsonParse ( dData, sData, bAutoconv, bToLowercase, bCheckSize, sMsg );
sMsg.MoveTo ( sError );
return bResult;
}
bool sphJsonParse ( CSphVector<BYTE> &dData, char * sData, bool bAutoconv, bool bToLowercase, bool bCheckSize, StringBuilder_c &sMsg )
{
auto iLen = (int) strlen ( sData );
if ( sData[iLen+1]!=0 )
{
sMsg << "internal error: input data passed to sphJsonParse() must be terminated with a double zero";
return false;
}
JsonParser_c tParser ( dData, bAutoconv, bToLowercase, sMsg );
yy2lex_init ( &tParser.m_pScanner );
tParser.m_pSource = sData; // sphJsonParse() is intentionally destructive, no need to copy data here
YY_BUFFER_STATE tLexerBuffer = yy2_scan_buffer ( sData, iLen+2, tParser.m_pScanner );
if ( !tLexerBuffer )
{
sMsg << "internal error: yy_scan_buffer() failed";
return false;
}
int iRes = yyparse ( &tParser );
yy2_delete_buffer ( tLexerBuffer, tParser.m_pScanner );
yy2lex_destroy ( tParser.m_pScanner );
tParser.Finalize();
if ( bCheckSize && dData.AllocatedBytes()>=0x400000 )
{
sMsg << "data exceeds 0x400000 bytes";
iRes = -1;
}
if ( iRes!=0 )
dData.Reset();
return ( iRes==0 );
}
//////////////////////////////////////////////////////////////////////////
DWORD sphJsonKeyMask ( const char * sKey, int iLen )
{
DWORD uCrc = sphCRC32 ( sKey, iLen );
DWORD uBloom1 = ( 1UL<<( uCrc & 31 ) );
DWORD uBloom2 = ( 1UL<<( ( uCrc>>8 ) & 31 ) );
// DWORD overflow protection as 0 at bloom mask means not the ROOT node
return ( ( uBloom1 + uBloom2 ) ? ( uBloom1 + uBloom2 ) : ( uBloom1 | uBloom2 ) );
}
static inline DWORD KeyMask ( const char * s )
{
return sphJsonKeyMask ( s, (int) strlen ( s ) );
}
// returns -1 if size is unreachable (for remote agents)
int sphJsonNodeSize ( ESphJsonType eType, const BYTE *pData )
{
int iLen;
const BYTE * p = pData;
switch ( eType )
{
case JSON_INT32:
return 4;
case JSON_INT64:
case JSON_DOUBLE:
return 8;
case JSON_INT32_VECTOR:
if ( !p )
return -1;
iLen = sphJsonUnpackInt ( &p );
return int ( p - pData ) + iLen * 4;
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
if ( !p )
return -1;
iLen = sphJsonUnpackInt ( &p );
return int ( p - pData ) + iLen * 8;
case JSON_STRING:
case JSON_STRING_VECTOR:
case JSON_MIXED_VECTOR:
case JSON_OBJECT:
if ( !p )
return -1;
iLen = sphJsonUnpackInt ( &p );
return int ( p - pData ) + iLen;
case JSON_ROOT:
if ( !p )
return -1;
p += 4; // skip filter
while (true)
{
auto eNode = (ESphJsonType) *p++;
if ( eNode==JSON_EOF )
break;
// skip key and node
iLen = sphJsonUnpackInt ( &p );
p += iLen;
sphJsonSkipNode ( eNode, &p );
}
return int ( p - pData );
default:
return 0;
}
}
int sphJsonSingleNodeSize ( ESphJsonType eType )
{
switch ( eType )
{
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
case JSON_STRING:
case JSON_STRING_VECTOR:
case JSON_MIXED_VECTOR:
case JSON_OBJECT:
case JSON_ROOT:
return -1;
case JSON_INT32:
return 4;
case JSON_INT64:
case JSON_DOUBLE:
return 8;
default:
return 0;
}
}
void sphJsonSkipNode ( ESphJsonType eType, const BYTE ** ppData )
{
int iSize = sphJsonNodeSize ( eType, *ppData );
*ppData += iSize;
}
int sphJsonFieldLength ( ESphJsonType eType, const BYTE * pData )
{
const BYTE * p = pData;
int iCount = 0;
switch ( eType )
{
case JSON_INT32:
case JSON_INT64:
case JSON_DOUBLE:
return 1;
case JSON_STRING_VECTOR:
case JSON_MIXED_VECTOR:
sphJsonUnpackInt ( &p );
return sphJsonUnpackInt ( &p );
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
return sphJsonUnpackInt ( &p );
case JSON_OBJECT:
sphJsonUnpackInt ( &p ); // skip size, then continue
// [[clang::fallthrough]];
case JSON_ROOT:
p += 4; // skip filter
while (true)
{
auto eNode = (ESphJsonType) *p++;
if ( eNode==JSON_EOF )
break;
// skip name of node
int iLen = sphJsonUnpackInt ( &p );
p += iLen;
sphJsonSkipNode ( eNode, &p );
++iCount;
}
return iCount;
default:
return 0;
}
}
ESphJsonType sphJsonGetCoreType ( ESphJsonType eType )
{
switch ( eType )
{
case JSON_INT32_VECTOR: return JSON_INT32;
case JSON_INT64_VECTOR: return JSON_INT64;
case JSON_DOUBLE_VECTOR: return JSON_DOUBLE;
case JSON_STRING_VECTOR: return JSON_STRING;
default:
return JSON_EOF;
}
}
ESphJsonType sphJsonFindFirst ( const BYTE ** ppData )
{
// non-zero bloom mask? that is JSON_ROOT (basically a JSON_OBJECT without node header)
if ( sphGetDword(*ppData) )
return JSON_ROOT;
// zero mask? must be followed by the type byte (typically JSON_EOF)
auto eType = (ESphJsonType)((*ppData)[4]);
*ppData += 5;
return eType;
}
ESphJsonType sphJsonFindByKey ( ESphJsonType eType, const BYTE ** ppValue, const void * pKey, int iLen, DWORD uMask )
{
if ( eType!=JSON_OBJECT && eType!=JSON_ROOT )
return JSON_EOF;
const BYTE * p = *ppValue;
if ( eType==JSON_OBJECT )
sphJsonUnpackInt ( &p );
if ( ( sphGetDword(p) & uMask )!=uMask )
return JSON_EOF;
p += 4;
while (true)
{
eType = (ESphJsonType) *p++;
if ( eType==JSON_EOF )
break;
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen;
if ( iStrLen==iLen && !memcmp ( p-iStrLen, pKey, iStrLen ) )
{
*ppValue = p;
return eType;
}
sphJsonSkipNode ( eType, &p );
}
return JSON_EOF;
}
ESphJsonType sphJsonFindByIndex ( ESphJsonType eType, const BYTE ** ppValue, int iIndex )
{
if ( iIndex<0 )
return JSON_EOF;
const BYTE * p = *ppValue;
switch ( eType )
{
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
{
int iLen = sphJsonUnpackInt ( &p );
if ( iIndex>=iLen )
return JSON_EOF;
p += iIndex * ( eType==JSON_INT32_VECTOR ? 4 : 8 );
*ppValue = p;
return eType==JSON_INT32_VECTOR ? JSON_INT32
: eType==JSON_INT64_VECTOR ? JSON_INT64
: JSON_DOUBLE;
}
case JSON_STRING_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
if ( iIndex>=iLen )
return JSON_EOF;
for ( int i=0; i<iIndex; ++i )
{
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen;
}
*ppValue = p;
return JSON_STRING;
}
case JSON_MIXED_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
if ( iIndex>=iLen )
return JSON_EOF;
for ( int i=0; i<iIndex; ++i )
{
eType = (ESphJsonType)*p++;
sphJsonSkipNode ( eType, &p );
}
eType = (ESphJsonType)*p;
*ppValue = p+1;
return eType;
}
default:
return JSON_EOF;
}
}
//////////////////////////////////////////////////////////////////////////
static const BYTE * JsonFormatStr ( JsonEscapedBuilder &sOut, const BYTE * p, bool bQuote=true )
{
int iLen = sphJsonUnpackInt ( &p );
if ( bQuote )
sOut.AppendEscaped ( ( const char * ) p, EscBld::eEscape, iLen );
else
sOut.AppendChunk ( {(const char *) p, iLen} );
return p+iLen;
}
void sphJsonFormat ( JsonEscapedBuilder & sOut, const BYTE * pData )
{
if ( !pData )
return;
ESphJsonType eType = sphJsonFindFirst ( &pData );
// check for the empty root
if ( eType==JSON_EOF )
sOut << "{}";
else
sphJsonFieldFormat ( sOut, pData, eType );
}
const BYTE * sphJsonFieldFormat ( JsonEscapedBuilder & sOut, const BYTE * pData, ESphJsonType eType, bool bQuoteString )
{
const BYTE szDouble = 32;
char sDouble[szDouble];
// format value
const BYTE * p = pData;
switch ( eType )
{
case JSON_INT32:
sOut.Sprintf ("%d", sphJsonLoadInt ( &p )); // NOLINT
break;
case JSON_INT64:
sOut.Sprintf ( "%l", sphJsonLoadBigint ( &p ) ); // NOLINT
break;
case JSON_DOUBLE:
{
auto iLen = snprintf ( sDouble, szDouble, "%lf", sphQW2D ( sphJsonLoadBigint ( &p ) ) ); // NOLINT
sOut.AppendChunk ( {sDouble, iLen} );
break;
}
case JSON_STRING:
p = JsonFormatStr ( sOut, p, bQuoteString );
break;
case JSON_STRING_VECTOR:
sOut.GrowEnough ( sphJsonUnpackInt ( &p ) );
{
auto _ = sOut.Array();
for ( int i = sphJsonUnpackInt ( &p ); i > 0; --i )
p = JsonFormatStr ( sOut, p );
}
break;
case JSON_INT32_VECTOR:
{
auto _ = sOut.Array();
for ( int i = sphJsonUnpackInt ( &p ); i > 0; --i )
sOut.Sprintf ( "%d", sphJsonLoadInt ( &p ) );
break;
}
case JSON_INT64_VECTOR:
{
auto _ = sOut.Array();
for ( int i = sphJsonUnpackInt ( &p ); i > 0; --i )
sOut.Sprintf ( "%l", sphJsonLoadBigint ( &p ) );
break;
}
case JSON_DOUBLE_VECTOR:
{
auto _ = sOut.Array ();
for ( int i = sphJsonUnpackInt ( &p ); i>0; --i )
{
auto iLen = snprintf ( sDouble, szDouble, "%lf", sphQW2D ( sphJsonLoadBigint ( &p ) ) ); // NOLINT
sOut.AppendChunk ( {sDouble, iLen} );
}
break;
}
case JSON_MIXED_VECTOR:
{
auto _ = sOut.Array ();
sphJsonUnpackInt ( &p );
for ( int i = sphJsonUnpackInt ( &p ); i>0; --i )
{
auto eNode = ( ESphJsonType ) *p++;
p = sphJsonFieldFormat ( sOut, p, eNode, true );
}
break;
}
case JSON_ROOT:
case JSON_OBJECT:
{
if ( eType==JSON_OBJECT )
sphJsonUnpackInt ( &p );
p += 4; // skip bloom table
sOut.ObjectBlock();
while (true)
{
ScopedComma_c sMuteCommas ( sOut, nullptr );
auto eNode = (ESphJsonType) *p++;
if ( eNode==JSON_EOF )
break;
p = JsonFormatStr ( sOut, p );
sOut.RawC (':');
p = sphJsonFieldFormat ( sOut, p, eNode, true );
}
sOut.FinishBlock (false);
break;
}
case JSON_TRUE: sOut << ( bQuoteString ? "true" : "1" ); break;
case JSON_FALSE: sOut << ( bQuoteString ? "false" : "0"); break;
case JSON_NULL: sOut << ( bQuoteString ? "null" : nullptr); break;
case JSON_EOF: break;
case JSON_TOTAL: break;
}
return p;
}
static bool FindNextSeparator ( const char * & pSep )
{
// find either '[' or '.', what comes first
while ( *pSep && *pSep!='.' && *pSep!='[' )
{
// check for invalid characters
if ( !sphIsAttr( *pSep ) && *pSep!=' ' )
return false;
++pSep;
}
return *pSep;
}
bool sphJsonNameSplit ( const char * szName, const char * szIndex, CSphString * pColumn )
{
if ( !szName )
return false;
const char * pSep = szName;
if ( !FindNextSeparator(pSep) )
return false;
if ( szIndex && *pSep=='.' && !strncmp ( szIndex, szName, pSep - szName ) )
{
// this was not a json separator, but a dot between table name and column name
pSep++;
if ( !FindNextSeparator(pSep) )
return false;
}
if ( pColumn )
{
pColumn->SetBinary ( szName, pSep-szName );
pColumn->Trim();
}
return true;
}
JsonKey_t::JsonKey_t ( const char * sKey, int iLen )
{
m_iLen = iLen;
m_uMask = sphJsonKeyMask ( sKey, m_iLen );
m_sKey.SetBinary ( sKey, m_iLen );
}
uint64_t sphJsonUnpackOffset ( uint64_t uPacked )
{
return uPacked & 0x00ffffffffffffffULL;
}
ESphJsonType sphJsonUnpackType ( uint64_t uPacked )
{
return (ESphJsonType)( uPacked >> 56 );
}
uint64_t sphJsonPackTypeOffset ( ESphJsonType eType, uint64_t uOffset )
{
assert ( uOffset<=0x00ffffffffffffffULL );
return uOffset | ( ((uint64_t)eType)<<56 );
}
bool sphJsonInplaceUpdate ( ESphJsonType eValueType, int64_t iValue, ISphExpr * pExpr, BYTE * pBlobPool, const CSphRowitem * pRow, bool bUpdate )
{
if ( !pExpr || !pBlobPool )
return false;
pExpr->Command ( SPH_EXPR_SET_BLOB_POOL, (void*)pBlobPool );
CSphMatch tMatch;
tMatch.m_pStatic = pRow;
uint64_t uPacked = pExpr->Int64Eval ( tMatch );
BYTE * pData = pBlobPool + sphJsonUnpackOffset ( uPacked );
ESphJsonType eType = sphJsonUnpackType ( uPacked );
switch ( eType )
{
case JSON_INT32:
if ( eValueType==JSON_DOUBLE )
iValue = (int64_t)sphQW2D ( iValue );
if ( int64_t(int(iValue))!=iValue )
return false;
if ( bUpdate )
StoreNUM32LE ( pData, (int)iValue );
break;
case JSON_INT64:
if ( bUpdate )
StoreBigintLE ( pData, eValueType==JSON_DOUBLE ? (int64_t)sphQW2D ( iValue ) : iValue );
break;
case JSON_DOUBLE:
if ( bUpdate )
StoreBigintLE ( pData, eValueType==JSON_DOUBLE ? iValue : sphD2QW ( (double)iValue ) );
break;
default:
return false;
}
return true;
}
inline bool is_json_whitespace (char c)
{
return c==' ' || c=='\n' || c=='\r' || c=='\t' || c=='\f';
}
// note that usual parsing of num is done by grammar parser;
// this function is used only when 'autoconversion' is in game
bool sphJsonStringToNumber ( const char * s, int iLen, ESphJsonType &eType, int64_t &iVal, double &fVal )
{
auto sEnd = s + iLen;
// skip whitespace
while ( s<sEnd && is_json_whitespace(*s) )
++s;
if ( s>=sEnd )
return false;
char sVal[64] = {0};
char * pVal = sVal;
char sDecimal_point = '.'; // m.b. set it locale-dependent?
bool bIsFloat = false;
for (int i=0; i<63 && s<sEnd ; ++i, ++pVal, ++s)
{
switch ( *s )
{
case '.':
*pVal = sDecimal_point;
bIsFloat = true;
break;
case 'e':
case 'E':
*pVal = 'e';
bIsFloat = true;
break;
case '-':
case '+':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
*pVal = *s;
break;
default:
if ( !is_json_whitespace(*s) )
return false;
i=64;
--pVal;
}
}
iLen = int ( pVal-sVal );
if ( !iLen || iLen==64 )
return false;
const char * pCheck = s;
// check string conversion is valid if only whitespaces left
while ( pCheck<sEnd && is_json_whitespace(*pCheck) )
++pCheck;
if ( pCheck!=sEnd )
return false;
char * pTail;
errno = 0;
if ( !bIsFloat )
{
int64_t iRes = strtoll ( sVal, &pTail, 10 );
if ( pTail==pVal && errno!=ERANGE )
{
eType = JSON_INT64;
iVal = iRes;
return true;
}
} else
{
double fRes = strtod ( sVal, &pTail );
if ( pTail==pVal && errno!=ERANGE )
{
eType = JSON_DOUBLE;
fVal = fRes;
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////
#if DISABLE_MEMROUTINES
static void * cJsonMalloc ( size_t uSize )
{
return malloc (uSize);
}
static void cJsonFree ( void * pPtr )
{
free ( pPtr );
}
#else
static void* cJsonMalloc ( size_t uSize )
{
return new BYTE[uSize];
}
static void cJsonFree ( void* pPtr )
{
delete[] (BYTE*)pPtr;
}
#endif
void sphInitCJson()
{
cJSON_Hooks tHooks { cJsonMalloc, cJsonFree };
cJSON_InitHooks ( &tHooks );
}
//////////////////////////////////////////////////////////////////////////
JsonObj_c::JsonObj_c ( bool bArray )
{
if ( bArray )
m_pRoot = cJSON_CreateArray();
else
m_pRoot = cJSON_CreateObject();
assert ( m_pRoot );
}
JsonObj_c::JsonObj_c ( cJSON * pRoot, bool bOwner )
{
m_pRoot = pRoot;
m_bOwner = bOwner;
}
JsonObj_c::JsonObj_c ( const char * szJson )
{
m_pRoot = cJSON_Parse ( szJson );
}
JsonObj_c::JsonObj_c ( Str_t sJson )
{
m_pRoot = cJSON_Parse ( sJson.first );
}
JsonObj_c::JsonObj_c ( JsonObj_c && rhs ) noexcept
: m_pRoot ( nullptr )
{
Swap (rhs);
}
void JsonObj_c::Swap ( JsonObj_c& rhs ) noexcept
{
::Swap ( m_pRoot, rhs.m_pRoot );
::Swap ( m_bOwner, rhs.m_bOwner );
}
JsonObj_c::~JsonObj_c()
{
if ( m_pRoot )
{
if ( m_bOwner )
cJSON_Delete(m_pRoot);
m_pRoot = nullptr;
}
}
JsonObj_c::operator bool() const
{
return !Empty();
}
JsonObj_c & JsonObj_c::operator = ( JsonObj_c rhs )
{
Swap(rhs);
return *this;
}
void JsonObj_c::AddStr ( const char * szName, const char * szValue )
{
assert ( m_pRoot );
cJSON_AddStringToObject ( m_pRoot, szName, szValue );
}
void JsonObj_c::AddStr ( const char * szName, const CSphString & sValue )
{
AddStr ( szName, sValue.cstr() );
}
void JsonObj_c::AddInt ( const char * szName, int64_t iValue )
{
assert ( m_pRoot );
cJSON_AddItemToObject ( m_pRoot, szName, CreateInt(iValue).Leak() );
}
void JsonObj_c::AddUint ( const char * szName, uint64_t uValue )
{
assert ( m_pRoot );
cJSON_AddItemToObject ( m_pRoot, szName, CreateUint(uValue).Leak() );
}
void JsonObj_c::AddBool ( const char * szName, bool bValue )
{
assert ( m_pRoot );
cJSON_AddBoolToObject ( m_pRoot, szName, bValue ? 1 : 0 );
}
void JsonObj_c::AddItem ( const char * szName, JsonObj_c & tObj )
{
assert ( m_pRoot );
cJSON_AddItemToObject ( m_pRoot, szName, tObj.Leak() );
}
void JsonObj_c::AddItem ( JsonObj_c & tObj )
{
assert ( m_pRoot );
cJSON_AddItemToArray ( m_pRoot, tObj.Leak() );
}
void JsonObj_c::DelItem ( const char * szName )
{
assert ( m_pRoot );
cJSON_DeleteItemFromObject ( m_pRoot, szName );
}
int JsonObj_c::Size() const
{
assert ( m_pRoot );
return cJSON_GetArraySize ( m_pRoot );
}
bool JsonObj_c::IsInt() const
{
assert ( m_pRoot );
return cJSON_IsInteger(m_pRoot);
}
bool JsonObj_c::IsUint() const
{
assert ( m_pRoot );
return cJSON_IsUInteger(m_pRoot);
}
bool JsonObj_c::IsDbl() const
{
assert ( m_pRoot );
return !!cJSON_IsNumber ( m_pRoot );
}
bool JsonObj_c::IsNum() const
{
assert ( m_pRoot );
return !!cJSON_IsNumeric ( m_pRoot );
}
bool JsonObj_c::IsBool() const
{
assert ( m_pRoot );
return !!cJSON_IsBool ( m_pRoot );
}
bool JsonObj_c::IsObj () const
{
assert ( m_pRoot );
return !!cJSON_IsObject ( m_pRoot );
}
bool JsonObj_c::IsStr() const
{
assert ( m_pRoot );
return !!cJSON_IsString ( m_pRoot );
}
bool JsonObj_c::IsArray() const
{
assert ( m_pRoot );
return !!cJSON_IsArray ( m_pRoot );
}
bool JsonObj_c::IsNull() const
{
return !!cJSON_IsNull ( m_pRoot );
}
JsonObj_c JsonObj_c::operator[] ( int iItem ) const
{
assert ( m_pRoot );
return JsonObj_c ( cJSON_GetArrayItem ( m_pRoot, iItem ), false );
}
JsonObj_c JsonObj_c::GetItem ( const char * szName ) const
{
assert ( m_pRoot );
return JsonObj_c ( cJSON_GetObjectItem ( m_pRoot, szName ), false );
}
JsonObj_c JsonObj_c::GetIntItem ( const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tChild = GetChild ( szName, sError, bIgnoreMissing );
if ( !tChild )
return JsonNull;
if ( !tChild.IsInt() )
{
sError.SetSprintf ( R"("%s" property value should be an integer)", szName );
return JsonNull;
}
return tChild;
}
JsonObj_c JsonObj_c::GetIntItem ( const char * szName1, const char * szName2, CSphString & sError ) const
{
JsonObj_c tResult = GetIntItem ( szName1, sError, true );
if ( !tResult )
{
if ( !sError.IsEmpty() )
return JsonNull;
tResult = GetIntItem ( szName2, sError, true );
}
return tResult;
}
JsonObj_c JsonObj_c::GetBoolItem ( const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tChild = GetChild ( szName, sError, bIgnoreMissing );
if ( !tChild )
return JsonNull;
if ( !tChild.IsBool() )
{
sError.SetSprintf ( R"("%s" property value should be a boolean)", szName );
return JsonNull;
}
return tChild;
}
JsonObj_c JsonObj_c::GetStrItem ( const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tChild = GetChild ( szName, sError, bIgnoreMissing );
if ( !tChild )
return JsonNull;
if ( !tChild.IsStr() )
{
sError.SetSprintf ( R"("%s" property value should be a string)", szName );
return JsonNull;
}
if ( tChild.StrVal().IsEmpty() && !bIgnoreMissing )
{
sError.SetSprintf ( R"("%s" property empty)", szName );
return JsonNull;
}
return tChild;
}
JsonObj_c JsonObj_c::GetStrItem ( const char * szName1, const char * szName2, CSphString & sError ) const
{
JsonObj_c tResult = GetStrItem ( szName1, sError, true );
if ( !tResult )
{
if ( !sError.IsEmpty() )
return JsonNull;
tResult = GetStrItem ( szName2, sError, true );
}
return tResult;
}
JsonObj_c JsonObj_c::GetObjItem ( const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tChild = GetChild ( szName, sError, bIgnoreMissing );
if ( !tChild )
return JsonNull;
if ( !tChild.IsObj() )
{
sError.SetSprintf ( R"("%s" property value should be an object)", szName );
return JsonNull;
}
return tChild;
}
JsonObj_c JsonObj_c::GetArrayItem ( const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tChild = GetChild ( szName, sError, bIgnoreMissing );
if ( !tChild )
return JsonNull;
if ( !tChild.IsArray() )
{
sError.SetSprintf ( R"("%s" property value should be an array)", szName );
return JsonNull;
}
return tChild;
}
bool JsonObj_c::FetchIntItem ( int & iValue, const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tItem = GetIntItem ( szName, sError, bIgnoreMissing );
if ( tItem )
iValue = (int)tItem.IntVal();
else if ( !sError.IsEmpty() )
return false;
return true;
}
bool JsonObj_c::FetchBoolItem ( bool & bValue, const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tItem = GetBoolItem ( szName, sError, bIgnoreMissing );
if ( tItem )
bValue = tItem.BoolVal();
else if ( !sError.IsEmpty() )
return false;
return true;
}
bool JsonObj_c::FetchStrItem ( CSphString & sValue, const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tItem = GetStrItem ( szName, sError, bIgnoreMissing );
if ( tItem )
sValue = tItem.StrVal();
else if ( !sError.IsEmpty() )
return false;
return true;
}
bool JsonObj_c::HasItem ( const char * szItem ) const
{
assert ( m_pRoot );
return !!cJSON_HasObjectItem ( m_pRoot, szItem );
}
JsonObj_c JsonObj_c::CreateInt ( int64_t iInt )
{
return JsonObj_c ( cJSON_CreateInteger(iInt) );
}
JsonObj_c JsonObj_c::CreateUint ( uint64_t uInt )
{
return JsonObj_c ( cJSON_CreateUInteger(uInt) );
}
JsonObj_c JsonObj_c::CreateStr ( const CSphString & sStr )
{
return JsonObj_c ( cJSON_CreateString ( sStr.cstr() ) );
}
bool JsonObj_c::Empty() const
{
return !m_pRoot;
}
const char * JsonObj_c::Name() const
{
assert ( m_pRoot );
return m_pRoot->string;
}
int64_t JsonObj_c::IntVal() const
{
assert ( m_pRoot );
return m_pRoot->valueint;
}
bool JsonObj_c::BoolVal() const
{
assert ( m_pRoot );
return !!cJSON_IsTrue(m_pRoot);
}
float JsonObj_c::FltVal() const
{
return (float)DblVal();
}
double JsonObj_c::DblVal() const
{
assert ( m_pRoot );
return m_pRoot->valuedouble;
}
const char * JsonObj_c::SzVal() const
{
assert ( m_pRoot );
return m_pRoot->valuestring;
}
CSphString JsonObj_c::StrVal() const
{
assert ( m_pRoot );
return m_pRoot->valuestring;
}
const char * JsonObj_c::GetErrorPtr() const
{
return cJSON_GetErrorPtr();
}
bool JsonObj_c::GetError ( const char * szBuf, int iBufLen, CSphString & sError ) const
{
if ( !GetErrorPtr() )
return false;
const int iErrorWindowLen = 20;
const char * szErrorStart = GetErrorPtr() - iErrorWindowLen/2;
if ( szErrorStart < szBuf )
szErrorStart = szBuf;
int iLen = iErrorWindowLen;
if ( szErrorStart-szBuf+iLen>iBufLen )
iLen = iBufLen - int ( szErrorStart - szBuf );
sError.SetSprintf ( "JSON parse error at: %.*s", iLen, szErrorStart );
return true;
}
bool JsonObj_c::GetError( const char* szBuf, int iBufLen ) const
{
CSphString sError;
if ( GetError ( szBuf, iBufLen, sError ) )
return !TlsMsg::Err ( sError );
return false;
}
cJSON * JsonObj_c::Leak()
{
cJSON * pRoot = m_pRoot;
m_pRoot = nullptr;
return pRoot;
}
JsonObj_c JsonObj_c::GetChild ( const char * szName, CSphString & sError, bool bIgnoreMissing ) const
{
JsonObj_c tChild = GetItem(szName);
if ( !tChild )
{
if ( !bIgnoreMissing )
sError.SetSprintf ( "\"%s\" property missing", szName );
return JsonNull;
}
return tChild;
}
cJSON * JsonObj_c::GetRoot() const
{
return m_pRoot;
}
CSphString JsonObj_c::AsString ( bool bFormat ) const
{
if ( m_pRoot )
{
// we can't take this string and just adopt it because we need extra 'gap' bytes at the end
char * szResult;
if ( bFormat )
szResult = cJSON_Print ( m_pRoot );
else
szResult = cJSON_PrintUnformatted ( m_pRoot );
CSphString sResult ( szResult );
cJsonFree ( szResult );
return sResult;
}
return "";
}
JsonObj_c & JsonObj_c::operator++()
{
if ( m_pRoot )
m_pRoot = m_pRoot->next;
return *this;
}
JsonObj_c JsonObj_c::operator*()
{
return JsonObj_c(m_pRoot,false);
}
JsonObj_c JsonObj_c::begin() const
{
return JsonObj_c ( m_pRoot ? m_pRoot->child : nullptr, false );
}
JsonObj_c JsonObj_c::end() const
{
return JsonNull;
}
void JsonObj_c::ReplaceItem ( int iIndex, JsonObj_c & tObj )
{
assert ( m_pRoot );
assert ( cJSON_IsArray ( m_pRoot ) );
assert ( iIndex<cJSON_GetArraySize ( m_pRoot ) );
cJSON_ReplaceItemInArray ( m_pRoot, iIndex, tObj.Leak() );
}
JsonObj_c JsonObj_c::Clone () const
{
if ( !m_pRoot )
return JsonNull;
JsonObj_c tNew ( cJSON_Duplicate ( m_pRoot, true ) );
return tNew;
}
const char * JsonObj_c::TypeName() const
{
if ( !m_pRoot )
return "invalid";
switch ( m_pRoot->type & 0xFF )
{
case cJSON_False:
case cJSON_True:
return "bool";
case cJSON_NULL:
return "null";
case cJSON_Number:
return "double";
case cJSON_Integer:
return "integet";
case cJSON_UInteger:
return "unsigned";
case cJSON_String:
return "string";
case cJSON_Raw:
return "raw";
case cJSON_Array:
return "array";
case cJSON_Object:
return "object";
default:
return "invalid";
}
}
//////////////////////////////////////////////////////////////////////////
using namespace bson;
bool bson::IsAssoc ( const NodeHandle_t & dNode )
{
return dNode.second==JSON_ROOT || dNode.second==JSON_OBJECT;
}
bool bson::IsArray ( const NodeHandle_t &dNode )
{
return dNode.second==JSON_STRING_VECTOR
|| dNode.second==JSON_MIXED_VECTOR
|| dNode.second==JSON_INT32_VECTOR
|| dNode.second==JSON_INT64_VECTOR
|| dNode.second==JSON_DOUBLE_VECTOR;
}
bool bson::IsPODBlob ( const NodeHandle_t &dNode )
{
return dNode.second==JSON_STRING
|| dNode.second==JSON_INT32_VECTOR
|| dNode.second==JSON_INT64_VECTOR
|| dNode.second==JSON_DOUBLE_VECTOR;
}
bool bson::IsString ( const NodeHandle_t &dNode )
{
return dNode.second==JSON_STRING;
}
bool bson::IsInt ( const NodeHandle_t &dNode )
{
return dNode.second==JSON_INT32
|| dNode.second==JSON_INT64;
}
bool bson::IsDouble ( const NodeHandle_t &dNode )
{
return dNode.second==JSON_DOUBLE;
}
bool bson::IsNumeric ( const NodeHandle_t &dNode )
{
return IsInt ( dNode ) || IsDouble ( dNode );
}
bool bson::Bool ( const NodeHandle_t &tLocator, bool bDefault )
{
switch ( tLocator.second )
{
case JSON_INT32:
case JSON_INT64: return !!Int ( tLocator );
case JSON_DOUBLE: return 0.0!=Double ( tLocator );
case JSON_TRUE: return true;
case JSON_FALSE: return false;
// fixme! Do we need also process here values like "True" (the string)?
default: break;
}
return bDefault;
}
int64_t bson::Int ( const NodeHandle_t &tLocator, int64_t iDefault )
{
const BYTE * p = tLocator.first;
switch ( tLocator.second )
{
case JSON_INT32: return GetNUM32LE<int> ( p );
case JSON_INT64: return sphJsonLoadBigint ( &p );
case JSON_DOUBLE: return int64_t ( sphQW2D ( sphJsonLoadBigint ( &p ) ) );
case JSON_TRUE: return 1;
case JSON_FALSE: return 0;
case JSON_STRING:
{
auto dBlob = RawBlob ( tLocator );
if ( !dBlob.second )
return 0;
ESphJsonType eType;
double fValue;
int64_t iValue;
if ( !sphJsonStringToNumber ( dBlob.first, dBlob.second, eType, iValue, fValue ) )
return 0;
if ( eType==JSON_DOUBLE )
return int64_t ( fValue );
return iValue;
}
default: break;
}
return iDefault;
}
double bson::Double ( const NodeHandle_t &tLocator, double fDefault )
{
const BYTE * p = tLocator.first;
switch ( tLocator.second )
{
case JSON_INT32: return GetNUM32LE<int> ( tLocator.first );
case JSON_INT64: return sphJsonLoadBigint ( &p );
case JSON_DOUBLE: return sphQW2D ( sphJsonLoadBigint ( &p ) );
case JSON_TRUE: return 1.0;
case JSON_FALSE: return 0.0;
case JSON_STRING:
{
auto dBlob = RawBlob ( tLocator );
if ( !dBlob.second )
return 0.0;
ESphJsonType eType;
double fValue;
int64_t iValue;
if ( !sphJsonStringToNumber ( dBlob.first, dBlob.second, eType, iValue, fValue ) )
return 0.0;
if ( eType==JSON_DOUBLE )
return fValue;
return iValue;
}
default: break;
}
return fDefault;
}
CSphString bson::String ( const NodeHandle_t &tLocator, CSphString sDefault )
{
if ( tLocator.second!=JSON_STRING )
return sDefault;
return CSphString { bson::RawBlob ( tLocator ) };
}
Str_t bson::ToStr ( const NodeHandle_t & tLocator )
{
if ( tLocator.second!=JSON_STRING )
return dEmptyStr;
auto dBlob = bson::RawBlob ( tLocator );
return dBlob;
}
void bson::ForEach ( const NodeHandle_t &tLocator, Action_f&& fAction )
{
const BYTE * p = tLocator.first;
switch ( tLocator.second )
{
case JSON_STRING_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
fAction ( { p, JSON_STRING } );
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen;
}
break;
}
case JSON_MIXED_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
auto eType = ( ESphJsonType ) *p++;
fAction ( { p, eType } );
sphJsonSkipNode ( eType, &p );
}
break;
}
case JSON_OBJECT: sphJsonUnpackInt ( &p );
// [[clang::fallthrough]];
case JSON_ROOT:
{
p += 4; // skip bloom
while ( true )
{
auto eType = ( ESphJsonType ) *p++;
if ( eType==JSON_EOF )
return;
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen; // skip name
fAction ( { p, eType } );
sphJsonSkipNode ( eType, &p );
}
}
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
{
auto eType = sphJsonGetCoreType ( tLocator.second );
auto iSize = sphJsonSingleNodeSize ( eType );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
fAction ( { p, eType } );
p += iSize;
}
break;
}
default: break;
}
}
void bson::ForEach ( const NodeHandle_t &tLocator, NamedAction_f&& fAction )
{
const BYTE * p = tLocator.first;
switch ( tLocator.second )
{
case JSON_STRING_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
fAction ( "", { p, JSON_STRING } );
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen;
}
break;
}
case JSON_MIXED_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
auto eType = ( ESphJsonType ) *p++;
fAction ( "", { p, eType } );
sphJsonSkipNode ( eType, &p );
}
break;
}
case JSON_OBJECT: sphJsonUnpackInt ( &p );
// [[clang::fallthrough]];
case JSON_ROOT:
{
p += 4; // skip bloom
while ( true )
{
auto eType = ( ESphJsonType ) *p++;
if ( eType==JSON_EOF )
return;
int iStrLen = sphJsonUnpackInt ( &p );
CSphString sName ( ( const char * ) p, iStrLen );
p += iStrLen; // skip name
fAction ( std::move (sName), { p, eType } );
sphJsonSkipNode ( eType, &p );
}
}
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
{
auto eType = sphJsonGetCoreType ( tLocator.second );
auto iSize = sphJsonSingleNodeSize ( eType );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
fAction ( "", { p, eType } );
p += iSize;
}
break;
}
default: break;
}
}
void bson::ForSome ( const NodeHandle_t &tLocator, CondAction_f&& fAction )
{
const BYTE * p = tLocator.first;
switch ( tLocator.second )
{
case JSON_STRING_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
if ( !fAction ( { p, JSON_STRING } ) )
return;
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen;
}
break;
}
case JSON_MIXED_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
auto eType = ( ESphJsonType ) *p++;
if ( !fAction ( { p, eType } ) )
return;
sphJsonSkipNode ( eType, &p );
}
break;
}
case JSON_OBJECT: sphJsonUnpackInt ( &p );
// [[clang::fallthrough]];
case JSON_ROOT:
{
p += 4; // skip bloom
while ( true )
{
auto eType = ( ESphJsonType ) *p++;
if ( eType==JSON_EOF )
return;
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen; // skip name
if ( !fAction ( { p, eType } ) )
return;
sphJsonSkipNode ( eType, &p );
}
}
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
{
auto eType = sphJsonGetCoreType ( tLocator.second );
auto iSize = sphJsonSingleNodeSize ( eType );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
if ( !fAction ( { p, eType } ) )
return;
p += iSize;
}
break;
}
default: break;
}
}
void bson::ForSome ( const NodeHandle_t &tLocator, CondNamedAction_f&& fAction )
{
const BYTE * p = tLocator.first;
switch ( tLocator.second )
{
case JSON_STRING_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
if ( !fAction ( "", { p, JSON_STRING } ) )
return;
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen;
}
break;
}
case JSON_MIXED_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
for ( int i = 0; i<iLen; ++i )
{
auto eType = ( ESphJsonType ) *p++;
if ( !fAction ( "", { p, eType } ) )
return;
sphJsonSkipNode ( eType, &p );
}
break;
}
case JSON_OBJECT: sphJsonUnpackInt ( &p );
// [[clang::fallthrough]];
case JSON_ROOT:
{
p += 4; // skip bloom
while ( true )
{
auto eType = ( ESphJsonType ) *p++;
if ( eType==JSON_EOF )
return;
int iStrLen = sphJsonUnpackInt ( &p );
CSphString sName ( ( const char * ) p, iStrLen );
p += iStrLen; // skip name
if ( !fAction ( std::move (sName), { p, eType } ) )
return;
sphJsonSkipNode ( eType, &p );
}
}
default: break;
}
}
Str_t bson::RawBlob ( const NodeHandle_t &tLocator )
{
if ( ::IsPODBlob ( tLocator ) )
{
const BYTE * p = tLocator.first;
int iLen = sphJsonUnpackInt ( &p );
return { ( const char * ) p, iLen };
}
return { nullptr, 0 };
}
Bson_c::Bson_c ( const VecTraits_T<BYTE> &dBlob )
{
if ( dBlob.IsEmpty () )
return;
const BYTE * pData = dBlob.begin ();
m_dData.second = sphJsonFindFirst ( &pData );
m_dData.first = pData;
}
// fast lookup (no need to iterate just to know if empty or not)
bool Bson_c::IsEmpty() const
{
const BYTE * p = m_dData.first;
switch ( m_dData.second )
{
case JSON_STRING_VECTOR: case JSON_MIXED_VECTOR:
sphJsonUnpackInt ( &p ); return 0==sphJsonUnpackInt ( &p );
case JSON_INT32_VECTOR: case JSON_INT64_VECTOR: case JSON_DOUBLE_VECTOR: case JSON_STRING:
return 0==sphJsonUnpackInt ( &p );
case JSON_OBJECT:
sphJsonUnpackInt ( &p ); // skip size, no break then
// [[clang::fallthrough]];
case JSON_ROOT:
return JSON_EOF == ( ESphJsonType ) p[4]; // skip bloom filter
default:
return true;
}
}
int Bson_c::CountValues () const
{
return sphJsonFieldLength ( m_dData.second, m_dData.first );
}
int Bson_c::StandaloneSize() const
{
const BYTE * p = m_dData.first;
switch ( m_dData.second )
{
case JSON_ROOT:
return sphJsonNodeSize ( JSON_ROOT, p );
case JSON_OBJECT:
return sphJsonUnpackInt ( &p );
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
case JSON_STRING_VECTOR:
case JSON_MIXED_VECTOR:
{
int iSize = sphJsonNodeSize ( m_dData.second, p );
if ( iSize<0 )
break;
return 5 + iSize;
}
case JSON_EOF:
return 5; // eof is actually empty root.
default:
break;
}
// technically speaking we can easy return here any other type (as INT, TRUE, etc) in root,
// but our original parser returns _only_ object or array in the root
return -1;
}
bool Bson_c::StrEq ( const char * sValue ) const
{
if ( !::IsString ( m_dData ) )
return false;
const BYTE * p = m_dData.first;
int iStrLen = sphJsonUnpackInt ( &p );
auto iLen = (int) strlen ( sValue );
if ( iStrLen==iLen && !memcmp ( p, sValue, iStrLen ) )
return true;
return false;
}
NodeHandle_t Bson_c::ChildByName ( const char * sName ) const
{
// access by key available only for 'root' or 'object' types
if ( !IsAssoc () )
return nullnode;
const BYTE * p = m_dData.first;
if ( m_dData.second==JSON_OBJECT )
sphJsonUnpackInt ( &p );
auto iLen = (int) strlen ( sName );
// fast reject by bloom filter
auto uMask = sphJsonKeyMask ( sName, iLen );
if ( ( sphGetDword ( p ) & uMask )!=uMask )
{
m_sError << "No such member " << sName;
return nullnode;
}
p += 4;
while ( true )
{
auto eType = ( ESphJsonType ) *p++;
if ( eType==JSON_EOF )
return nullnode;
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen;
if ( iStrLen==iLen && !memcmp ( p - iStrLen, sName, iStrLen ) )
return { p, eType };
sphJsonSkipNode ( eType, &p );
}
}
NodeHandle_t Bson_c::ChildByIndex ( int iIndex ) const
{
if ( iIndex<0 )
return nullnode;
// access by index available only for vectors
if ( !IsArray () )
return nullnode;
const BYTE * p = m_dData.first;
switch ( m_dData.second )
{
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
{
int iLen = sphJsonUnpackInt ( &p );
if ( iIndex>=iLen )
{
m_sError.Sprintf ( "In POD vector index %d is ouf of bound (%d)", iIndex, iLen );
return nullnode;
}
p += iIndex * ( m_dData.second==JSON_INT32_VECTOR ? 4 : 8 );
ESphJsonType eType = m_dData.second==JSON_INT32_VECTOR ? JSON_INT32
: m_dData.second==JSON_INT64_VECTOR ? JSON_INT64
: JSON_DOUBLE;
return { p, eType };
}
case JSON_STRING_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
if ( iIndex>=iLen )
{
m_sError.Sprintf ( "In string vector index %d is ouf of bound (%d)", iIndex, iLen );
return nullnode;
}
for ( int i = 0; i<iIndex; ++i )
{
int iStrLen = sphJsonUnpackInt ( &p );
p += iStrLen;
}
return { p, JSON_STRING };
}
case JSON_MIXED_VECTOR:
{
sphJsonUnpackInt ( &p );
int iLen = sphJsonUnpackInt ( &p );
if ( iIndex>=iLen )
{
m_sError.Sprintf ( "In mixed vector index %d is ouf of bound (%d)", iIndex, iLen );
return nullnode;
}
for ( int i = 0; i<iIndex; ++i )
{
auto eType = ( ESphJsonType ) *p++;
sphJsonSkipNode ( eType, &p );
}
return { p + 1, ( ESphJsonType ) *p };
}
default: break;
}
m_sError << "Node is not indexable";
return nullnode;
}
NodeHandle_t Bson_c::ChildByPath ( const char * sPath ) const
{
auto p = nullnode;
StrVec_t dMembers;
// split sPath by '.', then iterate by the chunks
sphSplit ( dMembers, sPath, "." );
for ( const auto &sMember : dMembers )
{
// split a chunk by '[', then iterate by chunks
StrVec_t dIndices;
sphSplit ( dIndices, sMember.scstr (), "[" );
if ( dIndices.GetLength ()<1 )
{
m_sError << "something wrong in parsing " << sMember << " member of " << sPath;
return nullnode;
}
auto &sKey = dIndices[0];
// check if we're start from scratch
if ( p==nullnode )
p = m_dData;
// first chunk is name. Navigate there
if ( !sKey.IsEmpty () )
p = Bson_c ( p ).ChildByName ( sKey.scstr () );
if ( p==nullnode )
return nullnode; // error! can't get by name...
// walk throw indices
for ( int i = 1; i<dIndices.GetLength (); ++i )
{
auto &sIdx = dIndices[i];
sIdx.Trim ();
if ( *sIdx.scstr ()==']' ) // obvious error of empty array
{
m_sError << "Can't look by empty index! " << sIdx;
return nullnode;
}
// convert str to int
char * sEnd;
auto iIdx = ( int ) strtoll ( sIdx.scstr (), &sEnd, 10 );
if ( *sEnd!=']' )
{
m_sError << "Can't convert index from string! " << sIdx;
return nullnode; // error! can't convert index from string
}
p = Bson_c ( p ).ChildByIndex ( iIdx );
if ( p==nullnode )
return nullnode; // error! can't get by idx...
}
}
return p;
}
bool Bson_c::HasAnyOf ( int iNames, ... ) const
{
// access by key available only for 'root' or 'object' types
if ( !IsAssoc () )
return false;
va_list ap;
va_start ( ap, iNames );
CSphFixedVector<const char*> dNames (iNames);
for ( auto& sName : dNames )
sName = va_arg ( ap, const char * );
va_end ( ap );
const BYTE * p = m_dData.first;
if ( m_dData.second==JSON_OBJECT )
sphJsonUnpackInt ( &p );
// fast reject by bloom filter
DWORD uNodeMask = sphGetDword ( p );
bool bMayBe = false;
for ( const char * sName : dNames )
{
auto iLen = (int) strlen ( sName );
auto uMask = sphJsonKeyMask ( sName, iLen );
bMayBe |= ( ( uNodeMask & uMask )==uMask );
if ( bMayBe )
break;
}
if ( !bMayBe ) // all bloom tries rejected
return false;
p += 4; // skip the bloom
while ( true )
{
auto eType = ( ESphJsonType ) *p++;
if ( eType==JSON_EOF )
return false;
int iStrLen = sphJsonUnpackInt ( &p );
for ( const char * sName : dNames )
{
auto iLen = (int) strlen ( sName );
if ( iStrLen==iLen && !memcmp ( p, sName, iStrLen ) )
return true;
}
p += iStrLen;
sphJsonSkipNode ( eType, &p );
}
}
bool Bson_c::HasAnyOf ( std::initializer_list<const char *> dNames ) const
{
// access by key available only for 'root' or 'object' types
if ( !IsAssoc () )
return false;
const BYTE * p = m_dData.first;
if ( m_dData.second==JSON_OBJECT )
sphJsonUnpackInt ( &p );
// fast reject by bloom filter
DWORD uNodeMask = sphGetDword ( p );
bool bMayBe = false;
for ( const char * sName : dNames )
{
auto iLen = (int) strlen ( sName );
auto uMask = sphJsonKeyMask ( sName, iLen );
bMayBe |= ( ( uNodeMask & uMask )==uMask );
if ( bMayBe )
break;
}
if ( !bMayBe ) // all bloom tries rejected
return false;
p += 4; // skip the bloom
while ( true )
{
auto eType = (ESphJsonType) *p++;
if ( eType==JSON_EOF )
return false;
int iStrLen = sphJsonUnpackInt ( &p );
for ( const char * sName : dNames )
{
auto iLen = (int) strlen ( sName );
if ( iStrLen==iLen && !memcmp ( p, sName, iStrLen ) )
return true;
}
p += iStrLen;
sphJsonSkipNode ( eType, &p );
}
}
std::pair<int, NodeHandle_t> Bson_c::GetFirstOf ( std::initializer_list<const char *> dNames ) const
{
// access by key available only for 'root' or 'object' types
if ( !IsAssoc () )
return { -1, nullnode };
const BYTE * p = m_dData.first;
if ( m_dData.second==JSON_OBJECT )
sphJsonUnpackInt ( &p );
// fast reject by bloom filter
DWORD uNodeMask = sphGetDword ( p );
bool bMayBe = false;
for ( const char * sName : dNames )
{
auto iLen = (int) strlen ( sName );
auto uMask = sphJsonKeyMask ( sName, iLen );
bMayBe |= ( ( uNodeMask & uMask )==uMask );
if ( bMayBe )
break;
}
if ( !bMayBe ) // all bloom tries rejected
return { -1, nullnode };
p += 4; // skip the bloom
while ( true )
{
auto eType = (ESphJsonType) *p++;
if ( eType==JSON_EOF )
return { -1, nullnode };
int iStrLen = sphJsonUnpackInt ( &p );
int iIdx = 0;
for ( const char * sName : dNames )
{
auto iLen = (int) strlen ( sName );
if ( iStrLen==iLen && !memcmp ( p, sName, iStrLen ) )
return { iIdx, { p+iStrLen, eType } };
++iIdx;
}
p += iStrLen;
sphJsonSkipNode ( eType, &p );
}
}
bool Bson_c::Bool () const
{
return bson::Bool ( m_dData );
}
int64_t Bson_c::Int () const
{
return bson::Int ( m_dData );
}
double Bson_c::Double () const
{
if ( m_dData.second==JSON_STRING )
{
auto dBlob = RawBlob ( m_dData );
if ( !dBlob.second )
{
m_sError << "empty string passed to float conversion";
return 0.0;
}
ESphJsonType eType;
double fValue;
int64_t iValue;
if ( !sphJsonStringToNumber ( dBlob.first, dBlob.second, eType, iValue, fValue ) )
{
m_sError << "Error in conversion " << CSphString ( dBlob.first, dBlob.second )
<< " to double";
return 0.0;
}
if ( eType==JSON_DOUBLE )
return fValue;
return iValue;
}
return bson::Double ( m_dData );
}
CSphString Bson_c::String () const
{
return bson::String ( m_dData );
}
void Bson_c::ForEach ( Action_f&& fAction ) const
{
bson::ForEach ( m_dData, std::move ( fAction ) );
}
void Bson_c::ForEach ( NamedAction_f&& fAction ) const
{
bson::ForEach ( m_dData, std::move ( fAction ) );
}
void Bson_c::ForSome ( CondAction_f&& fAction ) const
{
bson::ForSome ( m_dData, std::move ( fAction ) );
}
void Bson_c::ForSome ( CondNamedAction_f&& fAction ) const
{
bson::ForSome ( m_dData, std::move ( fAction ) );
}
bool Bson_c::BsonToJson ( CSphString & sResult ) const
{
return BsonToJson ( sResult, true );
}
bool Bson_c::BsonToJson ( CSphString & sResult, bool bQuot ) const
{
JsonEscapedBuilder sBuilder;
if ( !m_dData.first )
return false;
// check for the empty root
if ( m_dData.second==JSON_EOF )
sBuilder << "{}";
else
sphJsonFieldFormat ( sBuilder, m_dData.first, m_dData.second, bQuot );
sBuilder.MoveTo ( sResult );
return true;
}
bool Bson_c::BsonToBson ( BYTE* pDst ) const
{
switch ( m_dData.second )
{
case JSON_ROOT: // root - just dump as is
memcpy ( pDst, m_dData.first, sphJsonNodeSize ( JSON_ROOT, m_dData.first ) );
break;
case JSON_OBJECT: // object - throw out first packed int (len), then save as is (it became root then)
{
const BYTE * p = m_dData.first;
int iLen = sphJsonUnpackInt ( &p );
memcpy ( pDst, p, iLen );
}
break;
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
case JSON_STRING_VECTOR:
case JSON_MIXED_VECTOR: // arrays - write zero bloom, then type, then dump the node (artificial root)
StoreNUM32LE ( pDst, 0 );
pDst[4] = m_dData.second;
memcpy ( pDst+5, m_dData.first, sphJsonNodeSize ( m_dData.second, m_dData.first ) );
break;
case JSON_EOF:
StoreNUM32LE ( pDst, 0 );
pDst[4] = JSON_EOF;
break;
default: return false;
}
return true;
}
bool Bson_c::BsonToBson ( CSphVector<BYTE> &dOutput ) const
{
int iSize = StandaloneSize ();
if ( iSize<0 )
return false;
dOutput.Resize ( iSize );
return BsonToBson ( dOutput.begin() );
}
const char * Bson_c::sError () const
{
return m_sError.cstr();
}
BsonIterator_c::BsonIterator_c ( const NodeHandle_t &dParent )
{
if ( bson::IsNullNode ( dParent ) )
return;
m_pData = dParent.first;
m_eType = dParent.second;
switch ( m_eType )
{
case JSON_STRING_VECTOR:
sphJsonUnpackInt ( &m_pData );
m_iSize = sphJsonUnpackInt ( &m_pData );
m_dData = { m_pData, JSON_STRING };
break;
case JSON_MIXED_VECTOR:
sphJsonUnpackInt ( &m_pData );
m_iSize = sphJsonUnpackInt ( &m_pData );
m_dData.second = ESphJsonType ( *m_pData++ );
m_dData.first = m_pData;
break;
case JSON_OBJECT: sphJsonUnpackInt ( &m_pData );
// [[clang::fallthrough]];
case JSON_ROOT:
{
m_pData += 4; // skip bloom
m_dData.second = ESphJsonType ( *m_pData++ );
if ( m_dData.second == JSON_EOF )
Finish();
else
{
int iStrLen = sphJsonUnpackInt ( &m_pData );
m_sName.SetBinary ( ( const char * ) m_pData, iStrLen );
m_pData += iStrLen;
m_dData.first = m_pData;
}
break;
}
case JSON_INT32_VECTOR:
m_iSize = sphJsonUnpackInt ( &m_pData );
m_dData = { m_pData, JSON_INT32 };
break;
case JSON_INT64_VECTOR:
m_iSize = sphJsonUnpackInt ( &m_pData );
m_dData = { m_pData, JSON_INT64 };
break;
case JSON_DOUBLE_VECTOR:
m_iSize = sphJsonUnpackInt ( &m_pData );
m_dData = { m_pData, JSON_DOUBLE };
break;
case JSON_INT32:
case JSON_INT64:
case JSON_DOUBLE:
case JSON_STRING:
case JSON_TRUE:
case JSON_FALSE:
case JSON_NULL:
m_iSize = 1;
m_dData = dParent;
break;
case JSON_EOF:
Finish();
break;
default: break;
}
if ( !m_iSize )
Finish();
}
bool BsonIterator_c::Next()
{
switch ( m_eType )
{
case JSON_INT32:
case JSON_INT64:
case JSON_DOUBLE:
case JSON_STRING:
case JSON_TRUE:
case JSON_FALSE:
case JSON_NULL:
case JSON_EOF:
// nowhere to step next
return Finish();
case JSON_OBJECT: // these two have EOF as marker; no size.
case JSON_ROOT:
{
sphJsonSkipNode ( m_dData.second, &m_pData );
m_dData.second = ESphJsonType ( *m_pData );
if ( m_dData.second==JSON_EOF ) // in case of empty root/obj EOF is already here
return Finish ();
++m_pData;
int iStrLen = sphJsonUnpackInt ( &m_pData );
m_sName.SetBinary ( ( const char * ) m_pData, iStrLen );
m_pData += iStrLen;
m_dData.first = m_pData;
break;
}
case JSON_STRING_VECTOR: // these have size
case JSON_INT32_VECTOR:
case JSON_INT64_VECTOR:
case JSON_DOUBLE_VECTOR:
case JSON_MIXED_VECTOR:
--m_iSize;
if (m_iSize<=0)
return Finish ();
sphJsonSkipNode ( m_dData.second, &m_pData );
if ( m_eType==JSON_MIXED_VECTOR )
m_dData.second = ESphJsonType ( *m_pData++ );
m_dData.first = m_pData;
break;
default:
break;
}
return true;
}
inline ESphJsonType cJson2BsonType ( int iCjsonType )
{
const ESphJsonType BsonTypes[] = { JSON_TOTAL, JSON_FALSE, JSON_TRUE, JSON_NULL, JSON_DOUBLE, JSON_STRING
, JSON_MIXED_VECTOR, JSON_OBJECT, JSON_TOTAL, JSON_INT64 };
assert ( ( iCjsonType & 0xFF )>=0 );
assert ( ( iCjsonType & 0xFF )<sizeof ( BsonTypes ) );
return BsonTypes[iCjsonType & 0xFF];
}
class CJsonHelper
{
BsonHelper m_dStorage;
bool m_bAutoconv;
bool m_bToLowercase;
// StringBuilder_c m_sError;
public:
CJsonHelper ( CSphVector<BYTE> &dBuffer, bool bAutoconv, bool bToLowercase )
: m_dStorage ( dBuffer )
, m_bAutoconv ( bAutoconv )
, m_bToLowercase ( bToLowercase )
{}
inline ESphJsonType NumericFixup ( cJSON * pNode )
{
auto eOrigType = cJson2BsonType ( pNode->type );
// auto-convert string values, if necessary
if ( m_bAutoconv && eOrigType==JSON_STRING )
{
int64_t iFoo;
if ( !sphJsonStringToNumber ( pNode->valuestring, (int) strlen ( pNode->valuestring ), eOrigType, iFoo, pNode->valuedouble ) )
return eOrigType;
pNode->valueint = iFoo;
}
if ( eOrigType==JSON_INT64 && pNode->valueint==int64_t ( int ( pNode->valueint ) ) )
return JSON_INT32;
return eOrigType;
}
inline int MeasureAndOptimizeVector ( cJSON * pCJSON, ESphJsonType &eType )
{
int iSize = 0;
ESphJsonType eOutType = JSON_TOTAL;
cJSON * pNode;
bool bAllSame = true;
cJSON_ArrayForEach( pNode, pCJSON )
{
if ( !iSize )
eOutType = NumericFixup ( pNode );
else if ( bAllSame && ( eOutType!=NumericFixup ( pNode ) ) )
bAllSame = false;
++iSize;
}
if ( !iSize )
return 0;
if ( bAllSame )
switch ( eOutType )
{
case JSON_INT32: eType = JSON_INT32_VECTOR; break;
case JSON_INT64: eType = JSON_INT64_VECTOR; break;
case JSON_DOUBLE: eType = JSON_DOUBLE_VECTOR; break;
case JSON_STRING: eType = JSON_STRING_VECTOR; break;
default: break;
}
return iSize;
}
// save cjson as bson
bool cJsonToBsonNode ( cJSON * pCJSON, const char * sName = nullptr )
{
auto eType = NumericFixup ( pCJSON );
int iSize = 0; // have sense only for vectors
if ( eType==JSON_MIXED_VECTOR )
iSize = MeasureAndOptimizeVector ( pCJSON, eType );
m_dStorage.Add ( eType );
if ( sName )
m_dStorage.PackStr ( sName );
cJSON * pNode; // used in cJSON_ArrayForEach iterations
switch ( eType )
{
// basic types
case JSON_INT32: m_dStorage.StoreInt ( ( int ) pCJSON->valueint ); break;
case JSON_INT64: m_dStorage.StoreBigint ( pCJSON->valueint ); break;
case JSON_DOUBLE: m_dStorage.StoreBigint ( sphD2QW ( pCJSON->valuedouble ) ); break;
case JSON_STRING: m_dStorage.PackStr ( pCJSON->valuestring ); break;
// literals
case JSON_TRUE:
case JSON_FALSE:
case JSON_NULL:
// no content
break;
// associative arrays
case JSON_OBJECT:
{
DWORD uMask = 0;
int iOfs = m_dStorage.ReserveSize ();
m_dStorage.StoreInt ( 0 ); // place for mask
if ( m_bToLowercase )
{
cJSON_ArrayForEach( pNode, pCJSON )
{
auto iLen = (int) strlen ( pNode->string );
for ( auto i = 0; i<iLen; ++i )
pNode->string[i] = Mytolower ( pNode->string[i] );
uMask |= KeyMask ( pNode->string );
cJsonToBsonNode ( pNode, pNode->string );
}
} else
{
cJSON_ArrayForEach( pNode, pCJSON )
{
uMask |= KeyMask ( pNode->string );
cJsonToBsonNode ( pNode, pNode->string );
}
}
m_dStorage.Add ( JSON_EOF );
m_dStorage.StoreMask ( iOfs + 1, uMask );
m_dStorage.PackSize ( iOfs ); // MUST be in this order, because PackSize() might move the data!
break;
}
// mixed array
case JSON_MIXED_VECTOR:
{
int iOfs = m_dStorage.ReserveSize ();
m_dStorage.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pCJSON )
cJsonToBsonNode ( pNode );
m_dStorage.PackSize ( iOfs );
break;
}
// optimized (generic) arrays
case JSON_INT32_VECTOR: m_dStorage.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pCJSON )
m_dStorage.StoreInt ( ( int ) pNode->valueint );
break;
case JSON_INT64_VECTOR: m_dStorage.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pCJSON )
m_dStorage.StoreBigint ( pNode->valueint );
break;
case JSON_DOUBLE_VECTOR: m_dStorage.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pCJSON )
m_dStorage.StoreBigint ( sphD2QW ( pNode->valuedouble ) );
break;
case JSON_STRING_VECTOR:
{
int iOfs = m_dStorage.ReserveSize ();
m_dStorage.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pCJSON )
m_dStorage.PackStr ( pNode->valuestring );
m_dStorage.PackSize ( iOfs );
break;
}
default: assert ( 0 && "internal error: unhandled type" );
return false;
}
return true;
}
// save cjson as bson
bool cJsonToBson ( cJSON * pCJSON )
{
assert ( pCJSON );
if ( ( pCJSON->type & 0xFF )!=cJSON_Object ) // topmost obj write as 'root'
return cJsonToBsonNode ( pCJSON );
DWORD uMask = 0;
cJSON * pNode;
if ( m_bToLowercase )
{
cJSON_ArrayForEach( pNode, pCJSON )
{
auto iLen = (int) strlen ( pNode->string );
for ( auto i = 0; i<iLen; ++i )
pNode->string[i] = Mytolower ( pNode->string[i] );
uMask |= KeyMask ( pNode->string );
cJsonToBsonNode ( pNode, pNode->string );
}
} else
{
cJSON_ArrayForEach( pNode, pCJSON )
{
uMask |= KeyMask ( pNode->string );
cJsonToBsonNode ( pNode, pNode->string );
}
}
m_dStorage.Add ( JSON_EOF );
m_dStorage.StoreMask ( 0, uMask );
return true;
}
};
// save cjson as bson
bool bson::JsonObjToBson ( JsonObj_c & tJSON, CSphVector<BYTE> &dData, bool bAutoconv, bool bToLowercase/*, StringBuilder_c &sMsg*/ )
{
return bson::cJsonToBson ( tJSON.GetRoot(), dData, bAutoconv, bToLowercase );
}
bool bson::cJsonToBson ( cJSON * pCJSON, CSphVector<BYTE> &dData, bool bAutoconv, bool bToLowercase/*, StringBuilder_c &sMsg*/ )
{
dData.Resize (0);
CJsonHelper dOut ( dData, bAutoconv, bToLowercase ); // that will write bloom at the beginning
return dOut.cJsonToBson ( pCJSON );
}
BsonContainer_c::BsonContainer_c ( char * sJson, bool bAutoconv, bool bToLowercase, bool bCheckSize )
{
sphJsonParse ( m_Bson, sJson, bAutoconv, bToLowercase, bCheckSize, m_sError );
if ( m_Bson.IsEmpty () )
return;
const BYTE * pData = m_Bson.begin ();
m_dData.second = sphJsonFindFirst ( &pData );
m_dData.first = pData;
}
BsonContainer2_c::BsonContainer2_c ( const char * sJson, bool bAutoconv, bool bToLowercase )
{
auto pCjson = cJSON_Parse ( sJson );
m_Bson.Reserve ( (int) strlen ( sJson ) );
bson::cJsonToBson ( pCjson, m_Bson, bAutoconv, bToLowercase/*, m_sError*/ );
if ( pCjson )
cJSON_Delete ( pCjson );
if ( m_Bson.IsEmpty () )
return;
const BYTE * pData = m_Bson.begin ();
m_dData.second = sphJsonFindFirst ( &pData );
m_dData.first = pData;
}
static bool ValidateAsBson ( const char* szJson, CSphString* pError )
{
CSphString sError;
if ( !pError )
pError = &sError;
CSphVector<BYTE> dBson;
CSphString sJson ( szJson );
return sphJsonParse ( dBson, (char*)sJson.cstr(), false, false, false, *pError );
}
static bool ValidateAsCjson ( const char* szJson )
{
auto pCjson = cJSON_Parse ( szJson );
if ( !pCjson )
return false;
CSphVector<BYTE> dBson;
dBson.Reserve ( (int)strlen ( szJson ) );
bson::cJsonToBson ( pCjson, dBson, false, false );
cJSON_Delete ( pCjson );
return !dBson.IsEmpty();
}
bool bson::ValidateJson ( const char * szJson, JsonParser_e eParse, CSphString * pError )
{
switch ( eParse )
{
case JsonParser_e::BSON:
return ValidateAsBson ( szJson, pError );
case JsonParser_e::CJSON:
return ValidateAsCjson ( szJson );
default: break;
}
return false;
}
bool bson::ValidateJson ( const char* szJson, CSphString* pError )
{
bool bRes = ValidateAsBson ( szJson, pError ) && ValidateAsCjson ( szJson );
return bRes;
}
// unused for now
// bench, then m.b. throw out
/*
static bool sphJsonStringToNumberOld ( const char * s, int iLen, ESphJsonType & eType, int64_t & iVal, double & fVal )
{
// skip whitespace
while ( iLen>0 && ( *s==' ' || *s=='\n' || *s=='\r' || *s=='\t' || *s=='\f' ) )
{
++s;
--iLen;
}
if ( iLen<=0 )
return false;
// check whether the string looks like a numeric
const char * p = s;
const char * pEnd = p+iLen-1;
bool bNumeric = ( *p=='-' || *p=='.' || ( *p>='0' && *p<='9' ) );
bool bDot = ( *p=='.' );
bool bExp = false;
bool bExpSign = false;
while ( bNumeric && p<pEnd )
{
++p;
switch ( *p )
{
case '.':
if ( bDot )
bNumeric = false;
bDot = true;
break;
case 'e':
case 'E':
if ( bExp )
bNumeric = false;
bExp = true;
break;
case '-':
case '+':
if ( !bExp || bExpSign )
bNumeric = false;
bExpSign = true;
break;
default:
if ( *p<'0' || *p >'9' )
bNumeric = false;
}
}
// convert string to number
if ( bNumeric && iLen<32 )
{
char sVal[32];
memcpy ( sVal, s, iLen );
sVal[iLen] = '\0';
char * pCur;
// setting errno to zero is necessary because strtod/strtoll do not indicate
// whether it was an overflow or a valid input for borderline values
errno = 0;
if ( bDot || bExp )
{
double fRes = strtod ( sVal, &pCur );
if ( pCur==sVal+iLen && errno!=ERANGE )
{
eType = JSON_DOUBLE;
fVal = fRes;
return true;
}
} else
{
int64_t iRes = strtoll ( sVal, &pCur, 10 );
if ( pCur==sVal+iLen && errno!=ERANGE )
{
eType = JSON_INT64;
iVal = iRes;
return true;
}
}
}
return false;
}*/
// stuff below used only for testing/benching
// this one makes unescaped version by memmove in-place
int sphJsonUnescape ( char ** pEscaped, int iLen )
{
assert ( pEscaped );
char * s = *pEscaped;
// skip heading and trailing quotes
if ( ( s[0]=='\'' && s[iLen - 1]=='\'' ) || ( s[0]=='\"' && s[iLen - 1]=='\"' ) )
{
++s;
iLen -= 2;
}
char * sMax = s + iLen;
char * d = s;
char * pStart = d;
char sBuf[8] = { 0 };
char * sEscape = nullptr;
while ( s<sMax )
{
if ( s[0]=='\\' )
{
switch ( s[1] )
{
case 'b': *d++ = '\b';
break;
case 'n': *d++ = '\n';
break;
case 'r': *d++ = '\r';
break;
case 't': *d++ = '\t';
break;
case 'f': *d++ = '\f';
break; // formfeed (rfc 4627)
case 'u':
// convert 6-byte sequences \u four-hex-digits (rfc 4627) to UTF-8
if ( s + 6<=sMax && isxdigit ( s[2] ) && isxdigit ( s[3] ) && isxdigit ( s[4] ) && isxdigit ( s[5] ) )
{
memcpy ( sBuf, s + 2, 4 );
d += sphUTF8Encode ( ( BYTE * ) d, ( int ) strtol ( sBuf, NULL, 16 ) );
s += 4;
} else
*d++ = s[1];
break;
default: *d++ = s[1];
}
s += 2;
continue;
}
sEscape = ( char * ) memchr ( s, '\\', sMax - s );
if ( !sEscape )
sEscape = sMax;
auto iChunk = sEscape - s;
memmove ( d, s, iChunk );
d += iChunk;
s += iChunk;
}
*pEscaped = pStart;
return int ( d - pStart );
}
// this one moves finally nothing, just set point inside quotes and returns correct len
int sphJsonUnescape1 ( char ** pEscaped, int iLen )
{
assert ( pEscaped );
char * s = *pEscaped;
// skip heading and trailing quotes
if ( ( s[0]=='\'' && s[iLen - 1]=='\'' ) || ( s[0]=='\"' && s[iLen - 1]=='\"' ) )
{
++s;
iLen -= 2;
}
char * sMax = s + iLen;
char * d = s;
char * pStart = d;
char sBuf[8] = { 0 };
while ( s<sMax )
{
if ( s[0]=='\\' )
{
switch ( s[1] )
{
case 'b': *d++ = '\b';
break;
case 'n': *d++ = '\n';
break;
case 'r': *d++ = '\r';
break;
case 't': *d++ = '\t';
break;
case 'f': *d++ = '\f';
break; // formfeed (rfc 4627)
case 'u':
// convert 6-byte sequences \u four-hex-digits (rfc 4627) to UTF-8
if ( s + 6<=sMax && isxdigit ( s[2] ) && isxdigit ( s[3] ) && isxdigit ( s[4] ) && isxdigit ( s[5] ) )
{
memcpy ( sBuf, s + 2, 4 );
d += sphUTF8Encode ( ( BYTE * ) d, ( int ) strtol ( sBuf, NULL, 16 ) );
s += 4;
} else
*d++ = s[1];
break;
default: *d++ = s[1];
}
s += 2;
} else
*d++ = *s++;
}
*pEscaped = pStart;
return int ( d - pStart );
}
// Code below is non-recursive cJsonToBson.
// It is commented out, since it achieve same speed as recursive, but recursive is more plain to understand.
// Moreover, linear in typical usecases need 4K m for lazy vector (always),
// then will acquire more mem from Heap (if necessary),
// but recursive _can_ eat more, but usually eats less (we just never use so deep-nested jsons).
// So, if some hacker pushes us very-very-nested jsons, we can uncomment and roll to this code.
/*
struct BsonContext_t {
const cJSON * pNext;
DWORD uMask;
int iOfs;
ESphJsonType eType;
};
bool bson::cJsonToBsonLinear ( const cJSON * pNode, CSphVector<BYTE> &dData, StringBuilder_c &sMsg )
{
dData.Resize ( 0 );
CJsonHelper dOut ( dData ); // that will write bloom at the beginning
LazyVector_T<BsonContext_t> dStack;
BsonContext_t tParent;
if ( !pNode ) {
dOut.Add ( JSON_EOF );
return true;
}
if ( ( pNode->type & 0xFF )==cJSON_Object ) // topmost obj write as 'root'
{
tParent = { nullptr, 0, 0, JSON_ROOT };
pNode = pNode->child;
} else
tParent.eType = JSON_EOF;
while (true)
{
if ( !pNode ) // current elem is absent or finished
{
switch ( tParent.eType )
{
case JSON_ROOT: dOut.Add ( JSON_EOF );
dOut.StoreMask ( 0, tParent.uMask );
break;
case JSON_OBJECT: dOut.Add ( JSON_EOF );
dOut.StoreMask ( tParent.iOfs + 1, tParent.uMask );
dOut.PackSize ( tParent.iOfs ); // MUST be in this order, because PackSize() might move the data!
assert ( !dStack.IsEmpty () ); // because topmost object must be root!
break;
case JSON_MIXED_VECTOR: dOut.PackSize ( tParent.iOfs );
break;
default: assert ( 0 && "internal error: unhandled parent type" );
return false;
}
if ( dStack.IsEmpty () )
return true;
tParent = dStack.Pop ();
pNode = tParent.pNext;
continue;
}
auto eType = NumericFixup ( pNode );
int iSize = 0; // have sense only for vectors
if ( eType==JSON_MIXED_VECTOR )
iSize = MeasureAndOptimizeVector ( pNode, eType );
dOut.Add ( eType );
if ( tParent.eType==JSON_OBJECT || tParent.eType==JSON_ROOT )
{
auto iLen = (int) strlen ( pNode->string );
tParent.uMask |= sphJsonKeyMask ( pNode->string, iLen );
dOut.PackStr ( pNode->string, iLen );
}
switch ( eType )
{
// basic types
case JSON_INT32: dOut.StoreInt ( ( int ) pNode->valueint );
break;
case JSON_INT64: dOut.StoreBigint ( pNode->valueint );
break;
case JSON_DOUBLE: dOut.StoreBigint ( sphD2QW ( pNode->valuedouble ) );
break;
case JSON_STRING: dOut.PackStr ( pNode->valuestring );
break;
// literals
case JSON_TRUE:
case JSON_FALSE:
case JSON_NULL:
// no content
break;
// associative arrays
case JSON_OBJECT:
{
dStack.Add ( tParent );
tParent = { pNode->next, 0, dOut.ReserveSize (), JSON_OBJECT };
dOut.StoreInt ( 0 ); // place for mask
pNode = pNode->child;
continue;
}
// mixed array
case JSON_MIXED_VECTOR:
{
dStack.Add ( tParent );
tParent = { pNode->next, 0, dOut.ReserveSize (), JSON_MIXED_VECTOR };
dOut.PackInt ( iSize );
pNode = pNode->child;
continue;
}
// optimized (generic) arrays
case JSON_INT32_VECTOR: dOut.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pNode )
dOut.StoreInt ( ( int ) pNode->valueint );
break;
case JSON_INT64_VECTOR: dOut.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pNode )
dOut.StoreBigint ( pNode->valueint );
break;
case JSON_DOUBLE_VECTOR: dOut.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pNode )
dOut.StoreBigint ( sphD2QW ( pNode->valuedouble ) );
break;
case JSON_STRING_VECTOR:
{
int iOfs = dOut.ReserveSize ();
dOut.PackInt ( iSize );
cJSON_ArrayForEach( pNode, pNode )
dOut.PackStr ( pNode->string );
dOut.PackSize ( iOfs );
break;
}
default: assert ( 0 && "internal error: unhandled type" );
return false;
}
pNode = pNode->next;
}
}
*/
static const char * g_dTypeNames[JSON_TOTAL] =
{
"EOF", "INT32", "INT64", "DOUBLE", "STRING", "STRING_VECTOR", "INT32_VECTOR", "INT64_VECTOR", "DOUBLE_VECTOR", "MIXED_VECTOR", "OBJECT", "BOOL", "BOOL", "NULL", "ROOT_OBJECT"
};
const char * JsonTypeName ( ESphJsonType eType )
{
assert ( eType>=JSON_EOF && eType<JSON_TOTAL );
return g_dTypeNames[eType];
}
void bson::Assoc_c::StartTypedNode ( ESphJsonType eType, const char * szName )
{
m_uBloomMask |= KeyMask ( szName );
m_dBson.Add ( eType );
if ( szName )
PackStr ( m_dBson, szName );
}
void bson::Assoc_c::AddInt ( const char * szName, int64_t iValue )
{
if ( int ( iValue )==iValue )
{
StartTypedNode ( JSON_INT32, szName );
StoreInt ( m_dBson, (int) iValue );
} else
{
StartTypedNode ( JSON_INT64, szName );
StoreBigint ( m_dBson, iValue );
}
}
void bson::Assoc_c::AddDouble ( const char * szName, double fValue )
{
StartTypedNode ( JSON_DOUBLE, szName );
StoreBigint ( m_dBson, sphD2QW ( fValue ) );
}
void bson::Assoc_c::AddString ( const char * szName, const char * szValue )
{
StartTypedNode ( JSON_STRING, szName );
PackStr ( m_dBson, szValue );
}
void bson::Assoc_c::AddBlob ( const char * szName, const ByteBlob_t & dValue )
{
StartTypedNode ( JSON_STRING, szName );
PackStr ( m_dBson, (const char *) dValue.first, dValue.second );
}
void bson::Assoc_c::AddBool ( const char * szName, bool bValue )
{
StartTypedNode ( bValue ? JSON_TRUE : JSON_FALSE, szName );
}
void bson::Assoc_c::AddNull( const char * szName )
{
StartTypedNode ( JSON_NULL, szName );
}
void bson::Assoc_c::AddStringVec ( const char * szName, const VecTraits_T<CSphString> & dData )
{
StartTypedNode ( JSON_STRING_VECTOR, szName );
AddStringData ( m_dBson, dData );
}
void bson::Assoc_c::AddStringVec ( const char * szName, const VecTraits_T<const char *> & dData )
{
StartTypedNode ( JSON_STRING_VECTOR, szName );
AddStringData ( m_dBson, dData );
}
void bson::Assoc_c::AddIntVec ( const char * szName, const VecTraits_T<int> & dData )
{
StartTypedNode ( JSON_INT32_VECTOR, szName );
AddIntData ( m_dBson, dData );
}
void bson::Assoc_c::AddIntVec ( const char * szName, const VecTraits_T<int64_t> & dData )
{
if ( dData.any_of ( [] ( int64_t iValue ) { return ( iValue!=int ( iValue ) ); } ) )
{
StartTypedNode ( JSON_INT64_VECTOR, szName );
AddBigintData ( m_dBson, dData );
} else
{
StartTypedNode ( JSON_INT32_VECTOR, szName );
AddIntData ( m_dBson, dData );
}
}
void bson::Assoc_c::AddDoubleVec ( const char * szName, const VecTraits_T<double> & dData )
{
StartTypedNode ( JSON_DOUBLE_VECTOR, szName );
AddDoubleData ( m_dBson, dData );
}
CSphVector<BYTE> & bson::Assoc_c::StartObj ( const char * szName )
{
StartTypedNode ( JSON_OBJECT, szName );
return m_dBson;
}
CSphVector<BYTE> & bson::Assoc_c::StartStringVec ( const char * szName )
{
StartTypedNode ( JSON_STRING_VECTOR, szName );
return m_dBson;
}
CSphVector<BYTE> & bson::Assoc_c::StartIntVec ( const char * szName )
{
StartTypedNode ( JSON_INT32_VECTOR, szName );
return m_dBson;
}
CSphVector<BYTE> & bson::Assoc_c::StartBigintVec ( const char * szName )
{
StartTypedNode ( JSON_INT64_VECTOR, szName );
return m_dBson;
}
CSphVector<BYTE> & bson::Assoc_c::StartDoubleVec ( const char * szName )
{
StartTypedNode ( JSON_DOUBLE_VECTOR, szName );
return m_dBson;
}
CSphVector<BYTE> & bson::Assoc_c::StartMixedVec ( const char * szName )
{
StartTypedNode ( JSON_MIXED_VECTOR, szName );
return m_dBson;
}
bson::Root_c::Root_c ( CSphVector<BYTE> & dBsonTarget )
: Assoc_c { dBsonTarget }
{
StoreInt ( m_dBson, 0 );
}
bson::Root_c::~Root_c ()
{
Finalize ( m_dBson );
StoreMask ( m_dBson, 0, m_uBloomMask );
}
bson::Obj_c::Obj_c ( CSphVector<BYTE> & dBsonTarget )
: Assoc_c { dBsonTarget }
{
m_iStartPos = ReserveSize ( m_dBson );
StoreInt ( m_dBson, 0 );
}
bson::Obj_c::~Obj_c ()
{
Finalize ( m_dBson );
StoreMask ( m_dBson, m_iStartPos+1, m_uBloomMask );
PackSize ( m_dBson, m_iStartPos ); // MUST be in this order, because PackSize() might move the data!
}
bson::MixedVector_c::MixedVector_c ( CSphVector<BYTE> & dBson, int iSize )
: m_dBson ( dBson )
{
m_iStartPos = ReserveSize ( m_dBson );
PackInt ( m_dBson, iSize );
};
bson::MixedVector_c::~MixedVector_c()
{
PackSize ( m_dBson, m_iStartPos );
}
void bson::MixedVector_c::AddInt ( int64_t iValue )
{
if ( int ( iValue )==iValue )
{
m_dBson.Add ( JSON_INT32 );
StoreInt ( m_dBson, (int) iValue );
} else
{
m_dBson.Add ( JSON_INT64 );
StoreBigint ( m_dBson, iValue );
}
}
void bson::MixedVector_c::AddDouble ( double fValue )
{
m_dBson.Add ( JSON_DOUBLE );
StoreBigint ( m_dBson, sphD2QW ( fValue ) );
}
void bson::MixedVector_c::AddString ( const char * szValue )
{
m_dBson.Add ( JSON_STRING );
PackStr ( m_dBson, szValue );
}
void bson::MixedVector_c::AddBlob ( const ByteBlob_t & dValue )
{
m_dBson.Add ( JSON_STRING );
PackStr ( m_dBson, (const char *) dValue.first, dValue.second );
}
void bson::MixedVector_c::AddBool ( bool bValue )
{
m_dBson.Add ( bValue ? JSON_TRUE : JSON_FALSE );
}
void bson::MixedVector_c::AddNull()
{
m_dBson.Add ( JSON_NULL );
}
void bson::MixedVector_c::AddStringVec ( const VecTraits_T<CSphString> & dData )
{
m_dBson.Add ( JSON_STRING_VECTOR );
AddStringData ( m_dBson, dData );
}
void bson::MixedVector_c::AddStringVec ( const VecTraits_T<const char *> & dData )
{
m_dBson.Add ( JSON_STRING_VECTOR );
AddStringData ( m_dBson, dData );
}
void bson::MixedVector_c::AddIntVec ( const VecTraits_T<int> & dData )
{
m_dBson.Add ( JSON_INT32_VECTOR );
AddIntData ( m_dBson, dData );
}
void bson::MixedVector_c::AddIntVec ( const VecTraits_T<int64_t> & dData )
{
if ( dData.any_of ( [] ( int64_t iValue ) { return ( iValue!=int ( iValue ) ); } ) )
{
m_dBson.Add ( JSON_INT64_VECTOR );
AddBigintData ( m_dBson, dData );
} else
{
m_dBson.Add ( JSON_INT32_VECTOR );
AddIntData ( m_dBson, dData );
}
}
void bson::MixedVector_c::AddDoubleVec ( const VecTraits_T<double> & dData )
{
m_dBson.Add ( JSON_DOUBLE_VECTOR );
AddDoubleData ( m_dBson, dData );
}
CSphVector<BYTE> & bson::MixedVector_c::StartObj ()
{
m_dBson.Add ( JSON_OBJECT );
return m_dBson;
}
CSphVector<BYTE> & bson::MixedVector_c::StartStringVec ()
{
m_dBson.Add ( JSON_STRING_VECTOR );
return m_dBson;
}
CSphVector<BYTE> & bson::MixedVector_c::StartIntVec ()
{
m_dBson.Add ( JSON_INT32_VECTOR );
return m_dBson;
}
CSphVector<BYTE> & bson::MixedVector_c::StartBigintVec ()
{
m_dBson.Add ( JSON_INT64_VECTOR );
return m_dBson;
}
CSphVector<BYTE> & bson::MixedVector_c::StartDoubleVec ()
{
m_dBson.Add ( JSON_DOUBLE_VECTOR );
return m_dBson;
}
CSphVector<BYTE> & bson::MixedVector_c::StartMixedVec ()
{
m_dBson.Add ( JSON_MIXED_VECTOR );
return m_dBson;
}
bson::StringVector_c::StringVector_c ( CSphVector<BYTE> & dBson, int iSize )
: m_dBson ( dBson )
{
m_iStartPos = ReserveSize ( m_dBson );
PackInt ( m_dBson, iSize );
};
bson::StringVector_c::~StringVector_c ()
{
PackSize ( m_dBson, m_iStartPos );
}
void bson::StringVector_c::AddValue ( const char * szValue )
{
PackStr ( m_dBson, szValue );
}
void bson::StringVector_c::AddValue ( const ByteBlob_t & dValue )
{
PackStr ( m_dBson, (const char*) dValue.first, dValue.second );
}
void bson::StringVector_c::AddValues ( const VecTraits_T<CSphString> & dData )
{
dData.Apply ( [this] ( const CSphString & s ) { PackStr ( m_dBson, s.cstr () ); } );
}
void bson::StringVector_c::AddValues ( const VecTraits_T<const char *> & dData )
{
dData.Apply ( [this] ( const char * sz ) { PackStr ( m_dBson, sz ); } );
}
bson::IntVector_c::IntVector_c ( CSphVector<BYTE> & dBson, int iSize )
: m_dBson ( dBson )
{
PackInt ( m_dBson, iSize );
};
void bson::IntVector_c::AddValue ( int iValue )
{
StoreInt ( m_dBson, iValue );
}
void bson::IntVector_c::AddValues ( const VecTraits_T<int> & dData )
{
dData.Apply ( [this] ( int i ) { StoreInt ( m_dBson, i ); } );
}
bson::BigintVector_c::BigintVector_c ( CSphVector<BYTE> & dBson, int iSize )
: m_dBson ( dBson )
{
PackInt ( m_dBson, iSize );
};
void bson::BigintVector_c::AddValue ( int64_t iValue )
{
StoreBigint ( m_dBson, iValue );
}
void bson::BigintVector_c::AddValues ( const VecTraits_T<int64_t> & dData )
{
dData.Apply ( [this] ( int64_t i ) { StoreBigint ( m_dBson, i ); } );
}
bson::DoubleVector_c::DoubleVector_c ( CSphVector<BYTE> & dBson, int iSize )
: m_dBson ( dBson )
{
PackInt ( m_dBson, iSize );
};
void bson::DoubleVector_c::AddValue ( double fValue )
{
StoreBigint ( m_dBson, sphD2QW ( fValue ) );
}
void bson::DoubleVector_c::AddValues ( const VecTraits_T<double> & dData )
{
dData.Apply ( [this] ( double f ) { StoreBigint ( m_dBson, sphD2QW ( f ) ); } );
}
| 97,250
|
C++
|
.cpp
| 3,618
| 24.093698
| 175
| 0.651048
|
manticoresoftware/manticoresearch
| 8,893
| 493
| 500
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
16,814
|
searchdha.cpp
|
manticoresoftware_manticoresearch/src/searchdha.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 "sphinxint.h"
#include "searchdaemon.h"
#include "searchdha.h"
#include "searchdtask.h"
#include "coroutine.h"
#include "mini_timer.h"
#include "pollable_event.h"
#include "netpoll.h"
#include <utility>
#include <atomic>
#include <errno.h>
#if !_WIN32
#include <netinet/in.h>
#include <netdb.h>
#else
#include <WinSock2.h>
#include <MSWSock.h>
#include <WS2tcpip.h>
#pragma comment(lib, "WS2_32.Lib")
#endif
#if HAVE_GETADDRINFO_A
#include <signal.h>
#endif
#if HAVE_KQUEUE
#include <sys/event.h>
#endif
int64_t g_iPingIntervalUs = 0; // by default ping HA agents every 1 second
DWORD g_uHAPeriodKarmaS = 60; // by default use the last 1 minute statistic to determine the best HA agent
int g_iPersistentPoolSize = 0;
static auto& g_iTFO = sphGetTFO ();
CSphString HostDesc_t::GetMyUrl() const
{
CSphString sName;
switch ( m_iFamily )
{
case AF_INET: sName.SetSprintf ( "%s:%u", m_sAddr.cstr(), m_iPort ); break;
case AF_UNIX: sName = m_sAddr; break;
}
return sName;
}
#define VERBOSE_NETLOOP 0
#if VERBOSE_NETLOOP
#define sphLogDebugA( ... ) TimePrefixed::LogDebugv ("A ", __VA_ARGS__)
#define sphLogDebugL( ... ) TimePrefixed::LogDebugv ("L ", __VA_ARGS__)
#else
#if _WIN32
#pragma warning(disable:4390)
#endif
#define sphLogDebugA( ... )
#define sphLogDebugL( ... )
#endif
/////////////////////////////////////////////////////////////////////////////
// HostDashboard_t
//
// Dashboard contains generic statistic for a host like query time, answer time,
// num of errors a row, and all this data in retrospective on time
/////////////////////////////////////////////////////////////////////////////
HostDashboard_t::HostDashboard_t ( const HostDesc_t & tHost )
{
assert ( !tHost.m_pDash );
m_tHost.CloneFromHost ( tHost );
for_each ( m_dPeriodicMetrics, [] ( auto& dMetric ) { dMetric.m_dMetrics.Reset(); } );
}
HostDashboard_t::~HostDashboard_t ()
{
SafeDelete ( m_pPersPool );
}
int64_t HostDashboard_t::EngageTime () const NO_THREAD_SAFETY_ANALYSIS
{
// m_dMetricsLock is essential when we read/update all metrics a time, atomically.
// (for just one m_iLastAnswerTime it is enough that it is atomic itself, no lock necessary)
return m_iLastAnswerTime + g_iPingIntervalUs;
}
DWORD HostDashboard_t::GetCurSeconds()
{
int64_t iNow = sphMicroTimer()/1000000;
return DWORD ( iNow & 0xFFFFFFFF );
}
bool HostDashboard_t::IsHalfPeriodChanged ( DWORD * pLast )
{
assert ( pLast );
DWORD uSeconds = GetCurSeconds();
if ( ( uSeconds - *pLast )>( g_uHAPeriodKarmaS / 2 ) )
{
*pLast = uSeconds;
return true;
}
return false;
}
MetricsAndCounters_t& HostDashboard_t::GetCurrentMetrics ()
{
DWORD uCurrentPeriod = GetCurSeconds()/g_uHAPeriodKarmaS;
auto & dCurrentMetrics = m_dPeriodicMetrics[uCurrentPeriod % STATS_DASH_PERIODS];
if ( dCurrentMetrics.m_uPeriod!=uCurrentPeriod ) // we have new or reused stat
{
dCurrentMetrics.m_dMetrics.Reset ();
dCurrentMetrics.m_uPeriod = uCurrentPeriod;
}
return dCurrentMetrics.m_dMetrics;
}
void HostDashboard_t::GetCollectedMetrics ( HostMetricsSnapshot_t& dResult, int iPeriods ) const
{
DWORD uSeconds = GetCurSeconds();
if ( (uSeconds % g_uHAPeriodKarmaS) < (g_uHAPeriodKarmaS/2) )
++iPeriods;
iPeriods = Min ( iPeriods, STATS_DASH_PERIODS );
DWORD uCurrentPeriod = uSeconds/g_uHAPeriodKarmaS;
MetricsAndCounters_t tAccum;
tAccum.Reset ();
ScRL_t tRguard ( m_dMetricsLock );
for ( ; iPeriods>0; --iPeriods, --uCurrentPeriod )
// it might be no queries at all in the fixed time
if ( m_dPeriodicMetrics[uCurrentPeriod % STATS_DASH_PERIODS].m_uPeriod==uCurrentPeriod )
tAccum.Add ( m_dPeriodicMetrics[uCurrentPeriod % STATS_DASH_PERIODS].m_dMetrics );
for ( int i = 0; i<eMaxAgentStat; ++i )
dResult[i] = tAccum.m_dCounters[i].load(std::memory_order_relaxed);
for ( int i = 0; i<ehMaxStat; ++i )
dResult[i+eMaxAgentStat] = tAccum.m_dMetrics[i];
}
/////////////////////////////////////////////////////////////////////////////
// PersistentConnectionsPool_c
//
// This is pool of sockets which can be rented/returned by workers.
// returned socket may be in connected state, so later usage will not require
// connection, but can work immediately (in persistent mode).
/////////////////////////////////////////////////////////////////////////////
// modify size of the pool
// (actually we just need to close any extra sockets not fit in new limit. And do nothing otherwize).
void PersistentConnectionsPool_c::ReInit ( int iPoolSize )
{
assert ( iPoolSize >0 );
// close any extra sockets which are not fit in new limit
ScopedMutex_t tGuard ( m_dDataLock );
m_iLimit = iPoolSize;
m_dSockets.Reserve ( m_iLimit );
while ( m_iFreeWindow>m_iLimit )
{
--m_iFreeWindow;
int iSock = m_dSockets[Step ( &m_iRit )];
if ( iSock>=0 )
sphSockClose ( iSock );
}
}
// move the iterator to the next item, or loop the ring.
int PersistentConnectionsPool_c::Step ( int* pVar )
{
assert ( pVar );
int iRes = *pVar++;
if ( *pVar>=m_dSockets.GetLength () )
*pVar = 0;
return iRes;
}
// Rent first try to return the sockets which already were in work (i.e. which are connected)
// If no such socket available and the limit is not reached, it will add the new one.
int PersistentConnectionsPool_c::RentConnection ()
{
ScopedMutex_t tGuard ( m_dDataLock );
if ( m_iFreeWindow>0 )
{
--m_iFreeWindow;
return m_dSockets[Step ( &m_iRit )];
}
if ( m_dSockets.GetLength () >= m_iLimit )
return -2; // no more slots available;
// this branch will be executed only during initial 'heating'
m_dSockets.Add ( -1 );
return -1;
}
// write given socket into the pool.
void PersistentConnectionsPool_c::ReturnConnection ( int iSocket )
{
ScopedMutex_t tGuard ( m_dDataLock );
// overloaded pool
if ( m_iFreeWindow >= m_dSockets.GetLength () )
{
// no place at all (i.e. if pool was resized, but some sockets rented before,
// and now they are returned, but we have no place for them)
if ( m_dSockets.GetLength () >= m_iLimit )
{
sphSockClose ( iSocket );
return;
}
// add the place for one more returned socket
m_dSockets.Add ();
m_iWit = m_dSockets.GetLength ()-1;
}
++m_iFreeWindow;
if ( m_bShutdown )
{
sphSockClose ( iSocket );
iSocket = -1;
}
// if there were no free sockets until now, point the reading iterator to just released socket
if ( m_iFreeWindow==1 )
m_iRit = m_iWit;
m_dSockets[Step ( &m_iWit )] = iSocket;
}
// close all the sockets in the pool.
void PersistentConnectionsPool_c::Shutdown ()
{
ScopedMutex_t tGuard ( m_dDataLock );
m_bShutdown = true;
for ( int i = 0; i<m_iFreeWindow; ++i )
{
int& iSock = m_dSockets[Step ( &m_iRit )];
if ( iSock>=0 )
{
sphSockClose ( iSock );
iSock = -1;
}
}
}
void ClosePersistentSockets()
{
Dashboard::GetActiveHosts().Apply ([] ( HostDashboardRefPtr_t& pHost) { SafeDelete ( pHost->m_pPersPool ); });
}
// check whether sURL contains plain ip-address, and so, m.b. no need to resolve it many times.
// ip-address assumed as string from four .-separated positive integers, each in range 0..255
static bool IsIpAddress ( const char * sURL )
{
StrVec_t dParts;
sphSplit ( dParts, sURL, "." );
if ( dParts.GetLength ()!=4 )
return false;
for ( auto &dPart : dParts )
{
dPart.Trim ();
auto iLen = dPart.Length ();
for ( auto i = 0; i<iLen; ++i )
if ( !isdigit ( dPart.cstr ()[i] ) )
return false;
auto iRes = atoi ( dPart.cstr () );
if ( iRes<0 || iRes>255 )
return false;
}
return true;
}
WarnInfo_c::WarnInfo_c ( const char * szIndexName, const char * szAgent, CSphString & sError, StrVec_t * pWarnings )
: m_szIndexName ( szIndexName )
, m_szAgent ( szAgent )
, m_pWarnings ( pWarnings )
, m_sError ( sError )
{}
void WarnInfo_c::Warn ( const char * szFmt, ... ) const
{
va_list ap;
va_start ( ap, szFmt );
CSphString sWarning;
if ( m_szIndexName )
sWarning.SetSprintf ( "table '%s': agent '%s': %s", m_szIndexName, m_szAgent, szFmt );
else
sWarning.SetSprintf ( "host '%s': %s", m_szAgent, szFmt );
sWarning.SetSprintfVa ( sWarning.cstr(), ap );
sphInfo ( "%s", sWarning.cstr() );
if ( m_pWarnings )
m_pWarnings->Add(sWarning);
va_end ( ap );
}
bool WarnInfo_c::ErrSkip ( const char * szFmt, ... ) const
{
va_list ap;
va_start ( ap, szFmt );
CSphString sMsg;
if ( m_szIndexName )
sMsg.SetSprintf ( "table '%s': agent '%s': %s, - SKIPPING AGENT", m_szIndexName, m_szAgent, szFmt );
else
sMsg.SetSprintf ( "host '%s': %s, - SKIPPING AGENT", m_szAgent, szFmt );
sMsg.SetSprintfVa ( sMsg.cstr(), ap );
sphWarning ( "%s", sMsg.cstr() );
m_sError = sMsg;
va_end ( ap );
return false;
}
/// Set flag m_bNeedResolve if address is AF_INET, host is not empty and not plain IP address,
/// and also if global flag for postponed resolving is set.
/// Otherwise resolve address now (if appliable) and then forbid any name resolving in future.
static bool ResolveAddress ( AgentDesc_t &tAgent, const WarnInfo_c & tInfo )
{
tAgent.m_bNeedResolve = false;
if ( tAgent.m_iFamily!=AF_INET )
return true;
if ( tAgent.m_sAddr.IsEmpty () )
return tInfo.ErrSkip ( "invalid host name 'empty'" );
if ( IsIpAddress ( tAgent.m_sAddr.cstr () ) )
{
tAgent.m_uAddr = sphGetAddress ( tAgent.m_sAddr.cstr (), false, true );
if ( tAgent.m_uAddr )
return true;
// got plain ip and couldn't resolve it? Hm, strange...
if ( !g_bHostnameLookup )
return tInfo.ErrSkip ( "failed to lookup host name '%s' (error=%s)", tAgent.m_sAddr.cstr ()
, sphSockError () );
}
// if global flag set, don't resolve right now, it will be done on place.
tAgent.m_bNeedResolve = g_bHostnameLookup;
if ( tAgent.m_bNeedResolve )
return true;
tAgent.m_uAddr = sphGetAddress ( tAgent.m_sAddr.cstr () );
if ( tAgent.m_uAddr )
return true;
tAgent.m_bNeedResolve = true;
tInfo.ErrSkip ( "failed to lookup host name '%s' (error=%s)", tAgent.m_sAddr.cstr (), sphSockError () );
return true;
}
/// Async resolving
using CallBack_f = std::function<void ( DWORD )>;
class DNSResolver_c
{
struct addrinfo m_tHints { 0 };
CallBack_f m_pCallback = nullptr;
bool m_bCallbackInvoked = false;
CSphString m_sHost;
template <typename CALLBACK_F>
DNSResolver_c ( const char * sHost, CALLBACK_F&& pFunc )
: m_pCallback ( std::forward<CALLBACK_F> ( pFunc ) )
, m_sHost ( sHost )
{
m_tHints.ai_family = AF_INET;
m_tHints.ai_socktype = SOCK_STREAM;
}
~DNSResolver_c ()
{
assert ( m_pCallback );
if ( !m_bCallbackInvoked )
m_pCallback ( 0 );
}
void FinishResolve ( struct addrinfo * pResult )
{
assert ( m_pCallback );
if ( !pResult )
return;
auto * pSockaddr_ipv4 = ( struct sockaddr_in * ) pResult->ai_addr;
auto uIP = pSockaddr_ipv4->sin_addr.s_addr;
freeaddrinfo ( pResult );
m_pCallback ( uIP );
m_bCallbackInvoked = true;
}
// platform-specific part starts here.
#if HAVE_GETADDRINFO_A
struct gaicb m_dReq, *m_pReq;
static void ResolvingRoutine ( void * pResolver )
{
auto * pThis = ( DNSResolver_c * ) pResolver;
if ( pThis )
pThis->Resolve ();
SafeDelete ( pThis );
}
static void ResolvingWrapper ( sigval dSigval )
{
ResolvingRoutine ( dSigval.sival_ptr );
};
void ResolveBegin ()
{
m_dReq = { 0 };
m_dReq.ar_name = m_sHost.cstr ();
m_dReq.ar_request = &m_tHints;
m_pReq = &m_dReq;
sigevent_t dCallBack = {{ 0 }};
dCallBack.sigev_notify = SIGEV_THREAD;
dCallBack.sigev_value.sival_ptr = this;
dCallBack.sigev_notify_function = ResolvingWrapper;
getaddrinfo_a ( GAI_NOWAIT, &m_pReq, 1, &dCallBack );
}
void Resolve ()
{
auto * pResult = m_dReq.ar_result;
FinishResolve ( pResult );
}
#else
SphThread_t m_dResolverThread;
void ResolveBegin ()
{
Threads::Create ( &m_dResolverThread, [this] { Resolve(); delete this; }, true );
}
void Resolve ()
{
struct addrinfo * pResult = nullptr;
if ( !getaddrinfo ( m_sHost.cstr (), nullptr, &m_tHints, &pResult ) )
FinishResolve ( pResult );
}
#endif
public:
//! Non-blocking DNS resolver
//! Will call provided callback with single DWORD parameter - resolved IP. (or 0 on fail)
//! If there is no need to go background (i.e. we have plain ip address which not need to be
//! resolved any complex way), will call the callback immediately.
//! \param sHost - host address, as 'www.google.com', or '127.0.0.1'
//! \param pFunc - callback func/functor or lambda
template <typename CALLBACK_F>
static void GetAddress_a ( const char * sHost, CALLBACK_F && pFunc = nullptr )
{
if ( IsIpAddress ( sHost ) )
{
DWORD uResult = sphGetAddress ( sHost, false, true );
if ( uResult )
{
pFunc ( uResult );
return;
}
}
auto * pPayload = new DNSResolver_c ( sHost, std::forward<CALLBACK_F>(pFunc) );
pPayload->ResolveBegin();
}
};
/// initialize address resolving,
/// add to agent records of stats,
/// add agent into global dashboard hash
static bool ValidateAndAddDashboard ( AgentDesc_t& dAgent, const WarnInfo_c & tInfo )
{
assert ( !dAgent.m_pDash && !dAgent.m_pMetrics );
if ( !ResolveAddress ( dAgent, tInfo ) )
return false;
Dashboard::LinkHost ( dAgent );
dAgent.m_pMetrics = new MetricsAndCounters_t;
assert ( dAgent.m_pDash );
return true;
}
static IPinger* g_pPinger = nullptr;
void SetGlobalPinger ( IPinger* pPinger )
{
g_pPinger = pPinger;
}
// Subscribe hosts with just enabled pings (i.e. where iNeedPing is exactly 1, no more)
static void PingCheckAdd ( HostDashboardRefPtr_t pHost )
{
if ( !g_pPinger )
return;
if ( !pHost )
return;
assert ( pHost->m_iNeedPing>=0 );
if ( pHost->m_iNeedPing==1 )
g_pPinger->Subscribe ( pHost );
}
/////////////////////////////////////////////////////////////////////////////
// MultiAgentDesc_c
//
// That is set of hosts serving one and same agent (i.e., 'mirrors').
// class also provides mirror choosing using different strategies
/////////////////////////////////////////////////////////////////////////////
// global cache for sharing multiagents (i.e. several distr indexes with same multiagent will share one copy with all stats)
struct GlobalMultiAgents_t
{
using ReadOnlyAgentsHash_t = ReadOnlyHash_T<MultiAgentDesc_c>;
using WriteableAgentsHash_t = WriteableHash_T<MultiAgentDesc_c>;
using cRefCountedHashOfAgents_t = cRefCountedRefPtr_T<cRefCountedHashOfRefcnt_T<MultiAgentDesc_c>>;
mutable CSphMutex m_tMultiAgentsLock; // protects only changes of hash; reads are lock-free
ReadOnlyAgentsHash_t m_dGlobalHash GUARDED_BY ( m_tMultiAgentsLock );
WriteableAgentsHash_t MakeEmptyChanger () REQUIRES ( m_tMultiAgentsLock )
{
WriteableAgentsHash_t pRes { m_dGlobalHash };
pRes.InitEmptyHash();
return pRes;
}
WriteableAgentsHash_t MakeCopyChanger () REQUIRES ( m_tMultiAgentsLock )
{
WriteableAgentsHash_t pRes { m_dGlobalHash };
pRes.CopyOwnerHash();
return pRes;
}
cRefCountedHashOfAgents_t GetHash () const NO_THREAD_SAFETY_ANALYSIS
{
return m_dGlobalHash.GetHash();
}
};
static GlobalMultiAgents_t & g_MultiAgents()
{
static GlobalMultiAgents_t dGlobalHash;
return dGlobalHash;
}
// called from dtr of distr index. Make new snapshot with only actual multiagents, orphans will be removed.
void MultiAgentDesc_c::CleanupOrphaned()
{
bool bNeedGC = false;
auto& tAgents = g_MultiAgents();
{
ScopedMutex_t tLock { tAgents.m_tMultiAgentsLock };
auto tChanger = tAgents.MakeEmptyChanger();
auto pHash = tChanger.m_tOwner.GetHash();
for ( const auto& tAgent : *pHash )
{
if ( tAgent.second->IsLast() )
bNeedGC = true;
else
tChanger.m_pNewHash->Add ( tAgent.second, tAgent.first );
}
}
if ( bNeedGC )
Dashboard::CleanupOrphaned ();
}
// calculate uniq key for holding MultiAgent instance in global hash
CSphString MultiAgentDesc_c::GetKey ( const CSphVector<AgentDesc_t *> &dTemplateHosts, const AgentOptions_t &tOpt )
{
StringBuilder_c sKey;
for ( const auto* dHost : dTemplateHosts )
sKey << dHost->GetMyUrl () << ":" << dHost->m_sIndexes << "|";
sKey.Sprintf("[%d,%d,%d,%d,%d]",
tOpt.m_bBlackhole?1:0,
tOpt.m_bPersistent?1:0,
(int)tOpt.m_eStrategy,
tOpt.m_iRetryCount,
tOpt.m_iRetryCountMultiplier);
return sKey.cstr();
}
MultiAgentDescRefPtr_c MultiAgentDesc_c::GetAgent ( const CSphVector<AgentDesc_t*> & dHosts, const AgentOptions_t & tOpt, const WarnInfo_c & tWarn )
{
auto sKey = GetKey ( dHosts, tOpt );
auto& tAgents = g_MultiAgents();
{
auto pHash = tAgents.GetHash();
auto* pEntry = (*pHash) ( sKey );
if ( pEntry )
return ConstCastPtr ( *pEntry );
}
// create and init new agent
MultiAgentDescRefPtr_c pAgent { new MultiAgentDesc_c };
if ( !pAgent->Init ( dHosts, tOpt, tWarn ) )
return MultiAgentDescRefPtr_c();
ScopedMutex_t tLock { tAgents.m_tMultiAgentsLock };
auto tChanger = tAgents.MakeCopyChanger();
tChanger.Add ( pAgent, sKey );
return pAgent;
}
bool MultiAgentDesc_c::Init ( const CSphVector<AgentDesc_t *> &dHosts,
const AgentOptions_t &tOpt, const WarnInfo_c &tWarn ) NO_THREAD_SAFETY_ANALYSIS
{
// initialize options
m_eStrategy = tOpt.m_eStrategy;
m_iMultiRetryCount = tOpt.m_iRetryCount * tOpt.m_iRetryCountMultiplier;
m_sConfigStr = tWarn.m_szAgent;
// initialize hosts & weights
auto iLen = dHosts.GetLength ();
Reset ( iLen );
m_dWeights.Reset ( iLen );
if ( !iLen )
return tWarn.ErrSkip ( "Unable to initialize empty agent" );
auto fFrac = 100.0f / iLen;
ARRAY_FOREACH ( i, dHosts )
{
// we have templates parsed from config, NOT real working hosts!
assert ( !dHosts[i]->m_pDash && !dHosts[i]->m_pMetrics );
if ( !ValidateAndAddDashboard ( ( m_pData + i )->CloneFrom ( *dHosts[i] ), tWarn ) )
return false;
m_dWeights[i] = fFrac;
}
// agents with neeping!=0 will be pinged
m_bNeedPing = IsHA () && !tOpt.m_bBlackhole;
if ( m_bNeedPing )
for ( int i = 0; i<GetLength (); ++i )
{
++m_pData[i].m_pDash->m_iNeedPing;
PingCheckAdd ( m_pData[i].m_pDash );
}
return true;
}
MultiAgentDesc_c::~MultiAgentDesc_c()
{
if ( m_bNeedPing )
for ( int i = 0; i<GetLength (); ++i )
--m_pData[i].m_pDash->m_iNeedPing;
}
const AgentDesc_t &MultiAgentDesc_c::RRAgent ()
{
if ( !IsHA() )
return *m_pData;
auto iRRCounter = m_iRRCounter.load ( std::memory_order_relaxed );
int iNewCounter;
do
{
iNewCounter = iRRCounter+1;
if ( iNewCounter>=GetLength())
iNewCounter = 0;
} while ( !m_iRRCounter.compare_exchange_weak ( iRRCounter, iNewCounter, std::memory_order_acq_rel ) );
return m_pData[iRRCounter];
}
const AgentDesc_t &MultiAgentDesc_c::RandAgent ()
{
return m_pData[sphRand () % GetLength ()];
}
void MultiAgentDesc_c::ChooseWeightedRandAgent ( int * pBestAgent, CSphVector<int> & dCandidates )
{
assert ( pBestAgent );
ScRL_t tLock ( m_dWeightLock );
auto fBound = m_dWeights[*pBestAgent];
auto fLimit = fBound;
for ( auto j : dCandidates )
fLimit += m_dWeights[j];
auto fChance = sphRand () * fLimit / float(UINT_MAX);
if ( fChance<=fBound )
return;
for ( auto j : dCandidates )
{
fBound += m_dWeights[j];
*pBestAgent = j;
if ( fChance<=fBound )
break;
}
}
static void LogAgentWeights ( const float * pOldWeights, const float * pCurWeights, const int64_t * pTimers, const CSphFixedVector<AgentDesc_t> & dAgents )
{
ARRAY_FOREACH ( i, dAgents )
sphLogDebug ( "client=%s, mirror=%d, weight=%0.2f%%, %0.2f%%, timer=" INT64_FMT
, dAgents[i].GetMyUrl ().cstr (), i, pCurWeights[i], pOldWeights[i], pTimers[i] );
}
const AgentDesc_t &MultiAgentDesc_c::StDiscardDead ()
{
if ( !IsHA() )
return m_pData[0];
// threshold errors-a-row to be counted as dead
int iDeadThr = 3;
int iBestAgent = -1;
int64_t iErrARow = -1;
CSphVector<int> dCandidates;
CSphFixedVector<int64_t> dTimers ( GetLength() );
dCandidates.Reserve ( GetLength() );
for (int i=0; i<GetLength(); ++i)
{
// no locks for g_pStats since we're just reading, and read data is not critical.
const auto& pDash = m_pData[i].m_pDash;
HostMetricsSnapshot_t dMetricsSnapshot;
pDash->GetCollectedMetrics ( dMetricsSnapshot );// look at last 30..90 seconds.
uint64_t uQueries = 0;
for ( int j=0; j<eMaxAgentStat; ++j )
uQueries += dMetricsSnapshot[j];
if ( uQueries > 0 )
dTimers[i] = dMetricsSnapshot[ehTotalMsecs]/uQueries;
else
dTimers[i] = 0;
ScRL_t tRguard ( pDash->m_dMetricsLock );
int64_t iThisErrARow = ( pDash->m_iErrorsARow<=iDeadThr ) ? 0 : pDash->m_iErrorsARow;
if ( iErrARow < 0 )
iErrARow = iThisErrARow;
// 2. Among good nodes - select the one(s) with lowest errors/query rating
if ( iErrARow > iThisErrARow )
{
dCandidates.Reset();
iBestAgent = i;
iErrARow = iThisErrARow;
} else if ( iErrARow==iThisErrARow )
{
if ( iBestAgent>=0 )
dCandidates.Add ( iBestAgent );
iBestAgent = i;
}
}
// check if it is a time to recalculate the agent's weights
CheckRecalculateWeights ( dTimers );
// nothing to select, sorry. Just random agent...
if ( iBestAgent < 0 )
{
sphLogDebug ( "HA selector discarded all the candidates and just fall into simple Random" );
return RandAgent();
}
// only one node with lowest error rating. Return it.
if ( !dCandidates.GetLength() )
{
sphLogDebug ( "client=%s, HA selected %d node with best num of errors a row (" INT64_FMT ")"
, m_pData[iBestAgent].GetMyUrl().cstr(), iBestAgent, iErrARow );
return m_pData[iBestAgent];
}
// several nodes. Let's select the one.
ChooseWeightedRandAgent ( &iBestAgent, dCandidates );
if ( g_eLogLevel>=SPH_LOG_VERBOSE_DEBUG )
{
const HostDashboard_t & dDash = *m_pData[iBestAgent].m_pDash;
ScRL_t tRguard ( dDash.m_dMetricsLock );
auto fAge = float ( dDash.m_iLastAnswerTime-dDash.m_iLastQueryTime ) / 1000.0f;
sphLogDebugv ("client=%s, HA selected %d node by weighted random, with best EaR ("
INT64_FMT "), last answered in %.3f milliseconds, among %d candidates"
, m_pData[iBestAgent].GetMyUrl ().cstr(), iBestAgent, iErrARow, fAge, dCandidates.GetLength()+1 );
}
return m_pData[iBestAgent];
}
// Check the time and recalculate mirror weights, if necessary.
void MultiAgentDesc_c::CheckRecalculateWeights ( const CSphFixedVector<int64_t> & dTimers )
{
if ( !dTimers.GetLength () || !HostDashboard_t::IsHalfPeriodChanged ( &m_uTimestamp ) )
return;
CSphFixedVector<float> dWeights {0};
// since we'll update values anyway, acquire w-lock.
ScWL_t tWguard ( m_dWeightLock );
dWeights.CopyFrom ( m_dWeights );
RebalanceWeights ( dTimers, dWeights );
if ( g_eLogLevel>=SPH_LOG_DEBUG )
LogAgentWeights ( m_dWeights.Begin(), dWeights.Begin (), dTimers.Begin (), *this );
m_dWeights.SwapData (dWeights);
}
const AgentDesc_t &MultiAgentDesc_c::StLowErrors ()
{
if ( !IsHA() )
return *m_pData;
// how much error rating is allowed
float fAllowedErrorRating = 0.03f; // i.e. 3 errors per 100 queries is still ok
int iBestAgent = -1;
float fBestCriticalErrors = 1.0;
float fBestAllErrors = 1.0;
CSphVector<int> dCandidates;
CSphFixedVector<int64_t> dTimers ( GetLength() );
dCandidates.Reserve ( GetLength() );
for ( int i=0; i<GetLength(); ++i )
{
// no locks for g_pStats since we just reading, and read data is not critical.
const HostDashboard_t & dDash = *m_pData[i].m_pDash;
HostMetricsSnapshot_t dMetricsSnapshot;
dDash.GetCollectedMetrics ( dMetricsSnapshot ); // look at last 30..90 seconds.
uint64_t uQueries = 0;
uint64_t uCriticalErrors = 0;
uint64_t uAllErrors = 0;
uint64_t uSuccesses = 0;
for ( int j=0; j<eMaxAgentStat; ++j )
{
if ( j==eNetworkCritical )
uCriticalErrors = uQueries;
else if ( j==eNetworkNonCritical )
{
uAllErrors = uQueries;
uSuccesses = dMetricsSnapshot[j];
}
uQueries += dMetricsSnapshot[j];
}
if ( uQueries > 0 )
dTimers[i] = dMetricsSnapshot[ehTotalMsecs]/uQueries;
else
dTimers[i] = 0;
// 1. No successes queries last period (it includes the pings). Skip such node!
if ( !uSuccesses )
continue;
if ( uQueries )
{
// 2. Among good nodes - select the one(s) with lowest errors/query rating
float fCriticalErrors = (float) uCriticalErrors/uQueries;
float fAllErrors = (float) uAllErrors/uQueries;
if ( fCriticalErrors<=fAllowedErrorRating )
fCriticalErrors = 0.0f;
if ( fAllErrors<=fAllowedErrorRating )
fAllErrors = 0.0f;
if ( fCriticalErrors < fBestCriticalErrors )
{
dCandidates.Reset();
iBestAgent = i;
fBestCriticalErrors = fCriticalErrors;
fBestAllErrors = fAllErrors;
} else if ( fCriticalErrors==fBestCriticalErrors )
{
if ( fAllErrors < fBestAllErrors )
{
dCandidates.Reset();
iBestAgent = i;
fBestAllErrors = fAllErrors;
} else if ( fAllErrors==fBestAllErrors )
{
if ( iBestAgent>=0 )
dCandidates.Add ( iBestAgent );
iBestAgent = i;
}
}
}
}
// check if it is a time to recalculate the agent's weights
CheckRecalculateWeights ( dTimers );
// nothing to select, sorry. Just plain RR...
if ( iBestAgent < 0 )
{
sphLogDebug ( "HA selector discarded all the candidates and just fall into simple Random" );
return RandAgent();
}
// only one node with lowest error rating. Return it.
if ( !dCandidates.GetLength() )
{
sphLogDebug ( "client=%s, HA selected %d node with best error rating (%.2f)",
m_pData[iBestAgent].GetMyUrl().cstr(), iBestAgent, fBestCriticalErrors );
return m_pData[iBestAgent];
}
// several nodes. Let's select the one.
ChooseWeightedRandAgent ( &iBestAgent, dCandidates );
if ( g_eLogLevel>=SPH_LOG_VERBOSE_DEBUG )
{
const HostDashboard_t & dDash = *m_pData[iBestAgent].m_pDash;
ScRL_t tRguard ( dDash.m_dMetricsLock );
auto fAge = float ( dDash.m_iLastAnswerTime-dDash.m_iLastQueryTime ) / 1000.0f;
sphLogDebugv (
"client=%s, HA selected %d node by weighted random, "
"with best error rating (%.2f), answered %f seconds ago"
, m_pData[iBestAgent].GetMyUrl ().cstr(), iBestAgent, fBestCriticalErrors, fAge );
}
return m_pData[iBestAgent];
}
const AgentDesc_t &MultiAgentDesc_c::ChooseAgent ()
{
if ( !IsHA() )
{
assert ( m_pData && "Not initialized MultiAgent detected!");
if ( m_pData )
return *m_pData;
static AgentDesc_t dFakeHost; // avoid crash in release if not initialized.
return dFakeHost;
}
switch ( m_eStrategy )
{
case HA_AVOIDDEAD:
return StDiscardDead();
case HA_AVOIDERRORS:
return StLowErrors();
case HA_ROUNDROBIN:
return RRAgent();
default:
return RandAgent();
}
}
const char * Agent_e_Name ( Agent_e eState )
{
switch ( eState )
{
case Agent_e::HEALTHY: return "HEALTHY";
case Agent_e::CONNECTING: return "CONNECTING";
case Agent_e::RETRY: return "RETRY";
}
assert ( 0 && "UNKNOWN_STATE" );
return "UNKNOWN_STATE";
}
void InitSearchdStats() NO_THREAD_SAFETY_ANALYSIS
{
SearchdStats_t& tStats = gStats();
tStats.m_uStarted = (DWORD)time ( nullptr );
tStats.m_iConnections = 0;
tStats.m_iMaxedOut = 0;
tStats.m_iAgentConnect = 0;
tStats.m_iAgentConnectTFO = 0;
tStats.m_iQueries = 0;
tStats.m_iQueryTime = 0;
tStats.m_iQueryCpuTime = 0;
tStats.m_iDistQueries = 0;
tStats.m_iDistWallTime = 0;
tStats.m_iDistLocalTime = 0;
tStats.m_iDistWaitTime = 0;
tStats.m_iDiskReads = 0;
tStats.m_iDiskReadBytes = 0;
tStats.m_iDiskReadTime = 0;
tStats.m_iPredictedTime = 0;
tStats.m_iAgentPredictedTime = 0;
for ( auto & i : tStats.m_iCommandCount )
i = 0;
for ( auto & i: tStats.m_dDetailedStats )
i.m_tStats = MakeStatsContainer ();
}
void StatCountCommandDetails ( SearchdStats_t::EDETAILS eCmd, uint64_t uFoundRows, uint64_t tmStart )
{
auto tmNow = sphMicroTimer ();
auto & tDetail = gStats ().m_dDetailedStats[eCmd];
ScWL_t wLock ( tDetail.m_tStatsLock );
tDetail.m_tStats->Add ( uFoundRows, tmNow-tmStart, tmNow );
}
static void CalculateCommandStats ( SearchdStats_t::EDETAILS eCmd, QueryStats_t & tRowsFoundStats, QueryStats_t & tQueryTimeStats )
{
auto & tDetail = gStats ().m_dDetailedStats[eCmd];
ScRL_t rLock ( tDetail.m_tStatsLock );
CalcSimpleStats ( tDetail.m_tStats.get (), tRowsFoundStats, tQueryTimeStats );
}
void FormatCmdStats ( VectorLike & dStatus, const char * szPrefix, SearchdStats_t::EDETAILS eCmd )
{
using namespace QueryStats;
static std::array<const char *, TYPE_TOTAL> dStatTypeNames = { "avg", "min", "max", "pct95", "pct99" };
QueryStats_t tRowStats, tTimeStats;
bool bCalculated = false;
int iNulls = 0;
for ( int j = 0; j<TYPE_TOTAL; ++j )
{
if ( !dStatus.MatchAddf ( "%s_stats_ms_%s", szPrefix, dStatTypeNames[j] ) )
continue;
if ( !bCalculated )
{
CalculateCommandStats ( eCmd, tRowStats, tTimeStats );
iNulls = 0;
if ( UINT64_MAX==tTimeStats.m_dStats[INTERVAL_15MIN].m_dData[TYPE_MIN] )
iNulls = 3;
else if ( UINT64_MAX==tTimeStats.m_dStats[INTERVAL_5MIN].m_dData[TYPE_MIN] )
iNulls = 2;
else if ( UINT64_MAX==tTimeStats.m_dStats[INTERVAL_1MIN].m_dData[TYPE_MIN] )
iNulls = 1;
bCalculated = true;
}
StringBuilder_c sBuf;
switch ( iNulls )
{
case 0:
sBuf.Sprintf ( "%0.3D %0.3D %0.3D", tTimeStats.m_dStats[INTERVAL_1MIN].m_dData[j], tTimeStats.m_dStats[INTERVAL_5MIN].m_dData[j], tTimeStats.m_dStats[INTERVAL_15MIN].m_dData[j] );
break;
case 1:
sBuf.Sprintf ( "N/A %0.3D %0.3D", tTimeStats.m_dStats[INTERVAL_5MIN].m_dData[j], tTimeStats.m_dStats[INTERVAL_15MIN].m_dData[j] );
break;
case 2:
sBuf.Sprintf ( "N/A N/A %0.3D", tTimeStats.m_dStats[INTERVAL_15MIN].m_dData[j] );
break;
case 3:
sBuf << "N/A N/A N/A";
}
dStatus.Add ( sBuf.cstr () );
}
}
namespace {
SearchdStats_t tSt;
}
SearchdStats_t & gStats ()
{
return tSt;
}
// generic stats track - always to agent stats, separately to dashboard.
static void agent_stats_inc ( AgentConn_t &tAgent, AgentStats_e iCountID )
{
assert ( iCountID<=eMaxAgentStat );
assert ( tAgent.m_tDesc.m_pDash );
if ( tAgent.m_tDesc.m_pMetrics )
tAgent.m_tDesc.m_pMetrics->m_dCounters[iCountID].fetch_add(1,std::memory_order_relaxed);
HostDashboard_t &tIndexDash = *tAgent.m_tDesc.m_pDash;
ScWL_t tWguard ( tIndexDash.m_dMetricsLock );
MetricsAndCounters_t &tAgentMetrics = tIndexDash.GetCurrentMetrics ();
tAgentMetrics.m_dCounters[iCountID].fetch_add ( 1, std::memory_order_relaxed );;
if ( iCountID>=eNetworkNonCritical && iCountID<eMaxAgentStat )
tIndexDash.m_iErrorsARow = 0;
else
tIndexDash.m_iErrorsARow++;
tAgent.m_iEndQuery = sphMicroTimer ();
tIndexDash.m_iLastQueryTime = tAgent.m_iStartQuery;
tIndexDash.m_iLastAnswerTime = tAgent.m_iEndQuery;
// do not count query time for unlinked connections (pings)
// only count errors
if ( tAgent.m_tDesc.m_pMetrics )
{
tAgentMetrics.m_dMetrics[ehTotalMsecs] += tAgent.m_iEndQuery - tAgent.m_iStartQuery;
tAgent.m_tDesc.m_pMetrics->m_dMetrics[ehTotalMsecs] += tAgent.m_iEndQuery - tAgent.m_iStartQuery;
}
}
// special case of stats - all is ok, just need to track the time in dashboard.
static void track_processing_time ( AgentConn_t &tAgent )
{
// first we count temporary statistic (into dashboard)
assert ( tAgent.m_tDesc.m_pDash );
uint64_t uConnTime = ( uint64_t ) sphMicroTimer () - tAgent.m_iStartQuery;
{
ScWL_t tWguard ( tAgent.m_tDesc.m_pDash->m_dMetricsLock );
uint64_t * pMetrics = tAgent.m_tDesc.m_pDash->GetCurrentMetrics ().m_dMetrics;
++pMetrics[ehConnTries];
if ( uint64_t ( uConnTime )>pMetrics[ehMaxMsecs] )
pMetrics[ehMaxMsecs] = uConnTime;
if ( pMetrics[ehConnTries]>1 )
pMetrics[ehAverageMsecs] =
( pMetrics[ehAverageMsecs] * ( pMetrics[ehConnTries] - 1 ) + uConnTime ) / pMetrics[ehConnTries];
else
pMetrics[ehAverageMsecs] = uConnTime;
} // no need to hold dashboard anymore
if ( !tAgent.m_tDesc.m_pMetrics )
return;
// then we count permanent statistic (for show status)
uint64_t * pHStat = tAgent.m_tDesc.m_pMetrics->m_dMetrics;
++pHStat[ehConnTries];
if ( uint64_t ( uConnTime )>pHStat[ehMaxMsecs] )
pHStat[ehMaxMsecs] = uConnTime;
if ( pHStat[ehConnTries]>1 )
pHStat[ehAverageMsecs] =
( pHStat[ehAverageMsecs] * ( pHStat[ehConnTries] - 1 ) + uConnTime ) / pHStat[ehConnTries];
else
pHStat[ehAverageMsecs] = uConnTime;
}
/// try to parse hostname/ip/port or unixsocket on current pConfigLine.
/// fill pAgent fields on success and move ppLine pointer next after parsed instance
/// test cases and test group 'T_ParseAddressPort', are in gtest_searchdaemon.cpp.
bool ParseAddressPort ( HostDesc_t& dHost, const char ** ppLine, const WarnInfo_c & tInfo )
{
// extract host name or path
const char *&p = *ppLine;
const char * pAnchor = p;
if ( !p )
return false;
enum AddressType_e { apIP, apUNIX };
AddressType_e eState = apIP;
if ( *p=='/' ) // whether we parse inet or unix socket
eState = apUNIX;
while ( sphIsAlpha ( *p ) || *p=='.' || *p=='-' || *p=='/' )
++p;
if ( p==pAnchor )
return tInfo.ErrSkip ( "host name or path expected" );
CSphString sSub ( pAnchor, int ( p-pAnchor ) );
if ( eState==apUNIX )
{
#if !_WIN32
if ( strlen ( sSub.cstr () ) + 1>sizeof(((struct sockaddr_un *)0)->sun_path) )
return tInfo.ErrSkip ( "UNIX socket path is too long" );
#endif
dHost.m_iFamily = AF_UNIX;
dHost.m_sAddr = sSub;
return true;
}
// below is only deal with inet sockets
dHost.m_iFamily = AF_INET;
dHost.m_sAddr = sSub;
// expect ':' (and then portnum) after address
if ( *p!=':' )
{
dHost.m_iPort = IANA_PORT_SPHINXAPI;
tInfo.Warn ( "colon and portnum expected before '%s' - Using default IANA %d port", p, dHost.m_iPort );
return true;
}
pAnchor = ++p;
// parse portnum
while ( isdigit(*p) )
++p;
if ( p==pAnchor )
{
dHost.m_iPort = IANA_PORT_SPHINXAPI;
tInfo.Warn ( "portnum expected before '%s' - Using default IANA %d port", p, dHost.m_iPort );
--p; /// step back to ':'
return true;
}
dHost.m_iPort = atoi ( pAnchor );
if ( !IsPortInRange ( dHost.m_iPort ) )
return tInfo.ErrSkip ( "invalid port number near '%s'", p );
return true;
}
bool ParseStrategyHA ( const char * sName, HAStrategies_e & eStrategy )
{
if ( sphStrMatchStatic ( "random", sName ) )
eStrategy = HA_RANDOM;
else if ( sphStrMatchStatic ( "roundrobin", sName ) )
eStrategy = HA_ROUNDROBIN;
else if ( sphStrMatchStatic ( "nodeads", sName ) )
eStrategy = HA_AVOIDDEAD;
else if ( sphStrMatchStatic ( "noerrors", sName ) )
eStrategy = HA_AVOIDERRORS;
else
return false;
return true;
}
CSphString HAStrategyToStr ( HAStrategies_e eStrategy )
{
switch ( eStrategy )
{
case HA_RANDOM: return "random";
case HA_ROUNDROBIN: return "roundrobin";
case HA_AVOIDDEAD: return "nodeads";
case HA_AVOIDERRORS: return "noerrors";
}
return "";
}
void ParseIndexList ( const CSphString &sIndexes, StrVec_t &dOut )
{
CSphString sSplit = sIndexes;
if ( sIndexes.IsEmpty () )
return;
auto * p = const_cast<char *> ( sSplit.cstr() );
while ( *p )
{
// skip non-alphas
while ( *p && !isalpha ( *p ) && !isdigit ( *p ) && *p!='_' && *p!='.' && *p!='-' )
p++;
if ( !( *p ) )
break;
// FIXME?
// We no not check that index name shouldn't start with '_'.
// That means it's de facto allowed for API queries.
// But not for SphinxQL ones.
// this is my next index name
const char * sNext = p;
while ( isalpha ( *p ) || isdigit ( *p ) || *p=='_' || *p=='.' || *p=='-' )
p++;
assert ( sNext!=p );
if ( *p )
*p++ = '\0'; // if it was not the end yet, we'll continue from next char
dOut.Add ( sNext );
}
}
// parse agent's options line and modify pOptions
static bool ParseOptions ( AgentOptions_t * pOptions, const CSphString & sOptions, const WarnInfo_c & tWI )
{
StrVec_t dSplitParts;
sphSplit ( dSplitParts, sOptions.cstr (), "," ); // diff. options are ,-separated
for ( auto &sOption : dSplitParts )
{
if ( sOption.IsEmpty () )
continue;
// split '=' separated pair into tokens
StrVec_t dOption;
sphSplit ( dOption, sOption.cstr (), "=" );
if ( dOption.GetLength ()!=2 )
return tWI.ErrSkip ( "option %s error: option and value must be =-separated pair", sOption.cstr () );
for ( auto &sOpt : dOption )
sOpt.ToLower ().Trim ();
const char * sOptName = dOption[0].cstr ();
const char * sOptValue = dOption[1].cstr ();
if ( sphStrMatchStatic ( "conn", sOptName ) )
{
if ( sphStrMatchStatic ( "pconn", sOptValue ) || sphStrMatchStatic ( "persistent", sOptValue ) )
{
pOptions->m_bPersistent = true;
continue;
}
} else if ( sphStrMatchStatic ( "ha_strategy", sOptName ) )
{
if ( ParseStrategyHA ( sOptValue, pOptions->m_eStrategy ) )
continue;
} else if ( sphStrMatchStatic ( "blackhole", sOptName ) )
{
pOptions->m_bBlackhole = ( atoi ( sOptValue )!=0 );
continue;
} else if ( sphStrMatchStatic ( "retry_count", sOptName ) )
{
pOptions->m_iRetryCount = atoi ( sOptValue );
pOptions->m_iRetryCountMultiplier = 1;
continue;
}
return tWI.ErrSkip ( "unknown agent option '%s'", sOption.cstr () );
}
return true;
}
// check whether all index(es) in list are valid index names
static bool CheckIndexNames ( const CSphString & sIndexes, const WarnInfo_c & tWI )
{
StrVec_t dRawIndexes, dParsedIndexes;
// compare two lists: one made by raw splitting with ',' character,
// second made by our ParseIndexList function.
sphSplit(dRawIndexes, sIndexes.cstr(), ",");
ParseIndexList ( sIndexes, dParsedIndexes );
if ( dParsedIndexes.GetLength ()==dRawIndexes.GetLength () )
return true;
ARRAY_FOREACH( i, dParsedIndexes )
{
dRawIndexes[i].Trim();
if ( dRawIndexes[i]!= dParsedIndexes[i] )
return tWI.ErrSkip ("no such table: %s", dRawIndexes[i].cstr());
}
return true;
}
// parse agent string into template vec of AgentDesc_t, then configure them.
static bool ConfigureMirrorSet ( CSphVector<AgentDesc_t*> &tMirrors, AgentOptions_t * pOptions, const WarnInfo_c & tWI )
{
assert ( tMirrors.IsEmpty () );
StrVec_t dSplitParts;
sphSplit ( dSplitParts, tWI.m_szAgent, "[]" );
if ( dSplitParts.IsEmpty () )
return tWI.ErrSkip ( "empty agent definition" );
if ( dSplitParts[0].IsEmpty () )
return tWI.ErrSkip ( "one or more hosts/sockets expected before [" );
if ( dSplitParts.GetLength ()<1 || dSplitParts.GetLength ()>2 )
return tWI.ErrSkip ( "wrong syntax: expected one or more hosts/sockets, then m.b. []-enclosed options" );
// parse agents
// separate '|'-splitted records, normalize result
StrVec_t dRawAgents;
sphSplit ( dRawAgents, dSplitParts[0].cstr (), "|" );
for ( auto &sAgent : dRawAgents )
sAgent.Trim ();
if ( dSplitParts.GetLength ()==2 && !ParseOptions ( pOptions, dSplitParts[1], tWI ) )
return false;
assert ( dRawAgents.GetLength ()>0 );
// parse separate strings into agent descriptors
for ( auto &sAgent: dRawAgents )
{
if ( sAgent.IsEmpty () )
continue;
tMirrors.Add ( new AgentDesc_t );
AgentDesc_t &dMirror = *tMirrors.Last ();
const char * sRawAgent = sAgent.cstr ();
if ( !ParseAddressPort ( dMirror, &sRawAgent, tWI ) )
return false;
// apply per-mirror options
dMirror.m_bPersistent = pOptions->m_bPersistent;
dMirror.m_bBlackhole = pOptions->m_bBlackhole;
if ( *sRawAgent )
{
if ( *sRawAgent!=':' )
return tWI.ErrSkip ( "after host/socket expected ':', then table(s), but got '%s')", sRawAgent );
CSphString sIndexList = ++sRawAgent;
sIndexList.Trim ();
if ( sIndexList.IsEmpty () )
continue;
if ( !CheckIndexNames ( sIndexList, tWI ) )
return false;
dMirror.m_sIndexes = sIndexList;
}
}
// fixup multiplier (if it is 0, it is still not defined).
if ( !pOptions->m_iRetryCountMultiplier )
pOptions->m_iRetryCountMultiplier = tMirrors.GetLength ();
// fixup agent's indexes name: if no index assigned, stick the next one (or the parent).
CSphString sLastIndex = tWI.m_szIndexName;
for ( int i = tMirrors.GetLength () - 1; i>=0; --i )
if ( tMirrors[i]->m_sIndexes.IsEmpty () )
tMirrors[i]->m_sIndexes = sLastIndex;
else
sLastIndex = tMirrors[i]->m_sIndexes;
return true;
}
// different cases are tested in T_ConfigureMultiAgent, see gtests_searchdaemon.cpp
MultiAgentDescRefPtr_c ConfigureMultiAgent ( const char * szAgent, const char * szIndexName, AgentOptions_t tOptions, CSphString & sError, StrVec_t * pWarnings )
{
MultiAgentDescRefPtr_c pRes;
CSphVector<AgentDesc_t *> tMirrors;
AT_SCOPE_EXIT ( [&tMirrors] { tMirrors.for_each( [] ( auto * pMirror ) { SafeDelete ( pMirror ); } ); } );
WarnInfo_c tWI ( szIndexName, szAgent, sError, pWarnings );
if ( ConfigureMirrorSet ( tMirrors, &tOptions, tWI ) )
pRes = MultiAgentDesc_c::GetAgent ( tMirrors, tOptions, tWI );
return pRes;
}
HostDesc_t &HostDesc_t::CloneFromHost ( const HostDesc_t &rhs )
{
if ( &rhs==this )
return *this;
m_pDash = rhs.m_pDash;
m_bBlackhole = rhs.m_bBlackhole;
m_uAddr = rhs.m_uAddr;
m_bNeedResolve = rhs.m_bNeedResolve;
m_bPersistent = rhs.m_bPersistent;
m_iFamily = rhs.m_iFamily;
m_sAddr = rhs.m_sAddr;
m_iPort = rhs.m_iPort;
return *this;
}
AgentDesc_t &AgentDesc_t::CloneFrom ( const AgentDesc_t &rhs )
{
if ( &rhs==this )
return *this;
CloneFromHost ( rhs );
m_sIndexes = rhs.m_sIndexes;
m_pMetrics = rhs.m_pMetrics;
return *this;
}
//// global dashboard
namespace Dashboard
{
class Dashboard_c final
{
mutable RwLock_t m_tDashLock; // short-term
CSphVector<HostDashboardRefPtr_t> m_dDashes GUARDED_BY ( m_tDashLock );
private:
CSphVector<HostDashboardRefPtr_t> GetActiveHostsUnl() REQUIRES_SHARED ( m_tDashLock )
{
CSphVector<HostDashboardRefPtr_t> dRes;
for ( auto& pDash : m_dDashes )
if ( !pDash->IsLast() )
dRes.Add ( pDash );
return dRes;
}
public:
void CleanupOrphaned()
{
ScWL_t tWguard ( m_tDashLock );
auto dNew = GetActiveHostsUnl();
m_dDashes.SwapData ( dNew );
}
// linear search, since very rare template of usage
HostDashboardRefPtr_t FindAgent ( const CSphString& sAgent )
{
ScRL_t tRguard ( m_tDashLock );
for ( auto& pDash : m_dDashes )
if ( !pDash->IsLast() && pDash->m_tHost.GetMyUrl() == sAgent )
return pDash;
return HostDashboardRefPtr_t(); // not found
}
void LinkHost ( HostDesc_t& dHost )
{
assert ( !dHost.m_pDash );
dHost.m_pDash = FindAgent ( dHost.GetMyUrl() );
if ( dHost.m_pDash )
return;
// nothing found existing; so create the new.
dHost.m_pDash = new HostDashboard_t ( dHost );
ScWL_t tWguard ( m_tDashLock );
m_dDashes.Add ( dHost.m_pDash );
}
CSphVector<HostDashboardRefPtr_t> GetActiveHosts()
{
ScRL_t tRguard ( m_tDashLock );
return GetActiveHostsUnl();
}
};
Dashboard_c& GDash()
{
static Dashboard_c tDash;
return tDash;
}
void CleanupOrphaned ()
{
GDash().CleanupOrphaned();
}
// Due to very rare template of usage, linear search is quite enough here
HostDashboardRefPtr_t FindAgent ( const CSphString& sAgent )
{
return GDash().FindAgent(sAgent);
}
void LinkHost ( HostDesc_t &dHost )
{
GDash().LinkHost(dHost);
}
CSphVector<HostDashboardRefPtr_t> GetActiveHosts ()
{
return GDash().GetActiveHosts();
}
} // namespace Dashboard
/// IOVec_c : wrapper over vector of system iovec/WSABuf
/////////////////////////////////////////////////////////////////////////////
void IOVec_c::BuildFrom ( const SmartOutputBuffer_t &tSource )
{
tSource.GetIOVec ( m_dIOVec );
if ( m_dIOVec.IsEmpty () )
return;
m_iIOChunks = ( size_t ) m_dIOVec.GetLength ();
}
void IOVec_c::Reset()
{
m_dIOVec.Reset();
m_iIOChunks = 0;
}
void IOVec_c::StepForward ( size_t uStep )
{
auto iLen = m_dIOVec.GetLength ();
for ( ; m_iIOChunks>0; --m_iIOChunks )
{
auto & tIOVec = m_dIOVec[iLen - m_iIOChunks];
if ( uStep < IOLEN ( tIOVec ) )
{
IOPTR ( tIOVec ) = IOBUFTYPE ( ( BYTE * ) IOPTR ( tIOVec ) + uStep );
#if _WIN32
IOLEN ( tIOVec ) -= (DWORD)uStep;
#else
IOLEN ( tIOVec ) -= uStep;
#endif
break;
}
uStep -= IOLEN ( tIOVec );
}
}
void SafeCloseSocket ( int & iFD )
{
if ( iFD>=0 )
sphSockClose ( iFD );
iFD = -1;
}
inline static bool IS_PENDING ( int iErr )
{
#if _WIN32
return iErr==ERROR_IO_PENDING || iErr==0;
#else
return iErr==EAGAIN || iErr==EWOULDBLOCK;
#endif
}
inline static bool IS_PENDING_PROGRESS ( int iErr )
{
return IS_PENDING ( iErr ) || iErr==EINPROGRESS;
}
/////////////////////////////////////////////////////////////////////////////
// some extended win-specific stuff
#if _WIN32
static LPFN_CONNECTEX ConnectEx = nullptr;
#ifndef WSAID_CONNECTEX
#define WSAID_CONNECTEX \
{0x25a207b9,0xddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}
#endif
bool LoadExFunctions ()
{
GUID uGuidConnectX = WSAID_CONNECTEX;
// Dummy socket (for WSAIoctl call)
SOCKET iSocket = socket ( AF_INET, SOCK_STREAM, 0 );
if ( iSocket == INVALID_SOCKET )
return false;
// fill addr of ConnectX function
DWORD m_Bytes;
auto iRes = WSAIoctl ( iSocket, SIO_GET_EXTENSION_FUNCTION_POINTER,
&uGuidConnectX, sizeof ( uGuidConnectX ),
&ConnectEx, sizeof ( ConnectEx ),
&m_Bytes, NULL, NULL );
closesocket ( iSocket );
return ( iRes==0 );
}
#endif
/////////////////////////////////////////////////////////////////////////////
/// AgentConn_t
///
/// Network task: socket, io buffers, query/result parsers,
/// helper structs.
/////////////////////////////////////////////////////////////////////////////
AgentConn_t::~AgentConn_t ()
{
sphLogDebugv ( "AgentConn %p destroyed", this );
if ( m_iSock>=0 )
Finish ();
}
void AgentConn_t::State ( Agent_e eState )
{
sphLogDebugv ( "state %s > %s, sock %d, order %d, %p",
Agent_e_Name ( m_eConnState ), Agent_e_Name ( eState ), m_iSock, m_iStoreTag, this );
m_eConnState = eState;
if ( eState==Agent_e::RETRY )
gStats().m_iAgentRetry.fetch_add ( 1, std::memory_order_relaxed );
}
// initialize socket from persistent pool (it m.b. disconnected or not initialized, however).
bool AgentConn_t::IsPersistent ()
{
return m_tDesc.m_bPersistent && m_tDesc.m_pDash && m_tDesc.m_pDash->m_pPersPool;
}
// return socket to the pool (it m.b. connected!)
void AgentConn_t::ReturnPersist ()
{
assert ( ( m_iSock==-1 ) || IsPersistent () ); // otherwize it will leak...
if ( IsPersistent() )
m_tDesc.m_pDash->m_pPersPool->ReturnConnection ( m_iSock );
m_iSock = -1;
}
/// 'soft' failure - log and return false
bool AgentConn_t::Fail ( const char * sFmt, ... )
{
va_list ap;
va_start ( ap, sFmt );
m_sFailure.SetSprintfVa ( sFmt, ap );
va_end ( ap );
sphLogDebugv ( "%d Fail() %s, ref=%d", m_iStoreTag, m_sFailure.cstr (), ( int ) GetRefcount () ); // want to log failure at extended log mode wo recompile of daemon
return false;
}
//! 'hard' failure - close socket, switch to 'RETRY' state, then write stats, log and return false
//! \param eStat - error category
bool AgentConn_t::Fatal ( AgentStats_e eStat, const char * sMessage, ... )
{
va_list ap;
va_start ( ap, sMessage );
m_sFailure.SetSprintfVa ( sMessage, ap );
va_end ( ap );
sphLogDebugv ( "%d FATAL: %s", m_iStoreTag, m_sFailure.cstr () ); // want to log failure at extended log mode wo recompile of daemon
State ( Agent_e::RETRY );
Finish ( true );
agent_stats_inc ( *this, eStat );
return false;
}
/// correct way to close connection:
void AgentConn_t::Finish ( bool bFail )
{
if ( m_iSock>=0 && ( bFail || !IsPersistent() ) )
{
sphLogDebugA ( "%d Socket %d closed and turned to -1", m_iStoreTag, m_iSock );
SafeCloseSocket ( m_iSock );
}
sphLogDebugA ( "%d Abort all callbacks ref=%d", m_iStoreTag, ( int ) GetRefcount () );
LazyDeleteOrChange (); // remove timer and all callbacks, if any
m_pPollerTask = nullptr;
ReturnPersist ();
if ( m_iStartQuery )
m_iWall += sphMicroTimer () - m_iStartQuery; // imitated old behaviour
}
//! Failure from successfully ended session
//! (i.e. no network issues, but error in packet itself - like bad syntax, or simple 'try again').
//! so, we don't have to corrupt agent's stat in the case.
bool AgentConn_t::BadResult ( int iError )
{
sphLogDebugA ( "%d BadResult() ref=%d", m_iStoreTag, ( int ) GetRefcount () );
if ( iError==-1 )
sphLogDebugA ( "%d text error is %s", m_iStoreTag, m_sFailure.cstr () );
else if ( iError )
sphLogDebugA ( "%d error is %d, %s", m_iStoreTag, iError, sphSockError ( iError ) );
State ( Agent_e::RETRY );
Finish ();
if ( m_pResult )
m_pResult->Reset ();
return false;
}
void AgentConn_t::ReportFinish ( bool bSuccess )
{
if ( m_pReporter )
m_pReporter->Report ( bSuccess );
m_iRetries = -1; // avoid any accidental retry in future. fixme! better investigate why such accident may happen
m_bManyTries = false; // avoid report message because of it.
}
/// switch from 'connecting' to 'healthy' state.
/// track the time, modify timeout from 'connect' to 'query', inform poller about it.
void AgentConn_t::SendingState ()
{
if ( StateIs ( Agent_e::CONNECTING ) )
{
track_processing_time ( *this );
State ( Agent_e::HEALTHY );
m_iPoolerTimeoutPeriodUS = m_iMyQueryTimeoutMs* 1000;
m_iPoolerTimeoutUS = MonoMicroTimer() + m_iPoolerTimeoutPeriodUS;
LazyDeleteOrChange ( m_iPoolerTimeoutUS, m_iPoolerTimeoutPeriodUS ); // assign new time value, don't touch the handler
}
}
/// prepare all necessary things to connect
/// assume socket is NOT connected
bool AgentConn_t::StartNextRetry ()
{
sphLogDebugA ( "%d StartNextRetry() retries=%d, ref=%d", m_iStoreTag, m_iRetries, ( int ) GetRefcount () );
m_iSock = -1;
if ( m_pMultiAgent && !IsBlackhole () && m_iRetries>=0 )
{
m_tDesc.CloneFrom ( m_pMultiAgent->ChooseAgent () );
SwitchBlackhole ();
}
if ( m_iRetries--<0 )
return m_bManyTries && Fail ( "retries limit exceeded" );
sphLogDebugA ( "%d Connection %p, host %s, pers=%d", m_iStoreTag, this, m_tDesc.GetMyUrl().cstr(), m_tDesc.m_bPersistent );
if ( IsPersistent() )
{
assert ( m_iSock==-1 );
m_iSock = m_tDesc.m_pDash->m_pPersPool->RentConnection ();
m_tDesc.m_bPersistent = m_iSock!=-2;
if ( m_iSock>=0 && sphNBSockEof ( m_iSock ) )
SafeCloseSocket ( m_iSock );
}
return true;
}
// if we're blackhole, drop retries, parser, reporter and return true
bool AgentConn_t::SwitchBlackhole ()
{
if ( IsBlackhole () )
{
sphLogDebugA ( "%d Connection %p is blackhole (no retries, no parser, no reporter)", m_iStoreTag, this );
if ( m_iRetries>0 )
m_iRetries = 0;
m_bManyTries = false;
m_pParser = nullptr;
m_pReporter = nullptr;
return true;
}
return false;
}
// set up ll the stuff about async query. Namely - add timeout callback,
// initialize read/write task
void AgentConn_t::ScheduleCallbacks ()
{
LazyTask ( m_iPoolerTimeoutUS, m_iPoolerTimeoutPeriodUS, true, BYTE ( m_dIOVec.HasUnsent () ? 1 : 2 ) );
}
void FirePoller (); // forward definition
// retry timeout used when we need to pause before next retry, so just start connection when it fired
// hard timeout used when connection/query timed out. Drop existing connection and try again.
void AgentConn_t::TimeoutCallback ()
{
SetNetLoop ();
auto ePrevKind = m_eTimeoutKind;
m_eTimeoutKind = TIMEOUT_UNKNOWN;
// check if we accidentally orphaned (that is bug!)
if ( CheckOrphaned() )
return;
switch ( ePrevKind )
{
case TIMEOUT_RETRY:
if ( !DoQuery () )
StartRemoteLoopTry ();
FirePoller (); // fixme? M.b. no more necessary, since processing queue will restart on fired timeout.
sphLogDebugA ( "%d finished retry timeout ref=%d", m_iStoreTag, ( int ) GetRefcount () );
break;
case TIMEOUT_HARD:
if ( StateIs ( Agent_e::CONNECTING ) )
Fatal ( eTimeoutsConnect, "connect and query timed out" );
else
Fatal ( eTimeoutsQuery, "query timed out" );
StartRemoteLoopTry ();
sphLogDebugA ( "%d <- hard timeout (ref=%d)", m_iStoreTag, ( int ) GetRefcount () );
break;
case TIMEOUT_UNKNOWN:
default:
sphLogDebugA ("%d Unknown kind of timeout invoked. No action", m_iStoreTag );
}
}
// the reason for orphanes is suggested to be combined write, then read in netloop with epoll
bool AgentConn_t::CheckOrphaned()
{
// check if we accidentally orphaned (that is bug!)
if ( IsLast () && !IsBlackhole () )
{
sphLogDebug ( "Orphaned (last) connection detected!" );
return true;
}
if ( m_pReporter && m_pReporter->IsDone () )
{
sphLogDebug ( "Orphaned (kind of done) connection detected!" );
return true;
}
return false;
}
void AgentConn_t::AbortCallback()
{
ReportFinish (false);
}
void AgentConn_t::ErrorCallback ( int64_t iWaited )
{
SetNetLoop ();
if ( !m_pPollerTask )
return;
m_iWaited += iWaited;
int iErr = sphSockGetErrno ();
Fatal ( eNetworkErrors, "detected the error (errno=%d, msg=%s)", iErr, sphSockError ( iErr ) );
StartRemoteLoopTry ();
}
void AgentConn_t::SendCallback ( int64_t iWaited, DWORD uSent )
{
SetNetLoop ();
if ( !m_pPollerTask )
return;
if ( m_dIOVec.HasUnsent () )
{
m_iWaited += iWaited;
if ( !SendQuery ( uSent ) )
StartRemoteLoopTry ();
sphLogDebugA ( "%d <- finished SendCallback (ref=%d)", m_iStoreTag, ( int ) GetRefcount () );
}
}
void AgentConn_t::RecvCallback ( int64_t iWaited, DWORD uReceived )
{
SetNetLoop ();
if ( !m_pPollerTask )
return;
m_iWaited += iWaited;
if ( !ReceiveAnswer ( uReceived ) )
StartRemoteLoopTry ();
sphLogDebugA ( "%d <- finished RecvCallback", m_iStoreTag );
}
/// if iovec is empty, prepare (build) the request.
void AgentConn_t::BuildData ()
{
if ( m_pBuilder && m_dIOVec.IsEmpty () )
{
sphLogDebugA ( "%d BuildData for this=%p, m_pBuilder=%p", m_iStoreTag, this, m_pBuilder );
// prepare our data to send.
m_pBuilder->BuildRequest ( *this, m_tOutput );
m_dIOVec.BuildFrom ( m_tOutput );
} else
sphLogDebugA ( "%d BuildData, already done", m_iStoreTag );
}
//! How many bytes we can read to m_pReplyCur (in bytes)
size_t AgentConn_t::ReplyBufPlace () const
{
if ( !m_pReplyCur )
return 0;
if ( m_dReplyBuf.IsEmpty () )
return m_dReplyHeader.begin () + REPLY_HEADER_SIZE - m_pReplyCur;
return m_dReplyBuf.begin () + m_dReplyBuf.GetLength () - m_pReplyCur;
}
void AgentConn_t::InitReplyBuf ( int iSize )
{
sphLogDebugA ( "%d InitReplyBuf ( %d )", m_iStoreTag, iSize );
m_dReplyBuf.Reset ( iSize );
if ( m_dReplyBuf.IsEmpty () )
{
m_iReplySize = -1;
m_pReplyCur = m_dReplyHeader.begin ();
} else {
m_pReplyCur = m_dReplyBuf.begin ();
m_iReplySize = iSize;
}
}
#if _WIN32
void AgentConn_t::LeakRecvTo ( CSphFixedVector<BYTE>& dOut )
{
assert ( dOut.IsEmpty () );
if ( m_iReplySize<0 )
{
dOut.SwapData ( m_dReplyHeader );
m_dReplyHeader.Reset ( REPLY_HEADER_SIZE );
} else
dOut.SwapData ( m_dReplyBuf );
InitReplyBuf ();
}
void AgentConn_t::LeakSendTo ( CSphVector <ISphOutputBuffer* >& dOut, CSphVector<sphIovec>& dOutIO )
{
assert ( dOut.IsEmpty () );
assert ( dOutIO.IsEmpty () );
m_tOutput.LeakTo ( dOut );
m_dIOVec.LeakTo ( dOutIO );
}
#endif
/// raw (platform specific) send (scattered - from several buffers)
/// raw (platform specific) receive
#if _WIN32
inline SSIZE_T AgentConn_t::RecvChunk ()
{
assert ( !m_pPollerTask->m_dRead.m_bInUse );
if ( !m_pPollerTask )
ScheduleCallbacks ();
WSABUF dBuf;
dBuf.buf = (CHAR*) m_pReplyCur;
dBuf.len = (ULONG) ReplyBufPlace ();
DWORD uFlags = 0;
m_pPollerTask->m_dRead.Zero ();
sphLogDebugA ( "%d Scheduling overlapped WSARecv for %d bytes", m_iStoreTag, ReplyBufPlace () );
m_pPollerTask->m_dRead.m_bInUse = true;
WSARecv ( m_iSock, &dBuf, 1, nullptr, &uFlags, &m_pPollerTask->m_dRead, nullptr );
return -1;
}
inline SSIZE_T AgentConn_t::SendChunk ()
{
assert ( !m_pPollerTask->m_dWrite.m_bInUse );
SendingState ();
if ( !m_pPollerTask )
ScheduleCallbacks ();
m_pPollerTask->m_dWrite.Zero ();
sphLogDebugA ( "%d overlaped WSASend called for %d chunks", m_iStoreTag, m_dIOVec.IOSize () );
m_pPollerTask->m_dWrite.m_bInUse = true;
WSASend ( m_iSock, m_dIOVec.IOPtr (), (DWORD) m_dIOVec.IOSize (), nullptr, 0, &m_pPollerTask->m_dWrite, nullptr );
return -1;
}
#else
inline SSIZE_T AgentConn_t::RecvChunk ()
{
return sphSockRecv ( m_iSock, (char *) m_pReplyCur, ReplyBufPlace () );
}
inline SSIZE_T AgentConn_t::SendChunk ()
{
struct msghdr dHdr = { 0 };
dHdr.msg_iov = m_dIOVec.IOPtr ();
dHdr.msg_iovlen = m_dIOVec.IOSize ();
return ::sendmsg ( m_iSock, &dHdr, MSG_NOSIGNAL | MSG_DONTWAIT );
}
#endif
/// try to establish connection in the modern fast way, and also perform some data sending, if possible.
/// @return 1 on success, 0 if need fallback into usual (::connect), -1 on failure.
int AgentConn_t::DoTFO ( struct sockaddr * pSs, int iLen )
{
if ( pSs->sa_family==AF_UNIX || g_iTFO==TFO_ABSENT || !(g_iTFO & TFO_CONNECT) )
return 0;
m_iStartQuery = sphMicroTimer (); // copied old behaviour
#if _WIN32
if ( !ConnectEx )
return 0;
struct sockaddr_in sAddr;
ZeroMemory ( &sAddr, sizeof ( sAddr ) );
sAddr.sin_family = AF_INET;
sAddr.sin_addr.s_addr = INADDR_ANY;
sAddr.sin_port = 0;
int iRes = bind ( m_iSock, (SOCKADDR*) &sAddr, sizeof ( sAddr ) );
if ( iRes != 0 )
{
Fail ( "bind failed: %d %s", iRes, m_tDesc.m_sAddr.cstr() );
return 0;
}
#if defined ( TCP_FASTOPEN )
int iOn = 1;
iRes = setsockopt ( m_iSock, IPPROTO_TCP, TCP_FASTOPEN, (char*) &iOn, sizeof ( iOn ) );
if ( iRes )
sphLogDebug ( "setsockopt (TCP_FASTOPEN) failed: %s", sphSockError () );
sphLogDebugA ( "%d TFO branch", m_iStoreTag );
// fixme! ConnectEx doesn't accept scattered buffer. Need to prepare plain one for at least MSS size
#endif
BuildData ();
if ( !m_pPollerTask )
ScheduleCallbacks ();
sphLogDebugA ( "%d overlaped ConnectEx called", m_iStoreTag );
m_pPollerTask->m_dWrite.Zero();
// let us also send first chunk of the buff
sphIovec * pChunk = m_dIOVec.IOPtr ();
assert ( pChunk );
assert ( !m_pPollerTask->m_dWrite.m_bInUse );
m_pPollerTask->m_dWrite.m_bInUse = true;
iRes = ConnectEx ( m_iSock, pSs, iLen, pChunk->buf, pChunk->len, NULL, &m_pPollerTask->m_dWrite );
if ( iRes )
{
State ( Agent_e::CONNECTING );
gStats().m_iAgentConnectTFO.fetch_add ( 1, std::memory_order_relaxed );
return 1;
}
int iErr = sphSockGetErrno ();
if ( !IS_PENDING ( iErr ) )
{
Fatal ( eConnectFailures, "ConnectEx failed with %d, %s", iErr, sphSockError ( iErr ) );
return -1;
}
State ( Agent_e::CONNECTING );
gStats().m_iAgentConnect.fetch_add ( 1, std::memory_order_relaxed );
return 1;
#else // _WIN32
#if defined (MSG_FASTOPEN)
BuildData ();
struct msghdr dHdr = { 0 };
dHdr.msg_iov = m_dIOVec.IOPtr ();
dHdr.msg_iovlen = m_dIOVec.IOSize ();
dHdr.msg_name = pSs;
dHdr.msg_namelen = iLen;
auto iRes = ::sendmsg ( m_iSock, &dHdr, MSG_NOSIGNAL | MSG_FASTOPEN );
#elif defined (__APPLE__)
struct sa_endpoints sAddr = { 0 };
sAddr.sae_dstaddr = pSs;
sAddr.sae_dstaddrlen = iLen;
BuildData ();
size_t iSent = 0;
auto iRes = connectx ( m_iSock, &sAddr, SAE_ASSOCID_ANY, CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT
, m_dIOVec.IOPtr (), m_dIOVec.IOSize (), &iSent, nullptr );
if ( iSent )
{
sphLogDebugv ( "Mac OS TFO: advancing to %zu with %d, error %d (%s)", iSent, iRes, sphSockGetErrno(), strerror (sphSockGetErrno()) );
m_dIOVec.StepForward ( iSent );
if ( iRes<0 && m_dIOVec.HasUnsent () )
iRes = 0;
else if ( !m_dIOVec.HasUnsent() )
m_iPoolerTimeoutUS += m_iMyQueryTimeoutMs * 1000;
}
#else
int iRes = 0;
return iRes;
#endif
if ( iRes>=0 ) // lucky; we already sent something!
{
track_processing_time ( *this );
sphLogDebugA ( "%d sendmsg/connectx returned %d", m_iStoreTag, ( size_t ) iRes );
sphLogDebugv ( "TFO send succeeded, %zu bytes sent", ( size_t ) iRes );
// now 'connect' and 'query' merged, so timeout became common.
m_iPoolerTimeoutPeriodUS = m_iMyQueryTimeoutMs* 1000;
m_iPoolerTimeoutUS += m_iPoolerTimeoutPeriodUS;
gStats().m_iAgentConnectTFO.fetch_add ( 1, std::memory_order_relaxed );
return SendQuery ( iRes ) ? 1 : -1;
}
auto iErr = sphSockGetErrno ();
if ( iErr!=EINPROGRESS )
{
if ( iErr==EOPNOTSUPP )
{
assert ( g_iTFO!=TFO_ABSENT );
sphWarning("TFO client supoport unavailable, switch to usual connect()");
g_iTFO &= ~TFO_CONNECT;
return 0;
}
Fatal ( eConnectFailures, "sendmsg/connectx() failed: errno=%d, %s", iErr, sphSockError ( iErr ) );
return -1;
}
sphLogDebugA ( "%d TFO returned EINPROGRESS (usuall connect in game; scheduling callbacks)", m_iStoreTag );
ScheduleCallbacks ();
gStats().m_iAgentConnect.fetch_add ( 1, std::memory_order_relaxed );
return 1;
#endif
}
//! Simplified wrapper for ScheduleDistrJobs, wait for finish and return succeeded
int PerformRemoteTasks ( VectorAgentConn_t &dRemotes, RequestBuilder_i * pQuery, ReplyParser_i * pParser, int iQueryRetry, int iQueryDelay )
{
if ( dRemotes.IsEmpty() )
return 0;
CSphRefcountedPtr<RemoteAgentsObserver_i> tReporter { GetObserver () };
ScheduleDistrJobs ( dRemotes, pQuery, pParser, tReporter, iQueryRetry, iQueryDelay );
tReporter->Finish ();
return (int)tReporter->GetSucceeded ();
}
/// Add set of works (dRemotes) to the queue.
/// jobs themselves are ref-counted and owned by nobody (they're just released on finish, so
/// if nobody waits them (say, blackhole), they just dissapeared).
/// on return blackholes removed from dRemotes
void ScheduleDistrJobs ( VectorAgentConn_t &dRemotes, RequestBuilder_i * pQuery, ReplyParser_i * pParser,
Reporter_i * pReporter, int iQueryRetry, int iQueryDelay )
{
// sphLogSupress ( "L ", SPH_LOG_VERBOSE_DEBUG );
// sphLogSupress ( "- ", SPH_LOG_VERBOSE_DEBUG );
// TimePrefixed::TimeStart();
assert ( pReporter );
sphLogDebugv ( "S ==========> ScheduleDistrJobs() for %d remotes", dRemotes.GetLength () );
if ( dRemotes.IsEmpty () )
{
sphWarning ("Empty remotes provided to ScheduleDistrJobs. Consider to save resources and avoid it");
return;
}
bool bNeedKick = false; // if some of connections falled to waiting and need to kick the poller.
ARRAY_FOREACH ( i, dRemotes )
{
auto & pConnection = dRemotes[i];
pConnection->GenericInit ( pQuery, pParser, pReporter, iQueryRetry, iQueryDelay );
// start the actual job.
// It might lucky be completed immediately. Or, it will be acquired by async network
// (and addreffed there in the loop)
pReporter->FeedTask ( true );
pConnection->StartRemoteLoopTry ();
bNeedKick |= pConnection->FireKick ();
// remove and release blackholes from the queue.
if ( pConnection->IsBlackhole () )
{
sphLogDebugv ( "S Remove blackhole()" );
SafeReleaseAndZero ( pConnection );
dRemotes.RemoveFast ( i-- );
pReporter->FeedTask ( false );
}
}
if ( bNeedKick )
{
sphLogDebugA ( "A Events need fire. Do it..." );
FirePoller ();
}
sphLogDebugv ( "S ScheduleDistrJobs() done. Total %d", dRemotes.GetLength () );
}
class ReportCallback_c : public Reporter_i
{
public:
template <typename CALLBACK_F>
ReportCallback_c ( CALLBACK_F&& fAction, AgentConn_t* pConnection )
: m_pCallback { std::forward<CALLBACK_F> ( fAction ) }
, m_pConnection ( pConnection )
{}
void FeedTask ( bool bAdd ) final
{
if ( bAdd )
SafeAddRef ( m_pConnection );
else
SafeReleaseAndZero ( m_pConnection ); // yes, SafeReleaseAndZero will make m_pConnection=0 at the end!
}
void Report ( bool bParam ) final
{
assert ( m_pConnection && "strange Report called without the connection!" );
SafeReleaseAndZero ( m_pConnection );
if ( m_pCallback )
m_pCallback ( bParam );
}
// just always return 'false' here to suppress any kind of 'orphaned' stuff.
bool IsDone () const final { return false; }
private:
using BoolCallBack_f = std::function<void ( bool )>;
BoolCallBack_f m_pCallback = nullptr;
AgentConn_t * m_pConnection = nullptr;
};
/// Schedule one job (remote). Callback pAction will be called with bool 'success' param on finish.
/// If connection is blackhole, returns false, and callback will NOT be called in the case
/// (since blackholes live alone).
static bool RunRemoteTaskImpl ( AgentConn_t * pConnection, RequestBuilder_i * pQuery, ReplyParser_i * pParser, Reporter_i * pReporter, int iQueryRetry, int iQueryDelay )
{
sphLogDebugv ( "S ==========> ScheduleDistrJob()" );
pConnection->GenericInit ( pQuery, pParser, pReporter, iQueryRetry, iQueryDelay );
// start the actual job.
// It might lucky be completed immediately. Or, it will be acquired by async network
// (and addreffed there in the loop)
pReporter->FeedTask ( true );
pConnection->StartRemoteLoopTry ();
bool bNeedKick = pConnection->FireKick (); // if connection falled to waiting and need to kick the poller.
// blackhole is not traced; remove it
bool bBlackhole = pConnection->IsBlackhole ();
if ( bBlackhole)
{
sphLogDebugv ( "S Remove blackhole()" );
pReporter->FeedTask ( false );
}
if ( bNeedKick )
{
sphLogDebugA ( "A Events need fire. Do it..." );
FirePoller ();
}
sphLogDebugv ( "S ScheduleDistrJob() done. Result is %d", bBlackhole?0:1);
return !bBlackhole;
}
bool RunRemoteTask ( AgentConn_t* pConnection, RequestBuilder_i* pQuery, ReplyParser_i* pParser,
Deffered_f&& pAction, int iQueryRetry, int iQueryDelay )
{
CSphRefcountedPtr<Reporter_i> pReporter (
new ReportCallback_c ( std::move ( pAction ), pConnection ));
return RunRemoteTaskImpl ( pConnection, pQuery, pParser, pReporter, iQueryRetry, iQueryDelay );
}
// unused for now
/*
static bool RunRemoteTask ( AgentConn_t * pConnection, RequestBuilder_i * pQuery, ReplyParser_i * pParser, const Deffered_f & pAction, int iQueryRetry, int iQueryDelay )
{
CSphRefcountedPtr<Reporter_i> pReporter ( new ReportCallback_c ( pAction, pConnection ) );
return RunRemoteTaskImpl ( pConnection, pQuery, pParser, pReporter, iQueryRetry, iQueryDelay );
}
*/
// this is run once entering query loop for all retries (and all mirrors).
void AgentConn_t::GenericInit ( RequestBuilder_i * pQuery, ReplyParser_i * pParser,
Reporter_i * pReporter, int iQueryRetry, int iQueryDelay )
{
sphLogDebugA ( "%d GenericInit() pBuilder %p, parser %p, retries %d(%d), delay %d(%d), ref=%d",
m_iStoreTag, pQuery, pParser, iQueryRetry, m_iRetries, iQueryDelay, m_iDelay, ( int ) GetRefcount ());
if ( iQueryDelay>=0 )
m_iDelay = iQueryDelay;
m_pBuilder = pQuery;
m_iWall = 0;
m_iWaited = 0;
m_bNeedKick = false;
m_pPollerTask = nullptr;
if ( m_pMultiAgent || !SwitchBlackhole() )
{
SafeAddRef ( pReporter );
m_pReporter = pReporter;
m_pParser = pParser;
if ( iQueryRetry>=0 )
m_iRetries = iQueryRetry * m_iMirrorsCount;
m_bManyTries = m_iRetries>0;
}
SetNetLoop ( false );
State ( Agent_e::HEALTHY );
}
/// an entry point to the whole remote agent's work
void AgentConn_t::StartRemoteLoopTry ()
{
sphLogDebugA ( "%d StartRemoteLoopTry() ref=%d", m_iStoreTag, ( int ) GetRefcount () );
while ( StartNextRetry () )
{
/// reset state before every retry
m_dIOVec.Reset ();
m_tOutput.Reset ();
InitReplyBuf ();
m_bConnectHandshake = true;
m_bSuccess = false;
m_iStartQuery = 0;
m_pPollerTask = nullptr;
if ( StateIs ( Agent_e::RETRY ) )
{
assert ( !IsBlackhole () ); // blackholes never uses retry!
assert ( !m_pPollerTask ); // must be cleaned out before try!
// here we can came not only after delay, but also immediately (if iDelay==0)
State ( Agent_e::HEALTHY );
if ( m_iDelay>0 )
{
// can't start right now; need to postpone until timeout
sphLogDebugA ( "%d postpone DoQuery() for %d msecs", m_iStoreTag, m_iDelay );
LazyTask ( MonoMicroTimer () + 1000 * m_iDelay, 1000*m_iDelay, false );
return;
}
}
if ( DoQuery () )
return;
};
ReportFinish ( false );
sphLogDebugA ( "%d StartRemoteLoopTry() finished ref=%d", m_iStoreTag, ( int ) GetRefcount () );
}
// do oneshot query. Return true on any success
bool AgentConn_t::DoQuery()
{
sphLogDebugA ( "%d DoQuery() ref=%d", m_iStoreTag, ( int ) GetRefcount () );
auto iNow = sphMicroTimer ();
auto iMonoNow = MonoMicroTimer();
if ( m_iSock>=0 )
{
sphLogDebugA ( "%d branch for established(%d). Timeout " INT64_FMT, m_iStoreTag, m_iSock, m_iMyQueryTimeoutMs );
m_bConnectHandshake = false;
m_pReplyCur += sizeof ( int );
m_iStartQuery = iNow; /// copied from old behaviour
m_iPoolerTimeoutPeriodUS = m_iMyQueryTimeoutMs* 1000;
m_iPoolerTimeoutUS = iMonoNow + m_iPoolerTimeoutPeriodUS;
return SendQuery ();
}
// fill initial chunks
m_tOutput.SendDword ( SPHINX_CLIENT_VERSION );
m_tOutput.StartNewChunk ();
if ( IsPersistent() && m_iSock==-1 )
{
{
auto tHdr = APIHeader ( m_tOutput, SEARCHD_COMMAND_PERSIST );
m_tOutput.SendInt ( 1 ); // set persistent to 1.
}
m_tOutput.StartNewChunk ();
}
sphLogDebugA ( "%d branch for not established. Timeout " INT64_FMT, m_iStoreTag, m_iMyQueryTimeoutMs );
m_iPoolerTimeoutPeriodUS = 1000 * m_iMyConnectTimeoutMs;
m_iPoolerTimeoutUS = iMonoNow + m_iPoolerTimeoutPeriodUS;
if ( !m_tDesc.m_bNeedResolve )
return EstablishConnection ();
// here we're in case agent's remote addr need to be resolved (DNS required)
assert ( m_tDesc.m_iFamily==AF_INET );
AddRef ();
sphLogDebugA ( "%d -> async GetAddress_a scheduled() ref=%d", m_iStoreTag, ( int ) GetRefcount () );
DNSResolver_c::GetAddress_a ( m_tDesc.m_sAddr.cstr (), [this] ( DWORD uIP )
{
sphLogDebugA ( "%d :- async GetAddress_a callback (ip is %u) ref=%d", m_iStoreTag, uIP, ( int ) GetRefcount () );
m_tDesc.m_uAddr = uIP;
if ( !EstablishConnection () )
StartRemoteLoopTry ();
sphLogDebugA ( "%d <- async GetAddress_a returned() ref=%d", m_iStoreTag, ( int ) GetRefcount () );
if ( FireKick () )
FirePoller ();
Release ();
} );
// for blackholes we parse query immediately, since builder will be disposed
// outside once we returned from the function
if ( IsBlackhole () )
BuildData ();
return true;
}
// here ip resolved; socket is NOT connected.
// We can initiate connect, or even send the chunk using TFO.
bool AgentConn_t::EstablishConnection ()
{
sphLogDebugA ( "%d EstablishConnection() ref=%d", m_iStoreTag, ( int ) GetRefcount () );
// first check if we're in bounds of timeout.
// usually it is done by outside callback, however in case of deferred DNS we may be here out of sync and so need
// to check it explicitly.
if ( m_iPoolerTimeoutUS < MonoMicroTimer() )
return Fatal ( eConnectFailures, "connect timeout reached resolving address for %s", m_tDesc.m_sAddr.cstr () );
if ( m_tDesc.m_iFamily==AF_INET && !m_tDesc.m_uAddr )
return Fatal ( eConnectFailures, "can't get address for %s", m_tDesc.m_sAddr.cstr () );
assert (m_iSock==-1); ///< otherwize why we're here?
socklen_t len = 0;
sockaddr_storage ss = {0};
ss.ss_family = m_tDesc.m_iFamily;
if ( ss.ss_family==AF_INET )
{
auto * pIn = ( struct sockaddr_in * ) &ss;
pIn->sin_port = htons ( ( unsigned short ) m_tDesc.m_iPort );
pIn->sin_addr.s_addr = m_tDesc.m_uAddr;
len = sizeof ( *pIn );
}
#if !_WIN32
else if ( ss.ss_family==AF_UNIX )
{
auto * pUn = ( struct sockaddr_un * ) &ss;
strncpy ( pUn->sun_path, m_tDesc.m_sAddr.cstr (), sizeof ( pUn->sun_path ) );
len = sizeof ( *pUn );
}
#endif
m_iSock = (int)socket ( m_tDesc.m_iFamily, SOCK_STREAM, 0 );
sphLogDebugA ( "%d Created new socket %d", m_iStoreTag, m_iSock );
if ( m_iSock<0 )
return Fatal ( eConnectFailures, "socket() failed: %s", sphSockError () );
if ( sphSetSockNB ( m_iSock )<0 )
return Fatal ( eConnectFailures, "sphSetSockNB() failed: %s", sphSockError () );
// connection in progress
State ( Agent_e::CONNECTING );
// prepare our data to send.
auto iTfoRes = DoTFO ( ( struct sockaddr * ) &ss, len );
if ( iTfoRes==1 )
return true;
else if ( iTfoRes==-1 )
return false;
m_iStartQuery = sphMicroTimer (); // copied old behaviour
sphLogDebugA ( "%d usual ::connect invoked for %d", m_iStoreTag, m_iSock );
int iRes = ::connect ( m_iSock, ( struct sockaddr * ) &ss, len );
if ( iRes<0 )
{
int iErr = sphSockGetErrno ();
if ( iErr==EINTR || !IS_PENDING_PROGRESS ( iErr ) ) // check for EWOULDBLOCK is for winsock only
return Fatal ( eConnectFailures, "connect() failed: errno=%d, %s", iErr, sphSockError ( iErr ) );
}
gStats().m_iAgentConnect.fetch_add ( 1, std::memory_order_relaxed );
return SendQuery ();
}
/// send query (whole, or chunk)
/// if data is sent by external routine, param says how many bytes are sent.
bool AgentConn_t::SendQuery ( DWORD uSent )
{
sphLogDebugA ( "%d SendQuery() ref=%d", m_iStoreTag, ( int ) GetRefcount () );
// here we have connected socket and are in process of sending blob there.
// prepare our data to send.
if ( !uSent )
BuildData ();
SSIZE_T iRes = 0;
while ( m_dIOVec.HasUnsent () )
{
iRes = uSent ? std::exchange ( uSent, 0 ) : SendChunk();
if ( iRes==-1 )
break;
sphLogDebugA ( "%d sent %d bytes", m_iStoreTag, (int)iRes );
m_dIOVec.StepForward ( iRes );
if ( iRes>0 )
SendingState ();
}
if ( !m_dIOVec.HasUnsent () ) // we've abandoned output queue
{
sphLogDebugA ( "%d sending finished", m_iStoreTag );
DisableWrite();
return ReceiveAnswer ();
}
assert ( iRes==-1 );
int iErr = sphSockGetErrno ();
if ( !IS_PENDING_PROGRESS(iErr) )
{
if ( !( iErr==ENOTCONN && StateIs ( Agent_e::CONNECTING ) ) )
return Fatal ( eNetworkErrors, "error when sending data: %s", sphSockError ( iErr ) );
else
sphLogDebugA ( "%d Not connected, schedule... ref=%d", m_iStoreTag, ( int ) GetRefcount () );
}
sphLogDebugA ( "%d -> Schedule sender ref=%d", m_iStoreTag, ( int ) GetRefcount () );
ScheduleCallbacks ();
return true;
}
// here we fall when we're expect to read something from remote side
bool AgentConn_t::ReceiveAnswer ( DWORD uRecv )
{
sphLogDebugA ( "%d ReceiveAnswer() ref=%d", m_iStoreTag, ( int ) GetRefcount () );
// check if we just read anything, of already read something and have to continue.
SSIZE_T iRes = 0;
while ( ReplyBufPlace () )
{
iRes = uRecv ? std::exchange ( uRecv, 0 ) : RecvChunk ();
if ( iRes<=0 )
break;
m_pReplyCur += iRes;
auto iRest = ReplyBufPlace ();
sphLogDebugA ( "%d RecvChunk returned %d (%d bytes rest in input buffer)", m_iStoreTag, ( int ) iRes, iRest );
// We're in state of receiving the header (m_iReplySize==-1 is the indicator)
if ( IsReplyHeader () && iRest<=( REPLY_HEADER_SIZE - 4 ))
{
MemInputBuffer_c dBuf ( m_dReplyHeader.begin(), REPLY_HEADER_SIZE );
auto iVer = dBuf.GetInt ();
sphLogDebugA ( "%d Handshake is %d (this message may appear >1 times)", m_iStoreTag, iVer );
// parse handshake answer (if necessary)
if ( m_bConnectHandshake && iVer!=SPHINX_SEARCHD_PROTO && iVer!=0x01000000UL )
return Fatal ( eWrongReplies, "handshake failure (unexpected protocol version=%d)", iVer );
if ( !iRest ) // not only handshake, but whole header is here
{
auto uStat = dBuf.GetWord ();
auto VARIABLE_IS_NOT_USED uVer = dBuf.GetWord (); // there is version here. But it is not used.
auto iReplySize = dBuf.GetInt ();
sphLogDebugA ( "%d Header (Status=%d, Version=%d, answer need %d bytes)", m_iStoreTag, uStat, uVer, iReplySize );
if ( iReplySize<0 || ( m_bReplyLimitSize && iReplySize>g_iMaxPacketSize ) ) // FIXME! add reasonable max packet len too
return Fatal ( eWrongReplies, "invalid packet size (status=%d, len=%d, max_packet_size=%d)", uStat, iReplySize, g_iMaxPacketSize );
// allocate buf for reply
InitReplyBuf ( iReplySize );
m_eReplyStatus = ( SearchdStatus_e ) uStat;
}
}
}
if ( !ReplyBufPlace () ) // we've received full reply
{
auto bRes = CommitResult ();
if ( bRes )
ReportFinish ( true );
return bRes;
}
if ( !iRes ) // timeout or eof happens; retry.
return Fatal ( eUnexpectedClose, "agent closed connection" );
assert ( iRes==-1 );
int iErr = sphSockGetErrno ();
if ( !IS_PENDING ( iErr ) )
return Fatal ( eNetworkErrors, "receiving failure (errno=%d, msg=%s)", iErr, sphSockError ( iErr ) );
ScheduleCallbacks();
return true;
}
void AgentConn_t::SetNoLimitReplySize()
{
m_bReplyLimitSize = false;
}
// when full blob with expected size is received...
// just a fine: parse the answer, collect results, dispose agent as one is done.
bool AgentConn_t::CommitResult ()
{
sphLogDebugA ( "%d CommitResult() ref=%d, parser %p", m_iStoreTag, ( int ) GetRefcount (), m_pParser );
if ( !m_pParser )
{
Finish();
return true;
}
if ( m_pReporter && m_pReporter->IsDone ())
{
Finish ();
sphLogDebug ( "Orphaned (kind of done) connection detected!" );
return true;
}
MemInputBuffer_c tReq ( m_dReplyBuf.Begin (), m_iReplySize );
if ( m_eReplyStatus == SEARCHD_RETRY )
{
m_sFailure.SetSprintf ( "remote warning: %s", tReq.GetString ().cstr () );
return BadResult ( -1 );
}
if ( m_eReplyStatus == SEARCHD_ERROR )
{
m_sFailure.SetSprintf ( "remote error: %s", tReq.GetString ().cstr () );
return BadResult ( -1 );
}
bool bWarnings = ( m_eReplyStatus == SEARCHD_WARNING );
if ( bWarnings )
m_sFailure.SetSprintf ( "remote warning: %s", tReq.GetString ().cstr () );
if ( !m_pParser->ParseReply ( tReq, *this ) )
return BadResult ();
Finish();
if ( !bWarnings && m_pResult )
bWarnings = m_pResult->HasWarnings ();
agent_stats_inc ( *this, bWarnings ? eNetworkCritical : eNetworkNonCritical );
m_bSuccess = true;
return true;
}
void AgentConn_t::SetMultiAgent ( MultiAgentDescRefPtr_c pAgent )
{
assert ( pAgent );
m_iMirrorsCount = pAgent->GetLength ();
m_iRetries = pAgent->GetRetryLimit ();
m_pMultiAgent = std::move ( pAgent );
m_bManyTries = m_iRetries>0;
}
#if 0
// here is async dns resolution made on mac os
//#include <CoreFoundation/CoreFoundation.h>
#include <CFNetwork/CFNetwork.h>
// just a template based on https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/ResolvingDNSHostnames.html
void clbck ( CFHostRef theHost, CFHostInfoType typeInfo
, const CFStreamError * error
, void * info)
{
Boolean bOk;
auto arr = CFHostGetAddressing( theHost, &bOk );
if ( bOk )
{
auto iSize = CFArrayGetCount ( arr );
for ( auto i=0; i<iSize; ++i )
{
auto * pValue = ( CFDataRef )CFArrayGetValueAtIndex (arr, i);
struct sockaddr_in * remoteAddr = ( struct sockaddr_in * ) CFDataGetBytePtr ( pValue );
}
}
}
// see also https://stackoverflow.com/questions/1363787/is-it-safe-to-call-cfrunloopstop-from-another-thread
void macresolver()
{
CFStringRef a = CFStringCreateWithCString ( kCFAllocatorDefault, "hello.world.com", kCFStringEncodingUTF8 );
auto hostRef = CFHostCreateWithName ( kCFAllocatorDefault, a );
CFRelease (a);
CFHostClientContext ctx { 0 };
// ctx.info = this
Boolean set_ok = CFHostSetClient ( hostRef, &clbck, &ctx );
CFHostScheduleWithRunLoop ( hostRef, CFRunLoopGetCurrent (), kCFRunLoopCommonModes );
CFStreamError sError;
Boolean is_resolving = CFHostStartInfoResolution ( hostRef, kCFHostAddresses, &sError );
// CFRelease ( hostRef ); // fixme! where to put it? Here? Or in callback?
}
#endif
struct TaskNet_t:
#if _WIN32
DoubleOverlapped_t,
#endif
EnqueuedTimeout_t
{
enum IO : BYTE { NO = 0, RW = 1, RO = 2 };
AgentConn_t * m_pPayload = nullptr; // ext conn we hold
int64_t m_iPlannedTimeoutUS = 0; // asked timeout (-1 - delete task, 0 - no changes; >0 - set value)
int64_t m_iLastActivityTm = -1; // used with reset-on-packet timeout
int64_t m_iTimeoutPeriodUS = -1; // used to restore timeout
int m_ifd = -1;
int m_iStoredfd = -1; // helper to find original fd if socket was closed
int m_iTickProcessed=0; // tick # to detect and avoid reading callback in same loop with write
BYTE m_uIOActive = NO; // active IO callbacks: 0-none, 1-r+w, 2-r
BYTE m_uIOChanged = NO; // need IO changes: dequeue (if !m_uIOActive), 1-set to rw, 2-set to ro
};
static ThreadRole LazyThread;
// low-level ops depends from epoll/kqueue/iocp availability
#if _WIN32
class NetEvent_c
{
TaskNet_t * m_pTask = nullptr;
bool m_bWrite = false;
DWORD m_uNumberOfBytesTransferred = 0;
bool m_bSignaler = true;
public:
explicit NetEvent_c ( LPOVERLAPPED_ENTRY pEntry )
{
if ( !pEntry )
return;
m_bSignaler = !pEntry->lpOverlapped;
if ( m_bSignaler )
return;
auto pOvl = (SingleOverlapped_t *) pEntry->lpOverlapped;
auto uOffset = pOvl->m_uParentOffset;
m_pTask = (TaskNet_t *) ( (BYTE*) pOvl - uOffset );
m_bWrite = uOffset<sizeof ( OVERLAPPED );
m_uNumberOfBytesTransferred = pEntry->dwNumberOfBytesTransferred;
if ( m_pTask )
{
assert ( pOvl->m_bInUse );
pOvl->m_bInUse = false;
if ( m_pTask->m_ifd==-1 && m_pTask->m_pPayload==nullptr && !m_pTask->IsInUse() )
{
sphLogDebugL ( "L Removing deffered %p", m_pTask );
SafeDelete ( m_pTask );
}
}
}
inline TaskNet_t * GetTask () const noexcept
{
return m_pTask;
}
inline bool IsSignaler () const noexcept
{
return m_bSignaler;
}
inline int GetEvents() const noexcept
{
// return 0 for internal signal, or 1 for write, 1+sizeof(OVERLAPPED) for read.
return (!!m_pTask) + 2 * (!!m_bWrite);
}
inline bool IsError() const noexcept
{
return false;
}
inline bool IsEof() const noexcept
{
return !m_bWrite && !m_uNumberOfBytesTransferred;
}
inline bool IsRead() const noexcept
{
return !m_bWrite;
}
inline bool IsWrite() const noexcept
{
return m_bWrite;
}
inline DWORD BytesTransferred () const noexcept
{
return m_uNumberOfBytesTransferred;
}
};
#elif POLLING_EPOLL
class NetEvent_c
{
struct epoll_event * m_pEntry = nullptr;
const TaskNet_t * m_pSignalerTask = nullptr;
public:
NetEvent_c ( struct epoll_event * pEntry, const TaskNet_t * pSignaler )
: m_pEntry ( pEntry )
, m_pSignalerTask ( pSignaler )
{}
inline TaskNet_t * GetTask () const noexcept
{
assert ( m_pEntry );
return ( TaskNet_t * ) m_pEntry->data.ptr;
}
inline bool IsSignaler () const noexcept
{
assert ( m_pEntry );
auto pTask = GetTask ();
if ( pTask==m_pSignalerTask )
{
auto pSignaler = ( PollableEvent_t * ) m_pSignalerTask->m_pPayload;
pSignaler->DisposeEvent ();
}
return pTask==m_pSignalerTask;
}
inline int GetEvents () const noexcept
{
assert ( m_pEntry );
return m_pEntry->events;
}
inline bool IsError () const noexcept
{
assert ( m_pEntry );
return ( m_pEntry->events & EPOLLERR )!=0;
}
inline bool IsEof () const noexcept
{
assert ( m_pEntry );
return ( m_pEntry->events & EPOLLHUP )!=0;
}
inline bool IsRead () const noexcept
{
assert ( m_pEntry );
return ( m_pEntry->events & EPOLLIN )!=0;
}
inline bool IsWrite () const noexcept
{
assert ( m_pEntry );
return ( m_pEntry->events & EPOLLOUT )!=0;
}
inline DWORD BytesTransferred () const noexcept
{
assert ( m_pEntry );
return 0;
}
};
#elif POLLING_KQUEUE
class NetEvent_c
{
struct kevent * m_pEntry = nullptr;
public:
explicit NetEvent_c ( struct kevent * pEntry )
: m_pEntry ( pEntry )
{}
inline TaskNet_t * GetTask () const noexcept
{
assert ( m_pEntry );
return ( TaskNet_t * ) m_pEntry->udata;
}
inline bool IsSignaler () const noexcept
{
assert ( m_pEntry );
return m_pEntry->filter == EVFILT_USER;
}
inline int GetEvents () const noexcept
{
assert ( m_pEntry );
return m_pEntry->filter;
}
inline bool IsError () const noexcept
{
assert ( m_pEntry );
if ( ( m_pEntry->flags & EV_ERROR )==0 )
return false;
sphLogDebugL ( "L error for %u, errno=%u, %s", m_pEntry->ident, m_pEntry->data, strerror ( m_pEntry->data ) );
return true;
}
inline bool IsEof () const noexcept
{
assert ( m_pEntry );
return ( m_pEntry->flags & EV_EOF )!=0;
}
inline bool IsRead () const noexcept
{
assert ( m_pEntry );
return ( m_pEntry->filter==EVFILT_READ )!=0;
}
inline bool IsWrite () const noexcept
{
assert ( m_pEntry );
return ( m_pEntry->filter==EVFILT_WRITE )!=0;
}
inline DWORD BytesTransferred () const noexcept
{
assert ( m_pEntry );
return 0;
}
};
#endif
class NetEventsFlavour_c
{
protected:
int m_iEvents = 0; ///< how many events are in queue.
static constexpr int m_iCReserve = 256; /// will always provide extra that space of events to poller
// perform actual changing OR scheduling of pTask subscription state (on BSD we collect changes and will populate later)
// NOTE! m_uIOChanged==0 field here means active 'unsubscribe' (in use for deletion)
void events_change_io ( TaskNet_t * pTask )
{
assert ( pTask );
// check if 'pure timer' deletion asked (i.e. task which didn't have io at all)
if ( !pTask->m_uIOActive && !pTask->m_uIOChanged )
{
sphLogDebugL ( "L events_change_io invoked for pure timer (%p); nothing to do (m_ifd, btw, is %d)", pTask, pTask->m_ifd );
return;
}
auto iEvents = events_apply_task_changes ( pTask );
m_iEvents += iEvents;
pTask->m_uIOActive = std::exchange ( pTask->m_uIOChanged, TaskNet_t::NO );
sphLogDebugL ( "L events_apply_task_changes returned %d, now %d events counted", iEvents, m_iEvents );
}
protected:
#if _WIN32
// for windows it is one more level of indirection:
// we set and wait for the tasks in one thread,
// and iocp also have several working threads.
HANDLE m_IOCP = INVALID_HANDLE_VALUE;
CSphVector<DWORD> m_dIOThreads;
CSphVector<OVERLAPPED_ENTRY> m_dReady;
inline void poller_create ( int iSizeHint )
{
// fixme! m.b. more workers, or just one enough?
m_IOCP = CreateIoCompletionPort ( INVALID_HANDLE_VALUE, NULL, 0, 1 );
sphLogDebugL ( "L IOCP %d created", m_IOCP );
m_dReady.Reserve (m_iCReserve + iSizeHint);
}
inline void events_destroy ()
{
sphLogDebugv ( "iocp poller %d closed", m_IOCP );
// that is have to be done only when ALL reference sockets are closed.
// what about persistent? Actually we have to first close them, then close iocp.
// m.b. on finish of the daemon that is not so important, but just mentioned to be known.
CloseHandle ( m_IOCP );
}
inline void fire_event ()
{
if ( !PostQueuedCompletionStatus ( m_IOCP, 0, 0, 0 ) )
sphLogDebugv ( "L PostQueuedCompletionStatus failed with error %u", GetLastError() );
}
private:
// each action added one-by-one...
int events_apply_task_changes ( TaskNet_t * pTask )
{
// if socket already closed (say, FATAL in action),
// we don't need to unsubscribe events, but still need to return num of deleted events
// to keep in health poller's input buffer
bool bApply = pTask->m_ifd!=-1;
if ( !pTask->m_uIOChanged ) // requested delete
{
sphLogDebugL ( "L request to remove event (%d), %d events rest", pTask->m_ifd, m_iEvents );
if ( pTask->IsInUse () && pTask->m_pPayload && bApply )
{
if ( pTask->m_dRead.m_bInUse && pTask->m_dReadBuf.IsEmpty () )
{
sphLogDebugL ( "L canceling read" );
pTask->m_pPayload->LeakRecvTo ( pTask->m_dReadBuf );
CancelIoEx ( (HANDLE)(ULONG_PTR)pTask->m_ifd, &pTask->m_dRead );
}
if ( pTask->m_dWrite.m_bInUse && pTask->m_dWriteBuf.IsEmpty () && pTask->m_dOutIO.IsEmpty () )
{
sphLogDebugL ( "L canceling write" );
pTask->m_pPayload->LeakSendTo ( pTask->m_dWriteBuf, pTask->m_dOutIO );
CancelIoEx ( (HANDLE)(ULONG_PTR)pTask->m_ifd, &pTask->m_dWrite );
}
}
return pTask->m_ifd==-1 ? -2 : 0;
/*
Hackers way to unbind from IOCP:
Call NtSetInformationFile with the FileReplaceCompletionInformationenumerator value for
FileInformationClass and a pointer to a FILE_COMPLETION_INFORMATION structure for the FileInformation parameter.
In this structure, set the Port member to NULL (or nullptr, in C++) to disassociate the file from the port it's
currently attached to (I guess if it isn't attached to any port, nothing would happen), or set Port to a valid
HANDLE to another completion port to associate the file with that one instead.
However it 1-st, require win >=8.1, and also invoke DDK stuff which is highly non-desirable. So, leave it 'as is'.
*/
}
if ( !pTask->m_uIOActive )
{
sphLogDebugL ( "L Associate %d with iocp %d, %d events before", pTask->m_ifd, m_IOCP, m_iEvents );
if ( !CreateIoCompletionPort ( (HANDLE)(ULONG_PTR)pTask->m_ifd, m_IOCP, (ULONG_PTR) pTask->m_ifd, 0 ) )
sphLogDebugv ( "L Associate %d with port %d failed with error %u", pTask->m_ifd, m_IOCP, GetLastError() );
return 2;
}
sphLogDebugL ( "L According to state, %d already associated with iocp %d, no action", pTask->m_ifd, m_IOCP );
return 0;
}
protected:
// always return 0 (timeout) or 1 (since iocp returns per event, not the bigger group).
inline int events_wait ( int64_t iTimeoutUS )
{
ULONG uReady = 0;
DWORD uTimeout = ( iTimeoutUS>=0 ) ? ( iTimeoutUS/1000 ) : INFINITE;
m_dReady.Resize ( m_iEvents+m_iCReserve ); // +1 since our signaler is not added as resident of the queue
if ( !GetQueuedCompletionStatusEx ( m_IOCP, m_dReady.Begin (), m_dReady.GetLength (), &uReady, uTimeout, FALSE ) )
{
auto iErr = GetLastError ();
if ( iErr==WAIT_TIMEOUT )
return 0;
sphLogDebugL ( "L GetQueuedCompletionStatusEx failed with error %d", iErr );
return 0;
}
return uReady;
}
// returns task and also selects current event for all the functions below
NetEvent_c GetEvent ( int iReady )
{
if ( iReady>=0 )
return NetEvent_c ( &m_dReady[iReady] );
assert (false);
return NetEvent_c ( nullptr );
}
#else
int m_iEFD = -1;
inline void poller_create ( int iSizeHint )
{
epoll_or_kqueue_create_impl ( iSizeHint );
m_dReady.Reserve ( iSizeHint );
register_signaller();
}
#if POLLING_EPOLL
PollableEvent_t m_dSignaler;
TaskNet_t m_dSignalerTask;
CSphVector<epoll_event> m_dReady;
inline void register_signaller()
{
// special event to wake up
m_dSignalerTask.m_ifd = m_dSignaler.m_iPollablefd;
// m_pPayload here used ONLY as store for pointer for comparing with &m_dSignaller,
// NEVER called this way (since it NOT points to AgentConn_t instance)
m_dSignalerTask.m_pPayload = ( AgentConn_t * ) &m_dSignaler;
m_dSignalerTask.m_uIOChanged = TaskNet_t::RO;
sphLogDebugv( "Add internal signaller");
events_change_io ( &m_dSignalerTask );
sphLogDebugv ( "Internal signal action (for epoll/kqueue) added (%d), %p",
m_dSignaler.m_iPollablefd, &m_dSignalerTask );
}
inline void fire_event()
{
m_dSignaler.FireEvent();
}
private:
inline void epoll_or_kqueue_create_impl ( int iSizeHint )
{
m_iEFD = epoll_create ( iSizeHint ); // 1000 is dummy, see man
if ( m_iEFD==-1 )
sphDie ( "failed to create epoll main FD, errno=%d, %s", errno, strerrorm ( errno ) );
m_dReady.Reserve ( m_iCReserve + iSizeHint );
sphLogDebugv ( "epoll %d created", m_iEFD );
}
// apply changes in case of epoll
int events_apply_task_changes ( TaskNet_t * pTask ) const
{
auto iEvents = 0; // how many events we add/delete
// if socket already closed (say, FATAL in action),
// we don't need to unsubscribe events, but still need to return num of deleted events
// to keep in health poller's input buffer
bool bApply = pTask->m_ifd!=-1;
bool bWrite = pTask->m_uIOChanged==TaskNet_t::RW;
bool bRead = pTask->m_uIOChanged!=TaskNet_t::NO;
int iOp = 0;
epoll_event tEv = { 0 };
tEv.data.ptr = pTask;
// boring matrix of conditions...
if ( !pTask->m_uIOChanged )
{
iOp = EPOLL_CTL_DEL;
--iEvents;
sphLogDebugL ( "L EPOLL_CTL_DEL(%d), %d+%d events", pTask->m_ifd, m_iEvents, iEvents );
} else
{
tEv.events = ( bRead ? EPOLLIN : 0 ) | ( bWrite ? EPOLLOUT : 0 ) | ( ( pTask==&m_dSignalerTask ) ? 0 : EPOLLET );
if ( !pTask->m_uIOActive )
{
iOp = EPOLL_CTL_ADD;
++iEvents;
sphLogDebugL ( "L EPOLL_CTL_ADD(%d) -> %x, %d+%d events", pTask->m_ifd, tEv.events, m_iEvents, iEvents );
} else
{
iOp = EPOLL_CTL_MOD;
sphLogDebugL ( "L EPOLL_CTL_MOD(%d) -> %x, %d+%d events", pTask->m_ifd, tEv.events, m_iEvents, iEvents );
}
}
if ( bApply )
{
auto iRes = epoll_ctl ( m_iEFD, iOp, pTask->m_ifd, &tEv );
if ( iRes==-1 )
sphLogDebugL ( "L failed to perform epollctl for sock %d(%p), errno=%d, %s", pTask->m_ifd, pTask, errno, strerrorm ( errno ) );
} else
sphLogDebugL ( "L epoll_ctl not called since sock is closed" );
return iEvents;
}
protected:
inline void events_destroy ()
{
sphLogDebugv ( "epoll %d closed", m_iEFD );
SafeClose ( m_iEFD );
}
inline int events_wait ( int64_t iTimeoutUS )
{
m_dReady.Resize ( m_iEvents + m_iCReserve );
int iTimeoutMS = iTimeoutUS<0 ? -1 : ( ( iTimeoutUS + 500 ) / 1000 );
return epoll_wait ( m_iEFD, m_dReady.Begin (), m_dReady.GetLength (), iTimeoutMS );
};
// returns task and also selects current event for all the functions below
NetEvent_c GetEvent ( int iReady )
{
if ( iReady>=0 )
return NetEvent_c ( &m_dReady[iReady], &m_dSignalerTask );
assert ( false );
return NetEvent_c ( nullptr, &m_dSignalerTask );
}
#elif POLLING_KQUEUE
CSphVector<struct kevent> m_dReady;
struct kevent * m_pEntry = nullptr;
inline void register_signaller() const
{
struct kevent tSignaller;
EV_SET ( &tSignaller, 0, EVFILT_USER, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, 0 );
[[maybe_unused]] bool bRes = 0 == kevent ( m_iEFD, &tSignaller, 1, 0, 0, 0 );
assert ( bRes );
}
inline void fire_event() const
{
struct kevent tSignaller;
EV_SET ( &tSignaller, 0, EVFILT_USER, 0, NOTE_TRIGGER, 0, 0 );
[[maybe_unused]] bool bRes = 0 == kevent ( m_iEFD, &tSignaller, 1, 0, 0, 0 );
assert ( bRes );
}
private:
inline void epoll_or_kqueue_create_impl ( int iSizeHint )
{
m_iEFD = kqueue ();
if ( m_iEFD==-1 )
sphDie ( "failed to create kqueue main FD, errno=%d, %s", errno, strerrorm ( errno ) );
sphLogDebugv ( "kqueue %d created", m_iEFD );
m_dReady.Reserve ( iSizeHint * 2 + m_iCReserve );
}
int events_apply_task_changes ( TaskNet_t * pTask ) const
{
bool bWrite = pTask->m_uIOChanged==TaskNet_t::RW;
bool bRead = pTask->m_uIOChanged!=TaskNet_t::NO;
bool bWasWrite = pTask->m_uIOActive==TaskNet_t::RW;;
bool bWasRead = ( pTask->m_uIOActive!=TaskNet_t::NO);
struct kevent tEv[2];
auto pEv = &tEv[0];
// boring combination matrix below
if ( bRead && !bWasRead )
EV_SET ( pEv++, pTask->m_ifd, EVFILT_READ, EV_ADD, 0, 0, pTask );
if ( bWrite && !bWasWrite )
EV_SET ( pEv++, pTask->m_ifd, EVFILT_WRITE, EV_ADD, 0, 0, pTask );
if ( !bRead && bWasRead )
EV_SET ( pEv++, pTask->m_ifd, EVFILT_READ, EV_DELETE, 0, 0, pTask );
if ( !bWrite && bWasWrite )
EV_SET ( pEv++, pTask->m_ifd, EVFILT_WRITE, EV_DELETE, 0, 0, pTask );
const int nEvs = pEv - tEv;
assert ( nEvs <= 2 );
int iEvents = 0;
for ( int i = 0; i < nEvs; ++i )
{
iEvents += ( tEv[i].flags == EV_ADD ) ? 1 : -1;
sphLogDebugL ( "L kqueue setup, ev=%d, fl=%d, sock=%d (%d enqueued), %d in call", tEv[i].filter, tEv[i].flags, pTask->m_ifd, nEvs, iEvents );
}
bool bApply = pTask->m_ifd != -1;
if ( !bApply )
sphLogDebugL ( "L kqueue not called since sock is closed" );
else {
auto iRes = kevent ( m_iEFD, tEv, nEvs, nullptr, 0, nullptr );
if ( iRes == -1 )
sphLogDebugL ( "L failed to perform kevent for sock %d(%p), errno=%d, %s", pTask->m_ifd, pTask, errno, strerrorm ( errno ) );
}
return iEvents;
}
protected:
inline void events_destroy ()
{
sphLogDebugv ( "kqueue %d closed", m_iEFD );
SafeClose ( m_iEFD );
}
inline int events_wait ( int64_t iTimeoutUS )
{
m_dReady.Resize ( m_iEvents + m_iCReserve );
timespec ts;
timespec * pts = nullptr;
if ( iTimeoutUS>=0 )
{
ts.tv_sec = iTimeoutUS / 1000000;
ts.tv_nsec = ( long ) ( iTimeoutUS - ts.tv_sec * 1000000 ) * 1000;
pts = &ts;
}
// need positive timeout for communicate threads back and shutdown
return kevent ( m_iEFD, nullptr, 0, m_dReady.begin (), m_dReady.GetLength (), pts );
};
// returns task and also selects current event for all the functions below
NetEvent_c GetEvent ( int iReady )
{
if ( iReady>=0 )
return NetEvent_c ( &m_dReady[iReady] );
assert ( false );
return NetEvent_c ( nullptr );
}
#endif
#endif
};
/// Like ISphNetEvents, but most syscalls optimized out
class LazyNetEvents_c : ISphNoncopyable, protected NetEventsFlavour_c
{
using VectorTask_c = CSphVector<TaskNet_t*>;
// stuff to transfer (enqueue) tasks
VectorTask_c * m_pEnqueuedTasks GUARDED_BY (m_dActiveLock) = nullptr; // ext. mt queue where we add tasks
VectorTask_c m_dInternalTasks; // internal queue where we add our tasks without mutex
CSphMutex m_dActiveLock;
TimeoutQueue_c m_dTimeouts;
SphThread_t m_dWorkingThread;
int m_iLastReportedErrno = -1;
volatile int m_iTickNo = 1;
int64_t m_iNextTimeoutUS = 0;
private:
/// maps AgentConn_t -> Task_c for new/existing task
static inline TaskNet_t * CreateNewTask ( AgentConn_t * pConnection )
{
auto pTask = new TaskNet_t;
pTask->m_ifd = pTask->m_iStoredfd = pConnection->m_iSock;
pTask->m_pPayload = pConnection;
pConnection->m_pPollerTask = pTask;
pConnection->AddRef ();
sphLogDebugv ( "- CreateNewTask for (%p)->%p, ref=%d", pConnection, pTask, (int) pConnection->GetRefcount () );
return pTask;
}
// Simply deletes the task, but some tricks exist:
// 1. (general): keeping payload necessary when we fire timeout: the task is not necessary anyway,
// however timeout callback need to be called with still valid (if any) payload.
// 2. (win specific): On windows, however, another trick is in game: timeout condition we get from
// internal GetQueuedCompletionStatusEx function. At the same time overlapped ops (WSAsend or recv,
// or even both) are still in work, and so we need to keep the 'overlapped' structs alive for them.
// So, we can't just delete the task in the case. Instead, we invalidate it (set m_ifd=-1, nullify payload),
// so that the next return from events_wait will recognize it and finally totally destroy the task for us.
AgentConn_t * DeleteTask ( TaskNet_t * pTask, bool bReleasePayload=true )
{
assert ( pTask );
sphLogDebugL ( "L DeleteTask for %p, (conn %p, io %d), release=%d", pTask, pTask->m_pPayload, pTask->m_uIOActive, bReleasePayload );
pTask->m_uIOChanged = TaskNet_t::NO;
events_change_io ( pTask );
auto pConnection = pTask->m_pPayload;
pTask->m_pPayload = nullptr;
// if payload already invoked in another task (remember, we process deferred action!)
// we won't nullify it.
if ( pConnection && pConnection->m_pPollerTask==pTask )
pConnection->m_pPollerTask = nullptr;
#if _WIN32
pTask->m_ifd = -1;
pTask = nullptr; // save from delete below
#endif
SafeDelete ( pTask );
if ( bReleasePayload )
SafeReleaseAndZero ( pConnection );
return pConnection;
}
/// Atomically move m-t queue to single-thread internal queue.
VectorTask_c * PopQueue () REQUIRES ( LazyThread ) EXCLUDES ( m_dActiveLock )
{
ScopedMutex_t tLock ( m_dActiveLock );
return std::exchange ( m_pEnqueuedTasks, nullptr );
}
void ProcessChanges ( TaskNet_t * pTask )
{
sphLogDebugL ( "L ProcessChanges for %p, (conn %p) (%d->%d), tm=" INT64_FMT " sock=%d", pTask, pTask->m_pPayload, pTask->m_uIOActive, pTask->m_uIOChanged, pTask->m_iTimeoutTimeUS, pTask->m_ifd );
assert ( pTask->m_iTimeoutTimeUS!=0);
if ( pTask->m_iPlannedTimeoutUS<0 ) // process delete.
{
sphLogDebugL ( "L finally remove task %p", pTask );
m_dTimeouts.Remove ( pTask );
DeleteTask ( pTask );
sphLogDebugL ( "%s", m_dTimeouts.DebugDump ( "L " ).cstr () );
return;
}
// on enqueued tasks m_uIOChanged == 0 doesn't request unsubscribe, but means 'nope'.
// (unsubscription, in turn, means 'delete' and planned by setting timeout=-1)
if ( pTask->m_uIOChanged )
events_change_io ( pTask );
if ( pTask->m_iPlannedTimeoutUS )
{
pTask->m_iTimeoutTimeUS = std::exchange ( pTask->m_iPlannedTimeoutUS, 0 );
m_dTimeouts.Change ( pTask );
sphLogDebugL ( "L change/add timeout for %p, " INT64_FMT " (" INT64_FMT ") is changed one", pTask, pTask->m_iTimeoutTimeUS, ( pTask->m_iTimeoutTimeUS - MonoMicroTimer () ) );
sphLogDebugL ( "%s", m_dTimeouts.DebugDump ( "L " ).cstr () );
}
}
/// take current internal and external queues, parse them and enqueue changes.
/// actualy 1 task can have only 1 action (another change will change very same task).
void ProcessEnqueuedTasks () REQUIRES ( LazyThread )
{
sphLogDebugL ( "L ProcessEnqueuedTasks" );
auto VARIABLE_IS_NOT_USED uStartLen = m_dInternalTasks.GetLength ();
auto pExternalQueue = PopQueue ();
if ( pExternalQueue )
m_dInternalTasks.Append ( *pExternalQueue );
SafeDelete ( pExternalQueue );
auto VARIABLE_IS_NOT_USED uLastLen = m_dInternalTasks.GetLength ();
m_dInternalTasks.Uniq ();
if ( m_dInternalTasks.IsEmpty () )
{
sphLogDebugL ( "L No tasks in queue" );
return;
}
sphLogDebugL ( "L starting processing %d internal events (originally %d, sparsed %d)", m_dInternalTasks.GetLength (), uStartLen, uLastLen );
for ( auto * pTask : m_dInternalTasks )
{
sphLogDebugL ( "L Start processing task %p", pTask );
ProcessChanges ( pTask );
sphLogDebugL ( "L Finish processing task %p", pTask );
}
sphLogDebugL ( "L All events processed" );
m_dInternalTasks.Reset ();
}
/// main event loop run in separate thread.
void EventLoop () REQUIRES ( LazyThread )
{
sphLogDebugL ( "L LazyNetEvents_c::EventLoop started" );
while ( true )
if ( !EventTick () )
break;
}
/// abandon and release all timeouted events.
/// \return next active timeout (in uS), or -1 for infinite.
bool HasTimeoutActions() REQUIRES ( LazyThread )
{
bool bHasTimeout = false;
while ( !m_dTimeouts.IsEmpty () )
{
auto* pTask = ( TaskNet_t* ) m_dTimeouts.Root ();
assert ( pTask->m_iTimeoutTimeUS>0 );
auto iMonoTime = MonoMicroTimer();
m_iNextTimeoutUS = pTask->m_iTimeoutTimeUS - iMonoTime;
if ( m_iNextTimeoutUS>0 )
return bHasTimeout;
if ( g_bTimeoutEachPacket )
{
auto iTimeoutFromLastActivity = pTask->m_iLastActivityTm + pTask->m_iTimeoutPeriodUS;
if ( iTimeoutFromLastActivity > iMonoTime )
{
pTask->m_iTimeoutTimeUS = iTimeoutFromLastActivity;
m_iNextTimeoutUS = pTask->m_iTimeoutTimeUS - iMonoTime;
m_dTimeouts.Change ( pTask );
return bHasTimeout;
}
}
bHasTimeout = true;
sphLogDebugL ( "L timeout happens for %p task", pTask );
m_dTimeouts.Pop ();
// Delete task, adopt connection.
// Invoke Timeoutcallback for it
CSphRefcountedPtr<AgentConn_t> pKeepConn ( DeleteTask ( pTask, false ) );
sphLogDebugL ( "%s", m_dTimeouts.DebugDump ( "L heap:" ).cstr () );
if ( pKeepConn )
{
/*
* Timeout means that r/w actions for task might be still active.
* Suppose that timeout functor will unsubscribe socket from polling.
* However, if right now something came to the socket, next call to poller might
* signal it, and we catch the events on the next round.
*/
sphLogDebugL ( "L timeout action started" );
pKeepConn->TimeoutCallback ();
sphLogDebugL ( "L timeout action finished" );
}
}
m_iNextTimeoutUS = -1;
return bHasTimeout; /// means 'infinite'
}
/// abandon and release all events (on shutdown)
void AbortScheduled ()
{
while ( !m_dTimeouts.IsEmpty () )
{
auto pTask = ( TaskNet_t* ) m_dTimeouts.Root ();
m_dTimeouts.Pop ();
CSphRefcountedPtr<AgentConn_t> pKeepConn ( DeleteTask ( pTask, false ) );
if ( pKeepConn )
pKeepConn->AbortCallback ();
}
}
inline bool IsTickProcessed ( TaskNet_t * pTask ) const
{
return pTask && pTask->m_iTickProcessed==m_iTickNo;
}
/// one event cycle.
/// \return false to stop event loop and exit.
bool EventTick () REQUIRES ( LazyThread )
{
sphLogDebugL ( "L ---------------------------- EventTick(%d)", m_iTickNo );
do
ProcessEnqueuedTasks ();
while ( HasTimeoutActions () );
sphLogDebugL ( "L calculated timeout is " INT64_FMT " useconds", m_iNextTimeoutUS );
auto iStarted = sphMicroTimer ();
auto iEvents = events_wait ( m_iNextTimeoutUS );
auto iWaited = sphMicroTimer() - iStarted;
#if _WIN32
ProcessEnqueuedTasks (); // we have 'pushed' our iocp inside, if it is fired, the fire event is last
#endif
// tick # allows to trace different events over one and same task.
// Say, write action processing may initiate reading, or even
// invalidate connection closing it and releasing.
// If later in the same loop we have same task for another action, such changed state
// may cause crash (say, if underlying connection is released and deleted).
// With epoll we have only one task which may be both 'write' and 'read' state,
// so it seems that just do one ELSE another should always work.
// But on BSD we have separate event for read and another for write.
// If one processed, no guarantee that another is not also in the same resultset.
// For this case we actualize tick # on processing and then compare it with current one.
++m_iTickNo;
if ( !m_iTickNo ) ++m_iTickNo; // skip 0
if ( sphInterrupted() )
{
AbortScheduled();
sphLogDebugL ( "EventTick() exit because of shutdown=%d", sphInterrupted() );
return false;
}
if ( iEvents<0 )
{
int iErrno = sphSockGetErrno ();
if ( m_iLastReportedErrno!=iErrno )
{
sphLogDebugL ( "L poller tick failed: %s", sphSockError ( iErrno ) );
m_iLastReportedErrno = iErrno;
}
sphLogDebugL ( "L poller tick failed: %s", sphSockError ( iErrno ) );
return true;
}
sphLogDebugL ( "L poller wait returned %d events from %d", iEvents, m_iEvents );
m_dReady.Resize ( iEvents );
/// we have some events to speak about...
for ( int i = 0; i<iEvents; ++i )
{
auto tEvent = GetEvent (i);
if ( tEvent.IsSignaler () )
{
sphLogDebugL ( "L internal event. Disposed" );
continue;
}
TaskNet_t * pTask = tEvent.GetTask ();
if ( !pTask )
{
#if _WIN32
m_iEvents -= 2;
#endif
continue;
}
else
sphLogDebugL ( "L event action for task %p(%d), %d", pTask, pTask->m_ifd, tEvent.GetEvents () );
bool bError = tEvent.IsError ();
bool bEof = tEvent.IsEof ();
if ( bError )
{
sphLogDebugL ( "L error happened" );
if ( bEof )
{
sphLogDebugL ( "L assume that is eof, discard the error" );
bError = false;
}
}
auto pConn = pTask->m_pPayload;
if ( pConn && pTask->m_uIOActive && !IsTickProcessed ( pTask ) )
{
assert ( pTask );
pTask->m_iLastActivityTm = MonoMicroTimer();
if ( bError )
{
sphLogDebugL ( "L error action %p, waited " INT64_FMT, pTask, iWaited );
pTask->m_iTickProcessed = m_iTickNo;
pConn->ErrorCallback ( iWaited );
sphLogDebugL ( "L error action %p completed", pTask );
} else
{
if ( tEvent.IsWrite () )
{
if ( !bEof )
{
sphLogDebugL ( "L write action %p, waited " INT64_FMT ", transferred %d", pTask, iWaited, tEvent.BytesTransferred () );
pTask->m_iTickProcessed = m_iTickNo;
pConn->SendCallback ( iWaited, tEvent.BytesTransferred () );
sphLogDebugL ( "L write action %p completed", pTask );
} else
sphLogDebugL ( "L write action avoid because of eof or same-generation tick", pTask );
}
if ( tEvent.IsRead () && !IsTickProcessed ( pTask ) )
{
sphLogDebugL ( "L read action %p, waited " INT64_FMT ", transferred %d", pTask, iWaited, tEvent.BytesTransferred () );
pTask->m_iTickProcessed = m_iTickNo;
pConn->RecvCallback ( iWaited, tEvent.BytesTransferred () );
sphLogDebugL ( "L read action %p completed", pTask );
}
}
}
} // 'for' loop over ready events
return true;
}
void AddToQueue ( TaskNet_t * pTask, bool bInternal )
{
if ( bInternal )
{
sphLogDebugL ( "L AddToQueue, int=%d", m_dInternalTasks.GetLength () + 1 );
m_dInternalTasks.Add ( pTask );
} else
{
sphLogDebugL ( "- AddToQueue, ext=%d", m_pEnqueuedTasks ? m_pEnqueuedTasks->GetLength () + 1 : 1 );
ScopedMutex_t tLock ( m_dActiveLock );
if ( !m_pEnqueuedTasks )
m_pEnqueuedTasks = new VectorTask_c;
m_pEnqueuedTasks->Add ( pTask );
}
}
public:
explicit LazyNetEvents_c ( int iSizeHint )
{
poller_create ( iSizeHint );
Threads::CreateQ ( &m_dWorkingThread, [this] {
ScopedRole_c thLazy ( LazyThread );
EventLoop ();
}, false, "AgentsPoller" );
}
~LazyNetEvents_c ()
{
sphLogDebug ( "~LazyNetEvents_c. Shutdown=%d", sphInterrupted() );
Fire();
// might be crash - no need to hung waiting thread
if ( sphInterrupted () )
Threads::Join ( &m_dWorkingThread );
events_destroy();
}
/// New task (only applied to fresh connections; skip already enqueued)
bool EnqueueNewTask ( AgentConn_t * pConnection, int64_t iTimeoutUS, int64_t iTimeoutPeriodUS, BYTE uActivateIO )
{
if ( pConnection->m_pPollerTask )
return false;
TaskNet_t * pTask = CreateNewTask ( pConnection );
assert ( pTask );
assert ( iTimeoutUS>0 );
// check for same timeout as we have. Avoid dupes, if so.
pTask->m_iPlannedTimeoutUS = iTimeoutUS;
if ( uActivateIO )
pTask->m_uIOChanged = uActivateIO;
// for win it is vitable important to apply changes immediately,
// since iocp has to be enqueued before read/write op, not after!
// Tomat: moved here to fix race between call from main thd from ScheduleDistrJobs and loop processing from ProcessEnqueuedTasks
#if _WIN32
if ( uActivateIO )
events_change_io ( pTask );
#endif
sphLogDebugv ( "- %d EnqueueNewTask %p (%p) " INT64_FMT " Us, IO(%d->%d), sock %d", pConnection->m_iStoreTag, pTask, pConnection, iTimeoutUS, pTask->m_uIOActive, pTask->m_uIOChanged, pConnection->m_iSock );
AddToQueue ( pTask, pConnection->InNetLoop () );
return true;
}
void ChangeDeleteTask ( AgentConn_t * pConnection, int64_t iTimeoutUS, int64_t iTimeoutPeriodUS )
{
auto pTask = ( TaskNet_t * ) pConnection->m_pPollerTask;
assert ( pTask );
pTask->m_iTimeoutPeriodUS = iTimeoutPeriodUS;
pTask->m_iLastActivityTm = MonoMicroTimer();
// check for same timeout as we have. Avoid dupes, if so.
if ( !iTimeoutUS || pTask->m_iTimeoutTimeUS==iTimeoutUS )
return;
pTask->m_iPlannedTimeoutUS = iTimeoutUS;
// case of delete: pConn socket m.b. already closed and ==-1. Actualize it right now.
if ( iTimeoutUS<0 )
{
pTask->m_ifd = pConnection->m_iSock;
pConnection->m_pPollerTask = nullptr; // this will allow to create another task.
sphLogDebugv ( "- %d Delete task (task %p), fd=%d (%d) " INT64_FMT "Us", pConnection->m_iStoreTag, pTask, pTask->m_ifd, pTask->m_iStoredfd, pTask->m_iTimeoutTimeUS );
} else
sphLogDebugv ( "- %d Change task (task %p), fd=%d (%d) " INT64_FMT "Us -> " INT64_FMT "Us", pConnection->m_iStoreTag, pTask, pTask->m_ifd, pTask->m_iStoredfd, pTask->m_iTimeoutTimeUS, iTimeoutUS );
AddToQueue ( pTask, pConnection->InNetLoop () );
}
void DisableWrite ( AgentConn_t * pConnection )
{
auto pTask = ( TaskNet_t * ) pConnection->m_pPollerTask;
assert ( pTask );
if ( TaskNet_t::RO!=pTask->m_uIOActive )
{
pTask->m_uIOChanged = TaskNet_t::RO;
sphLogDebugv ( "- %d DisableWrite enqueueing (task %p) (%d->%d), innet=%d", pConnection->m_iStoreTag, pTask, pTask->m_uIOActive, pTask->m_uIOChanged, pConnection->InNetLoop());
AddToQueue ( pTask, pConnection->InNetLoop () );
}
}
/// then signal the poller.
void Fire ()
{
sphLogDebugL ("L Fire an event invoked");
fire_event ();
}
};
//! Get static (singletone) instance of lazy poller
//! C++11 guarantees it to be mt-safe (magic-static).
LazyNetEvents_c & LazyPoller ()
{
static LazyNetEvents_c dEvents ( 1000 );
return dEvents;
}
//! Add or change task for poller.
void AgentConn_t::LazyTask ( int64_t iTimeoutUS, int64_t iTimeoutPeriodUS, bool bHardTimeout, BYTE uActivateIO )
{
assert ( iTimeoutUS>0 );
m_bNeedKick = !InNetLoop();
m_eTimeoutKind = bHardTimeout ? TIMEOUT_HARD : TIMEOUT_RETRY;
LazyPoller ().EnqueueNewTask ( this, iTimeoutUS, iTimeoutPeriodUS, uActivateIO );
}
void AgentConn_t::LazyDeleteOrChange ( int64_t iTimeoutMS, int64_t iTimeoutPeriodUS )
{
// skip del/change for not scheduled conns
if ( !m_pPollerTask )
return;
LazyPoller ().ChangeDeleteTask ( this, iTimeoutMS, iTimeoutPeriodUS );
}
void AgentConn_t::DisableWrite ()
{
// skip del/change for not scheduled conns
if ( !m_pPollerTask )
return;
LazyPoller ().DisableWrite ( this );
}
void FirePoller ()
{
LazyPoller ().Fire ();
}
class CRemoteAgentsObserver : public RemoteAgentsObserver_i
{
protected:
std::atomic<int> m_iSucceeded { 0 }; //< num of tasks finished successfully
std::atomic<int> m_iFinished { 0 }; //< num of tasks finished.
std::atomic<int> m_iTasks { 0 }; //< total num of tasks
Threads::Coro::Event_c m_tChanged; //< the signaller
public:
void FeedTask ( bool bAdd ) final
{
if ( bAdd )
m_iTasks.fetch_add ( 1, std::memory_order_acq_rel );
else
m_iTasks.fetch_sub ( 1, std::memory_order_acq_rel );
}
// check that there are no works to do
bool IsDone () const final
{
if ( m_iFinished.load(std::memory_order_relaxed) > m_iTasks.load ( std::memory_order_relaxed ) )
sphWarning ( "Orphaned chain detected (expected %d, got %d)",
m_iTasks.load ( std::memory_order_relaxed ), m_iFinished.load ( std::memory_order_relaxed ) );
return m_iFinished.load ( std::memory_order_acquire )>=m_iTasks.load ( std::memory_order_acquire );
}
// block execution until all tasks are finished
void Finish () final
{
while (!IsDone())
WaitChanges ();
}
inline long GetSucceeded() const final
{
return m_iSucceeded.load ( std::memory_order_relaxed );
}
inline long GetFinished () const final
{
return m_iFinished.load ( std::memory_order_relaxed );
}
public:
void Report ( bool bSuccess ) final
{
if ( bSuccess )
m_iSucceeded.fetch_add ( 1, std::memory_order_relaxed );
m_iFinished.fetch_add ( 1, std::memory_order_acq_rel );
m_tChanged.SetEvent ();
}
// block execution while some works finished
void WaitChanges () final
{
CrashQueryKeeper_c _; // that will keep our crash query over context switch possible in WaitEvent()
m_tChanged.WaitEvent ();
}
};
// coro-based lock-free observer:
// WaitChanges check boolean signal and either returns immediately, either yield.
// reporter either just set signal, either reschedule waitchanges continuation
RemoteAgentsObserver_i * GetObserver ()
{
return new CRemoteAgentsObserver;
}
/// check if a non-blocked socket is still connected
bool sphNBSockEof ( int iSock )
{
if ( iSock<0 )
return true;
char cBuf;
// since socket is non-blocked, ::recv will not block anyway
int iRes = ::recv ( iSock, &cBuf, sizeof ( cBuf ), MSG_PEEK );
if ( (!iRes) || (iRes<0
&& sphSockGetErrno ()!=EWOULDBLOCK
&& sphSockGetErrno ()!=EAGAIN ))
return true;
return false;
}
| 114,555
|
C++
|
.cpp
| 3,308
| 32.002418
| 208
| 0.691446
|
manticoresoftware/manticoresearch
| 8,893
| 493
| 500
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
16,815
|
taskpreread.cpp
|
manticoresoftware_manticoresearch/src/taskpreread.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 "taskpreread.h"
#include "searchdtask.h"
#include "searchdaemon.h"
namespace {
OneshotEvent_c g_tPrereadFinished; // invoked from main thread, so use raw (not coro) event.
bool g_bPrereadStarted = false;
void DoPreread ()
{
auto pDesc = PublishSystemInfo ( "PREREAD" );
int64_t tmStart = sphMicroTimer ();
StrVec_t dIndexes;
ServedSnap_t hLocals = g_pLocalIndexes->GetHash();
for ( auto& tIt : *hLocals )
{
if ( tIt.second )
dIndexes.Add ( tIt.first );
}
sphInfo ( "prereading %d tables", dIndexes.GetLength ());
int iRead = 0;
for ( const CSphString& sName : dIndexes )
{
if ( sphInterrupted() )
break;
auto pServed = GetServed ( sName );
if ( !pServed || pServed->m_eType==IndexType_e::TEMPLATE )
continue;
int64_t tmReading = sphMicroTimer ();
sphLogDebug ( "prereading table '%s'", sName.cstr ());
RWIdx_c pIdx {pServed};
pIdx->Preread ();
pServed->UpdateMass();
if ( !pIdx->GetLastWarning ().IsEmpty ())
sphWarning ( "'%s' preread: %s", sName.cstr (), pIdx->GetLastWarning ().cstr ());
int64_t tmRead = sphMicroTimer () - tmReading;
sphLogDebug ( "preread table '%s' in %0.3f sec", sName.cstr (), float ( tmRead ) / 1000000.0f );
++iRead;
}
int64_t tmFinished = sphMicroTimer () - tmStart;
sphInfo ( "preread %d tables in %0.3f sec", iRead, float ( tmFinished ) / 1000000.0f );
g_tPrereadFinished.SetEvent ();
}
} // namespace
bool WaitPrereadFinished ( int64_t uSec )
{
if ( !g_bPrereadStarted )
return true;
return g_tPrereadFinished.WaitEvent ( int ( uSec / 1000 ));
}
void PrereadIndexes ( bool bForce )
{
g_bPrereadStarted = true;
if ( bForce )
return Threads::CallCoroutine ( DoPreread );
Threads::StartJob ( DoPreread );
}
| 2,202
|
C++
|
.cpp
| 66
| 31.151515
| 98
| 0.704438
|
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
|
16,816
|
distinct.cpp
|
manticoresoftware_manticoresearch/src/distinct.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 "distinct.h"
template <typename HLL, typename HASH>
static void CopyHashToHLL ( HLL & tHLL, const HASH & tHash )
{
int64_t i = 0;
SphAttr_t * pRes;
while ( ( pRes = tHash.Iterate(i) ) != nullptr )
tHLL.Add ( (uint64_t)*pRes );
}
/////////////////////////////////////////////////////////////////////
UniqHLLTraits_c::Container_t::Container_t ( const Container_t & tRhs )
: m_pArray ( tRhs.m_pArray )
, m_eType ( tRhs.m_eType )
, m_iHashIdx ( tRhs.m_iHashIdx )
{}
UniqHLLTraits_c::Container_t & UniqHLLTraits_c::Container_t::operator = ( Container_t && tRhs )
{
m_pArray = std::move ( tRhs.m_pArray );
m_eType = std::move ( tRhs.m_eType );
m_iHashIdx = std::move ( tRhs.m_iHashIdx );
tRhs.m_pArray = nullptr;
tRhs.m_eType = ContainterType_e::ARRAY;
tRhs.m_iHashIdx = 0;
return *this;
}
UniqHLLTraits_c::Container_t & UniqHLLTraits_c::Container_t::operator = ( const Container_t & tRhs )
{
// we assume that the caller is responsible for managing the copied pointers
Container_t tNew(tRhs);
*this = std::move(tNew);
return *this;
}
int UniqHLLTraits_c::Container_t::Estimate() const
{
switch ( m_eType )
{
case ContainterType_e::ARRAY: return m_pArray->GetLength();
case ContainterType_e::HASH: return m_pHash->GetLength();
case ContainterType_e::HLL_DENSE_PACKED: return int( m_pHLLDensePacked->Estimate() );
case ContainterType_e::HLL_DENSE_NONPACKED: return int( m_pHLLDenseNonPacked->Estimate() );
default:
assert ( 0 && "Unknown container type" );
return 0;
}
}
void UniqHLLTraits_c::Container_t::Reset()
{
switch ( m_eType )
{
case ContainterType_e::ARRAY: SafeDelete ( m_pArray ); break;
case ContainterType_e::HASH: SafeDelete ( m_pHash ); break;
case ContainterType_e::HLL_DENSE_PACKED: SafeDelete ( m_pHLLDensePacked ); break;
case ContainterType_e::HLL_DENSE_NONPACKED: SafeDelete ( m_pHLLDenseNonPacked ); break;
default: assert ( 0 && "Unknown container type" ); break;
}
}
bool UniqHLLTraits_c::Container_t::IsEmpty() const
{
return m_eType==ContainterType_e::ARRAY && ( !m_pArray || m_pArray->IsEmpty() );
}
UniqHLLTraits_c::UniqHLLTraits_c()
{
SetAccuracy ( m_iAccuracy );
}
void UniqHLLTraits_c::AddToContainer ( Container_t & tContainer, SphAttr_t tValue )
{
switch ( tContainer.m_eType )
{
case ContainterType_e::ARRAY:
{
if ( tContainer.FindInArray(tValue) )
break;
if ( tContainer.m_pArray->GetLength() >= SMALL_ARRAY_SIZE )
{
ConvertToHash(tContainer);
AddToContainer ( tContainer, tValue );
}
else
tContainer.m_pArray->Add(tValue);
}
break;
case ContainterType_e::HASH:
{
auto & pHash = tContainer.m_pHash;
if ( pHash->Find(tValue) )
break;
if ( !pHash->IsFull() )
{
pHash->Add(tValue);
break;
}
if ( pHash->GetSize()==m_iMaxHashSize )
{
if ( m_iAccuracy > NON_PACKED_HLL_THRESH )
ConvertToHLLDensePacked(tContainer);
else
ConvertToHLLDenseNonPacked(tContainer);
AddToContainer ( tContainer, tValue );
}
else
{
MoveToLargerHash(tContainer);
pHash->Add(tValue);
}
}
break;
case ContainterType_e::HLL_DENSE_PACKED:
tContainer.m_pHLLDensePacked->Add ( (uint64_t)tValue );
break;
case ContainterType_e::HLL_DENSE_NONPACKED:
tContainer.m_pHLLDenseNonPacked->Add ( (uint64_t)tValue );
break;
default:
assert ( 0 && "Unknown container type" );
break;
}
}
UniqHLLTraits_c::Hash_c * UniqHLLTraits_c::AllocateHash ( int iIdx )
{
auto & dHashes = m_dUnusedHashes[iIdx];
if ( dHashes.GetLength() )
{
Hash_c * pNew = dHashes.Pop();
pNew->Clear();
return pNew;
}
return new Hash_c ( 1 << ( iIdx + sphLog2const(MIN_HASH_SIZE) - 1 ) );
}
UniqHLLTraits_c::HLLDensePacked_c * UniqHLLTraits_c::AllocateHLLDensePacked()
{
if ( m_dUnusedHLLDensePacked.GetLength() )
{
HLLDensePacked_c * pNew = m_dUnusedHLLDensePacked.Pop();
pNew->Clear();
return pNew;
}
return new HLLDensePacked_c ( m_iAccuracy );
}
UniqHLLTraits_c::HLLDenseNonPacked_c * UniqHLLTraits_c::AllocateHLLDenseNonPacked()
{
if ( m_dUnusedHLLDenseNonPacked.GetLength() )
{
HLLDenseNonPacked_c * pNew = m_dUnusedHLLDenseNonPacked.Pop();
pNew->Clear();
return pNew;
}
return new HLLDenseNonPacked_c ( m_iAccuracy );
}
void UniqHLLTraits_c::ConvertToHash ( Container_t & tContainer )
{
assert ( tContainer.m_eType==ContainterType_e::ARRAY );
Hash_c * pHash = AllocateHash(0);
assert(pHash);
for ( const auto & i : *tContainer.m_pArray )
pHash->Add(i);
FreeContainer ( tContainer );
tContainer.m_pHash = pHash;
tContainer.m_iHashIdx = 0;
tContainer.m_eType = ContainterType_e::HASH;
}
void UniqHLLTraits_c::ConvertToHLLDensePacked ( Container_t & tContainer )
{
assert ( tContainer.m_eType==ContainterType_e::HASH );
HLLDensePacked_c * pHLL = AllocateHLLDensePacked();
assert ( pHLL && tContainer.m_pHash );
CopyHashToHLL ( *pHLL, *tContainer.m_pHash );
FreeContainer ( tContainer );
tContainer.m_pHLLDensePacked = pHLL;
tContainer.m_eType = ContainterType_e::HLL_DENSE_PACKED;
}
void UniqHLLTraits_c::ConvertToHLLDenseNonPacked ( Container_t & tContainer )
{
assert ( tContainer.m_eType==ContainterType_e::HASH );
HLLDenseNonPacked_c * pHLL = AllocateHLLDenseNonPacked();
assert ( pHLL && tContainer.m_pHash );
CopyHashToHLL ( *pHLL, *tContainer.m_pHash );
FreeContainer ( tContainer );
tContainer.m_pHLLDenseNonPacked = pHLL;
tContainer.m_eType = ContainterType_e::HLL_DENSE_NONPACKED;
}
void UniqHLLTraits_c::MoveToLargerHash ( Container_t & tContainer )
{
int & iIdx = tContainer.m_iHashIdx;
Hash_c * pNewHash = AllocateHash ( iIdx + 1 );
tContainer.m_pHash->MoveTo ( *pNewHash );
m_dUnusedHashes[iIdx].Add ( tContainer.m_pHash );
tContainer.m_pHash = pNewHash;
iIdx++;
}
UniqHLLTraits_c & UniqHLLTraits_c::operator = ( UniqHLLTraits_c && tRhs )
{
m_dUnusedArray = std::move ( tRhs.m_dUnusedArray );
m_dUnusedHashes = std::move ( tRhs.m_dUnusedHashes );
m_dUnusedHLLDensePacked = std::move ( tRhs.m_dUnusedHLLDensePacked );
m_dUnusedHLLDenseNonPacked = std::move ( tRhs.m_dUnusedHLLDenseNonPacked );
m_iMaxHashSize = std::move ( tRhs.m_iMaxHashSize );
return *this;
}
void UniqHLLTraits_c::Reset()
{
for ( auto i : m_dUnusedArray )
SafeDelete(i);
for ( auto & i : m_dUnusedHashes )
for ( auto j : i )
SafeDelete(j);
for ( auto i : m_dUnusedHLLDensePacked )
SafeDelete(i);
for ( auto i : m_dUnusedHLLDenseNonPacked )
SafeDelete(i);
m_dUnusedArray.Resize(0);
m_dUnusedHashes.Resize(0);
m_dUnusedHLLDensePacked.Resize(0);
m_dUnusedHLLDenseNonPacked.Resize(0);
}
void UniqHLLTraits_c::SetAccuracy ( int iAccuracy )
{
m_iAccuracy = iAccuracy;
m_iMaxHashSize = 1 << ( m_iAccuracy - 4 );
for ( auto & i : m_dUnusedHashes )
for ( auto j : i )
SafeDelete(j);
m_dUnusedHashes.Resize ( sphLog2 ( m_iMaxHashSize ) - sphLog2const ( MIN_HASH_SIZE ) + 1 );
}
UniqHLLTraits_c::Container_t & UniqHLL_c::Get ( SphGroupKey_t tGroup )
{
int iLen = m_hGroups.GetLength();
UniqHLLTraits_c::Container_t & tCont = m_hGroups.Acquire ( tGroup );
// need reset value in case of the Container_t just added
if ( iLen!=m_hGroups.GetLength() )
tCont = UniqHLLTraits_c::Container_t();
return tCont;
}
template <typename T>
void CopyContainerTo ( SphGroupKey_t tGroup, const UniqHLLTraits_c::Container_t & tFrom, T & tRhs )
{
if ( tFrom.IsEmpty() )
return;
UniqHLLTraits_c::Container_t & tTo = tRhs.Get ( tGroup );
if ( tTo.IsEmpty() )
tTo.m_pArray = tRhs.AllocateArray();
if ( tFrom.m_eType==UniqHLLTraits_c::ContainterType_e::ARRAY )
{
for ( auto i : *tFrom.m_pArray )
tRhs.Add ( { tGroup, i, 1 } );
} else if ( tFrom.m_eType==UniqHLLTraits_c::ContainterType_e::HASH )
{
int64_t i = 0;
SphAttr_t * pRes;
while ( ( pRes = tFrom.m_pHash->Iterate(i) ) != nullptr )
tRhs.Add ( { tGroup, *pRes, 1 } );
} else
{
if ( tTo.m_eType==UniqHLLTraits_c::ContainterType_e::ARRAY )
tRhs.ConvertToHash ( tTo );
if ( tTo.m_eType==UniqHLLTraits_c::ContainterType_e::HASH )
{
assert ( tRhs.m_iAccuracy==tRhs.m_iAccuracy );
if ( tRhs.m_iAccuracy > UniqHLLTraits_c::NON_PACKED_HLL_THRESH )
{
tRhs.ConvertToHLLDensePacked ( tTo );
tTo.m_pHLLDensePacked->Merge ( *tFrom.m_pHLLDensePacked );
}
else
{
tRhs.ConvertToHLLDenseNonPacked ( tTo );
tTo.m_pHLLDenseNonPacked->Merge ( *tFrom.m_pHLLDenseNonPacked );
}
}
}
}
/////////////////////////////////////////////////////////////////////
UniqHLL_c & UniqHLL_c::operator = ( UniqHLL_c && tRhs )
{
BASE::operator = ( std::move(tRhs) );
m_hGroups = std::move ( tRhs.m_hGroups );
m_iHashIterator = std::move ( tRhs.m_iHashIterator );
return *this;
}
int UniqHLL_c::CountStart ( SphGroupKey_t & tOutGroup )
{
m_iHashIterator = 0;
return CountNext ( tOutGroup );
}
int UniqHLL_c::CountNext ( SphGroupKey_t & tOutGroup )
{
auto tRes = m_hGroups.Iterate ( m_iHashIterator );
if ( !tRes.second )
return 0;
tOutGroup = tRes.first;
assert ( tRes.second );
return tRes.second->Estimate();
}
void UniqHLL_c::Compact ( VecTraits_T<SphGroupKey_t> & dRemoveGroups )
{
for ( auto i : dRemoveGroups )
{
Container_t tContainer = m_hGroups.FindAndDelete(i);
FreeContainer(tContainer);
}
}
void UniqHLL_c::Reset()
{
int64_t iIterator = 0;
std::pair<SphGroupKey_t, Container_t*> tRes;
while ( ( tRes = m_hGroups.Iterate ( iIterator ) ).second )
tRes.second->Reset();
m_hGroups.Reset(0);
BASE::Reset();
}
void UniqHLL_c::CopyTo ( UniqHLL_c & tRhs ) const
{
int64_t iIterator = 0;
std::pair<SphGroupKey_t, Container_t*> tRes;
while ( ( tRes = m_hGroups.Iterate ( iIterator ) ).second )
{
// can not move Container_t into dRhs as move invalidates this
CopyContainerTo ( tRes.first, *tRes.second, tRhs );
}
}
/////////////////////////////////////////////////////////////////////////////
UniqHLLSingle_c & UniqHLLSingle_c::operator = ( UniqHLLSingle_c && tRhs )
{
BASE::operator = ( std::move(tRhs) );
m_tContainer = std::move ( tRhs.m_tContainer );
return *this;
}
void UniqHLLSingle_c::CopyTo ( UniqHLLSingle_c & tRhs ) const
{
CopyContainerTo ( 0, m_tContainer, tRhs );
}
void UniqHLLSingle_c::Reset()
{
m_tContainer.Reset();
BASE::Reset();
}
| 10,644
|
C++
|
.cpp
| 346
| 28.393064
| 100
| 0.698019
|
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
|
16,817
|
memio.cpp
|
manticoresoftware_manticoresearch/src/memio.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 "memio.h"
MemoryReader_c::MemoryReader_c ( const BYTE * pData, int iLen ) noexcept
: m_pData ( pData )
, m_iLen ( iLen )
, m_pCur ( pData )
{}
MemoryReader_c::MemoryReader_c ( ByteBlob_t dData ) noexcept
: m_pData ( dData.first )
, m_iLen ( dData.second )
, m_pCur ( dData.first )
{}
int MemoryReader_c::GetPos() const
{
return ( m_pCur - m_pData );
}
void MemoryReader_c::SetPos ( int iOff )
{
assert ( iOff>=0 && iOff<=m_iLen );
m_pCur = m_pData + iOff;
}
CSphString MemoryReader_c::GetString()
{
CSphString sRes;
DWORD uLen = GetDword();
if ( uLen )
{
sRes.Reserve ( uLen );
GetBytes ( (BYTE *)sRes.cstr(), uLen );
}
return sRes;
}
void MemoryReader_c::GetBytes ( void * pData, int iLen )
{
if ( !iLen )
return;
assert ( m_pCur );
assert ( m_pCur<m_pData+m_iLen );
assert ( m_pCur+iLen<=m_pData+m_iLen );
memcpy ( pData, m_pCur, iLen );
m_pCur += iLen;
}
const BYTE * MemoryReader_c::Begin() const
{
return m_pData;
}
int MemoryReader_c::GetLength() const
{
return m_iLen;
}
bool MemoryReader_c::HasData() const
{
return GetPos() < m_iLen;
}
DWORD MemoryReader_c::UnzipInt()
{
return UnzipIntLE ( m_pCur );
}
uint64_t MemoryReader_c::UnzipOffset()
{
return UnzipOffsetLE ( m_pCur );
}
//////////////////////////////////////////////////////////////////////////
MemoryWriter_c::MemoryWriter_c ( CSphVector<BYTE> & dBuf )
: m_dBuf ( dBuf )
{}
int MemoryWriter_c::GetPos()
{
return m_dBuf.GetLength();
}
void MemoryWriter_c::PutString ( const CSphString & sVal )
{
int iLen = sVal.Length();
PutDword ( iLen );
if ( iLen )
PutBytes ( (const BYTE *)sVal.cstr(), iLen );
}
void MemoryWriter_c::PutString ( const char * sVal )
{
int iLen = 0;
if ( sVal )
iLen = (int) strlen ( sVal );
PutDword ( iLen );
if ( iLen )
PutBytes ( (const BYTE *)sVal, iLen );
}
void MemoryWriter_c::PutZString ( const CSphString & sVal )
{
int iLen = sVal.Length ();
ZipOffset ( iLen );
if ( iLen )
PutBytes ( (const BYTE *) sVal.cstr (), iLen );
}
void MemoryWriter_c::PutZString ( const char * sVal )
{
int iLen = 0;
if ( sVal )
iLen = (int) strlen ( sVal );
ZipOffset ( iLen );
if ( iLen )
PutBytes ( (const BYTE *) sVal, iLen );
}
void MemoryWriter_c::PutBytes ( const void * pData, int64_t iLen )
{
if ( !iLen )
return;
BYTE * pCur = m_dBuf.AddN ( iLen );
memcpy ( pCur, pData, iLen );
}
void MemoryWriter_c::PutByte ( BYTE uVal )
{
m_dBuf.Add ( uVal );
}
void MemoryWriter_c::ZipOffset ( uint64_t uVal )
{
ZipValueLE ( [this] ( BYTE b ) { PutByte ( b ); }, uVal );
}
void MemoryWriter_c::ZipInt ( DWORD uVal )
{
ZipValueLE ( [this] ( BYTE b ) { PutByte ( b ); }, uVal );
}
//////////////////////////////////////////////////////////////////////////
MemoryReader2_c::MemoryReader2_c ( const BYTE * pData, int iLen )
: MemoryReader_c ( pData, iLen )
{}
uint64_t MemoryReader2_c::UnzipInt()
{
return UnzipIntBE(m_pCur);
}
uint64_t MemoryReader2_c::UnzipOffset()
{
return UnzipOffsetBE(m_pCur);
}
//////////////////////////////////////////////////////////////////////////
MemoryWriter2_c::MemoryWriter2_c ( CSphVector<BYTE> & dBuf )
: MemoryWriter_c ( dBuf )
{}
void MemoryWriter2_c::ZipOffset ( uint64_t uVal )
{
ZipValueBE ( [this] ( BYTE b ) { PutByte ( b ); }, uVal );
}
void MemoryWriter2_c::ZipInt ( DWORD uVal )
{
ZipValueBE ( [this] ( BYTE b ) { PutByte ( b ); }, uVal );
}
| 3,868
|
C++
|
.cpp
| 155
| 23.141935
| 80
| 0.637531
|
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
|
16,818
|
attribute.cpp
|
manticoresoftware_manticoresearch/src/attribute.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 "attribute.h"
#include "sphinxint.h"
#include "sphinxjson.h"
#include "indexcheck.h"
#include "schema/locator.h"
#if __has_include( <charconv>)
#include <charconv>
#endif
//////////////////////////////////////////////////////////////////////////
// blob attributes
enum
{
BLOB_ROW_LEN_BYTE = 0,
BLOB_ROW_LEN_WORD = 1,
BLOB_ROW_LEN_DWORD = 2
};
static BYTE CalcBlobRowFlags ( DWORD uTotalLen )
{
if ( uTotalLen<0xFF )
return BLOB_ROW_LEN_BYTE;
if ( uTotalLen<0xFFFF )
return BLOB_ROW_LEN_WORD;
return BLOB_ROW_LEN_DWORD;
}
static DWORD RowFlagsToLen ( BYTE uFlags )
{
switch ( uFlags )
{
case BLOB_ROW_LEN_BYTE: return 1;
case BLOB_ROW_LEN_WORD: return 2;
case BLOB_ROW_LEN_DWORD: return 4;
default:
assert ( 0 && "Unknown blob flags" );
return 0;
}
}
class AttributePacker_i
{
public:
virtual ~AttributePacker_i(){}
virtual bool SetData ( const BYTE * pData, int iDataLen, CSphString & sError ) = 0;
virtual const CSphVector<BYTE> & GetData() const = 0;
};
class AttributePacker_c : public AttributePacker_i
{
public:
bool SetData ( const BYTE * pData, int iDataLen, CSphString & /*sError*/ ) override
{
m_dData.Resize ( iDataLen );
memcpy ( m_dData.Begin(), pData, iDataLen );
return true;
}
const CSphVector<BYTE> & GetData() const override
{
return m_dData;
}
protected:
CSphVector<BYTE> m_dData;
};
template <typename T, typename IN_T>
class AttributePacker_MVA_T : public AttributePacker_c
{
public:
AttributePacker_MVA_T ( bool bNeedSorting = false ) : m_bNeedSorting ( bNeedSorting ) {}
bool SetData ( const BYTE * pData, int iDataLen, CSphString & /*sError*/ ) override
{
int iValueSize = sizeof ( int64_t );
int iNumValues = iDataLen/iValueSize;
if ( m_bNeedSorting )
{
m_dUnsorted.Resize(iNumValues);
auto * pUnsorted = (T*)m_dUnsorted.Begin();
for ( int i = 0; i<iNumValues; i++ )
{
auto iVal = sphUnalignedRead ( *(int64_t*)const_cast<BYTE*>(pData) );
*pUnsorted++ = ConvertType<IN_T>(iVal);
pData += iValueSize;
}
m_dUnsorted.Uniq();
iNumValues = m_dUnsorted.GetLength();
m_dData.Resize ( m_dUnsorted.GetLengthBytes() );
memcpy ( m_dData.Begin(), m_dUnsorted.Begin(), m_dData.GetLengthBytes() );
}
else
{
m_dData.Resize ( iNumValues*sizeof(T) );
auto * pResult = (T*)m_dData.Begin();
for ( int i = 0; i<iNumValues; i++ )
{
auto iVal = sphUnalignedRead ( *(int64_t*)const_cast<BYTE*>(pData) );
*pResult++ = ConvertType<IN_T>(iVal);
pData += iValueSize;
}
}
return true;
}
protected:
bool m_bNeedSorting = true;
CSphVector<T> m_dUnsorted;
};
using AttributePacker_MVA32_c = AttributePacker_MVA_T<DWORD,DWORD>;
using AttributePacker_MVA64_c = AttributePacker_MVA_T<int64_t,int64_t>;
using AttributePacker_FloatVec_c = AttributePacker_MVA_T<float,float>;
using AttributePacker_Int2FloatVec_c = AttributePacker_MVA_T<float,DWORD>;
class AttributePacker_Json_c : public AttributePacker_c
{
public:
bool SetData ( const BYTE * pData, int iDataLen, CSphString & sError ) override
{
m_dData.Resize(0);
if ( !iDataLen )
return true;
// WARNING, tricky bit
// flex lexer needs last two (!) bytes to be zeroes
// asciiz string supplies one, and we fill out the extra one
// and that works, because CSphString always allocates a small extra gap
char * szData = const_cast<char*>((const char*)pData);
szData[iDataLen] = '\0';
szData[iDataLen+1] = '\0';
return sphJsonParse ( m_dData, szData, g_bJsonAutoconvNumbers, g_bJsonKeynamesToLowercase, true, sError );
}
};
//////////////////////////////////////////////////////////////////////////
class BlobRowBuilder_Base_c : public BlobRowBuilder_i
{
public:
bool SetAttr ( int iAttr, const BYTE * pData, int iDataLen, CSphString & sError ) override { return m_dAttrs[iAttr]->SetData ( pData, iDataLen, sError ); }
protected:
CSphVector<std::unique_ptr<AttributePacker_i>> m_dAttrs;
};
class BlobRowBuilder_File_c : public BlobRowBuilder_Base_c
{
public:
BlobRowBuilder_File_c ( const ISphSchema & tSchema, SphOffset_t tSpaceForUpdates, bool bJsonPacked, int iBufferSize );
bool Setup ( const CSphString & sFile, CSphString & sError );
std::pair<SphOffset_t,SphOffset_t> Flush() override;
std::pair<SphOffset_t,SphOffset_t> Flush ( const BYTE * pOldRow ) override;
bool Done ( CSphString & sError ) override;
private:
CSphWriter m_tWriter;
SphOffset_t m_tSpaceForUpdates = 0;
int m_iBufferSize = 0;
};
BlobRowBuilder_File_c::BlobRowBuilder_File_c ( const ISphSchema & tSchema, SphOffset_t tSpaceForUpdates, bool bJsonPacked, int iBufferSize )
: m_tSpaceForUpdates ( tSpaceForUpdates )
, m_iBufferSize ( iBufferSize )
{
for ( int i = 0; i < tSchema.GetAttrsCount(); i++ )
{
const CSphColumnInfo & tCol = tSchema.GetAttr(i);
if ( !sphIsBlobAttr(tCol) )
continue;
switch ( tCol.m_eAttrType )
{
case SPH_ATTR_STRING:
case SPH_ATTR_INT64SET:
m_dAttrs.Add ( std::make_unique<AttributePacker_c>() );
break;
case SPH_ATTR_UINT32SET:
m_dAttrs.Add ( std::make_unique<AttributePacker_MVA32_c>() );
break;
case SPH_ATTR_FLOAT_VECTOR:
m_dAttrs.Add ( std::make_unique<AttributePacker_FloatVec_c>() );
break;
case SPH_ATTR_JSON:
if ( bJsonPacked )
m_dAttrs.Add ( std::make_unique<AttributePacker_c>() );
else
m_dAttrs.Add ( std::make_unique<AttributePacker_Json_c>() );
break;
default:
break;
}
}
}
bool BlobRowBuilder_File_c::Setup ( const CSphString & sFile, CSphString & sError )
{
m_tWriter.SetBufferSize ( m_iBufferSize );
if ( !m_tWriter.OpenFile ( sFile, sError ) )
return false;
// reserve space
m_tWriter.PutOffset(0);
return true;
}
std::pair<SphOffset_t,SphOffset_t> BlobRowBuilder_File_c::Flush()
{
SphOffset_t tRowOffset = m_tWriter.GetPos();
DWORD uTotalLen = 0;
for ( const auto & i : m_dAttrs )
uTotalLen += i->GetData().GetLength();
BYTE uFlags = CalcBlobRowFlags(uTotalLen);
m_tWriter.PutByte(uFlags);
uTotalLen = 0;
for ( const auto & i : m_dAttrs )
{
uTotalLen += i->GetData().GetLength();
switch ( uFlags )
{
case BLOB_ROW_LEN_BYTE:
m_tWriter.PutByte((BYTE)uTotalLen);
break;
case BLOB_ROW_LEN_WORD:
m_tWriter.PutWord((WORD)uTotalLen);
break;
case BLOB_ROW_LEN_DWORD:
m_tWriter.PutDword(uTotalLen);
break;
default:
break;
}
}
for ( const auto & i : m_dAttrs )
m_tWriter.PutBytes ( i->GetData().Begin(), i->GetData().GetLength() );
return { tRowOffset, m_tWriter.GetPos()-tRowOffset };
}
std::pair<SphOffset_t,SphOffset_t> BlobRowBuilder_File_c::Flush ( const BYTE * pOldRow )
{
assert ( pOldRow );
SphOffset_t tRowOffset = m_tWriter.GetPos();
m_tWriter.PutBytes ( pOldRow, sphGetBlobTotalLen ( pOldRow, m_dAttrs.GetLength() ) );
return { tRowOffset, m_tWriter.GetPos()-tRowOffset };
}
bool BlobRowBuilder_File_c::Done ( CSphString & sError )
{
SphOffset_t tTotalSize = m_tWriter.GetPos();
SeekAndPutOffset ( m_tWriter, 0, tTotalSize );
m_tWriter.SeekTo ( tTotalSize + m_tSpaceForUpdates, true );
m_tWriter.CloseFile(); // closing file implies it will NOT be unlinked
if ( m_tWriter.IsError() )
{
sError.SetSprintf ( "error writing .SPB, %s", sError.cstr() ); // keep original error from writer
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
class BlobRowBuilder_Mem_c : public BlobRowBuilder_Base_c
{
public:
BlobRowBuilder_Mem_c ( CSphTightVector<BYTE> & dPool );
BlobRowBuilder_Mem_c ( const ISphSchema & tSchema, CSphTightVector<BYTE> & dPool );
std::pair<SphOffset_t,SphOffset_t> Flush() override;
std::pair<SphOffset_t,SphOffset_t> Flush ( const BYTE * pOldRow ) override { assert (0); return {0,0}; }
bool Done ( CSphString & /*sError*/ ) override { return true; }
protected:
CSphTightVector<BYTE> & m_dPool;
};
BlobRowBuilder_Mem_c::BlobRowBuilder_Mem_c ( CSphTightVector<BYTE> & dPool )
: m_dPool ( dPool )
{}
BlobRowBuilder_Mem_c::BlobRowBuilder_Mem_c ( const ISphSchema & tSchema, CSphTightVector<BYTE> & dPool )
: m_dPool ( dPool )
{
for ( int i = 0; i < tSchema.GetAttrsCount(); i++ )
{
const CSphColumnInfo & tCol = tSchema.GetAttr(i);
if ( tCol.IsColumnar() )
continue;
switch ( tCol.m_eAttrType )
{
case SPH_ATTR_STRING:
case SPH_ATTR_JSON: // json doesn't go to a separate packer because we work with pre-parsed json in this case
case SPH_ATTR_INT64SET:
m_dAttrs.Add ( std::make_unique<AttributePacker_c>() );
break;
case SPH_ATTR_UINT32SET:
m_dAttrs.Add ( std::make_unique<AttributePacker_MVA32_c>() );
break;
case SPH_ATTR_FLOAT_VECTOR:
m_dAttrs.Add ( std::make_unique<AttributePacker_FloatVec_c>() );
break;
default:
break;
}
}
}
std::pair<SphOffset_t,SphOffset_t> BlobRowBuilder_Mem_c::Flush()
{
SphOffset_t tRowOffset = m_dPool.GetLength();
DWORD uTotalLen = 0;
for ( const auto & i : m_dAttrs )
uTotalLen += i->GetData().GetLength();
m_dPool.Reserve ( uTotalLen + m_dAttrs.GetLength()*sizeof(DWORD) + 1 );
BYTE uFlags = CalcBlobRowFlags(uTotalLen);
m_dPool.Add(uFlags);
uTotalLen = 0;
BYTE * pPtr;
for ( const auto & i : m_dAttrs )
{
uTotalLen += i->GetData().GetLength();
switch ( uFlags )
{
case BLOB_ROW_LEN_BYTE:
m_dPool.Add((BYTE)uTotalLen);
break;
case BLOB_ROW_LEN_WORD:
pPtr = m_dPool.AddN ( sizeof(WORD) );
sphUnalignedWrite ( pPtr, (WORD)uTotalLen );
break;
case BLOB_ROW_LEN_DWORD:
pPtr = m_dPool.AddN ( sizeof(DWORD) );
sphUnalignedWrite ( pPtr, (DWORD)uTotalLen );
break;
}
}
for ( const auto & i : m_dAttrs )
{
int iLen = i->GetData().GetLength();
pPtr = m_dPool.AddN(iLen);
memcpy ( pPtr, i->GetData().Begin(), iLen );
}
return { tRowOffset, m_dPool.GetLength()-tRowOffset };
}
//////////////////////////////////////////////////////////////////////////
class BlobRowBuilder_MemUpdate_c : public BlobRowBuilder_Mem_c
{
public:
BlobRowBuilder_MemUpdate_c ( const ISphSchema & tSchema, const CSphVector<TypedAttribute_t> & dAttrs, CSphTightVector<BYTE> & dPool, const CSphBitvec & dAttrsUpdated );
};
BlobRowBuilder_MemUpdate_c::BlobRowBuilder_MemUpdate_c ( const ISphSchema & tSchema, const CSphVector<TypedAttribute_t> & dAttrs, CSphTightVector<BYTE> & dPool, const CSphBitvec & dAttrsUpdated )
: BlobRowBuilder_Mem_c ( dPool )
{
for ( int i = 0; i < tSchema.GetAttrsCount(); i++ )
{
const CSphColumnInfo & tCol = tSchema.GetAttr(i);
if ( !sphIsBlobAttr(tCol) || tCol.IsColumnar() )
continue;
if ( !dAttrsUpdated.BitGet(i) )
{
m_dAttrs.Add ( std::make_unique<AttributePacker_c>() );
continue;
}
switch ( tCol.m_eAttrType )
{
case SPH_ATTR_STRING:
m_dAttrs.Add ( std::make_unique<AttributePacker_c>() );
break;
case SPH_ATTR_UINT32SET:
m_dAttrs.Add ( std::make_unique<AttributePacker_MVA32_c>(true) );
break;
case SPH_ATTR_INT64SET:
m_dAttrs.Add ( std::make_unique<AttributePacker_MVA64_c>(true) );
break;
case SPH_ATTR_FLOAT_VECTOR:
{
ESphAttr eInAttrType = SPH_ATTR_FLOAT_VECTOR;
for ( auto & tInAttr : dAttrs )
if ( tInAttr.m_sName==tCol.m_sName )
{
eInAttrType = tInAttr.m_eType;
break;
}
if ( eInAttrType==SPH_ATTR_FLOAT_VECTOR )
m_dAttrs.Add ( std::make_unique<AttributePacker_FloatVec_c>() );
else
m_dAttrs.Add ( std::make_unique<AttributePacker_Int2FloatVec_c>() );
}
break;
case SPH_ATTR_JSON:
m_dAttrs.Add ( std::make_unique<AttributePacker_Json_c>() );
break;
default:
break;
}
}
}
//////////////////////////////////////////////////////////////////////////
std::unique_ptr<BlobRowBuilder_i> sphCreateBlobRowBuilder ( const ISphSchema & tSchema, const CSphString & sFile, SphOffset_t tSpaceForUpdates, int iBufferSize, CSphString & sError )
{
auto pBuilder = std::make_unique<BlobRowBuilder_File_c> ( tSchema, tSpaceForUpdates, false, iBufferSize );
if ( !pBuilder->Setup ( sFile, sError ) )
pBuilder = nullptr;
return pBuilder;
}
std::unique_ptr<BlobRowBuilder_i> sphCreateBlobRowJsonBuilder ( const ISphSchema & tSchema, const CSphString & sFile, SphOffset_t tSpaceForUpdates, int iBufferSize, CSphString & sError )
{
auto pBuilder = std::make_unique<BlobRowBuilder_File_c> ( tSchema, tSpaceForUpdates, true, iBufferSize );
if ( !pBuilder->Setup ( sFile, sError ) )
pBuilder = nullptr;
return pBuilder;
}
std::unique_ptr<BlobRowBuilder_i> sphCreateBlobRowBuilder ( const ISphSchema & tSchema, CSphTightVector<BYTE> & dPool )
{
return std::make_unique<BlobRowBuilder_Mem_c> ( tSchema, dPool );
}
std::unique_ptr<BlobRowBuilder_i> sphCreateBlobRowBuilderUpdate ( const ISphSchema & tSchema, const CSphVector<TypedAttribute_t> & dAttrs, CSphTightVector<BYTE> & dPool, const CSphBitvec & dAttrsUpdated )
{
return std::make_unique<BlobRowBuilder_MemUpdate_c> ( tSchema, dAttrs, dPool, dAttrsUpdated );
}
//////////////////////////////////////////////////////////////////////////
static int64_t GetBlobRowOffset ( const CSphRowitem * pDocinfo, int iBlobRowOffset )
{
return sphUnalignedRead ( *( (const int64_t*)pDocinfo + iBlobRowOffset ) );
}
static int64_t GetBlobRowOffset ( const CSphMatch & tMatch, const CSphAttrLocator & tLocator )
{
// blob row locator NEEDS to be 1st or 2nd attribute after docid (see tLocator.m_iBlobRowOffset)
return GetBlobRowOffset ( tLocator.m_bDynamic ? tMatch.m_pDynamic : tMatch.m_pStatic, tLocator.m_iBlobRowOffset );
}
template <typename T>
static const BYTE * GetBlobAttr ( int iBlobAttrId, int nBlobAttrs, const BYTE * pRow, int & iLengthBytes )
{
T uLen1 = sphUnalignedRead ( *( (const T*)pRow + iBlobAttrId ) );
T uLen0 = iBlobAttrId > 0 ? sphUnalignedRead ( *( (const T*)pRow + iBlobAttrId - 1 ) ) : 0;
iLengthBytes = (int)uLen1 - uLen0;
assert ( iLengthBytes >= 0 );
return iLengthBytes ? (const BYTE*)( (const T*)pRow + nBlobAttrs ) + uLen0 : nullptr;
}
static const BYTE * GetBlobAttr ( const BYTE * pRow, int iBlobAttrId, int nBlobAttrs, int & iLengthBytes )
{
switch ( *pRow )
{
case BLOB_ROW_LEN_BYTE: return GetBlobAttr<BYTE> ( iBlobAttrId, nBlobAttrs, pRow+1, iLengthBytes );
case BLOB_ROW_LEN_WORD: return GetBlobAttr<WORD> ( iBlobAttrId, nBlobAttrs, pRow+1, iLengthBytes );
case BLOB_ROW_LEN_DWORD: return GetBlobAttr<DWORD>( iBlobAttrId, nBlobAttrs, pRow+1, iLengthBytes );
default:
break;
}
assert ( 0 && "Unknown blob row type" );
return nullptr;
}
// same as above, but returns pair instead of confusing result-by-ref.
template <typename T>
static ByteBlob_t GetBlobAttr ( int iBlobAttrId, int nBlobAttrs, const BYTE * pRow )
{
auto pTRow = (const T*)pRow;
T uLen1 = sphUnalignedRead ( pTRow[iBlobAttrId] );
T uLen0 = (iBlobAttrId > 0) ? sphUnalignedRead ( pTRow[iBlobAttrId - 1] ) : 0;
auto iLengthBytes = (int)uLen1-uLen0;
assert ( iLengthBytes>=0 );
return {iLengthBytes ? (const BYTE *)(pTRow + nBlobAttrs) + uLen0 : nullptr, iLengthBytes };
}
static ByteBlob_t GetBlobAttr ( const BYTE * pRow, int iBlobAttrId, int nBlobAttrs )
{
switch ( *pRow )
{
case BLOB_ROW_LEN_BYTE: return GetBlobAttr<BYTE> ( iBlobAttrId, nBlobAttrs, pRow+1 );
case BLOB_ROW_LEN_WORD: return GetBlobAttr<WORD> ( iBlobAttrId, nBlobAttrs, pRow+1 );
case BLOB_ROW_LEN_DWORD: return GetBlobAttr<DWORD>( iBlobAttrId, nBlobAttrs, pRow+1 );
default:
break;
}
assert ( 0 && "Unknown blob row type" );
return { nullptr, 0 };
}
ByteBlob_t sphGetBlobAttr ( const BYTE * pBlobRow, const CSphAttrLocator & tLocator )
{
return GetBlobAttr ( pBlobRow, tLocator.m_iBlobAttrId, tLocator.m_nBlobAttrs );
}
const BYTE * sphGetBlobAttr ( const CSphMatch & tMatch, const CSphAttrLocator & tLocator, const BYTE * pBlobPool, int & iLengthBytes )
{
assert ( pBlobPool );
int64_t iOffset = GetBlobRowOffset ( tMatch, tLocator );
return GetBlobAttr ( pBlobPool+iOffset, tLocator.m_iBlobAttrId, tLocator.m_nBlobAttrs, iLengthBytes );
}
ByteBlob_t sphGetBlobAttr ( const CSphMatch & tMatch, const CSphAttrLocator & tLocator, const BYTE * pBlobPool )
{
assert ( pBlobPool );
int64_t iOffset = GetBlobRowOffset ( tMatch, tLocator );
return GetBlobAttr ( pBlobPool+iOffset, tLocator.m_iBlobAttrId, tLocator.m_nBlobAttrs );
}
const BYTE * sphGetBlobAttr ( const CSphRowitem * pDocinfo, const CSphAttrLocator & tLocator, const BYTE * pBlobPool, int & iLengthBytes )
{
assert ( pBlobPool );
int64_t iOffset = GetBlobRowOffset ( pDocinfo, tLocator.m_iBlobRowOffset );
return GetBlobAttr ( pBlobPool+iOffset, tLocator.m_iBlobAttrId, tLocator.m_nBlobAttrs, iLengthBytes );
}
ByteBlob_t sphGetBlobAttr ( const CSphRowitem * pDocinfo, const CSphAttrLocator & tLocator, const BYTE * pBlobPool )
{
assert ( pBlobPool );
int64_t iOffset = GetBlobRowOffset ( pDocinfo, tLocator.m_iBlobRowOffset );
return GetBlobAttr ( pBlobPool+iOffset, tLocator.m_iBlobAttrId, tLocator.m_nBlobAttrs );
}
template <typename T>
static int GetBlobAttrLen ( int iBlobAttrId, const BYTE * pRow )
{
assert ( pRow );
T uLen1 = sphUnalignedRead ( *((const T*)pRow + iBlobAttrId) );
T uLen0 = iBlobAttrId > 0 ? sphUnalignedRead ( *((const T*)pRow+iBlobAttrId-1) ) : 0;
return (int)uLen1-uLen0;
}
int sphGetBlobAttrLen ( const CSphMatch & tMatch, const CSphAttrLocator & tLocator, const BYTE * pBlobPool )
{
assert ( pBlobPool );
int64_t iOffset = GetBlobRowOffset ( tMatch, tLocator );
const BYTE * pRow = pBlobPool+iOffset;
switch ( *pRow )
{
case BLOB_ROW_LEN_BYTE: return GetBlobAttrLen<BYTE> ( tLocator.m_iBlobAttrId, pRow+1 );
case BLOB_ROW_LEN_WORD: return GetBlobAttrLen<WORD> ( tLocator.m_iBlobAttrId, pRow+1 );
case BLOB_ROW_LEN_DWORD: return GetBlobAttrLen<DWORD> ( tLocator.m_iBlobAttrId, pRow+1 );
default:
break;
}
assert ( 0 && "Unknown blob row type" );
return 0;
}
template <typename T>
static int GetBlobTotalLen ( const BYTE * pRow, int nBlobAttrs )
{
assert ( pRow );
return sphUnalignedRead ( *((const T *)pRow + nBlobAttrs - 1 ) ) + nBlobAttrs*sizeof(T) + 1;
}
DWORD sphGetBlobTotalLen ( const BYTE * pRow, int nBlobAttrs )
{
switch ( *pRow )
{
case BLOB_ROW_LEN_BYTE: return GetBlobTotalLen<BYTE> ( pRow+1, nBlobAttrs );
case BLOB_ROW_LEN_WORD: return GetBlobTotalLen<WORD> ( pRow+1, nBlobAttrs );
case BLOB_ROW_LEN_DWORD: return GetBlobTotalLen<DWORD> ( pRow+1, nBlobAttrs );
default:
break;
}
assert ( 0 && "Unknown blob row type" );
return 0;
}
int64_t sphCopyBlobRow ( CSphTightVector<BYTE> & dDstPool, const CSphTightVector<BYTE> & dSrcPool, int64_t iOffset, int nBlobs )
{
const BYTE * pSrcBlob = dSrcPool.Begin()+iOffset;
int iBlobLen = sphGetBlobTotalLen ( pSrcBlob, nBlobs );
int64_t iNewOffset = dDstPool.GetLength();
dDstPool.Append ( pSrcBlob, iBlobLen );
return iNewOffset;
}
void sphAddAttrToBlobRow ( const CSphRowitem * pDocinfo, CSphTightVector<BYTE> & dBlobRow, const BYTE * pPool, int nBlobs, const CSphAttrLocator * pOldBlobRowLoc )
{
dBlobRow.Resize ( 0 );
if ( nBlobs )
{
assert(pOldBlobRowLoc);
const BYTE * pOldRow = pPool + sphGetRowAttr ( pDocinfo, *pOldBlobRowLoc );
DWORD uOldBlobLen = sphGetBlobTotalLen ( pOldRow, nBlobs );
DWORD uLenSize = RowFlagsToLen ( *pOldRow );
dBlobRow.Resize ( uOldBlobLen + uLenSize );
BYTE * pNewRow = dBlobRow.Begin();
DWORD uAttrLengthSize = uLenSize*nBlobs+1; // old blob lengths + flags
memcpy ( pNewRow, pOldRow, uAttrLengthSize );
pNewRow += uAttrLengthSize;
pOldRow += uAttrLengthSize;
memcpy ( pNewRow, pOldRow-uLenSize, uLenSize ); // new attr length (last cumulative length)
pNewRow += uLenSize;
memcpy ( pNewRow, pOldRow, uOldBlobLen-uAttrLengthSize );
}
else
{
dBlobRow.Add ( CalcBlobRowFlags(0) ); // 1-byte flags
dBlobRow.Add ( 0 ); // 1-byte length
}
}
void sphRemoveAttrFromBlobRow ( const CSphRowitem * pDocinfo, CSphTightVector<BYTE> & dBlobRow, const BYTE * pPool, int nBlobs, int iBlobAttrId, const CSphAttrLocator & tBlobRowLoc )
{
if ( nBlobs<=1 )
{
dBlobRow.Resize(0);
return;
}
const BYTE * pOldRow = pPool + sphGetRowAttr ( pDocinfo, tBlobRowLoc );
BYTE uFlags = *pOldRow;
CSphVector<DWORD> dAttrLengths;
for ( int i = 0; i < nBlobs; i++ )
if ( i!=iBlobAttrId )
{
switch ( uFlags )
{
case BLOB_ROW_LEN_BYTE:
dAttrLengths.Add ( GetBlobAttrLen<BYTE> ( i, pOldRow+1 ) );
break;
case BLOB_ROW_LEN_WORD:
dAttrLengths.Add ( GetBlobAttrLen<WORD> ( i, pOldRow+1 ) );
break;
case BLOB_ROW_LEN_DWORD:
dAttrLengths.Add ( GetBlobAttrLen<DWORD> ( i, pOldRow+1 ) );
break;
default:
break;
}
}
DWORD uTotalLength = 0;
for ( auto i : dAttrLengths )
uTotalLength += i;
dBlobRow.Resize ( 1 + (nBlobs-1)*RowFlagsToLen(uFlags) + uTotalLength );
BYTE * pNewRow = dBlobRow.Begin();
// flags
BYTE uNewFlags = CalcBlobRowFlags ( uTotalLength );
*pNewRow++ = uNewFlags;
// attribute lengths
DWORD uCumulativeLength = 0;
ARRAY_FOREACH ( i, dAttrLengths )
{
uCumulativeLength += dAttrLengths[i];
switch ( uNewFlags )
{
case BLOB_ROW_LEN_BYTE:
sphUnalignedWrite ( pNewRow, (BYTE)uCumulativeLength );
pNewRow += sizeof(BYTE);
break;
case BLOB_ROW_LEN_WORD:
sphUnalignedWrite ( pNewRow, (WORD)uCumulativeLength );
pNewRow += sizeof(WORD);
break;
case BLOB_ROW_LEN_DWORD:
sphUnalignedWrite ( pNewRow, (DWORD)uCumulativeLength );
pNewRow += sizeof(DWORD);
break;
default:
break;
}
}
// attribute data
for ( int i = 0; i < nBlobs; i++ )
if ( i!=iBlobAttrId )
{
int iLengthBytes = 0;
const BYTE * pBlob = GetBlobAttr ( pOldRow, i, nBlobs, iLengthBytes );
memcpy ( pNewRow, pBlob, iLengthBytes );
pNewRow += iLengthBytes;
}
}
template<typename T>
static bool CheckMVAValues ( const T * pMVA, DWORD uLengthBytes, int iBlobAttrId, CSphString & sError )
{
if ( uLengthBytes % sizeof(T) )
{
sError.SetSprintf ( "Blob row error: MVA attribute length=%u is not a multiple of %u (blob attribute %d)", uLengthBytes, DWORD(sizeof(T)), iBlobAttrId );
return false;
}
int nValues = int(uLengthBytes/sizeof(T));
for ( int i = 0; i < nValues-1; i++ )
if ( pMVA[i]>=pMVA[i+1] )
{
sError.SetSprintf ( "Blob row error: descending MVA values found (blob attribute %d)", iBlobAttrId );
return false;
}
return true;
}
bool sphCheckBlobRow ( int64_t iOff, DebugCheckReader_i & tBlobs, const CSphSchema & tSchema, CSphString & sError )
{
CSphVector<ESphAttr> dBlobAttrs;
for ( int i = 0; i < tSchema.GetAttrsCount(); i++ )
{
const CSphColumnInfo & tAttr = tSchema.GetAttr(i);
if ( sphIsBlobAttr(tAttr) )
dBlobAttrs.Add ( tAttr.m_eAttrType );
}
int64_t iBlobsElemCount = tBlobs.GetLengthBytes();
if ( iOff<0 || iOff>iBlobsElemCount )
{
sError.SetSprintf ( "Blob offset out of bounds: " INT64_FMT " (max: " INT64_FMT ")", iOff, iBlobsElemCount );
return false;
}
tBlobs.SeekTo ( iOff, 16 );
BYTE uType = 0;
tBlobs.GetBytes ( &uType, sizeof(uType) );
if ( uType!=BLOB_ROW_LEN_BYTE && uType!=BLOB_ROW_LEN_WORD && uType!=BLOB_ROW_LEN_DWORD )
{
sError.SetSprintf ( "Unknown blob row type: %u", uType );
return false;
}
int nBlobAttrs = dBlobAttrs.GetLength();
DWORD uLenSize = RowFlagsToLen ( uType );
DWORD uAttrLengths = uLenSize*nBlobAttrs;
if ( iOff + uAttrLengths > iBlobsElemCount )
sError = "Blob row too long";
CSphFixedVector<BYTE> dLengths ( uAttrLengths );
tBlobs.GetBytes ( dLengths.Begin(), (int) dLengths.GetLengthBytes() );
const BYTE * pLen = dLengths.Begin();
CSphVector<int> dAttrLengths ( nBlobAttrs );
for ( int i = 0; i < nBlobAttrs; i++ )
{
switch ( uType )
{
case BLOB_ROW_LEN_BYTE: dAttrLengths[i] = GetBlobAttrLen<BYTE> ( i, pLen ); break;
case BLOB_ROW_LEN_WORD: dAttrLengths[i] = GetBlobAttrLen<WORD> ( i, pLen ); break;
case BLOB_ROW_LEN_DWORD: dAttrLengths[i] = GetBlobAttrLen<DWORD> ( i, pLen ); break;
default:
break;
}
}
for ( int i = 0; i < nBlobAttrs-1; i++ )
if ( dAttrLengths[i]<0 )
{
sError = "Blob row error: negative attribute length";
return false;
}
DWORD uTotalLength = 0;
for ( auto i : dAttrLengths )
uTotalLength += (DWORD)i;
if ( iOff+uAttrLengths+uTotalLength > iBlobsElemCount )
{
sError = "Blob row too long";
return false;
}
CSphFixedVector<BYTE> dAttrs ( uTotalLength );
tBlobs.GetBytes ( dAttrs.Begin(), (int) dAttrs.GetLengthBytes() );
const BYTE * pAttr = dAttrs.Begin();
for ( int i = 0; i < nBlobAttrs; i++ )
{
DWORD uLength = (DWORD)dAttrLengths[i];
switch ( dBlobAttrs[i] )
{
case SPH_ATTR_UINT32SET:
if ( !CheckMVAValues ( (const DWORD *)pAttr, uLength, i, sError ) )
return false;
break;
case SPH_ATTR_INT64SET:
if ( !CheckMVAValues ( (const int64_t *)pAttr, uLength, i, sError ) )
return false;
break;
case SPH_ATTR_STRING:
for ( DWORD j = 0; j < uLength; j++ )
if ( !pAttr[j] )
{
sError.SetSprintf ( "Blob row error: string value contains zeroes (blob attribute %d)", i );
return false;
}
break;
default:
break;
}
pAttr += uLength;
}
return true;
}
const char * sphGetBlobLocatorName()
{
static const char * BLOB_LOCATOR_ATTR = "$_blob_locator";
return BLOB_LOCATOR_ATTR;
}
const char * GetNullMaskAttrName()
{
static const char * szNullMaskAttrName = "$_null_mask";
return szNullMaskAttrName;
}
static const CSphString g_sDocidName { "id" };
const char * sphGetDocidName()
{
return g_sDocidName.cstr();
}
const CSphString & sphGetDocidStr()
{
return g_sDocidName;
}
bool sphIsBlobAttr ( ESphAttr eAttr )
{
return eAttr==SPH_ATTR_STRING || eAttr==SPH_ATTR_JSON || eAttr==SPH_ATTR_UINT32SET || eAttr==SPH_ATTR_INT64SET || eAttr==SPH_ATTR_FLOAT_VECTOR;
}
bool sphIsBlobAttr ( const CSphColumnInfo & tAttr )
{
if ( tAttr.IsColumnar() )
return false;
return sphIsBlobAttr ( tAttr.m_eAttrType );
}
bool IsMvaAttr ( ESphAttr eAttr )
{
return eAttr==SPH_ATTR_UINT32SET || eAttr==SPH_ATTR_INT64SET || eAttr==SPH_ATTR_FLOAT_VECTOR || eAttr==SPH_ATTR_UINT32SET_PTR || eAttr==SPH_ATTR_INT64SET_PTR || eAttr==SPH_ATTR_FLOAT_VECTOR_PTR;
}
//////////////////////////////////////////////////////////////////////////
// data ptr attributes
int sphCalcPackedLength ( int iLengthBytes )
{
return sphCalcZippedLen(iLengthBytes) + iLengthBytes;
}
BYTE * sphPackedBlob ( ByteBlob_t dBlob )
{
if ( !dBlob.first ) return nullptr;
return const_cast<BYTE*>(dBlob.first-sphCalcZippedLen (dBlob.second));
}
// allocate buf and pack blob tBlob into it, return pointer to buf
BYTE * sphPackPtrAttr ( ByteBlob_t dBlob )
{
if ( !dBlob.second )
return nullptr;
assert ( dBlob.first );
BYTE * pPacked = sphAllocateSmall ( sphCalcPackedLength ( dBlob.second ));
sphPackPtrAttr ( pPacked, std::move(dBlob) );
return pPacked;
}
// pack blob pData[iLengthBytes] into preallocated buf
int sphPackPtrAttr ( BYTE * pPrealloc, ByteBlob_t dBlob )
{
assert ( pPrealloc && IsValid ( dBlob ) );
int iZippedLen = ZipToPtrBE ( pPrealloc, dBlob.second );
memcpy ( pPrealloc+iZippedLen, dBlob.first, dBlob.second );
return iZippedLen+dBlob.second;
}
void sphPackPtrAttrInPlace ( TightPackedVec_T<BYTE> & dAttr, int iSize )
{
BYTE bSize[20];
if ( iSize<0 ) iSize = dAttr.GetLength();
int iZippedLen = ZipToPtrBE ( bSize, iSize );
dAttr.Resize ( iZippedLen+iSize );
BYTE * pData = dAttr.Begin ();
memmove ( pData+iZippedLen, pData, iSize );
memcpy ( pData, bSize, iZippedLen );
}
// allocate buf for pack of iLengthBytes, pack size, then put pointer to payload in *ppData, and return buf
BYTE * sphPackPtrAttr ( int iLengthBytes, BYTE ** ppData )
{
assert ( ppData );
BYTE * pPacked = sphAllocateSmall ( sphCalcPackedLength ( iLengthBytes ) );
*ppData = pPacked;
*ppData += ZipToPtrBE ( pPacked, iLengthBytes );
return pPacked;
}
ByteBlob_t sphUnpackPtrAttr ( const BYTE * pData )
{
if ( !pData )
return { nullptr, 0 };
auto iLen = (int)UnzipIntBE ( pData );
return { pData, iLen };
}
BYTE * sph::CopyPackedAttr ( const BYTE* pData )
{
return sphPackPtrAttr ( sphUnpackPtrAttr ( pData ));
}
ESphAttr sphPlainAttrToPtrAttr ( ESphAttr eAttrType )
{
switch ( eAttrType )
{
case SPH_ATTR_STRING: return SPH_ATTR_STRINGPTR;
case SPH_ATTR_JSON: return SPH_ATTR_JSON_PTR;
case SPH_ATTR_UINT32SET: return SPH_ATTR_UINT32SET_PTR;
case SPH_ATTR_INT64SET: return SPH_ATTR_INT64SET_PTR;
case SPH_ATTR_FLOAT_VECTOR: return SPH_ATTR_FLOAT_VECTOR_PTR;
case SPH_ATTR_JSON_FIELD: return SPH_ATTR_JSON_FIELD_PTR;
default: return eAttrType;
};
}
bool sphIsDataPtrAttr ( ESphAttr eAttr )
{
return eAttr==SPH_ATTR_STRINGPTR || eAttr==SPH_ATTR_FACTORS || eAttr==SPH_ATTR_FACTORS_JSON
|| eAttr==SPH_ATTR_UINT32SET_PTR || eAttr==SPH_ATTR_INT64SET_PTR || eAttr==SPH_ATTR_FLOAT_VECTOR_PTR
|| eAttr==SPH_ATTR_JSON_PTR || eAttr==SPH_ATTR_JSON_FIELD_PTR;
}
//////////////////////////////////////////////////////////////////////////
// misc attribute-related
template < typename T >
static void MVA2Str ( const T * pMVA, int iLengthBytes, StringBuilder_c &dStr )
{
int nValues = iLengthBytes / sizeof ( T );
dStr.GrowEnough (( SPH_MAX_NUMERIC_STR+1 ) * nValues );
Comma_c sComma ( "," );
for ( int i = 0; i<nValues; ++i )
{
dStr << sComma;
#if __has_include( <charconv>)
dStr.SetPos ( std::to_chars ( dStr.end (), dStr.AfterEnd(), pMVA[i] ).ptr );
#else
dStr += sph::NtoA ( dStr.end(), pMVA[i] );
#endif
}
*dStr.end() = '\0';
}
static void FloatVec2Str ( const float * pFloatVec, int iLengthBytes, StringBuilder_c & dStr )
{
int iNumValues = iLengthBytes / sizeof (float);
dStr.GrowEnough ( (SPH_MAX_NUMERIC_STR+1)*iNumValues );
Comma_c sComma ( "," );
for ( int i = 0; i < iNumValues; ++i )
{
dStr << sComma;
dStr << pFloatVec[i];
}
*dStr.end() = '\0';
}
bool sphIsInternalAttr ( const CSphString & sAttrName )
{
return sAttrName==sphGetBlobLocatorName() || sAttrName==GetNullMaskAttrName();
}
bool sphIsInternalAttr ( const CSphColumnInfo & tCol )
{
return sphIsInternalAttr ( tCol.m_sName );
}
void sphMVA2Str ( ByteBlob_t dMVA, bool b64bit, StringBuilder_c & dStr )
{
if ( b64bit )
MVA2Str ( ( const int64_t * ) dMVA.first, dMVA.second, dStr );
else
MVA2Str ( ( const DWORD * ) dMVA.first, dMVA.second, dStr );
}
void sphPackedMVA2Str ( const BYTE * pMVA, bool b64bit, StringBuilder_c & dStr )
{
auto dMVA = sphUnpackPtrAttr ( pMVA );
sphMVA2Str( dMVA, b64bit, dStr );
}
void sphFloatVec2Str ( ByteBlob_t dFloatVec, StringBuilder_c & dStr )
{
FloatVec2Str ( (const float*)dFloatVec.first, dFloatVec.second, dStr );
}
void sphPackedFloatVec2Str ( const BYTE * pData, StringBuilder_c & dStr )
{
auto dFloatVec = sphUnpackPtrAttr ( pData );
sphFloatVec2Str ( dFloatVec, dStr );
}
bool IsNotRealAttribute ( const CSphColumnInfo & tColumn )
{
return tColumn.m_uFieldFlags & CSphColumnInfo::FIELD_STORED;
}
const char * AttrType2Str ( ESphAttr eAttrType )
{
switch ( eAttrType )
{
case SPH_ATTR_NONE: return "SPH_ATTR_NONE";
case SPH_ATTR_INTEGER: return "SPH_ATTR_INTEGER";
case SPH_ATTR_TIMESTAMP: return "SPH_ATTR_TIMESTAMP";
case SPH_ATTR_BOOL: return "SPH_ATTR_BOOL";
case SPH_ATTR_FLOAT: return "SPH_ATTR_FLOAT";
case SPH_ATTR_BIGINT: return "SPH_ATTR_BIGINT";
case SPH_ATTR_STRING: return "SPH_ATTR_STRING";
case SPH_ATTR_POLY2D: return "SPH_ATTR_POLY2D";
case SPH_ATTR_STRINGPTR: return "SPH_ATTR_STRINGPTR";
case SPH_ATTR_TOKENCOUNT: return "SPH_ATTR_TOKENCOUNT";
case SPH_ATTR_JSON: return "SPH_ATTR_JSON";
case SPH_ATTR_UINT32SET: return "SPH_ATTR_UINT32SET";
case SPH_ATTR_INT64SET: return "SPH_ATTR_INT64SET";
case SPH_ATTR_MAPARG: return "SPH_ATTR_MAPARG";
case SPH_ATTR_FACTORS: return "SPH_ATTR_FACTORS";
case SPH_ATTR_JSON_FIELD: return "SPH_ATTR_JSON_FIELD";
case SPH_ATTR_FACTORS_JSON: return "SPH_ATTR_FACTORS_JSON";
case SPH_ATTR_UINT32SET_PTR: return "SPH_ATTR_UINT32SET_PTR";
case SPH_ATTR_INT64SET_PTR: return "SPH_ATTR_INT64SET_PTR";
case SPH_ATTR_JSON_PTR: return "SPH_ATTR_JSON_PTR";
case SPH_ATTR_JSON_FIELD_PTR: return "SPH_ATTR_JSON_FIELD_PTR";
default: return "";
}
return "SPH_ATTR_NONE";
}
| 32,335
|
C++
|
.cpp
| 936
| 32.056624
| 204
| 0.704214
|
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
|
16,819
|
columnarsort.cpp
|
manticoresoftware_manticoresearch/src/columnarsort.cpp
|
//
// 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/
//
#include "columnarsort.h"
#include "attribute.h"
#include "sortcomp.h"
#include "conversion.h"
class CompareSingleError_fn
{
public:
FORCE_INLINE static bool IsLess ( RowID_t tRowIdA, SphAttr_t a, RowID_t tRowIdB, SphAttr_t b )
{
assert ( 0 && "Internal error" );
return false;
}
};
template <bool INV>
class CompareSingleInt_fn
{
public:
FORCE_INLINE static bool IsLess ( RowID_t tRowIdA, SphAttr_t a, RowID_t tRowIdB, SphAttr_t b )
{
if ( a!=b ) return ( a>b ) ^ INV;
return tRowIdA>tRowIdB;
}
};
template <bool INV>
class CompareSingleFloat_fn
{
public:
FORCE_INLINE static bool IsLess ( RowID_t tRowIdA, SphAttr_t a, RowID_t tRowIdB, SphAttr_t b )
{
float fA = sphDW2F(DWORD(a));
float fB = sphDW2F(DWORD(b));
if ( fA!=fB ) return ( fA>fB ) ^ INV;
return tRowIdA>tRowIdB;
}
};
/////////////////////////////////////////////////////////////////////
class CompareError_fn
{
public:
FORCE_INLINE static bool IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
assert ( 0 && "Internal error" );
return false;
}
};
template <int ARGS>
class CompareInt_fn
{
public:
FORCE_INLINE static bool IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
assert ( 0 && "Internal error" );
return false;
}
};
template <>
FORCE_INLINE bool CompareInt_fn<2>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
DWORD uAttrDesc = tState.m_uAttrDesc;
if ( dA[0]!=dB[0] ) return ( dA[0]>dB[0] ) ^ ( ( uAttrDesc >> 0 ) & 1 );
if ( dA[1]!=dB[1] ) return ( dA[1]>dB[1] ) ^ ( ( uAttrDesc >> 1 ) & 1 );
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool CompareInt_fn<3>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
DWORD uAttrDesc = tState.m_uAttrDesc;
if ( dA[0]!=dB[0] ) return ( dA[0]>dB[0] ) ^ ( ( uAttrDesc >> 0 ) & 1 );
if ( dA[1]!=dB[1] ) return ( dA[1]>dB[1] ) ^ ( ( uAttrDesc >> 1 ) & 1 );
if ( dA[2]!=dB[2] ) return ( dA[2]>dB[2] ) ^ ( ( uAttrDesc >> 2 ) & 1 );
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool CompareInt_fn<4>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
DWORD uAttrDesc = tState.m_uAttrDesc;
if ( dA[0]!=dB[0] ) return ( dA[0]>dB[0] ) ^ ( ( uAttrDesc >> 0 ) & 1 );
if ( dA[1]!=dB[1] ) return ( dA[1]>dB[1] ) ^ ( ( uAttrDesc >> 1 ) & 1 );
if ( dA[2]!=dB[2] ) return ( dA[2]>dB[2] ) ^ ( ( uAttrDesc >> 2 ) & 1 );
if ( dA[3]!=dB[3] ) return ( dA[3]>dB[3] ) ^ ( ( uAttrDesc >> 3 ) & 1 );
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool CompareInt_fn<5>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
DWORD uAttrDesc = tState.m_uAttrDesc;
if ( dA[0]!=dB[0] ) return ( dA[0]>dB[0] ) ^ ( ( uAttrDesc >> 0 ) & 1 );
if ( dA[1]!=dB[1] ) return ( dA[1]>dB[1] ) ^ ( ( uAttrDesc >> 1 ) & 1 );
if ( dA[2]!=dB[2] ) return ( dA[2]>dB[2] ) ^ ( ( uAttrDesc >> 2 ) & 1 );
if ( dA[3]!=dB[3] ) return ( dA[3]>dB[3] ) ^ ( ( uAttrDesc >> 3 ) & 1 );
if ( dA[4]!=dB[4] ) return ( dA[4]>dB[4] ) ^ ( ( uAttrDesc >> 4 ) & 1 );
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
/////////////////////////////////////////////////////////////////////
#define COMPARE_FLOATS(A,B,INV) \
{ \
float fA = sphDW2F(DWORD(A)); \
float fB = sphDW2F(DWORD(B)); \
if ( fA!=fB ) return ( fA>fB ) ^ INV; \
}
template <int ARGS>
class CompareFloat_fn
{
public:
FORCE_INLINE static bool IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
assert ( 0 && "Internal error" );
return false;
}
};
template <>
FORCE_INLINE bool CompareFloat_fn<2>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
DWORD uAttrDesc = tState.m_uAttrDesc;
COMPARE_FLOATS ( dA[0], dB[0], ( ( uAttrDesc >> 0 ) & 1 ) );
COMPARE_FLOATS ( dA[1], dB[1], ( ( uAttrDesc >> 1 ) & 1 ) );
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool CompareFloat_fn<3>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
DWORD uAttrDesc = tState.m_uAttrDesc;
COMPARE_FLOATS ( dA[0], dB[0], ( ( uAttrDesc >> 0 ) & 1 ) );
COMPARE_FLOATS ( dA[1], dB[1], ( ( uAttrDesc >> 1 ) & 1 ) );
COMPARE_FLOATS ( dA[2], dB[2], ( ( uAttrDesc >> 2 ) & 1 ) );
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool CompareFloat_fn<4>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
DWORD uAttrDesc = tState.m_uAttrDesc;
COMPARE_FLOATS ( dA[0], dB[0], ( ( uAttrDesc >> 0 ) & 1 ) );
COMPARE_FLOATS ( dA[1], dB[1], ( ( uAttrDesc >> 1 ) & 1 ) );
COMPARE_FLOATS ( dA[2], dB[2], ( ( uAttrDesc >> 2 ) & 1 ) );
COMPARE_FLOATS ( dA[3], dB[3], ( ( uAttrDesc >> 3 ) & 1 ) );
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool CompareFloat_fn<5>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
DWORD uAttrDesc = tState.m_uAttrDesc;
COMPARE_FLOATS ( dA[0], dB[0], ( ( uAttrDesc >> 0 ) & 1 ) );
COMPARE_FLOATS ( dA[1], dB[1], ( ( uAttrDesc >> 1 ) & 1 ) );
COMPARE_FLOATS ( dA[2], dB[2], ( ( uAttrDesc >> 2 ) & 1 ) );
COMPARE_FLOATS ( dA[3], dB[3], ( ( uAttrDesc >> 3 ) & 1 ) );
COMPARE_FLOATS ( dA[4], dB[4], ( ( uAttrDesc >> 4 ) & 1 ) );
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
/////////////////////////////////////////////////////////////////////
#define TEST_PAIR(_aa,_bb,_idx ) \
if ( (_aa)!=(_bb) ) \
return ( (tState.m_uAttrDesc >> (_idx)) & 1 ) ^ ( (_aa) > (_bb) );
#define TEST_KEYPART(_idx) \
switch ( tState.m_eKeypart[_idx] ) \
{ \
case SPH_KEYPART_ROWID: TEST_PAIR ( tMatchA.m_tRowID, tMatchB.m_tRowID, _idx ); break; \
case SPH_KEYPART_WEIGHT: TEST_PAIR ( tMatchA.m_iWeight, tMatchB.m_iWeight, _idx ); break; \
case SPH_KEYPART_INT: \
{ \
SphAttr_t aa = dA[tState.m_dAttrs[_idx]]; \
SphAttr_t bb = dB[tState.m_dAttrs[_idx]]; \
TEST_PAIR ( aa, bb, _idx ); \
break; \
} \
case SPH_KEYPART_FLOAT: \
{ \
float aa = sphDW2F ( dA[tState.m_dAttrs[_idx]] ); \
float bb = sphDW2F ( dB[tState.m_dAttrs[_idx]] ); \
TEST_PAIR ( aa, bb, _idx ) \
break; \
} \
case SPH_KEYPART_DOUBLE: \
{ \
double aa = sphQW2D ( dA[tState.m_dAttrs[_idx]] ); \
double bb = sphQW2D ( dB[tState.m_dAttrs[_idx]] ); \
TEST_PAIR ( aa, bb, _idx ) \
break; \
} \
default: \
assert ( 0 && "Internal error" ); \
break; \
}
template <int ARGS>
class Compare_fn
{
public:
FORCE_INLINE static bool IsLess ( RowID_t tRowIdA, SphAttr_t a, RowID_t tRowIdB, SphAttr_t b, bool bInv )
{
assert ( 0 && "Internal error" );
return false;
}
FORCE_INLINE static bool IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
assert ( 0 && "Internal error" );
return false;
}
};
template <>
FORCE_INLINE bool Compare_fn<1>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
TEST_KEYPART(0);
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool Compare_fn<2>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
TEST_KEYPART(0);
TEST_KEYPART(1);
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool Compare_fn<3>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
TEST_KEYPART(0);
TEST_KEYPART(1);
TEST_KEYPART(2);
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool Compare_fn<4>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
TEST_KEYPART(0);
TEST_KEYPART(1);
TEST_KEYPART(2);
TEST_KEYPART(3);
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
template <>
FORCE_INLINE bool Compare_fn<5>::IsLess ( const CSphMatch & tMatchA, SphAttr_t * dA, const CSphMatch & tMatchB, SphAttr_t * dB, const CSphMatchComparatorState & tState )
{
TEST_KEYPART(0);
TEST_KEYPART(1);
TEST_KEYPART(2);
TEST_KEYPART(3);
TEST_KEYPART(4);
return tMatchA.m_tRowID>tMatchB.m_tRowID;
}
/////////////////////////////////////////////////////////////////////
template <typename GENERIC, typename COMP, typename SINGLE>
class ColumnarProxySorter_T : public ISphMatchSorter
{
public:
ColumnarProxySorter_T ( ISphMatchSorter * pSorter, int iSize, int iFastPathAttrs );
~ColumnarProxySorter_T() override;
bool Push ( const CSphMatch & tEntry ) final { return PushMatch(tEntry); }
void Push ( const VecTraits_T<const CSphMatch> & dMatches ) override { assert ( 0 && "No batch push to proxy sorter" ); }
bool IsGroupby() const override { return m_pSorter->IsGroupby(); }
bool PushGrouped ( const CSphMatch & tEntry, bool bNewSet ) override { return m_pSorter->PushGrouped ( tEntry, bNewSet ); }
int GetLength () override;
void Finalize ( MatchProcessor_i & tProcessor, bool bCallProcessInResultSetOrder, bool bFinalizeMatches ) override;
int Flatten ( CSphMatch * pTo ) override;
void MoveTo ( ISphMatchSorter * pRhs, bool bCopyMeta ) override;
ISphMatchSorter * Clone() const override { return new ColumnarProxySorter_T<GENERIC,COMP,SINGLE> ( m_pSorter->Clone(), m_iSize, m_iFastPathAttrs ); }
void CloneTo ( ISphMatchSorter * pTrg ) const override;
void SetState ( const CSphMatchComparatorState & tState ) override;
const CSphMatchComparatorState & GetState() const override { return m_pSorter->GetState(); }
void SetSchema ( ISphSchema * pSchema, bool bRemapCmp ) override;
const ISphSchema * GetSchema() const override { return m_pSchema; }
void SetColumnar ( columnar::Columnar_i * pColumnar ) override;
int64_t GetTotalCount() const override { return m_pSorter->GetTotalCount(); }
void SetFilteredAttrs ( const sph::StringSet & hAttrs, bool bAddDocid ) override { m_pSorter->SetFilteredAttrs ( hAttrs, bAddDocid ); }
void TransformPooled2StandalonePtrs ( GetBlobPoolFromMatch_fn fnBlobPoolFromMatch, GetColumnarFromMatch_fn fnGetColumnarFromMatch, bool bFinalizeSorters ) override;
bool IsRandom() const override { return m_pSorter->IsRandom(); }
void SetRandom ( bool bRandom ) override { m_pSorter->SetRandom(bRandom); }
int GetMatchCapacity() const override { return m_pSorter->GetMatchCapacity(); }
RowTagged_t GetJustPushed() const override { assert (0 && "Not supported" ); return RowTagged_t(); }
VecTraits_T<RowTagged_t> GetJustPopped() const override { assert (0 && "Not supported" ); return {}; }
void SetMerge ( bool bMerge ) override {}
private:
struct IteratorWithLocator_t
{
std::unique_ptr<columnar::Iterator_i> m_pIterator;
CSphAttrLocator m_tLocator;
};
static const int MATCH_BUFFER_SIZE = 1024;
CSphFixedVector<CSphMatch> m_dData{MATCH_BUFFER_SIZE};
CSphVector<CSphRowitem> m_dDynamic;
CSphVector<IteratorWithLocator_t> m_dIterators;
CSphFixedVector<uint32_t> m_dRowIDs{MATCH_BUFFER_SIZE};
CSphFixedVector<int64_t> m_dValues{0};
columnar::Columnar_i * m_pColumnar = nullptr;
std::unique_ptr<ISphMatchSorter> m_pSorter;
const ISphSchema * m_pSchema = nullptr;
CSphMatch * m_pCurMatch = nullptr;
CSphMatch * m_pEndMatch = nullptr;
uint32_t * m_pCurRowID = nullptr;
CSphMatchComparatorState m_tState; // a copy of underlying sorter's state, but may have modified m_dAttrs
int m_iDynamicSize = 0;
int m_iSize = 0;
int64_t m_iPushed = 0;
int m_iFastPathAttrs = 0;
FORCE_INLINE bool PushMatch ( const CSphMatch & tEntry );
void PushCollectedToSorter();
void FetchColumnarValues ( VecTraits_T<CSphMatch> & dMatches );
void SpawnIterators();
void DoSetSchema ( const ISphSchema * pSchema );
void FetchValuesIteratorGeneric ( VecTraits_T<CSphMatch> & dMatches );
void FetchValuesIterator1Single ( VecTraits_T<CSphMatch> & dMatches );
void FetchValuesMultiIterator ( VecTraits_T<CSphMatch> & dMatches );
// these are unrolled versions of FetchValuesMultiIterator
void FetchValuesIterator1 ( VecTraits_T<CSphMatch> & dMatches );
void FetchValuesIterator2 ( VecTraits_T<CSphMatch> & dMatches );
void FetchValuesIterator3 ( VecTraits_T<CSphMatch> & dMatches );
void FetchValuesIterator4 ( VecTraits_T<CSphMatch> & dMatches );
void FetchValuesIterator5 ( VecTraits_T<CSphMatch> & dMatches );
};
template <typename GENERIC, typename COMP, typename SINGLE>
ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::ColumnarProxySorter_T ( ISphMatchSorter * pSorter, int iSize, int iFastPathAttrs )
: m_pSorter ( pSorter )
, m_iSize ( iSize )
, m_iFastPathAttrs ( iFastPathAttrs )
{
assert(pSorter);
m_pCurMatch = m_dData.Begin();
m_pEndMatch = m_pCurMatch + m_dData.GetLength();
m_pCurRowID = m_dRowIDs.Begin();
m_dValues.Reset ( ( iFastPathAttrs ? iFastPathAttrs : 1 ) * MATCH_BUFFER_SIZE );
DoSetSchema ( pSorter->GetSchema() );
m_tState = pSorter->GetState();
}
template <typename GENERIC, typename COMP, typename SINGLE>
ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::~ColumnarProxySorter_T()
{
for ( auto & i : m_dData )
i.m_pDynamic = nullptr;
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::SetSchema ( ISphSchema * pSchema, bool bRemapCmp )
{
m_pSorter->SetSchema ( pSchema, bRemapCmp );
DoSetSchema(pSchema);
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::DoSetSchema ( const ISphSchema * pSchema )
{
m_pSchema = pSchema;
if ( !m_pSchema )
return;
m_iDynamicSize = m_pSchema->GetDynamicSize();
#if NDEBUG
int iStride = m_iDynamicSize;
#else
int iStride = m_iDynamicSize+1;
#endif
m_dDynamic.Resize ( iStride*m_dData.GetLength() );
CSphRowitem * pDynamic = m_dDynamic.Begin();
CSphMatch tMatch;
// set the dynamic part to point to out buffer
for ( auto & i : m_dData )
{
#if NDEBUG
i.m_pDynamic = pDynamic;
#else
*pDynamic = m_iDynamicSize;
i.m_pDynamic = pDynamic+1;
#endif
pDynamic += iStride;
}
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::CloneTo ( ISphMatchSorter * pTrg ) const
{
pTrg->SetRandom ( IsRandom() );
pTrg->SetState ( GetState() );
pTrg->SetSchema ( m_pSchema->CloneMe(), false );
}
template <typename GENERIC, typename COMP, typename SINGLE>
int ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::GetLength()
{
assert(m_pSorter);
PushCollectedToSorter();
return m_pSorter->GetLength();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::SetColumnar ( columnar::Columnar_i * pColumnar )
{
// we might be working with an RT index
// in that case SetColumnar call tells us that we need to calculate all values and push them to sorter
if ( m_pColumnar )
PushCollectedToSorter();
m_pColumnar = pColumnar;
m_pSorter->SetColumnar(pColumnar);
SpawnIterators();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::TransformPooled2StandalonePtrs ( GetBlobPoolFromMatch_fn fnBlobPoolFromMatch, GetColumnarFromMatch_fn fnGetColumnarFromMatch, bool bFinalizeSorters )
{
assert(m_pSorter);
PushCollectedToSorter();
m_pSorter->TransformPooled2StandalonePtrs ( fnBlobPoolFromMatch, fnGetColumnarFromMatch, bFinalizeSorters );
m_pSchema = m_pSorter->GetSchema();
}
template <typename GENERIC, typename COMP, typename SINGLE>
bool ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::PushMatch ( const CSphMatch & tEntry )
{
// this is a simplified (faster) version of match cloning
CSphMatch & tMatch = *m_pCurMatch++;
tMatch.m_tRowID = tEntry.m_tRowID;
tMatch.m_iWeight = tEntry.m_iWeight;
tMatch.m_pStatic = tEntry.m_pStatic;
tMatch.m_iTag = tEntry.m_iTag;
memcpy ( tMatch.m_pDynamic, tEntry.m_pDynamic, m_iDynamicSize*sizeof(CSphRowitem) );
*m_pCurRowID++ = tEntry.m_tRowID;
if ( m_pCurMatch==m_pEndMatch )
PushCollectedToSorter();
return true;
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::Finalize ( MatchProcessor_i & tProcessor, bool bCallProcessInResultSetOrder, bool bFinalizeMatches )
{
assert(m_pSorter);
PushCollectedToSorter();
m_pSorter->Finalize ( tProcessor, bCallProcessInResultSetOrder, bFinalizeMatches );
}
template <typename GENERIC, typename COMP, typename SINGLE>
int ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::Flatten ( CSphMatch * pTo )
{
assert(m_pSorter);
PushCollectedToSorter();
return m_pSorter->Flatten(pTo);
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::MoveTo ( ISphMatchSorter * pRhs, bool bCopyMeta )
{
// we assume that the rhs sorter is of the same type, i.e. proxy
auto pRhsProxy = (ColumnarProxySorter_T<GENERIC,COMP,SINGLE>*)pRhs;
PushCollectedToSorter();
pRhsProxy->PushCollectedToSorter();
m_pSorter->MoveTo ( pRhsProxy->m_pSorter.get(), bCopyMeta );
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::SetState ( const CSphMatchComparatorState & tState )
{
assert(m_pSorter);
m_pSorter->SetState(tState);
m_tState = m_pSorter->GetState();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::PushCollectedToSorter()
{
assert(m_pSorter);
CSphMatch * pData = m_dData.Begin();
int iNumMatches = m_pCurMatch-pData;
if ( !iNumMatches )
return;
VecTraits_T<CSphMatch> dMatches = { pData, iNumMatches };
FetchColumnarValues(dMatches);
m_pSorter->Push(dMatches);
m_pCurMatch = m_dData.Begin();
m_pCurRowID = m_dRowIDs.Begin();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::SpawnIterators()
{
assert ( m_pSchema && m_pSorter && m_pColumnar );
const CSphMatchComparatorState & tOriginalState = m_pSorter->GetState();
m_dIterators.Reset();
for ( int i = 0; i < CSphMatchComparatorState::MAX_ATTRS; i++ )
{
if ( tOriginalState.m_dAttrs[i]==-1 )
continue;
const CSphColumnInfo & tAttr = m_pSchema->GetAttr ( tOriginalState.m_dAttrs[i] );
if ( tAttr.IsColumnarExpr() )
{
CSphString sAliasedCol;
tAttr.m_pExpr->Command ( SPH_EXPR_GET_COLUMNAR_COL, &sAliasedCol );
std::string sError;
// need to fixup attribute ids to use fastpath match comparison func
if ( m_iFastPathAttrs )
m_tState.m_dAttrs[i] = m_dIterators.GetLength();
m_dIterators.Add ( { CreateColumnarIterator ( m_pColumnar, sAliasedCol.cstr(), sError ), tAttr.m_tLocator } );
assert ( m_dIterators.Last().m_pIterator.get() );
}
}
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchValuesIterator1Single ( VecTraits_T<CSphMatch> & dMatches )
{
IteratorWithLocator_t & tIterator = m_dIterators[0];
int iNumValues = dMatches.GetLength();
util::Span_T<uint32_t> dRowIDs ( m_dRowIDs.Begin(), iNumValues );
util::Span_T<int64_t> dValues ( m_dValues.Begin(), iNumValues );
tIterator.m_pIterator->Fetch ( dRowIDs, dValues );
int64_t * pValue = m_dValues.Begin();
assert(m_pSorter);
const CSphMatch * pWorst = m_pSorter->GetWorst();
if ( pWorst && m_iPushed>=m_iSize )
{
SphAttr_t tWorstValue = pWorst->GetAttr ( tIterator.m_tLocator );
RowID_t tWorstRowID = pWorst->m_tRowID;
int iNumMatches = 0;
for ( auto & tMatch : dMatches )
{
int64_t tValue = *pValue++;
if ( SINGLE::IsLess ( tMatch.m_tRowID, tValue, tWorstRowID, tWorstValue ) )
tMatch.m_tRowID = INVALID_ROWID;
else
{
sphSetRowAttr ( tMatch.m_pDynamic, tIterator.m_tLocator, tValue );
iNumMatches++;
}
}
m_iPushed += iNumMatches;
}
else
{
for ( auto & tMatch : dMatches )
sphSetRowAttr ( tMatch.m_pDynamic, tIterator.m_tLocator, *pValue++ );
m_iPushed += dMatches.GetLength();
}
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchValuesIterator1 ( VecTraits_T<CSphMatch> & dMatches )
{
IteratorWithLocator_t & tIt = m_dIterators[0];
int iNumValues = dMatches.GetLength();
util::Span_T<uint32_t> dRowIDs ( m_dRowIDs.Begin(), iNumValues );
util::Span_T<int64_t> dValues ( m_dValues.Begin(), iNumValues );
tIt.m_pIterator->Fetch ( dRowIDs, dValues );
int64_t * pValue = m_dValues.Begin();
SphAttr_t dValueRow[CSphMatchComparatorState::MAX_ATTRS];
SphAttr_t dWorstValueRow[CSphMatchComparatorState::MAX_ATTRS];
memset ( dValueRow, 0, sizeof(dValueRow) );
memset ( dWorstValueRow, 0, sizeof(dWorstValueRow) );
assert(m_pSorter);
const CSphMatch * pWorst = m_pSorter->GetWorst();
if ( pWorst && m_iPushed>=m_iSize )
{
dWorstValueRow[0] = pWorst->GetAttr ( tIt.m_tLocator );
int iNumMatches = 0;
for ( auto & tMatch : dMatches )
{
dValueRow[0] = *pValue++;
if ( COMP::IsLess ( tMatch, dValueRow, *pWorst, dWorstValueRow, m_tState ) )
tMatch.m_tRowID = INVALID_ROWID;
else
{
sphSetRowAttr ( tMatch.m_pDynamic, tIt.m_tLocator, dValueRow[0] );
iNumMatches++;
}
}
m_iPushed += iNumMatches;
return;
}
else
{
for ( auto & tMatch : dMatches )
sphSetRowAttr ( tMatch.m_pDynamic, tIt.m_tLocator, *pValue++ );
m_iPushed += dMatches.GetLength();
}
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchValuesIterator2 ( VecTraits_T<CSphMatch> & dMatches )
{
IteratorWithLocator_t & tIt0 = m_dIterators[0];
IteratorWithLocator_t & tIt1 = m_dIterators[1];
int64_t * pValues0 = m_dValues.Begin();
int64_t * pValues1 = m_dValues.Begin() + MATCH_BUFFER_SIZE;
int iNumValues = dMatches.GetLength();
util::Span_T<uint32_t> dRowIDs ( m_dRowIDs.Begin(), iNumValues );
util::Span_T<int64_t> dValues0 ( pValues0, iNumValues );
util::Span_T<int64_t> dValues1 ( pValues1, iNumValues );
tIt0.m_pIterator->Fetch ( dRowIDs, dValues0 );
tIt1.m_pIterator->Fetch ( dRowIDs, dValues1 );
SphAttr_t dValueRow[CSphMatchComparatorState::MAX_ATTRS];
SphAttr_t dWorstValueRow[CSphMatchComparatorState::MAX_ATTRS];
memset ( dValueRow, 0, sizeof(dValueRow) );
memset ( dWorstValueRow, 0, sizeof(dWorstValueRow) );
assert(m_pSorter);
const CSphMatch * pWorst = m_pSorter->GetWorst();
if ( pWorst && m_iPushed>=m_iSize )
{
dWorstValueRow[0] = pWorst->GetAttr ( tIt0.m_tLocator );
dWorstValueRow[1] = pWorst->GetAttr ( tIt1.m_tLocator );
int iNumMatches = 0;
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
dValueRow[0] = *(pValues0 + iMatch);
dValueRow[1] = *(pValues1 + iMatch);
if ( COMP::IsLess ( tMatch, dValueRow, *pWorst, dWorstValueRow, m_tState ) )
tMatch.m_tRowID = INVALID_ROWID;
else
{
sphSetRowAttr ( tMatch.m_pDynamic, tIt0.m_tLocator, *(pValues0 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt1.m_tLocator, *(pValues1 + iMatch) );
iNumMatches++;
}
}
m_iPushed += iNumMatches;
return;
}
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
sphSetRowAttr ( tMatch.m_pDynamic, tIt0.m_tLocator, *(pValues0 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt1.m_tLocator, *(pValues1 + iMatch) );
}
m_iPushed += dMatches.GetLength();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchValuesIterator3 ( VecTraits_T<CSphMatch> & dMatches )
{
IteratorWithLocator_t & tIt0 = m_dIterators[0];
IteratorWithLocator_t & tIt1 = m_dIterators[1];
IteratorWithLocator_t & tIt2 = m_dIterators[2];
int64_t * pValues0 = m_dValues.Begin();
int64_t * pValues1 = m_dValues.Begin() + MATCH_BUFFER_SIZE;
int64_t * pValues2 = m_dValues.Begin() + MATCH_BUFFER_SIZE*2;
int iNumValues = dMatches.GetLength();
util::Span_T<uint32_t> dRowIDs ( m_dRowIDs.Begin(), iNumValues );
util::Span_T<int64_t> dValues0 ( pValues0, iNumValues );
util::Span_T<int64_t> dValues1 ( pValues1, iNumValues );
util::Span_T<int64_t> dValues2 ( pValues2, iNumValues );
tIt0.m_pIterator->Fetch ( dRowIDs, dValues0 );
tIt1.m_pIterator->Fetch ( dRowIDs, dValues1 );
tIt2.m_pIterator->Fetch ( dRowIDs, dValues2 );
SphAttr_t dValueRow[CSphMatchComparatorState::MAX_ATTRS];
SphAttr_t dWorstValueRow[CSphMatchComparatorState::MAX_ATTRS];
memset ( dValueRow, 0, sizeof(dValueRow) );
memset ( dWorstValueRow, 0, sizeof(dWorstValueRow) );
assert(m_pSorter);
const CSphMatch * pWorst = m_pSorter->GetWorst();
if ( pWorst && m_iPushed>=m_iSize )
{
dWorstValueRow[0] = pWorst->GetAttr ( tIt0.m_tLocator );
dWorstValueRow[1] = pWorst->GetAttr ( tIt1.m_tLocator );
dWorstValueRow[2] = pWorst->GetAttr ( tIt2.m_tLocator );
int iNumMatches = 0;
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
dValueRow[0] = *(pValues0 + iMatch);
dValueRow[1] = *(pValues1 + iMatch);
dValueRow[2] = *(pValues2 + iMatch);
if ( COMP::IsLess ( tMatch, dValueRow, *pWorst, dWorstValueRow, m_tState ) )
tMatch.m_tRowID = INVALID_ROWID;
else
{
sphSetRowAttr ( tMatch.m_pDynamic, tIt0.m_tLocator, *(pValues0 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt1.m_tLocator, *(pValues1 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt2.m_tLocator, *(pValues2 + iMatch) );
iNumMatches++;
}
}
m_iPushed += iNumMatches;
return;
}
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
sphSetRowAttr ( tMatch.m_pDynamic, tIt0.m_tLocator, *(pValues0 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt1.m_tLocator, *(pValues1 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt2.m_tLocator, *(pValues2 + iMatch) );
}
m_iPushed += dMatches.GetLength();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchValuesIterator4 ( VecTraits_T<CSphMatch> & dMatches )
{
IteratorWithLocator_t & tIt0 = m_dIterators[0];
IteratorWithLocator_t & tIt1 = m_dIterators[1];
IteratorWithLocator_t & tIt2 = m_dIterators[2];
IteratorWithLocator_t & tIt3 = m_dIterators[3];
int64_t * pValues0 = m_dValues.Begin();
int64_t * pValues1 = m_dValues.Begin() + MATCH_BUFFER_SIZE;
int64_t * pValues2 = m_dValues.Begin() + MATCH_BUFFER_SIZE*2;
int64_t * pValues3 = m_dValues.Begin() + MATCH_BUFFER_SIZE*3;
int iNumValues = dMatches.GetLength();
util::Span_T<uint32_t> dRowIDs ( m_dRowIDs.Begin(), iNumValues );
util::Span_T<int64_t> dValues0 ( pValues0, iNumValues );
util::Span_T<int64_t> dValues1 ( pValues1, iNumValues );
util::Span_T<int64_t> dValues2 ( pValues2, iNumValues );
util::Span_T<int64_t> dValues3 ( pValues3, iNumValues );
tIt0.m_pIterator->Fetch ( dRowIDs, dValues0 );
tIt1.m_pIterator->Fetch ( dRowIDs, dValues1 );
tIt2.m_pIterator->Fetch ( dRowIDs, dValues2 );
tIt3.m_pIterator->Fetch ( dRowIDs, dValues3 );
SphAttr_t dValueRow[CSphMatchComparatorState::MAX_ATTRS];
SphAttr_t dWorstValueRow[CSphMatchComparatorState::MAX_ATTRS];
memset ( dValueRow, 0, sizeof(dValueRow) );
memset ( dWorstValueRow, 0, sizeof(dWorstValueRow) );
assert(m_pSorter);
const CSphMatch * pWorst = m_pSorter->GetWorst();
if ( pWorst && m_iPushed>=m_iSize )
{
dWorstValueRow[0] = pWorst->GetAttr ( tIt0.m_tLocator );
dWorstValueRow[1] = pWorst->GetAttr ( tIt1.m_tLocator );
dWorstValueRow[2] = pWorst->GetAttr ( tIt2.m_tLocator );
dWorstValueRow[3] = pWorst->GetAttr ( tIt3.m_tLocator );
int iNumMatches = 0;
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
dValueRow[0] = *(pValues0 + iMatch);
dValueRow[1] = *(pValues1 + iMatch);
dValueRow[2] = *(pValues2 + iMatch);
dValueRow[3] = *(pValues3 + iMatch);
if ( COMP::IsLess ( tMatch, dValueRow, *pWorst, dWorstValueRow, m_tState ) )
tMatch.m_tRowID = INVALID_ROWID;
else
{
sphSetRowAttr ( tMatch.m_pDynamic, tIt0.m_tLocator, *(pValues0 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt1.m_tLocator, *(pValues1 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt2.m_tLocator, *(pValues2 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt3.m_tLocator, *(pValues3 + iMatch) );
iNumMatches++;
}
}
m_iPushed += iNumMatches;
return;
}
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
sphSetRowAttr ( tMatch.m_pDynamic, tIt0.m_tLocator, *(pValues0 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt1.m_tLocator, *(pValues1 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt2.m_tLocator, *(pValues2 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt3.m_tLocator, *(pValues3 + iMatch) );
}
m_iPushed += dMatches.GetLength();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchValuesIterator5 ( VecTraits_T<CSphMatch> & dMatches )
{
IteratorWithLocator_t & tIt0 = m_dIterators[0];
IteratorWithLocator_t & tIt1 = m_dIterators[1];
IteratorWithLocator_t & tIt2 = m_dIterators[2];
IteratorWithLocator_t & tIt3 = m_dIterators[3];
IteratorWithLocator_t & tIt4 = m_dIterators[4];
int64_t * pValues0 = m_dValues.Begin();
int64_t * pValues1 = m_dValues.Begin() + MATCH_BUFFER_SIZE;
int64_t * pValues2 = m_dValues.Begin() + MATCH_BUFFER_SIZE*2;
int64_t * pValues3 = m_dValues.Begin() + MATCH_BUFFER_SIZE*3;
int64_t * pValues4 = m_dValues.Begin() + MATCH_BUFFER_SIZE*4;
int iNumValues = dMatches.GetLength();
util::Span_T<uint32_t> dRowIDs ( m_dRowIDs.Begin(), iNumValues );
util::Span_T<int64_t> dValues0 ( pValues0, iNumValues );
util::Span_T<int64_t> dValues1 ( pValues1, iNumValues );
util::Span_T<int64_t> dValues2 ( pValues2, iNumValues );
util::Span_T<int64_t> dValues3 ( pValues3, iNumValues );
util::Span_T<int64_t> dValues4 ( pValues4, iNumValues );
tIt0.m_pIterator->Fetch ( dRowIDs, dValues0 );
tIt1.m_pIterator->Fetch ( dRowIDs, dValues1 );
tIt2.m_pIterator->Fetch ( dRowIDs, dValues2 );
tIt3.m_pIterator->Fetch ( dRowIDs, dValues3 );
tIt4.m_pIterator->Fetch ( dRowIDs, dValues4 );
SphAttr_t dValueRow[CSphMatchComparatorState::MAX_ATTRS];
SphAttr_t dWorstValueRow[CSphMatchComparatorState::MAX_ATTRS];
memset ( dValueRow, 0, sizeof(dValueRow) );
memset ( dWorstValueRow, 0, sizeof(dWorstValueRow) );
assert(m_pSorter);
const CSphMatch * pWorst = m_pSorter->GetWorst();
if ( pWorst && m_iPushed>=m_iSize )
{
dWorstValueRow[0] = pWorst->GetAttr ( tIt0.m_tLocator );
dWorstValueRow[1] = pWorst->GetAttr ( tIt1.m_tLocator );
dWorstValueRow[2] = pWorst->GetAttr ( tIt2.m_tLocator );
dWorstValueRow[3] = pWorst->GetAttr ( tIt3.m_tLocator );
dWorstValueRow[4] = pWorst->GetAttr ( tIt4.m_tLocator );
int iNumMatches = 0;
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
dValueRow[0] = *(pValues0 + iMatch);
dValueRow[1] = *(pValues1 + iMatch);
dValueRow[2] = *(pValues2 + iMatch);
dValueRow[3] = *(pValues3 + iMatch);
dValueRow[4] = *(pValues4 + iMatch);
if ( COMP::IsLess ( tMatch, dValueRow, *pWorst, dWorstValueRow, m_tState ) )
tMatch.m_tRowID = INVALID_ROWID;
else
{
sphSetRowAttr ( tMatch.m_pDynamic, tIt0.m_tLocator, *(pValues0 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt1.m_tLocator, *(pValues1 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt2.m_tLocator, *(pValues2 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt3.m_tLocator, *(pValues3 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt4.m_tLocator, *(pValues4 + iMatch) );
iNumMatches++;
}
}
m_iPushed += iNumMatches;
return;
}
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
sphSetRowAttr ( tMatch.m_pDynamic, tIt0.m_tLocator, *(pValues0 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt1.m_tLocator, *(pValues1 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt2.m_tLocator, *(pValues2 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt3.m_tLocator, *(pValues3 + iMatch) );
sphSetRowAttr ( tMatch.m_pDynamic, tIt4.m_tLocator, *(pValues4 + iMatch) );
}
m_iPushed += dMatches.GetLength();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchValuesMultiIterator ( VecTraits_T<CSphMatch> & dMatches )
{
int iNumValues = dMatches.GetLength();
util::Span_T<uint32_t> dRowIDs ( m_dRowIDs.Begin(), iNumValues );
ARRAY_FOREACH ( i, m_dIterators )
{
util::Span_T<int64_t> dValues ( m_dValues.Begin() + i*MATCH_BUFFER_SIZE, iNumValues );
m_dIterators[i].m_pIterator->Fetch ( dRowIDs, dValues );
}
SphAttr_t dValueRow[CSphMatchComparatorState::MAX_ATTRS];
SphAttr_t dWorstValueRow[CSphMatchComparatorState::MAX_ATTRS];
memset ( dValueRow, 0, sizeof(dValueRow) );
memset ( dWorstValueRow, 0, sizeof(dWorstValueRow) );
assert(m_pSorter);
const CSphMatch * pWorst = m_pSorter->GetWorst();
if ( pWorst && m_iPushed>=m_iSize )
{
ARRAY_FOREACH ( i, m_dIterators )
dWorstValueRow[i] = pWorst->GetAttr ( m_dIterators[i].m_tLocator );
int iNumMatches = 0;
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
int iOffset = 0;
ARRAY_FOREACH ( i, m_dIterators )
{
dValueRow[i] = *(m_dValues.Begin() + iMatch + iOffset);
iOffset += MATCH_BUFFER_SIZE;
}
if ( COMP::IsLess ( tMatch, dValueRow, *pWorst, dWorstValueRow, m_tState ) )
tMatch.m_tRowID = INVALID_ROWID;
else
{
iOffset = 0;
ARRAY_FOREACH ( i, m_dIterators )
{
sphSetRowAttr ( tMatch.m_pDynamic, m_dIterators[i].m_tLocator, *(m_dValues.Begin() + iMatch + iOffset) );
iOffset += MATCH_BUFFER_SIZE;
}
iNumMatches++;
}
}
m_iPushed += iNumMatches;
return;
}
ARRAY_FOREACH ( iMatch, dMatches )
{
CSphMatch & tMatch = dMatches[iMatch];
int iOffset = 0;
ARRAY_FOREACH ( i, m_dIterators )
{
sphSetRowAttr ( tMatch.m_pDynamic, m_dIterators[i].m_tLocator, *(m_dValues.Begin() + iMatch + iOffset) );
iOffset += MATCH_BUFFER_SIZE;
}
}
m_iPushed += dMatches.GetLength();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchValuesIteratorGeneric ( VecTraits_T<CSphMatch> & dMatches )
{
for ( auto & i : m_dIterators )
{
int iNumValues = dMatches.GetLength();
util::Span_T<uint32_t> dRowIDs ( m_dRowIDs.Begin(), iNumValues );
util::Span_T<int64_t> dValues ( m_dValues.Begin(), iNumValues );
i.m_pIterator->Fetch ( dRowIDs, dValues );
int64_t * pValue = m_dValues.Begin();
for ( auto & tMatch : dMatches )
sphSetRowAttr ( tMatch.m_pDynamic, i.m_tLocator, *pValue++ );
}
assert(m_pSorter);
const CSphMatch * pWorst = m_pSorter->GetWorst();
if ( pWorst && m_iPushed>=m_iSize )
{
int iNumMatches = 0;
for ( auto & tMatch : dMatches )
{
if ( GENERIC::IsLess ( tMatch, *pWorst, m_tState ) )
tMatch.m_tRowID = INVALID_ROWID;
else
iNumMatches++;
}
m_iPushed += iNumMatches;
}
else
m_iPushed += dMatches.GetLength();
}
template <typename GENERIC, typename COMP, typename SINGLE>
void ColumnarProxySorter_T<GENERIC,COMP,SINGLE>::FetchColumnarValues ( VecTraits_T<CSphMatch> & dMatches )
{
if ( !m_iFastPathAttrs )
{
FetchValuesIteratorGeneric(dMatches);
return;
}
if ( m_iFastPathAttrs==1 && m_iFastPathAttrs==m_dIterators.GetLength() )
{
FetchValuesIterator1Single(dMatches);
return;
}
switch ( m_dIterators.GetLength() )
{
case 1: FetchValuesIterator1(dMatches); break;
case 2: FetchValuesIterator2(dMatches); break;
case 3: FetchValuesIterator3(dMatches); break;
case 4: FetchValuesIterator4(dMatches); break;
case 5: FetchValuesIterator5(dMatches); break;
default: FetchValuesMultiIterator(dMatches); break;
}
}
static bool CanCreateColumnarSorter ( const ISphSchema & tSchema, const CSphMatchComparatorState & tState, bool bNeedFactors, bool bComputeItems, bool bMulti )
{
// everything precomputed? no need for batched sorter
if ( !bComputeItems )
return false;
// CalcSort is the same for all sorters, so we can't remove an expression from it just for our sorter
// so no support for multi-sorter case, at least for now
if ( bMulti )
return false;
// can't expose immediate pushed/popped matches, so no luck
if ( bNeedFactors )
return false;
// check that we don't have strings/mvas in presort/prefilter
// in this case match cloning is slow, so there's no point in spawning proxy sorter
for ( int i = 0; i < tSchema.GetAttrsCount(); i++ )
{
const CSphColumnInfo & tAttr = tSchema.GetAttr(i);
if ( tAttr.m_eStage<=SPH_EVAL_PRESORT && tAttr.m_pExpr && sphIsDataPtrAttr ( tAttr.m_eAttrType ) )
return false;
if ( tAttr.IsJoined() )
return false;
}
bool bHaveColumnar = false;
bool bAllColumnar = true;
for ( int i = 0; i < CSphMatchComparatorState::MAX_ATTRS; i++ )
{
if ( tState.m_dAttrs[i]==-1 )
continue;
const CSphColumnInfo & tAttr = tSchema.GetAttr ( tState.m_dAttrs[i] );
if ( sphIsDataPtrAttr ( tAttr.m_eAttrType ) )
return false;
// all sorter-related columnar attrs should be replaced by expressions at this point
assert ( !tAttr.IsColumnar() );
if ( tAttr.IsColumnarExpr() )
bHaveColumnar = true;
else
bAllColumnar = false;
}
return bHaveColumnar && bAllColumnar;
}
/////////////////////////////////////////////////////////////////////
template <typename GENERIC>
static ISphMatchSorter * CreateProxySorter ( ISphMatchSorter * pSorter, int iMaxMatches, const ISphSchema & tSchema, const CSphMatchComparatorState & tState, int iSortFastPath, bool bAllInt, bool bAllFloat )
{
if ( iSortFastPath==0 )
return new ColumnarProxySorter_T<GENERIC,CompareError_fn,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
if ( bAllInt )
{
switch ( iSortFastPath )
{
case 1:
if ( tState.m_uAttrDesc & 1 )
return new ColumnarProxySorter_T<GENERIC,CompareInt_fn<1>,CompareSingleInt_fn<true>> ( pSorter, iMaxMatches, iSortFastPath );
else
return new ColumnarProxySorter_T<GENERIC,CompareInt_fn<1>,CompareSingleInt_fn<false>> ( pSorter, iMaxMatches, iSortFastPath );
case 2: return new ColumnarProxySorter_T<GENERIC,CompareInt_fn<2>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 3: return new ColumnarProxySorter_T<GENERIC,CompareInt_fn<3>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 4: return new ColumnarProxySorter_T<GENERIC,CompareInt_fn<4>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 5: return new ColumnarProxySorter_T<GENERIC,CompareInt_fn<5>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
default: break;
}
}
if ( bAllFloat )
{
switch ( iSortFastPath )
{
case 1:
if ( tState.m_uAttrDesc & 1 )
return new ColumnarProxySorter_T<GENERIC,CompareFloat_fn<1>,CompareSingleFloat_fn<true>> ( pSorter, iMaxMatches, iSortFastPath );
else
return new ColumnarProxySorter_T<GENERIC,CompareFloat_fn<1>,CompareSingleFloat_fn<false>> ( pSorter, iMaxMatches, iSortFastPath );
case 2: return new ColumnarProxySorter_T<GENERIC,CompareFloat_fn<2>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 3: return new ColumnarProxySorter_T<GENERIC,CompareFloat_fn<3>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 4: return new ColumnarProxySorter_T<GENERIC,CompareFloat_fn<4>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 5: return new ColumnarProxySorter_T<GENERIC,CompareFloat_fn<5>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
default: break;
}
}
switch ( iSortFastPath )
{
case 1: return new ColumnarProxySorter_T<GENERIC,Compare_fn<1>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 2: return new ColumnarProxySorter_T<GENERIC,Compare_fn<2>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 3: return new ColumnarProxySorter_T<GENERIC,Compare_fn<3>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 4: return new ColumnarProxySorter_T<GENERIC,Compare_fn<4>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
case 5: return new ColumnarProxySorter_T<GENERIC,Compare_fn<5>,CompareSingleError_fn> ( pSorter, iMaxMatches, iSortFastPath );
default: break;
}
assert ( 0 && "Internal error" );
return nullptr;
}
ISphMatchSorter * CreateColumnarProxySorter ( ISphMatchSorter * pSorter, int iMaxMatches, const ISphSchema & tSchema, const CSphMatchComparatorState & tState, ESphSortFunc eSortFunc, bool bNeedFactors, bool bComputeItems, bool bMulti )
{
if ( !CanCreateColumnarSorter ( tSchema, tState, bNeedFactors, bComputeItems, bMulti ) )
return pSorter;
for ( int i = 0; i < CSphMatchComparatorState::MAX_ATTRS; i++ )
{
if ( tState.m_dAttrs[i]==-1 )
continue;
const CSphColumnInfo & tAttr = tSchema.GetAttr ( tState.m_dAttrs[i] );
assert ( !tAttr.IsColumnar() );
// proxy sorter will be evaluating this, so no need to evaluate this separately
if ( tAttr.IsColumnarExpr() && tAttr.m_eStage==SPH_EVAL_PRESORT )
const_cast<CSphColumnInfo &>(tAttr).m_eStage = SPH_EVAL_SORTER;
}
// at this point we have columnar attributes and non-attributes
// if all sort-bys are attributes of the same type, we can use a fastpath
int iSortFastPath;
switch ( eSortFunc )
{
case FUNC_GENERIC1: iSortFastPath = 1; break;
case FUNC_GENERIC2: iSortFastPath = 2; break;
case FUNC_GENERIC3: iSortFastPath = 3; break;
case FUNC_GENERIC4: iSortFastPath = 4; break;
case FUNC_GENERIC5: iSortFastPath = 5; break;
default: iSortFastPath = 0;
}
bool bAllInt = true;
bool bAllFloat = true;
for ( int i = 0; i < iSortFastPath; i++ )
{
if ( tState.m_dAttrs[i]==-1 )
{
bAllInt = false;
bAllFloat = false;
break;
}
const CSphColumnInfo & tAttr = tSchema.GetAttr ( tState.m_dAttrs[i] );
bool bInt = tAttr.m_eAttrType==SPH_ATTR_INTEGER || tAttr.m_eAttrType==SPH_ATTR_TIMESTAMP || tAttr.m_eAttrType==SPH_ATTR_BOOL || tAttr.m_eAttrType==SPH_ATTR_BIGINT;
bool bFloat = tAttr.m_eAttrType==SPH_ATTR_FLOAT;
bAllInt &= bInt;
bAllFloat &= bFloat;
}
switch ( eSortFunc )
{
case FUNC_REL_DESC: return CreateProxySorter<MatchRelevanceLt_fn> ( pSorter, iMaxMatches, tSchema, tState, iSortFastPath, bAllInt, bAllFloat );
case FUNC_TIMESEGS: return CreateProxySorter<MatchTimeSegments_fn> ( pSorter, iMaxMatches, tSchema, tState, iSortFastPath, bAllInt, bAllFloat );
case FUNC_GENERIC1: return CreateProxySorter<MatchGeneric1_fn> ( pSorter, iMaxMatches, tSchema, tState, iSortFastPath, bAllInt, bAllFloat );
case FUNC_GENERIC2: return CreateProxySorter<MatchGeneric2_fn> ( pSorter, iMaxMatches, tSchema, tState, iSortFastPath, bAllInt, bAllFloat );
case FUNC_GENERIC3: return CreateProxySorter<MatchGeneric3_fn> ( pSorter, iMaxMatches, tSchema, tState, iSortFastPath, bAllInt, bAllFloat );
case FUNC_GENERIC4: return CreateProxySorter<MatchGeneric4_fn> ( pSorter, iMaxMatches, tSchema, tState, iSortFastPath, bAllInt, bAllFloat );
case FUNC_GENERIC5: return CreateProxySorter<MatchGeneric5_fn> ( pSorter, iMaxMatches, tSchema, tState, iSortFastPath, bAllInt, bAllFloat );
case FUNC_EXPR: return CreateProxySorter<MatchExpr_fn> ( pSorter, iMaxMatches, tSchema, tState, iSortFastPath, bAllInt, bAllFloat );
default: return pSorter;
}
return pSorter;
}
| 44,432
|
C++
|
.cpp
| 1,061
| 39.402451
| 235
| 0.714732
|
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
|
16,820
|
collation.cpp
|
manticoresoftware_manticoresearch/src/collation.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 "collation.h"
#include "attribute.h"
#include "sphinxint.h"
#include "secondary/secondary.h"
#include "secondarylib.h"
static const char * EMPTY_STR = "";
inline static void UnpackStrings ( ByteBlob_t& dStr1, ByteBlob_t& dStr2, bool bDataPtr )
{
// strings that are stored in index don't need to be unpacked
if ( bDataPtr )
{
dStr1 = sphUnpackPtrAttr ( dStr1.first );
dStr2 = sphUnpackPtrAttr ( dStr2.first );
}
if ( !dStr1.first )
dStr1 = {(const BYTE *) EMPTY_STR, 0};
if ( !dStr2.first )
dStr2 = {(const BYTE *) EMPTY_STR, 0};
}
static int CollateBinary ( ByteBlob_t dStr1, ByteBlob_t dStr2, bool bDataPtr )
{
UnpackStrings ( dStr1, dStr2, bDataPtr );
int iRes = memcmp ( (const char *) dStr1.first, (const char *)dStr2.first, Min ( dStr1.second, dStr2.second ) );
return iRes ? iRes : ( dStr1.second-dStr2.second );
}
/// libc_ci, wrapper for strcasecmp
static int CollateLibcCI ( ByteBlob_t dStr1, ByteBlob_t dStr2, bool bDataPtr )
{
UnpackStrings ( dStr1, dStr2, bDataPtr );
int iRes = strncasecmp ( (const char *) dStr1.first, (const char *) dStr2.first, Min ( dStr1.second, dStr2.second ) );
return iRes ? iRes : ( dStr1.second-dStr2.second );
}
/// libc_cs, wrapper for strcoll
static int CollateLibcCS ( ByteBlob_t dStr1, ByteBlob_t dStr2, bool bDataPtr )
{
#define COLLATE_STACK_BUFFER 1024
UnpackStrings ( dStr1, dStr2, bDataPtr );
// strcoll wants asciiz strings, so we would have to copy them over
// lets use stack buffer for smaller ones, and allocate from heap for bigger ones
int iRes = 0;
int iLen = Min ( dStr1.second, dStr2.second );
if ( iLen<COLLATE_STACK_BUFFER )
{
// small strings on stack
BYTE sBuf1[COLLATE_STACK_BUFFER];
BYTE sBuf2[COLLATE_STACK_BUFFER];
memcpy ( sBuf1, dStr1.first, iLen );
memcpy ( sBuf2, dStr2.first, iLen );
sBuf1[iLen] = sBuf2[iLen] = '\0';
iRes = strcoll ( (const char*)sBuf1, (const char*)sBuf2 );
} else
{
// big strings on heap
char * pBuf1 = new char[iLen + 1];
char * pBuf2 = new char[iLen + 1];
memcpy ( pBuf1, dStr1.first, iLen );
memcpy ( pBuf2, dStr2.first, iLen );
pBuf1[iLen] = pBuf2[iLen] = '\0';
iRes = strcoll ( (const char*)pBuf1, (const char*)pBuf2 );
SafeDeleteArray ( pBuf2 );
SafeDeleteArray ( pBuf1 );
}
return iRes ? iRes : ( dStr1.second-dStr2.second );
}
/////////////////////////////
// UTF8_GENERAL_CI COLLATION
/////////////////////////////
/// 1st level LUT
static unsigned short * g_dCollPlanes_UTF8CI[0x100];
/// 2nd level LUT, non-trivial collation data
static unsigned short g_dCollWeights_UTF8CI[0xb00] =
{
// weights for 0x0 to 0x5ff
0, 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, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 924, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
65, 65, 65, 65, 65, 65, 198, 67, 69, 69, 69, 69, 73, 73, 73, 73,
208, 78, 79, 79, 79, 79, 79, 215, 216, 85, 85, 85, 85, 89, 222, 83,
65, 65, 65, 65, 65, 65, 198, 67, 69, 69, 69, 69, 73, 73, 73, 73,
208, 78, 79, 79, 79, 79, 79, 247, 216, 85, 85, 85, 85, 89, 222, 89,
65, 65, 65, 65, 65, 65, 67, 67, 67, 67, 67, 67, 67, 67, 68, 68,
272, 272, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 71, 71, 71, 71,
71, 71, 71, 71, 72, 72, 294, 294, 73, 73, 73, 73, 73, 73, 73, 73,
73, 73, 306, 306, 74, 74, 75, 75, 312, 76, 76, 76, 76, 76, 76, 319,
319, 321, 321, 78, 78, 78, 78, 78, 78, 329, 330, 330, 79, 79, 79, 79,
79, 79, 338, 338, 82, 82, 82, 82, 82, 82, 83, 83, 83, 83, 83, 83,
83, 83, 84, 84, 84, 84, 358, 358, 85, 85, 85, 85, 85, 85, 85, 85,
85, 85, 85, 85, 87, 87, 89, 89, 89, 90, 90, 90, 90, 90, 90, 83,
384, 385, 386, 386, 388, 388, 390, 391, 391, 393, 394, 395, 395, 397, 398, 399,
400, 401, 401, 403, 404, 502, 406, 407, 408, 408, 410, 411, 412, 413, 414, 415,
79, 79, 418, 418, 420, 420, 422, 423, 423, 425, 426, 427, 428, 428, 430, 85,
85, 433, 434, 435, 435, 437, 437, 439, 440, 440, 442, 443, 444, 444, 446, 503,
448, 449, 450, 451, 452, 452, 452, 455, 455, 455, 458, 458, 458, 65, 65, 73,
73, 79, 79, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 398, 65, 65,
65, 65, 198, 198, 484, 484, 71, 71, 75, 75, 79, 79, 79, 79, 439, 439,
74, 497, 497, 497, 71, 71, 502, 503, 78, 78, 65, 65, 198, 198, 216, 216,
65, 65, 65, 65, 69, 69, 69, 69, 73, 73, 73, 73, 79, 79, 79, 79,
82, 82, 82, 82, 85, 85, 85, 85, 83, 83, 84, 84, 540, 540, 72, 72,
544, 545, 546, 546, 548, 548, 65, 65, 69, 69, 79, 79, 79, 79, 79, 79,
79, 79, 89, 89, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575,
576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591,
592, 593, 594, 385, 390, 597, 393, 394, 600, 399, 602, 400, 604, 605, 606, 607,
403, 609, 610, 404, 612, 613, 614, 615, 407, 406, 618, 619, 620, 621, 622, 412,
624, 625, 413, 627, 628, 415, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639,
422, 641, 642, 425, 644, 645, 646, 647, 430, 649, 433, 434, 652, 653, 654, 655,
656, 657, 439, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671,
672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687,
688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703,
704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719,
720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735,
736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751,
752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767,
768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783,
784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799,
800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815,
816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831,
832, 833, 834, 835, 836, 921, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847,
848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863,
864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879,
880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895,
896, 897, 898, 899, 900, 901, 913, 903, 917, 919, 921, 907, 927, 909, 933, 937,
921, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927,
928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 921, 933, 913, 917, 919, 921,
933, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927,
928, 929, 931, 931, 932, 933, 934, 935, 936, 937, 921, 933, 927, 933, 937, 975,
914, 920, 978, 978, 978, 934, 928, 983, 984, 985, 986, 986, 988, 988, 990, 990,
992, 992, 994, 994, 996, 996, 998, 998, 1000, 1000, 1002, 1002, 1004, 1004, 1006, 1006,
922, 929, 931, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023,
1045, 1045, 1026, 1043, 1028, 1029, 1030, 1030, 1032, 1033, 1034, 1035, 1050, 1048, 1059, 1039,
1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055,
1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071,
1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055,
1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071,
1045, 1045, 1026, 1043, 1028, 1029, 1030, 1030, 1032, 1033, 1034, 1035, 1050, 1048, 1059, 1039,
1120, 1120, 1122, 1122, 1124, 1124, 1126, 1126, 1128, 1128, 1130, 1130, 1132, 1132, 1134, 1134,
1136, 1136, 1138, 1138, 1140, 1140, 1140, 1140, 1144, 1144, 1146, 1146, 1148, 1148, 1150, 1150,
1152, 1152, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1164, 1166, 1166,
1168, 1168, 1170, 1170, 1172, 1172, 1174, 1174, 1176, 1176, 1178, 1178, 1180, 1180, 1182, 1182,
1184, 1184, 1186, 1186, 1188, 1188, 1190, 1190, 1192, 1192, 1194, 1194, 1196, 1196, 1198, 1198,
1200, 1200, 1202, 1202, 1204, 1204, 1206, 1206, 1208, 1208, 1210, 1210, 1212, 1212, 1214, 1214,
1216, 1046, 1046, 1219, 1219, 1221, 1222, 1223, 1223, 1225, 1226, 1227, 1227, 1229, 1230, 1231,
1040, 1040, 1040, 1040, 1236, 1236, 1045, 1045, 1240, 1240, 1240, 1240, 1046, 1046, 1047, 1047,
1248, 1248, 1048, 1048, 1048, 1048, 1054, 1054, 1256, 1256, 1256, 1256, 1069, 1069, 1059, 1059,
1059, 1059, 1059, 1059, 1063, 1063, 1270, 1271, 1067, 1067, 1274, 1275, 1276, 1277, 1278, 1279,
1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295,
1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311,
1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327,
1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343,
1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359,
1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375,
1376, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343,
1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359,
1360, 1361, 1362, 1363, 1364, 1365, 1366, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423,
1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439,
1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455,
1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471,
1472, 1473, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487,
1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503,
1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519,
1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535,
// weights for codepoints 0x1e00 to 0x1fff
65, 65, 66, 66, 66, 66, 66, 66, 67, 67, 68, 68, 68, 68, 68, 68,
68, 68, 68, 68, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 70, 70,
71, 71, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 73, 73, 73, 73,
75, 75, 75, 75, 75, 75, 76, 76, 76, 76, 76, 76, 76, 76, 77, 77,
77, 77, 77, 77, 78, 78, 78, 78, 78, 78, 78, 78, 79, 79, 79, 79,
79, 79, 79, 79, 80, 80, 80, 80, 82, 82, 82, 82, 82, 82, 82, 82,
83, 83, 83, 83, 83, 83, 83, 83, 83, 83, 84, 84, 84, 84, 84, 84,
84, 84, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 86, 86, 86, 86,
87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88, 88, 89, 89,
90, 90, 90, 90, 90, 90, 72, 84, 87, 89, 7834, 83, 7836, 7837, 7838, 7839,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 69, 69, 69, 69, 69, 69, 69, 69,
69, 69, 69, 69, 69, 69, 69, 69, 73, 73, 73, 73, 79, 79, 79, 79,
79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
79, 79, 79, 79, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
85, 85, 89, 89, 89, 89, 89, 89, 89, 89, 7930, 7931, 7932, 7933, 7934, 7935,
913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913,
917, 917, 917, 917, 917, 917, 7958, 7959, 917, 917, 917, 917, 917, 917, 7966, 7967,
919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919,
921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921, 921,
927, 927, 927, 927, 927, 927, 8006, 8007, 927, 927, 927, 927, 927, 927, 8014, 8015,
933, 933, 933, 933, 933, 933, 933, 933, 8024, 933, 8026, 933, 8028, 933, 8030, 933,
937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937,
913, 8123, 917, 8137, 919, 8139, 921, 8155, 927, 8185, 933, 8171, 937, 8187, 8062, 8063,
913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913, 913,
919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919, 919,
937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937, 937,
913, 913, 913, 913, 913, 8117, 913, 913, 913, 913, 913, 8123, 913, 8125, 921, 8127,
8128, 8129, 919, 919, 919, 8133, 919, 919, 917, 8137, 919, 8139, 919, 8141, 8142, 8143,
921, 921, 921, 8147, 8148, 8149, 921, 921, 921, 921, 921, 8155, 8156, 8157, 8158, 8159,
933, 933, 933, 8163, 929, 929, 933, 933, 933, 933, 933, 8171, 929, 8173, 8174, 8175,
8176, 8177, 937, 937, 937, 8181, 937, 937, 927, 8185, 937, 8187, 937, 8189, 8190, 8191
// space for codepoints 0x21xx, 0x24xx, 0xffxx (generated)
};
template <class HASH>
uint64_t HashStrLen ( const BYTE * pStr, int iLen )
{
if ( !pStr || !iLen )
return SPH_FNV64_SEED;
else
return HASH::Hash ( pStr, iLen );
}
/// initialize collation LUTs
void sphCollationInit()
{
const int dWeightPlane[0x0b] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x1e, 0x1f, 0x21, 0x24, 0xff };
// generate missing weights
for ( int i=0; i<0x100; i++ )
{
g_dCollWeights_UTF8CI[i+0x800] = (unsigned short)( 0x2100 + i - ( i>=0x70 && i<=0x7f )*16 ); // 2170..217f, -16
g_dCollWeights_UTF8CI[i+0x900] = (unsigned short)( 0x2400 + i - ( i>=0xd0 && i<=0xe9 )*26 ); // 24d0..24e9, -26
g_dCollWeights_UTF8CI[i+0xa00] = (unsigned short)( 0xff00 + i - ( i>=0x41 && i<=0x5a )*32 ); // ff41..ff5a, -32
}
// generate planes table
for ( auto& dCollPlanes : g_dCollPlanes_UTF8CI )
dCollPlanes = nullptr;
for ( int i=0; i<0x0b; i++ )
g_dCollPlanes_UTF8CI [ dWeightPlane[i] ] = g_dCollWeights_UTF8CI + 0x100*i;
}
/// collate a single codepoint
static inline int CollateUTF8CI ( int iCode )
{
return ( ( iCode>>16 ) || !g_dCollPlanes_UTF8CI [ iCode>>8 ] )
? iCode
: g_dCollPlanes_UTF8CI [ iCode>>8 ][ iCode&0xff ];
}
/// utf8_general_ci
static int CollateUtf8GeneralCI ( ByteBlob_t dStr1, ByteBlob_t dStr2, bool bDataPtr)
{
UnpackStrings ( dStr1, dStr2, bDataPtr );
const BYTE * pMax1 = dStr1.first + dStr1.second;
const BYTE * pMax2 = dStr2.first + dStr2.second;
while (dStr1.first<pMax1 && dStr2.first<pMax2 )
{
// FIXME! on broken data, decode might go beyond buffer bounds
int iCode1 = sphUTF8Decode ( dStr1.first );
int iCode2 = sphUTF8Decode ( dStr2.first );
if ( !iCode1 && !iCode2 )
return 0;
if ( !iCode1 || !iCode2 )
return !iCode1 ? -1 : 1;
if ( iCode1==iCode2 )
continue;
iCode1 = CollateUTF8CI ( iCode1 );
iCode2 = CollateUTF8CI ( iCode2 );
if ( iCode1!=iCode2 )
return iCode1-iCode2;
}
if ( dStr1.first>=pMax1 && dStr2.first>=pMax2 )
return 0;
return ( dStr1.first<pMax1 ) ? 1 : -1;
}
SphStringCmp_fn GetStringCmpFunc ( ESphCollation eCollation )
{
switch ( eCollation )
{
case SPH_COLLATION_LIBC_CS: return CollateLibcCS;
case SPH_COLLATION_UTF8_GENERAL_CI: return CollateUtf8GeneralCI;
case SPH_COLLATION_BINARY: return CollateBinary;
default: return CollateLibcCI;
}
}
/////////////////////////////
// hashing functions
/////////////////////////////
uint64_t LibcCSHash_fn::Hash ( const BYTE * pStr, int iLen, uint64_t uPrev )
{
const int LOCALE_SAFE_GAP = 16;
assert ( pStr && iLen );
int iCompositeLen = iLen + 1 + (int)( 3.0f * (float)iLen ) + LOCALE_SAFE_GAP;
CSphFixedVector<BYTE> dBuf { iCompositeLen };
memcpy ( dBuf.Begin(), pStr, iLen );
dBuf[iLen] = '\0';
BYTE * pDst = dBuf.Begin()+iLen+1;
int iDstAvailable = dBuf.GetLength() - iLen - LOCALE_SAFE_GAP;
auto iDstLen = (int) strxfrm ( (char *)pDst, (const char *) dBuf.Begin(), iDstAvailable );
assert ( iDstLen<iDstAvailable+LOCALE_SAFE_GAP );
uint64_t uAcc = sphFNV64 ( pDst, iDstLen, uPrev );
return uAcc;
}
uint64_t LibcCIHash_fn::Hash ( const BYTE * pStr, int iLen, uint64_t uPrev )
{
assert ( pStr && iLen );
uint64_t uAcc = uPrev;
while ( iLen-- )
{
int iChar = tolower ( *pStr++ );
uAcc = sphFNV64 ( &iChar, 4, uAcc );
}
return uAcc;
}
uint64_t Utf8CIHash_fn::Hash ( const BYTE * pStr, int iLen, uint64_t uPrev )
{
assert ( pStr && iLen );
uint64_t uAcc = uPrev;
while ( iLen-- )
{
const BYTE * pCur = pStr++;
int iCode = sphUTF8Decode ( pCur );
iCode = CollateUTF8CI ( iCode );
uAcc = sphFNV64 ( &iCode, 4, uAcc );
}
return uAcc;
}
uint64_t BinaryHash_fn::Hash ( const BYTE * pStr, int iLen, uint64_t uPrev )
{
assert ( pStr && iLen );
return sphFNV64 ( pStr, iLen, uPrev );
}
/////////////////////////////////////////////////////////////////////
StrHashCalc_fn GetStringHashCalcFunc ( ESphCollation eCollation )
{
switch ( eCollation )
{
case SPH_COLLATION_LIBC_CS: return LibcCSHash_fn::Hash;
case SPH_COLLATION_UTF8_GENERAL_CI: return Utf8CIHash_fn::Hash;
case SPH_COLLATION_BINARY: return BinaryHash_fn::Hash;
default: return LibcCIHash_fn::Hash;
}
}
volatile ESphCollation& GlobalCollation()
{
static ESphCollation eCollation = SPH_COLLATION_DEFAULT;
return eCollation;
}
ESphCollation sphCollationFromName ( const CSphString & sName, CSphString * pError )
{
assert ( pError );
// FIXME! replace with a hash lookup?
if ( sName=="libc_ci" )
return SPH_COLLATION_LIBC_CI;
else if ( sName=="libc_cs" )
return SPH_COLLATION_LIBC_CS;
else if ( sName=="utf8_general_ci" )
return SPH_COLLATION_UTF8_GENERAL_CI;
else if ( sName=="binary" )
return SPH_COLLATION_BINARY;
pError->SetSprintf ( "Unknown collation: '%s'", sName.cstr() );
return SPH_COLLATION_DEFAULT;
}
static CSphString g_sLocale;
static std::locale g_tLocale;
static bool g_bGlobalLocaleSet = false;
void SetLocale ( const CSphString & sLocale, bool bSet )
{
g_sLocale = sLocale;
g_tLocale = std::locale();
if ( g_sLocale.IsEmpty() )
return;
g_bGlobalLocaleSet = bSet;
g_tLocale = std::locale ( sLocale.cstr() );
}
const std::locale & GlobalLocale()
{
return g_tLocale;
}
bool IsGlobalLocaleSet()
{
return g_bGlobalLocaleSet;
}
| 18,736
|
C++
|
.cpp
| 381
| 47.091864
| 119
| 0.638009
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.