diff --git a/LICENSE b/LICENSE index 9ec03dc..97ab189 100644 --- a/LICENSE +++ b/LICENSE @@ -1,10 +1,8 @@ Notes Toolkit (NotesTK) is a set of tools for building applications focused on taking and organising notes. Copyright (C) 2023 James Grogan (grogan.ox@gmail.com) -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -See https://opensource.org/licenses/MIT + You should have received a copy of the GNU General Public License along with this program. If not, see . diff --git a/README.md b/README.md index bdf29ab..1574540 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,14 @@ -# NotesTK +# Stuff From Scratch -Notes Toolkit (NotesTK) is a set of tools for building applications focused on taking and organising notes, like study or research materials. +This is a hobby-repo I use for learning about different software technologies by trying to build stuff from scratch. -## Project Goals +It covers a bunch of areas: -* Cross-platform -* Low third-party dependencies -* Permissive licensing -* Simplicity over performance +* Build tooling +* Audio and Video +* 3D modelling +* Desktop window management and UIs -## Project Status +Nothing here should be used in a real project :) -🚨🚨🚨 The codebase is at a very early/prototype stage and under heavy active development🚨🚨🚨 -In addition to feature development I've been using it to get up-to-speed on various media formats and desktop and rendering APIs. It is strongly recommended to only use it as a reading reference. - -Expect: - -* No Docs or tagged releases -* Large commits and significant breaking changes -* Unreliable/untested APIs -* Naive/low-performance implementations - -The only currently recommended use case is if you are implementing some element of the library functionality and want to see how someone else has tackled it, maybe you will see something useful. - -# Building - -Many project features (e.g. Wayland integration) only build if suitable third-party dependencies are found on the system, otherwise they will be automatically disabled. You can find dependency requirements in the `README.md` file in each module's `src`directory. - -A minimal set of dependencies for each platform are included below. - -## Linux - -Install dependencies: - -```bash -sudo apt-get install build-essential pkg-config cmake -``` - -Build: - -```bash -mkdir build -cd build -cmake $PATH_TO_SOURCE -make -apps/$NAME_OF_APP -``` - -## Windows - -Tested with Visual Studio 17 with 'Desktop Development with C++' tooling, including ATL and Windows SDK 10 (10.0.19041.0). Additionally, install `cmake`. - -```bash -mkdir build -cd build -cmake $PATH_TO_SOURCE -``` - -You can open the resulting `NotesTK.sln`in Visual Studio and build. diff --git a/apps/notes_tk/NotesTk.cpp b/apps/notes_tk/NotesTk.cpp index d230835..7b2ef2e 100644 --- a/apps/notes_tk/NotesTk.cpp +++ b/apps/notes_tk/NotesTk.cpp @@ -16,7 +16,7 @@ #include "DesktopManager.h" #include "MainApplication.h" -NotesTk::NotesTk(std::unique_ptr args, std::unique_ptr mainApp) +NotesTk::NotesTk(Ptr args, Ptr mainApp) : GuiApplication(std::move(args), std::move(mainApp)) { diff --git a/apps/notes_tk/NotesTk.h b/apps/notes_tk/NotesTk.h index 29e0567..1206165 100644 --- a/apps/notes_tk/NotesTk.h +++ b/apps/notes_tk/NotesTk.h @@ -5,7 +5,7 @@ class NotesTk : public GuiApplication { public: - NotesTk(std::unique_ptr args = nullptr, std::unique_ptr mainApp = nullptr); + NotesTk(Ptr args = nullptr, Ptr mainApp = nullptr); protected: void initializeViews() override; diff --git a/apps/notes_tk/audio_editor/AudioEditorView.cpp b/apps/notes_tk/audio_editor/AudioEditorView.cpp index d234cf7..942cb40 100644 --- a/apps/notes_tk/audio_editor/AudioEditorView.cpp +++ b/apps/notes_tk/audio_editor/AudioEditorView.cpp @@ -12,7 +12,7 @@ AudioEditorView::AudioEditorView() addWidget(std::move(label)); } -std::unique_ptr AudioEditorView::Create() +Ptr AudioEditorView::Create() { return std::make_unique(); } diff --git a/apps/notes_tk/audio_editor/AudioEditorView.h b/apps/notes_tk/audio_editor/AudioEditorView.h index d5de4ad..f00d723 100644 --- a/apps/notes_tk/audio_editor/AudioEditorView.h +++ b/apps/notes_tk/audio_editor/AudioEditorView.h @@ -8,7 +8,7 @@ public: AudioEditorView(); - static std::unique_ptr Create(); + static Ptr Create(); }; -using AudioEditorViewUPtr = std::unique_ptr; +using AudioEditorViewUPtr = Ptr; diff --git a/apps/notes_tk/canvas/CanvasController.cpp b/apps/notes_tk/canvas/CanvasController.cpp index 83829d3..248415b 100644 --- a/apps/notes_tk/canvas/CanvasController.cpp +++ b/apps/notes_tk/canvas/CanvasController.cpp @@ -1,6 +1,6 @@ #include "CanvasController.h" -std::unique_ptr CanvasController::Create() +Ptr CanvasController::Create() { return std::make_unique(); } diff --git a/apps/notes_tk/canvas/CanvasController.h b/apps/notes_tk/canvas/CanvasController.h index 9d56ec5..88ece5c 100644 --- a/apps/notes_tk/canvas/CanvasController.h +++ b/apps/notes_tk/canvas/CanvasController.h @@ -1,9 +1,9 @@ #pragma once -#include +#include "Pointer.h" class CanvasController { public: - static std::unique_ptr Create(); + static Ptr Create(); }; diff --git a/apps/notes_tk/canvas/CanvasDrawingArea.h b/apps/notes_tk/canvas/CanvasDrawingArea.h index c42034e..1fa065f 100644 --- a/apps/notes_tk/canvas/CanvasDrawingArea.h +++ b/apps/notes_tk/canvas/CanvasDrawingArea.h @@ -24,6 +24,6 @@ private: CanvasDrawCommand mActiveDrawingCommand{CanvasDrawCommand::LINE}; - std::vector > mSceneNodes; + Vector > mSceneNodes; bool mContentDirty{false}; }; diff --git a/apps/notes_tk/canvas/CanvasView.cpp b/apps/notes_tk/canvas/CanvasView.cpp index 3dd447c..5ead04f 100644 --- a/apps/notes_tk/canvas/CanvasView.cpp +++ b/apps/notes_tk/canvas/CanvasView.cpp @@ -27,7 +27,7 @@ CanvasView::~CanvasView() } -std::unique_ptr CanvasView::Create() +Ptr CanvasView::Create() { return std::make_unique(); } @@ -70,7 +70,7 @@ void CanvasView::onDrawCommandChanged(CanvasDrawCommand command) mDrawingArea->setActiveDrawingCommand(command); } -std::unique_ptr CanvasView::initializeCacheButtons() +Ptr CanvasView::initializeCacheButtons() { auto saveButton = Button::Create(); saveButton->setLabel("Save"); diff --git a/apps/notes_tk/canvas/CanvasView.h b/apps/notes_tk/canvas/CanvasView.h index f845f2d..e4053b6 100644 --- a/apps/notes_tk/canvas/CanvasView.h +++ b/apps/notes_tk/canvas/CanvasView.h @@ -13,17 +13,17 @@ public: ~CanvasView(); - static std::unique_ptr Create(); + static Ptr Create(); private: void onDrawCommandChanged(CanvasDrawCommand command); void initialize(); - std::unique_ptr initializeCacheButtons(); + Ptr initializeCacheButtons(); - std::unique_ptr mController; + Ptr mController; CanvasDrawingArea* mDrawingArea{nullptr}; }; -using CanvasViewPtr = std::unique_ptr; +using CanvasViewPtr = Ptr; diff --git a/apps/notes_tk/image_editor/ImageEditorView.cpp b/apps/notes_tk/image_editor/ImageEditorView.cpp index 85c04ff..a7c5a91 100644 --- a/apps/notes_tk/image_editor/ImageEditorView.cpp +++ b/apps/notes_tk/image_editor/ImageEditorView.cpp @@ -28,7 +28,7 @@ ImageEditorView::~ImageEditorView() } -std::unique_ptr ImageEditorView::Create() +Ptr ImageEditorView::Create() { return std::make_unique(); } diff --git a/apps/notes_tk/image_editor/ImageEditorView.h b/apps/notes_tk/image_editor/ImageEditorView.h index 070aae4..3e3ffc0 100644 --- a/apps/notes_tk/image_editor/ImageEditorView.h +++ b/apps/notes_tk/image_editor/ImageEditorView.h @@ -10,7 +10,7 @@ public: virtual ~ImageEditorView(); - static std::unique_ptr Create(); + static Ptr Create(); }; -using ImageEditorViewUPtr = std::unique_ptr; +using ImageEditorViewUPtr = Ptr; diff --git a/apps/notes_tk/image_editor/ImageViewWidget.h b/apps/notes_tk/image_editor/ImageViewWidget.h index cb45b45..84cf9ba 100644 --- a/apps/notes_tk/image_editor/ImageViewWidget.h +++ b/apps/notes_tk/image_editor/ImageViewWidget.h @@ -16,5 +16,5 @@ private: unsigned mNumX{5}; unsigned mNumY{5}; - std::unique_ptr mGridNode; + Ptr mGridNode; }; diff --git a/apps/notes_tk/main-win.cpp b/apps/notes_tk/main-win.cpp index 30019cc..c14df2e 100644 --- a/apps/notes_tk/main-win.cpp +++ b/apps/notes_tk/main-win.cpp @@ -13,8 +13,8 @@ #include "windows.h" #include -#include -#include +#include "Vector.h" +#include "String.h" int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) { diff --git a/apps/notes_tk/main.cpp b/apps/notes_tk/main.cpp index f864fb8..fbd0fbb 100644 --- a/apps/notes_tk/main.cpp +++ b/apps/notes_tk/main.cpp @@ -1,4 +1,4 @@ -#include +#include "Pointer.h" #include "NotesTk.h" #include "MainApplication.h" @@ -12,7 +12,7 @@ int main(int argc, char *argv[]) // Start the gui app auto app = NotesTk(std::move(args)); - //app.setUiInterfaceBackend(UiInterfaceFactory::Backend::X11_RASTER); + app.setUiInterfaceBackend(UiInterfaceFactory::Backend::WAYLAND_RASTER); app.run(); return 0; diff --git a/apps/notes_tk/mesh_viewer/MeshViewerView.cpp b/apps/notes_tk/mesh_viewer/MeshViewerView.cpp index e5644a9..07de438 100644 --- a/apps/notes_tk/mesh_viewer/MeshViewerView.cpp +++ b/apps/notes_tk/mesh_viewer/MeshViewerView.cpp @@ -10,7 +10,7 @@ #include -std::unique_ptr MeshViewerView::Create() +Ptr MeshViewerView::Create() { return std::make_unique(); } diff --git a/apps/notes_tk/mesh_viewer/MeshViewerView.h b/apps/notes_tk/mesh_viewer/MeshViewerView.h index 5fbfce7..7c48f6a 100644 --- a/apps/notes_tk/mesh_viewer/MeshViewerView.h +++ b/apps/notes_tk/mesh_viewer/MeshViewerView.h @@ -10,10 +10,10 @@ class MeshViewerView : public Widget public: MeshViewerView(); ~MeshViewerView(); - static std::unique_ptr Create(); + static Ptr Create(); void doPaint(const PaintEvent* event) override; private: - std::unique_ptr mMesh; - std::unique_ptr mMeshNode; + Ptr mMesh; + Ptr mMeshNode; }; diff --git a/apps/notes_tk/text_editor/PlainTextDocument.cpp b/apps/notes_tk/text_editor/PlainTextDocument.cpp index 18e5782..c2628b8 100644 --- a/apps/notes_tk/text_editor/PlainTextDocument.cpp +++ b/apps/notes_tk/text_editor/PlainTextDocument.cpp @@ -6,17 +6,17 @@ PlainTextDocument::PlainTextDocument() } -std::unique_ptr PlainTextDocument::Create() +Ptr PlainTextDocument::Create() { return std::make_unique(); } -std::string PlainTextDocument::GetContent() const +String PlainTextDocument::GetContent() const { return mContent; } -void PlainTextDocument::SetContent(const std::string& content) +void PlainTextDocument::SetContent(const String& content) { mContent = content; } diff --git a/apps/notes_tk/text_editor/PlainTextDocument.h b/apps/notes_tk/text_editor/PlainTextDocument.h index ae32420..f3354a5 100644 --- a/apps/notes_tk/text_editor/PlainTextDocument.h +++ b/apps/notes_tk/text_editor/PlainTextDocument.h @@ -1,24 +1,24 @@ #pragma once -#include -#include +#include "String.h" +#include "Pointer.h" class PlainTextDocument { - std::string mContent; + String mContent; public: PlainTextDocument(); - static std::unique_ptr Create(); + static Ptr Create(); - std::string GetContent() const; + String GetContent() const; - void SetContent(const std::string& content); + void SetContent(const String& content); void Clear(); }; -using PlainTextDocumentUPtr = std::unique_ptr; +using PlainTextDocumentUPtr = Ptr; diff --git a/apps/notes_tk/text_editor/TextEditorController.cpp b/apps/notes_tk/text_editor/TextEditorController.cpp index 36adacb..c2fe661 100644 --- a/apps/notes_tk/text_editor/TextEditorController.cpp +++ b/apps/notes_tk/text_editor/TextEditorController.cpp @@ -9,17 +9,17 @@ TextEditorController::TextEditorController() } -std::unique_ptr TextEditorController::Create() +Ptr TextEditorController::Create() { return std::make_unique(); } -void TextEditorController::SetContent(const std::string& content) +void TextEditorController::SetContent(const String& content) { mModel->GetDocument()->SetContent(content); } -std::string TextEditorController::GetContent() const +String TextEditorController::GetContent() const { return mModel->GetDocument()->GetContent(); } diff --git a/apps/notes_tk/text_editor/TextEditorController.h b/apps/notes_tk/text_editor/TextEditorController.h index 37d717d..8601a7e 100644 --- a/apps/notes_tk/text_editor/TextEditorController.h +++ b/apps/notes_tk/text_editor/TextEditorController.h @@ -1,5 +1,5 @@ #pragma once -#include +#include "Pointer.h" #include #include "TextEditorModel.h" @@ -9,7 +9,7 @@ public: TextEditorController(); - static std::unique_ptr Create(); + static Ptr Create(); void OnSave(); @@ -17,9 +17,9 @@ public: void OnLoad(); - std::string GetContent() const; + String GetContent() const; - void SetContent(const std::string& content); + void SetContent(const String& content); void SetSavePath(const std::filesystem::path& path); @@ -31,4 +31,4 @@ private: std::filesystem::path mLoadPath; }; -using TextEditorControllerUPtr = std::unique_ptr; +using TextEditorControllerUPtr = Ptr; diff --git a/apps/notes_tk/text_editor/TextEditorModel.cpp b/apps/notes_tk/text_editor/TextEditorModel.cpp index 9e299ec..12cc345 100644 --- a/apps/notes_tk/text_editor/TextEditorModel.cpp +++ b/apps/notes_tk/text_editor/TextEditorModel.cpp @@ -6,7 +6,7 @@ TextEditorModel::TextEditorModel() } -std::unique_ptr TextEditorModel::Create() +Ptr TextEditorModel::Create() { return std::make_unique(); } diff --git a/apps/notes_tk/text_editor/TextEditorModel.h b/apps/notes_tk/text_editor/TextEditorModel.h index 39289e5..55e4d8e 100644 --- a/apps/notes_tk/text_editor/TextEditorModel.h +++ b/apps/notes_tk/text_editor/TextEditorModel.h @@ -1,7 +1,7 @@ #pragma once #include "PlainTextDocument.h" -#include +#include "Pointer.h" class TextEditorModel { @@ -11,9 +11,9 @@ public: TextEditorModel(); - static std::unique_ptr Create(); + static Ptr Create(); PlainTextDocument* GetDocument() const; }; -using TextEditorModelUPtr = std::unique_ptr; +using TextEditorModelUPtr = Ptr; diff --git a/apps/notes_tk/text_editor/TextEditorView.cpp b/apps/notes_tk/text_editor/TextEditorView.cpp index ab072d3..339dd52 100644 --- a/apps/notes_tk/text_editor/TextEditorView.cpp +++ b/apps/notes_tk/text_editor/TextEditorView.cpp @@ -81,7 +81,7 @@ void TextEditorView::initialize() addWidget(std::move(hSpacer)); } -std::unique_ptr TextEditorView::Create() +Ptr TextEditorView::Create() { return std::make_unique(); } diff --git a/apps/notes_tk/text_editor/TextEditorView.h b/apps/notes_tk/text_editor/TextEditorView.h index 40546da..957766f 100644 --- a/apps/notes_tk/text_editor/TextEditorView.h +++ b/apps/notes_tk/text_editor/TextEditorView.h @@ -13,7 +13,7 @@ class TextEditorView : public Widget public: TextEditorView(); - static std::unique_ptr Create(); + static Ptr Create(); TextEditorController* getController(); @@ -23,4 +23,4 @@ private: TextBox* mTextBox; TextEditorControllerUPtr mController; }; -using TextEditorViewUPtr = std::unique_ptr; +using TextEditorViewUPtr = Ptr; diff --git a/apps/notes_tk/web_client/WebClientView.cpp b/apps/notes_tk/web_client/WebClientView.cpp index 92c9b6f..099d3cb 100644 --- a/apps/notes_tk/web_client/WebClientView.cpp +++ b/apps/notes_tk/web_client/WebClientView.cpp @@ -14,7 +14,7 @@ WebClientView::WebClientView() addWidget(std::move(label)); } -std::unique_ptr WebClientView::Create() +Ptr WebClientView::Create() { return std::make_unique(); } diff --git a/apps/notes_tk/web_client/WebClientView.h b/apps/notes_tk/web_client/WebClientView.h index 32cd128..309156d 100644 --- a/apps/notes_tk/web_client/WebClientView.h +++ b/apps/notes_tk/web_client/WebClientView.h @@ -8,7 +8,7 @@ public: WebClientView(); - static std::unique_ptr Create(); + static Ptr Create(); }; -using WebClientViewUPtr = std::unique_ptr; +using WebClientViewUPtr = Ptr; diff --git a/apps/website-generator/ContentFile.cpp b/apps/website-generator/ContentFile.cpp index 2d00b80..6f2c9e2 100644 --- a/apps/website-generator/ContentFile.cpp +++ b/apps/website-generator/ContentFile.cpp @@ -23,7 +23,7 @@ Path ContentFile::getFilename() const return mFilename; } -std::string ContentFile::getOutputLocation() const +String ContentFile::getOutputLocation() const { const auto metadata_item = getMetadataItem("save_as"); return metadata_item.empty() ? PathUtils::getBaseFilename(mFilename) : metadata_item; @@ -55,7 +55,7 @@ void ContentFile::doLinkTagSubstitution(const Path& basePath) } } -std::string ContentFile::getMetadataItem(const std::string& key) const +String ContentFile::getMetadataItem(const String& key) const { const auto check = mMetadata.find(key); if (check == mMetadata.end()) diff --git a/apps/website-generator/ContentFile.h b/apps/website-generator/ContentFile.h index 993a0a8..b240bd0 100644 --- a/apps/website-generator/ContentFile.h +++ b/apps/website-generator/ContentFile.h @@ -3,17 +3,17 @@ #include "MarkdownContentParser.h" #include "File.h" -#include +#include "String.h" #include -#include +#include Map.h class MarkdownDocument; class ContentFile { public: - using FileMetadata = std::unordered_map; - using FileContentBody = std::vector; + using FileMetadata = Map; + using FileContentBody = Vector; ContentFile(const Path& filename); @@ -23,9 +23,9 @@ public: virtual void load(); - std::string getMetadataItem(const std::string& key) const; + String getMetadataItem(const String& key) const; - virtual std::string getOutputLocation() const; + virtual String getOutputLocation() const; MarkdownDocument* getContentBody() const { @@ -36,15 +36,15 @@ public: void write(const Path& path); - void setProcessedOutput(const std::string& output) + void setProcessedOutput(const String& output) { mProcessedOutput = output; } protected: Path mFilename; FileMetadata mMetadata; - std::unique_ptr mContentBody; - std::string mProcessedOutput; + Ptr mContentBody; + String mProcessedOutput; }; class ContentArticle : public ContentFile diff --git a/apps/website-generator/MarkdownContentParser.cpp b/apps/website-generator/MarkdownContentParser.cpp index 382134b..db148f4 100644 --- a/apps/website-generator/MarkdownContentParser.cpp +++ b/apps/website-generator/MarkdownContentParser.cpp @@ -7,7 +7,7 @@ #include "File.h" -std::pair> MarkdownContentParser::run(const Path& path) +std::pair> MarkdownContentParser::run(const Path& path) { FileMetadata metadata; FileMetadata output_metadata; @@ -15,7 +15,7 @@ std::pair const auto lines = File(path).readLines(); bool metadata_finished = false; - std::string content_body; + String content_body; for (const auto& line : lines) { if (!metadata_finished) @@ -54,11 +54,11 @@ std::pair return {output_metadata, std::move(document)}; } -std::optional MarkdownContentParser::checkForMetadataItem(const std::string& line) const +Optional MarkdownContentParser::checkForMetadataItem(const String& line) const { unsigned char_count = 0; - std::string prefix; - std::string suffix; + String prefix; + String suffix; bool building_prefix = true; for (const auto c : line) { diff --git a/apps/website-generator/MarkdownContentParser.h b/apps/website-generator/MarkdownContentParser.h index 5ab4f0c..b8eeae6 100644 --- a/apps/website-generator/MarkdownContentParser.h +++ b/apps/website-generator/MarkdownContentParser.h @@ -1,10 +1,10 @@ #pragma once -#include +#include "String.h" #include -#include +#include Map.h #include -#include +#include "Vector.h" using Path = std::filesystem::path; @@ -13,10 +13,10 @@ class MarkdownDocument; class MarkdownContentParser { public: - using FileMetadataItem = std::pair; - using FileMetadata = std::unordered_map; + using FileMetadataItem = std::pair; + using FileMetadata = Map; - std::pair> run(const Path& path); + std::pair> run(const Path& path); private: - std::optional checkForMetadataItem(const std::string& line) const; + Optional checkForMetadataItem(const String& line) const; }; diff --git a/apps/website-generator/SiteGeneratorConfig.cpp b/apps/website-generator/SiteGeneratorConfig.cpp index dd3375a..599441a 100644 --- a/apps/website-generator/SiteGeneratorConfig.cpp +++ b/apps/website-generator/SiteGeneratorConfig.cpp @@ -5,7 +5,7 @@ Path SiteGeneratorConfig::getThemePath() const return mThemesPath; } -std::string SiteGeneratorConfig::getActiveTheme() const +String SiteGeneratorConfig::getActiveTheme() const { return mActiveTheme; } @@ -15,7 +15,7 @@ void SiteGeneratorConfig::setThemePath(const Path& path) mThemesPath = path; } -void SiteGeneratorConfig::setActiveTheme(const std::string& theme) +void SiteGeneratorConfig::setActiveTheme(const String& theme) { mActiveTheme = theme; } diff --git a/apps/website-generator/SiteGeneratorConfig.h b/apps/website-generator/SiteGeneratorConfig.h index 0970113..68e69ff 100644 --- a/apps/website-generator/SiteGeneratorConfig.h +++ b/apps/website-generator/SiteGeneratorConfig.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "String.h" #include using Path = std::filesystem::path; @@ -10,13 +10,13 @@ class SiteGeneratorConfig public: Path getThemePath() const; - std::string getActiveTheme() const; + String getActiveTheme() const; void setThemePath(const Path& path); - void setActiveTheme(const std::string& theme); + void setActiveTheme(const String& theme); private: Path mThemesPath; - std::string mActiveTheme; + String mActiveTheme; }; diff --git a/apps/website-generator/WebsiteGenerator.cpp b/apps/website-generator/WebsiteGenerator.cpp index 0953933..c1967a4 100644 --- a/apps/website-generator/WebsiteGenerator.cpp +++ b/apps/website-generator/WebsiteGenerator.cpp @@ -30,7 +30,7 @@ WebsiteGenerator::~WebsiteGenerator() } -void WebsiteGenerator::findProject(const std::string& searchPath) +void WebsiteGenerator::findProject(const String& searchPath) { const auto config_path = std::filesystem::path(searchPath) / "config.toml"; if (std::filesystem::exists(config_path)) diff --git a/apps/website-generator/WebsiteGenerator.h b/apps/website-generator/WebsiteGenerator.h index 1ca0527..eb46075 100644 --- a/apps/website-generator/WebsiteGenerator.h +++ b/apps/website-generator/WebsiteGenerator.h @@ -1,10 +1,10 @@ #pragma once -#include +#include "String.h" #include #include -#include -#include +#include Map.h +#include "Vector.h" using Path = std::filesystem::path; @@ -22,7 +22,7 @@ public: void doSubstitutions(); - void findProject(const std::string& searchPath); + void findProject(const String& searchPath); void parseContentFiles(); @@ -47,9 +47,9 @@ private: std::filesystem::path mProjectPath; - std::unique_ptr mConfig; - std::unique_ptr mTemplateEngine; + Ptr mConfig; + Ptr mTemplateEngine; - std::vector > mPages; - std::vector > mArticles; + Vector > mPages; + Vector > mArticles; }; diff --git a/bootstrap.sh b/bootstrap.sh new file mode 100755 index 0000000..dff6eba --- /dev/null +++ b/bootstrap.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +SOURCE_DIR=$SCRIPT_DIR/src +CORE_SRC_DIR=$SOURCE_DIR/base/core + +g++ $SOURCE_DIR/main.cpp \ + $CORE_SRC_DIR/base_types/Error.cpp \ + $CORE_SRC_DIR/base_types/Index.cpp \ + $CORE_SRC_DIR/base_types/Char.cpp \ + $SOURCE_DIR/base/compiler/buildsystem/BuildEnvironment.cpp \ + $SOURCE_DIR/base/compiler/buildsystem/BuildConfig.cpp \ + $SOURCE_DIR/base/compiler/buildsystem/BuildBinary.cpp \ + $SOURCE_DIR/base/compiler/buildsystem/BuildTarget.cpp \ + $SOURCE_DIR/base/compiler/buildsystem/BuildLibrary.cpp \ + $SOURCE_DIR/base/compiler/buildsystem/BuildExecutable.cpp \ + $SOURCE_DIR/base/compiler/buildsystem/BuildSession.cpp \ + $CORE_SRC_DIR/data_structures/String.cpp \ + $CORE_SRC_DIR/filesystem/FileSystemPath.cpp \ + $CORE_SRC_DIR/filesystem/File.cpp \ + $CORE_SRC_DIR/filesystem/FileFormats.cpp \ + $CORE_SRC_DIR/filesystem/posix/FilePosixImpl.cpp \ + $CORE_SRC_DIR/filesystem/Directory.cpp \ + $CORE_SRC_DIR/logging/ConsoleLogger.cpp \ + $CORE_SRC_DIR/logging/Logger.cpp \ + $CORE_SRC_DIR/serialization/yaml/YamlDocuments.cpp \ + $CORE_SRC_DIR/serialization/yaml/YamlDocument.cpp \ + $CORE_SRC_DIR/serialization/yaml/YamlParser.cpp \ + $CORE_SRC_DIR/streams/FileStream.cpp \ + $CORE_SRC_DIR/streams/Stream.cpp \ + $CORE_SRC_DIR/system/process/Process.cpp \ + $CORE_SRC_DIR/time/Time.cpp \ + -o builder -g -fno-exceptions -fno-rtti \ + -I$CORE_SRC_DIR/base_types \ + -I$SOURCE_DIR/base/compiler/buildsystem \ + -I$CORE_SRC_DIR/data_structures \ + -I$CORE_SRC_DIR/encoding \ + -I$CORE_SRC_DIR/filesystem \ + -I$CORE_SRC_DIR/filesystem/posix \ + -I$CORE_SRC_DIR/logging \ + -I$CORE_SRC_DIR/memory \ + -I$CORE_SRC_DIR/serialization/yaml \ + -I$CORE_SRC_DIR/streams \ + -I$CORE_SRC_DIR/system/process \ + -I$CORE_SRC_DIR/time + diff --git a/plugins/circuits/src/CircuitElement.h b/plugins/circuits/src/CircuitElement.h index 03fe480..59e7b92 100644 --- a/plugins/circuits/src/CircuitElement.h +++ b/plugins/circuits/src/CircuitElement.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "String.h" +#include "Pointer.h" class CircuitElement diff --git a/plugins/circuits/src/ElectronicCircuit.h b/plugins/circuits/src/ElectronicCircuit.h index b24fe34..978986d 100644 --- a/plugins/circuits/src/ElectronicCircuit.h +++ b/plugins/circuits/src/ElectronicCircuit.h @@ -1,13 +1,13 @@ #pragma once -#include -#include +#include "Pointer.h" +#include "Vector.h" #include "CircuitElement.h" #include "LogicGate.h" #include "Terminal.h" -using LogicGatePtr = std::unique_ptr; +using LogicGatePtr = Ptr; class ElectronicCircuit { @@ -20,33 +20,33 @@ public: void addLogicGate(LogicGatePtr gate); - const std::vector& getInputTerminals() const + const Vector& getInputTerminals() const { return mInputTerminals; } - const std::vector& getOutputTerminals() const + const Vector& getOutputTerminals() const { return mOutputTerminals; } - const std::vector& getLogicGates() const + const Vector& getLogicGates() const { return mLogicGates; } - const std::vector& getWires() const + const Vector& getWires() const { return mWires; } private: - std::vector mInputTerminals; - std::vector mOutputTerminals; + Vector mInputTerminals; + Vector mOutputTerminals; - std::vector mWires; + Vector mWires; - std::vector mLogicGates; + Vector mLogicGates; - std::vector > mElements; + Vector > mElements; }; diff --git a/plugins/circuits/src/Terminal.cpp b/plugins/circuits/src/Terminal.cpp index c54a9a3..803100b 100644 --- a/plugins/circuits/src/Terminal.cpp +++ b/plugins/circuits/src/Terminal.cpp @@ -1,6 +1,6 @@ #include "Terminal.h" -Terminal::Terminal(TerminalType type, const std::string& label) +Terminal::Terminal(TerminalType type, const String& label) : mLabel(label), mType(type) diff --git a/plugins/circuits/src/Terminal.h b/plugins/circuits/src/Terminal.h index 85b67d4..9d27877 100644 --- a/plugins/circuits/src/Terminal.h +++ b/plugins/circuits/src/Terminal.h @@ -2,7 +2,7 @@ #include "CircuitElement.h" -#include +#include "String.h" class Wire; @@ -15,7 +15,7 @@ public: OUTPUT }; - Terminal(TerminalType type, const std::string& label = {}); + Terminal(TerminalType type, const String& label = {}); Wire* getConnection() const; @@ -27,8 +27,8 @@ public: void setConnection(Wire* connection); private: - std::string mLabel; + String mLabel; TerminalType mType; Wire* mConnection{ nullptr }; }; -using TerminalPtr = std::unique_ptr; +using TerminalPtr = Ptr; diff --git a/plugins/circuits/src/TruthTable.h b/plugins/circuits/src/TruthTable.h index e4d411c..954abac 100644 --- a/plugins/circuits/src/TruthTable.h +++ b/plugins/circuits/src/TruthTable.h @@ -1,14 +1,14 @@ #pragma once #include -#include +#include "Vector.h" class TruthTable { public: - using TableData = std::map, std::vector >; + using TableData = std::map, Vector >; - TruthTable(std::size_t, std::size_t) + TruthTable(size_t, size_t) //: mNumInputColumns(numInputColumns), // mNumOutputColumns(numOutputColumns) { @@ -25,8 +25,8 @@ public: static const TruthTable::TableData AND_TRUTH_TABLE; private: - //std::size_t mNumInputColumns{ 0 }; - //std::size_t mNumOutputColumns{ 0 }; + //size_t mNumInputColumns{ 0 }; + //size_t mNumOutputColumns{ 0 }; TableData mTable; }; diff --git a/plugins/circuits/src/Wire.h b/plugins/circuits/src/Wire.h index b1dc23d..907750b 100644 --- a/plugins/circuits/src/Wire.h +++ b/plugins/circuits/src/Wire.h @@ -18,7 +18,7 @@ private: CircuitElement* mInput{ nullptr }; CircuitElement* mOutput{ nullptr }; }; -using WirePtr = std::unique_ptr; +using WirePtr = Ptr; class Fanout : public CircuitElement { diff --git a/plugins/circuits/src/gates/LogicGate.cpp b/plugins/circuits/src/gates/LogicGate.cpp index fe1248b..6a05cef 100644 --- a/plugins/circuits/src/gates/LogicGate.cpp +++ b/plugins/circuits/src/gates/LogicGate.cpp @@ -1,6 +1,6 @@ #include "LogicGate.h" -NInMOutLogicGate::NInMOutLogicGate(std::size_t numIn, std::size_t numOut, std::vector inputs, std::vector outputs) +NInMOutLogicGate::NInMOutLogicGate(size_t numIn, size_t numOut, Vector inputs, Vector outputs) : LogicGate(), mNumIn(numIn), mNumOut(numOut) @@ -11,7 +11,7 @@ NInMOutLogicGate::NInMOutLogicGate(std::size_t numIn, std::size_t numOut, std::v } else { - mInputs = std::vector(numIn, nullptr); + mInputs = Vector(numIn, nullptr); } if (outputs.size() == mNumOut) @@ -20,21 +20,21 @@ NInMOutLogicGate::NInMOutLogicGate(std::size_t numIn, std::size_t numOut, std::v } else { - mOutputs = std::vector(numOut, nullptr); + mOutputs = Vector(numOut, nullptr); } } -std::size_t NInMOutLogicGate::getNumInputs() const +size_t NInMOutLogicGate::getNumInputs() const { return mNumIn; } -std::size_t NInMOutLogicGate::getNumOutputs() const +size_t NInMOutLogicGate::getNumOutputs() const { return mNumOut; } -Wire* NInMOutLogicGate::getInput(std::size_t idx) const +Wire* NInMOutLogicGate::getInput(size_t idx) const { if (idx < mNumIn) { @@ -46,7 +46,7 @@ Wire* NInMOutLogicGate::getInput(std::size_t idx) const } } -Wire* NInMOutLogicGate::getOutput(std::size_t idx) const +Wire* NInMOutLogicGate::getOutput(size_t idx) const { if (idx < mNumOut) { @@ -58,7 +58,7 @@ Wire* NInMOutLogicGate::getOutput(std::size_t idx) const } } -void NInMOutLogicGate::setAtInput(std::size_t idx, Wire* value) +void NInMOutLogicGate::setAtInput(size_t idx, Wire* value) { if (idx < mInputs.size()) { @@ -66,7 +66,7 @@ void NInMOutLogicGate::setAtInput(std::size_t idx, Wire* value) } } -void NInMOutLogicGate::setAtOutput(std::size_t idx, Wire* value) +void NInMOutLogicGate::setAtOutput(size_t idx, Wire* value) { if (idx < mOutputs.size()) { diff --git a/plugins/circuits/src/gates/LogicGate.h b/plugins/circuits/src/gates/LogicGate.h index 6a6ef9a..e36dcf6 100644 --- a/plugins/circuits/src/gates/LogicGate.h +++ b/plugins/circuits/src/gates/LogicGate.h @@ -4,8 +4,8 @@ #include "TruthTable.h" #include "Wire.h" -#include -#include +#include "Pointer.h" +#include "Vector.h" class LogicGate : public CircuitElement { @@ -20,13 +20,13 @@ public: }; virtual ~LogicGate() = default; - virtual std::size_t getNumInputs() const = 0; + virtual size_t getNumInputs() const = 0; - virtual std::size_t getNumOutputs() const = 0; + virtual size_t getNumOutputs() const = 0; - virtual Wire* getInput(std::size_t idx) const = 0; + virtual Wire* getInput(size_t idx) const = 0; - virtual Wire* getOutput(std::size_t idx) const = 0; + virtual Wire* getOutput(size_t idx) const = 0; virtual const TruthTable& getTruthTable() = 0; @@ -41,28 +41,28 @@ public: class NInMOutLogicGate : public LogicGate { public: - NInMOutLogicGate(std::size_t numIn, std::size_t numOut, std::vector inputs = {}, std::vector outputs = {}); + NInMOutLogicGate(size_t numIn, size_t numOut, Vector inputs = {}, Vector outputs = {}); virtual ~NInMOutLogicGate() = default; - std::size_t getNumInputs() const override; + size_t getNumInputs() const override; - std::size_t getNumOutputs() const override; + size_t getNumOutputs() const override; - Wire* getInput(std::size_t idx) const override; + Wire* getInput(size_t idx) const override; - Wire* getOutput(std::size_t idx) const override; + Wire* getOutput(size_t idx) const override; - void setAtInput(std::size_t idx, Wire* value); + void setAtInput(size_t idx, Wire* value); - void setAtOutput(std::size_t idx, Wire* value); + void setAtOutput(size_t idx, Wire* value); private: - std::size_t mNumIn{ 1 }; - std::size_t mNumOut{ 1 }; + size_t mNumIn{ 1 }; + size_t mNumOut{ 1 }; - std::vector mInputs; - std::vector mOutputs; + Vector mInputs; + Vector mOutputs; }; class TwoInOneOutLogicGate : public NInMOutLogicGate diff --git a/plugins/circuits/src/visuals/ElectronicCircuitNode.cpp b/plugins/circuits/src/visuals/ElectronicCircuitNode.cpp index 8a3dfad..7984a45 100644 --- a/plugins/circuits/src/visuals/ElectronicCircuitNode.cpp +++ b/plugins/circuits/src/visuals/ElectronicCircuitNode.cpp @@ -37,12 +37,12 @@ void ElectronicCircuitNode::buildWireConnections() for (auto gate : mContent->getLogicGates()) { - for (std::size_t idx = 0; idx < gate->getNumInputs(); idx++) + for (size_t idx = 0; idx < gate->getNumInputs(); idx++) { mWireInputConnections[gate->getInput(idx)] = gate; } - for (std::size_t idx = 0; idx < gate->getNumOutputs(); idx++) + for (size_t idx = 0; idx < gate->getNumOutputs(); idx++) { mWireOutputConnections[gate->getOutput(idx)] = gate; } diff --git a/plugins/circuits/src/visuals/ElectronicCircuitNode.h b/plugins/circuits/src/visuals/ElectronicCircuitNode.h index e38a4ee..0088098 100644 --- a/plugins/circuits/src/visuals/ElectronicCircuitNode.h +++ b/plugins/circuits/src/visuals/ElectronicCircuitNode.h @@ -4,7 +4,7 @@ #include "ElectronicCircuit.h" -#include +#include Map.h class WireNode; class TerminalNode; @@ -31,13 +31,13 @@ private: ElectronicCircuit* mContent{ nullptr }; bool mContentDirty{ true }; - std::vector > mInputTerminalNodes; - std::vector > mOutputTerminalNodes; - std::vector > mWireNodes; - std::vector > mLogicGateNodes; + Vector > mInputTerminalNodes; + Vector > mOutputTerminalNodes; + Vector > mWireNodes; + Vector > mLogicGateNodes; - std::unordered_map mWireInputConnections; - std::unordered_map mWireOutputConnections; + Map mWireInputConnections; + Map mWireOutputConnections; - std::unordered_map mNodesForContent; + Map mNodesForContent; }; diff --git a/plugins/circuits/src/visuals/LogicGateNode.cpp b/plugins/circuits/src/visuals/LogicGateNode.cpp index 31bc9fb..e64e18e 100644 --- a/plugins/circuits/src/visuals/LogicGateNode.cpp +++ b/plugins/circuits/src/visuals/LogicGateNode.cpp @@ -21,9 +21,9 @@ LogicGateNode::~LogicGateNode() Point2 LogicGateNode::getConnectionLocation(Wire* wire) const { bool is_input{ false }; - std::size_t connection_id{ 0 }; + size_t connection_id{ 0 }; - for (std::size_t idx = 0; idx < mContent->getNumInputs(); idx++) + for (size_t idx = 0; idx < mContent->getNumInputs(); idx++) { if (mContent->getInput(idx) == wire) { @@ -33,7 +33,7 @@ Point2 LogicGateNode::getConnectionLocation(Wire* wire) const } } - for (std::size_t idx = 0; idx < mContent->getNumOutputs(); idx++) + for (size_t idx = 0; idx < mContent->getNumOutputs(); idx++) { if (mContent->getOutput(idx) == wire) { diff --git a/plugins/circuits/src/visuals/LogicGateNode.h b/plugins/circuits/src/visuals/LogicGateNode.h index 47d10ad..fd8b6ca 100644 --- a/plugins/circuits/src/visuals/LogicGateNode.h +++ b/plugins/circuits/src/visuals/LogicGateNode.h @@ -25,6 +25,6 @@ private: LogicGate* mContent{ nullptr }; bool mContentDirty{ true }; - std::unique_ptr mPrimaryPath; - std::unique_ptr mNegationGlyph; + Ptr mPrimaryPath; + Ptr mNegationGlyph; }; diff --git a/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.cpp b/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.cpp index a4d0522..cd89ba2 100644 --- a/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.cpp +++ b/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.cpp @@ -1,11 +1,11 @@ #include "LogicGatePrimitiveShapes.h" -std::string LogicGatePrimitiveShapes::getAndGateShape() +String LogicGatePrimitiveShapes::getAndGateShape() { return "M4 8 h24 a16 16 0 0 1 0 32 h-24Z"; } -Point2 LogicGatePrimitiveShapes::getAndGateConnectionLocation(bool isInput, std::size_t idx) +Point2 LogicGatePrimitiveShapes::getAndGateConnectionLocation(bool isInput, size_t idx) { if (isInput) { @@ -24,12 +24,12 @@ Point2 LogicGatePrimitiveShapes::getAndGateConnectionLocation(bool isInput, std: } } -std::string LogicGatePrimitiveShapes::getOrGateShape() +String LogicGatePrimitiveShapes::getOrGateShape() { return "M4 8 h16 q16 2 24 16 q-12 16 -24 16 h-16 q12 -16 0 -32Z"; } -Point2 LogicGatePrimitiveShapes::getOrGateConnectionLocation(bool isInput, std::size_t idx) +Point2 LogicGatePrimitiveShapes::getOrGateConnectionLocation(bool isInput, size_t idx) { if (isInput) { diff --git a/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.h b/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.h index 2350087..01b628a 100644 --- a/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.h +++ b/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.h @@ -2,16 +2,16 @@ #include "Point.h" -#include +#include "String.h" class LogicGatePrimitiveShapes { public: - static Point2 getAndGateConnectionLocation(bool isInput, std::size_t idx); + static Point2 getAndGateConnectionLocation(bool isInput, size_t idx); - static std::string getAndGateShape(); + static String getAndGateShape(); - static Point2 getOrGateConnectionLocation(bool isInput, std::size_t idx); + static Point2 getOrGateConnectionLocation(bool isInput, size_t idx); - static std::string getOrGateShape(); + static String getOrGateShape(); }; \ No newline at end of file diff --git a/plugins/circuits/src/visuals/TerminalNode.h b/plugins/circuits/src/visuals/TerminalNode.h index 14c79d0..9fa78c5 100644 --- a/plugins/circuits/src/visuals/TerminalNode.h +++ b/plugins/circuits/src/visuals/TerminalNode.h @@ -19,7 +19,7 @@ public: private: void createOrUpdateGeometry(SceneInfo* sceneInfo); - std::unique_ptr mMarker; + Ptr mMarker; Terminal* mContent{ nullptr }; bool mContentDirty{ true }; diff --git a/plugins/circuits/src/visuals/WireNode.cpp b/plugins/circuits/src/visuals/WireNode.cpp index 8509f58..ca2ae86 100644 --- a/plugins/circuits/src/visuals/WireNode.cpp +++ b/plugins/circuits/src/visuals/WireNode.cpp @@ -48,7 +48,7 @@ void WireNode::createOrUpdateGeometry(SceneInfo*) auto loc = mOutputLocation; loc.moveBy(-mInputLocation.getX(), -mInputLocation.getY(), -mInputLocation.getZ()); - std::vector points; + Vector points; if (loc.getY() == 0.0) { diff --git a/plugins/circuits/src/visuals/WireNode.h b/plugins/circuits/src/visuals/WireNode.h index ee52d1a..0f806f0 100644 --- a/plugins/circuits/src/visuals/WireNode.h +++ b/plugins/circuits/src/visuals/WireNode.h @@ -26,5 +26,5 @@ private: Point2 mInputLocation; Point2 mOutputLocation; - std::unique_ptr mLine; + Ptr mLine; }; \ No newline at end of file diff --git a/plugins/music/src/midi/MetaMidiEvent.cpp b/plugins/music/src/midi/MetaMidiEvent.cpp index 0790cc0..b1c2a42 100644 --- a/plugins/music/src/midi/MetaMidiEvent.cpp +++ b/plugins/music/src/midi/MetaMidiEvent.cpp @@ -9,7 +9,7 @@ MetaMidiEvent::MetaMidiEvent() } -std::unique_ptr MetaMidiEvent::Create() +Ptr MetaMidiEvent::Create() { return std::make_unique(); } @@ -79,7 +79,7 @@ void MetaMidiEvent::SetValue(int value) mValue = value; } -void MetaMidiEvent::SetLabel(const std::string& label) +void MetaMidiEvent::SetLabel(const String& label) { mLabel = label; } diff --git a/plugins/music/src/midi/MetaMidiEvent.h b/plugins/music/src/midi/MetaMidiEvent.h index 4b003cd..7567462 100644 --- a/plugins/music/src/midi/MetaMidiEvent.h +++ b/plugins/music/src/midi/MetaMidiEvent.h @@ -2,8 +2,8 @@ #include "MidiEvent.h" #include "MidiElements.h" -#include -#include +#include "Pointer.h" +#include "String.h" class MetaMidiEvent : public MidiEvent { @@ -51,13 +51,13 @@ private: public: MetaMidiEvent(); - static std::unique_ptr Create(); + static Ptr Create(); void SetValue(int value); void SetType(char c); Type GetType() const; - void SetLabel(const std::string& label); + void SetLabel(const String& label); void SetTimeSignature(const MidiTimeSignature& timeSig); void SetTimeCode(const MidiSmtpeTimecode& timeCode); void SetKeySignature(const MidiKeySignature& keySig); @@ -65,11 +65,11 @@ public: private: Type mType {Type::UNSET}; char mUnKnownMarker{0}; - std::string mLabel; + String mLabel; int mValue { 0 }; MidiTimeSignature mTimeSig; MidiSmtpeTimecode mTimecode; MidiKeySignature mKeySig; }; -using MetaMidiEventPtr = std::unique_ptr; +using MetaMidiEventPtr = Ptr; diff --git a/plugins/music/src/midi/MidiChannelEvent.cpp b/plugins/music/src/midi/MidiChannelEvent.cpp index cf0826f..0e62d8f 100644 --- a/plugins/music/src/midi/MidiChannelEvent.cpp +++ b/plugins/music/src/midi/MidiChannelEvent.cpp @@ -9,7 +9,7 @@ MidiChannelEvent::MidiChannelEvent() } -std::unique_ptr MidiChannelEvent::Create() +Ptr MidiChannelEvent::Create() { return std::make_unique(); } diff --git a/plugins/music/src/midi/MidiChannelEvent.h b/plugins/music/src/midi/MidiChannelEvent.h index 75f790b..dec6075 100644 --- a/plugins/music/src/midi/MidiChannelEvent.h +++ b/plugins/music/src/midi/MidiChannelEvent.h @@ -1,7 +1,7 @@ #pragma once #include "MidiEvent.h" -#include +#include "String.h" class MidiChannelEvent : public MidiEvent { @@ -52,7 +52,7 @@ private: public: MidiChannelEvent(); - static std::unique_ptr Create(); + static Ptr Create(); void SetTypeAndChannel(char c); void SetType(Type type); @@ -69,4 +69,4 @@ private: int mValue1 {1}; }; -using MidiChannelEventPtr = std::unique_ptr; +using MidiChannelEventPtr = Ptr; diff --git a/plugins/music/src/midi/MidiDocument.cpp b/plugins/music/src/midi/MidiDocument.cpp index 775a71e..5ae7b13 100644 --- a/plugins/music/src/midi/MidiDocument.cpp +++ b/plugins/music/src/midi/MidiDocument.cpp @@ -7,7 +7,7 @@ MidiDocument::MidiDocument() } -std::unique_ptr MidiDocument::Create() +Ptr MidiDocument::Create() { return std::make_unique(); } @@ -32,9 +32,9 @@ void MidiDocument::SetTimeDivision(const MidiTimeDivision& timeDivision) mTimeDivision = timeDivision; } -std::string MidiDocument::Serialize() const +String MidiDocument::Serialize() const { - std::string output = "MidiDocument\n"; + String output = "MidiDocument\n"; output += "Format type: " + std::to_string(mFormatType) + "\n"; output += "Expected Tracks: " + std::to_string(mExpectedTracks) + "\n"; output += "Use fps: " + std::to_string(mTimeDivision.mUseFps) + "\n"; diff --git a/plugins/music/src/midi/MidiDocument.h b/plugins/music/src/midi/MidiDocument.h index 24888ba..d7c3ed2 100644 --- a/plugins/music/src/midi/MidiDocument.h +++ b/plugins/music/src/midi/MidiDocument.h @@ -1,20 +1,20 @@ #pragma once -#include -#include -#include +#include "Vector.h" +#include "Pointer.h" +#include "String.h" #include "MidiElements.h" class MidiTrack; -using MidiTrackPtr = std::unique_ptr; +using MidiTrackPtr = Ptr; class MidiDocument { public: MidiDocument(); - static std::unique_ptr Create(); + static Ptr Create(); void AddTrack(MidiTrackPtr track); @@ -22,13 +22,13 @@ public: void SetExpectedTracks(int expected); void SetTimeDivision(const MidiTimeDivision& timeDivision); - std::string Serialize() const; + String Serialize() const; private: int mFormatType = 0; int mExpectedTracks = 0; MidiTimeDivision mTimeDivision; - std::vector mTracks; + Vector mTracks; }; -using MidiDocumentPtr = std::unique_ptr; +using MidiDocumentPtr = Ptr; diff --git a/plugins/music/src/midi/MidiEvent.cpp b/plugins/music/src/midi/MidiEvent.cpp index dfc867d..cd89778 100644 --- a/plugins/music/src/midi/MidiEvent.cpp +++ b/plugins/music/src/midi/MidiEvent.cpp @@ -6,7 +6,7 @@ MidiEvent::MidiEvent() } -std::unique_ptr MidiEvent::Create() +Ptr MidiEvent::Create() { return std::make_unique(); } diff --git a/plugins/music/src/midi/MidiEvent.h b/plugins/music/src/midi/MidiEvent.h index 5130540..80f8d2f 100644 --- a/plugins/music/src/midi/MidiEvent.h +++ b/plugins/music/src/midi/MidiEvent.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Pointer.h" class MidiEvent { @@ -13,7 +13,7 @@ public: MidiEvent(); virtual ~MidiEvent() = default; - static std::unique_ptr Create(); + static Ptr Create(); void SetTimeDelta(int delta); @@ -26,4 +26,4 @@ private: int mTimeDelta{0}; }; -using MidiEventPtr = std::unique_ptr; +using MidiEventPtr = Ptr; diff --git a/plugins/music/src/midi/MidiTrack.cpp b/plugins/music/src/midi/MidiTrack.cpp index 2bd4a25..61dec89 100644 --- a/plugins/music/src/midi/MidiTrack.cpp +++ b/plugins/music/src/midi/MidiTrack.cpp @@ -17,19 +17,19 @@ void MidiTrack::AddEvent(MidiEventPtr event) mEvents.push_back(std::move(event)); } -MidiEvent* MidiTrack::GetEvent(std::size_t idx) const +MidiEvent* MidiTrack::GetEvent(size_t idx) const { return mEvents[idx].get(); } -std::size_t MidiTrack::GetNumEvents() +size_t MidiTrack::GetNumEvents() { return mEvents.size(); } -std::string MidiTrack::Serialize() const +String MidiTrack::Serialize() const { - std::string output = "MidiTrack\n"; + String output = "MidiTrack\n"; output += "Num Events: " + std::to_string(mEvents.size()) + "\n"; return output; } diff --git a/plugins/music/src/midi/MidiTrack.h b/plugins/music/src/midi/MidiTrack.h index 888313c..ba58b56 100644 --- a/plugins/music/src/midi/MidiTrack.h +++ b/plugins/music/src/midi/MidiTrack.h @@ -1,12 +1,12 @@ #pragma once -#include -#include -#include +#include "Vector.h" +#include "Pointer.h" +#include "String.h" #include "MidiEvent.h" class MidiEvent; -using MidiEventPtr = std::unique_ptr; +using MidiEventPtr = Ptr; class MidiTrack { @@ -18,13 +18,13 @@ public: void AddEvent(MidiEventPtr event); - MidiEvent* GetEvent(std::size_t idx) const; + MidiEvent* GetEvent(size_t idx) const; - std::size_t GetNumEvents(); + size_t GetNumEvents(); - std::string Serialize() const; + String Serialize() const; private: - std::vector mEvents; + Vector mEvents; }; diff --git a/plugins/music/src/midi/reader/MidiChannelEventAdapter.cpp b/plugins/music/src/midi/reader/MidiChannelEventAdapter.cpp index f02217f..cd9c640 100644 --- a/plugins/music/src/midi/reader/MidiChannelEventAdapter.cpp +++ b/plugins/music/src/midi/reader/MidiChannelEventAdapter.cpp @@ -1,7 +1,7 @@ #include "MidiChannelEventAdapter.h" #include "BinaryStream.h" -#include "ByteUtils.h" +#include "Bits.h" #include #include @@ -19,7 +19,7 @@ int MidiChannelEventAdapter::readEvent(std::ifstream* file, char firstByte, Midi unsigned byteCount = 0; //std::cout << "Channel: " << midi_channel << std::endl; - const bool isStatusByte = ByteUtils::MostSignificantBitIsOne(firstByte); + const bool isStatusByte = Bits::MostSignificantBitIsOne(firstByte); if(isStatusByte) { event->SetTypeAndChannel(firstByte); diff --git a/plugins/music/src/midi/reader/MidiMetaEventAdapter.cpp b/plugins/music/src/midi/reader/MidiMetaEventAdapter.cpp index 5e475a6..7fdbe90 100644 --- a/plugins/music/src/midi/reader/MidiMetaEventAdapter.cpp +++ b/plugins/music/src/midi/reader/MidiMetaEventAdapter.cpp @@ -1,7 +1,7 @@ #include "MidiMetaEventAdapter.h" #include "BinaryStream.h" -#include "ByteUtils.h" +#include "Bits.h" #include #include @@ -83,7 +83,7 @@ int MidiMetaEventAdapter::ReadStringEvent(std::ifstream* file, MetaMidiEvent* ev int length = *BinaryStream::getNextByteAsInt(file); byteCount++; - std::string name; + String name; BinaryStream::getNextString(file, name, length); byteCount += length; event->SetLabel(name); @@ -104,11 +104,11 @@ int MidiMetaEventAdapter::ReadIntEvent(std::ifstream* file, MetaMidiEvent* event byteCount ++; } - std::string buffer; + String buffer; BinaryStream::getNextNBytes(file, buffer.data(), length); byteCount += length; - const int value = ByteUtils::ToType(buffer.data(), length); + const int value = Bits::ToType(buffer.data(), length); event->SetValue(value); return byteCount; } @@ -119,11 +119,11 @@ int MidiMetaEventAdapter::ReadChannelPrefixEvent(std::ifstream* file, MetaMidiEv int length = *BinaryStream::getNextByteAsInt(file); byteCount ++; - std::string buffer; + String buffer; BinaryStream::getNextNBytes(file, buffer.data(), length); byteCount += length; - const int value = ByteUtils::ToType(buffer.data(), length); + const int value = Bits::ToType(buffer.data(), length); event->SetValue(value); lastMidiChannel = value; return byteCount; diff --git a/plugins/music/src/midi/reader/MidiReader.cpp b/plugins/music/src/midi/reader/MidiReader.cpp index f31a614..9cb83f6 100644 --- a/plugins/music/src/midi/reader/MidiReader.cpp +++ b/plugins/music/src/midi/reader/MidiReader.cpp @@ -1,7 +1,7 @@ #include "MidiReader.h" #include "MidiDocument.h" -#include "ByteUtils.h" +#include "Bits.h" #include "MidiTrack.h" #include "BinaryStream.h" #include "FileLogger.h" diff --git a/plugins/music/src/midi/reader/MidiReader.h b/plugins/music/src/midi/reader/MidiReader.h index ea7219f..a32417a 100644 --- a/plugins/music/src/midi/reader/MidiReader.h +++ b/plugins/music/src/midi/reader/MidiReader.h @@ -7,7 +7,7 @@ #include "File.h" #include -#include +#include "String.h" using Path = std::filesystem::path; @@ -29,7 +29,7 @@ private: int processEvent(MidiTrack* track); private: - std::unique_ptr mFile; + Ptr mFile; MidiDocumentPtr mDocument; int mLastMidiChannel {0}; MidiChannelEvent::Type mLastChannelEventType; diff --git a/plugins/music/src/midi/reader/MidiTimeAdapter.cpp b/plugins/music/src/midi/reader/MidiTimeAdapter.cpp index 106ebae..f36a1b0 100644 --- a/plugins/music/src/midi/reader/MidiTimeAdapter.cpp +++ b/plugins/music/src/midi/reader/MidiTimeAdapter.cpp @@ -1,7 +1,7 @@ #include "MidiTimeAdapter.h" #include "BinaryStream.h" -#include "ByteUtils.h" +#include "Bits.h" #include #include @@ -13,7 +13,7 @@ int MidiTimeAdapter::ReadEventTimeDelta(std::ifstream* file, int& delta) file->get(c); byteCount++; - if(!ByteUtils::MostSignificantBitIsOne(c)) + if(!Bits::MostSignificantBitIsOne(c)) { delta = int(c); //std::cout << "Time delta final: " << delta << std::endl; @@ -54,13 +54,13 @@ int MidiTimeAdapter::ReadTimeDivision(std::ifstream* file, MidiTimeDivision& div return -1; } - division.mUseFps = ByteUtils::GetWordFirstBit(*time_division); + division.mUseFps = Bits::GetWordFirstBit(*time_division); if (division.mUseFps) { const int TOP_7_BITS = 0x7F00; // 0111 1111 - 0000 0000 division.mFps = ((~(*time_division) & TOP_7_BITS) >> 8) - 1; // Reverse 2complement of next 7 bits } - division.mTicks = ByteUtils::GetWordLastByte(*time_division); + division.mTicks = Bits::GetWordLastByte(*time_division); return 2; // Bytes advanced } diff --git a/plugins/quantum_computing/src/QuantumCircuit.cpp b/plugins/quantum_computing/src/QuantumCircuit.cpp index 2ee58f1..c39f1d9 100644 --- a/plugins/quantum_computing/src/QuantumCircuit.cpp +++ b/plugins/quantum_computing/src/QuantumCircuit.cpp @@ -28,22 +28,22 @@ void QuantumCircuit::addLogicGate(QuantumGatePtr gate) mElements.push_back(std::move(gate)); } -const std::vector& QuantumCircuit::getInputTerminals() const +const Vector& QuantumCircuit::getInputTerminals() const { return mInputTerminals; } -const std::vector& QuantumCircuit::getOutputTerminals() const +const Vector& QuantumCircuit::getOutputTerminals() const { return mOutputTerminals; } -const std::vector& QuantumCircuit::getLogicGates() const +const Vector& QuantumCircuit::getLogicGates() const { return mGates; } -const std::vector& QuantumCircuit::getQuantumWires() const +const Vector& QuantumCircuit::getQuantumWires() const { return mWires; } @@ -94,7 +94,7 @@ void QuantumCircuit::buildWireConnections() { if (wire->getOutput() == gate) { - for (std::size_t idx = 0; idx < gate->getNumInputs(); idx++) + for (size_t idx = 0; idx < gate->getNumInputs(); idx++) { if (gate->getInput(idx) == nullptr) { @@ -107,7 +107,7 @@ void QuantumCircuit::buildWireConnections() if (wire->getInput() == gate) { - for (std::size_t idx = 0; idx < gate->getNumOutputs(); idx++) + for (size_t idx = 0; idx < gate->getNumOutputs(); idx++) { if (gate->getOutput(idx) == nullptr) { diff --git a/plugins/quantum_computing/src/QuantumCircuit.h b/plugins/quantum_computing/src/QuantumCircuit.h index 220931d..92e013e 100644 --- a/plugins/quantum_computing/src/QuantumCircuit.h +++ b/plugins/quantum_computing/src/QuantumCircuit.h @@ -6,7 +6,7 @@ #include "QuantumWire.h" #include "QuantumState.h" -#include +#include "Vector.h" class QuantumCircuit { @@ -21,24 +21,24 @@ public: void buildWireConnections(); - const std::vector& getInputTerminals() const; + const Vector& getInputTerminals() const; - const std::vector& getOutputTerminals() const; + const Vector& getOutputTerminals() const; - const std::vector& getLogicGates() const; + const Vector& getLogicGates() const; - const std::vector& getQuantumWires() const; + const Vector& getQuantumWires() const; QuantumState getInputState() const; private: bool connectivityIsValid() const; - std::vector mInputTerminals; - std::vector mOutputTerminals; + Vector mInputTerminals; + Vector mOutputTerminals; - std::vector mWires; - std::vector mGates; + Vector mWires; + Vector mGates; - std::vector > mElements; + Vector > mElements; }; \ No newline at end of file diff --git a/plugins/quantum_computing/src/QuantumCircuitReader.cpp b/plugins/quantum_computing/src/QuantumCircuitReader.cpp index ae30274..cc5c6cd 100644 --- a/plugins/quantum_computing/src/QuantumCircuitReader.cpp +++ b/plugins/quantum_computing/src/QuantumCircuitReader.cpp @@ -10,18 +10,18 @@ #include "StringUtils.h" #include "FileLogger.h" -std::unique_ptr QuantumCircuitReader::read(const Path& path) +Ptr QuantumCircuitReader::read(const Path& path) { File file(path); return read(file.readText()); } -std::unique_ptr QuantumCircuitReader::read(const std::string& content) +Ptr QuantumCircuitReader::read(const String& content) { auto circuit = std::make_unique(); mWorkingCircuit = circuit.get(); - std::size_t cursor = 0; + size_t cursor = 0; for (const auto& line : StringUtils::toLines(content)) { onLine(line, cursor); @@ -31,15 +31,15 @@ std::unique_ptr QuantumCircuitReader::read(const std::string& co return circuit; } -void QuantumCircuitReader::onLine(const std::string& line, std::size_t jdx) +void QuantumCircuitReader::onLine(const String& line, size_t jdx) { mWorkingString.clear(); - std::size_t cursor = 0; + size_t cursor = 0; while (cursor < line.size()) { const auto c = line[cursor]; - MLOG_INFO("Working char: " << std::string(1, c)); + MLOG_INFO("Working char: " << String(1, c)); if (c == '|') { @@ -103,7 +103,7 @@ void QuantumCircuitReader::onLineEnd() mWorkingElement = nullptr; } -void QuantumCircuitReader::onGate(Location, const std::string value) +void QuantumCircuitReader::onGate(Location, const String value) { MLOG_INFO("Got gate: " << value); @@ -128,9 +128,9 @@ void QuantumCircuitReader::onGate(Location, const std::string value) } } -std::string QuantumCircuitReader::checkForGate(const std::string& segment) +String QuantumCircuitReader::checkForGate(const String& segment) { - std::string working_string; + String working_string; for (const auto c : segment) { if (c == '-') @@ -142,7 +142,7 @@ std::string QuantumCircuitReader::checkForGate(const std::string& segment) return working_string; } -void QuantumCircuitReader::onKet(Location, const std::string value) +void QuantumCircuitReader::onKet(Location, const String value) { MLOG_INFO("Got input state: " << value); Qubit qubit; @@ -157,9 +157,9 @@ void QuantumCircuitReader::onKet(Location, const std::string value) mWorkingCircuit->addInputTerminal(std::move(input_terminal)); } -std::size_t QuantumCircuitReader::getWireEnd(const std::string& segment) +size_t QuantumCircuitReader::getWireEnd(const String& segment) { - std::size_t idx = 0; + size_t idx = 0; for (const auto c : segment) { if (c != '-') @@ -171,9 +171,9 @@ std::size_t QuantumCircuitReader::getWireEnd(const std::string& segment) return idx; } -std::string QuantumCircuitReader::checkForKet(const std::string& segment) +String QuantumCircuitReader::checkForKet(const String& segment) { - std::string working_string; + String working_string; bool found{ false }; for (const auto c : segment) diff --git a/plugins/quantum_computing/src/QuantumCircuitReader.h b/plugins/quantum_computing/src/QuantumCircuitReader.h index 11148a2..576204c 100644 --- a/plugins/quantum_computing/src/QuantumCircuitReader.h +++ b/plugins/quantum_computing/src/QuantumCircuitReader.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include "String.h" using Path = std::filesystem::path; @@ -11,30 +11,30 @@ class QuantumCircuitElement; class QuantumCircuitReader { public: - std::unique_ptr read(const Path& path); + Ptr read(const Path& path); - std::unique_ptr read(const std::string& content); + Ptr read(const String& content); private: - using Location = std::pair; + using Location = std::pair; - void onLine(const std::string& line, std::size_t jdx); + void onLine(const String& line, size_t jdx); - std::string checkForKet(const std::string& segment); + String checkForKet(const String& segment); - std::string checkForGate(const std::string& segment); + String checkForGate(const String& segment); - std::size_t getWireEnd(const std::string& segment); + size_t getWireEnd(const String& segment); - void onGate(Location loc, const std::string value); + void onGate(Location loc, const String value); - void onKet(Location loc, const std::string value); + void onKet(Location loc, const String value); void onLineEnd(); void onVertialQuantumWire(Location loc); - std::string mWorkingString; + String mWorkingString; QuantumCircuitElement* mWorkingElement{ nullptr }; QuantumCircuit* mWorkingCircuit{ nullptr }; }; \ No newline at end of file diff --git a/plugins/quantum_computing/src/QuantumState.cpp b/plugins/quantum_computing/src/QuantumState.cpp index aaafbc7..028df64 100644 --- a/plugins/quantum_computing/src/QuantumState.cpp +++ b/plugins/quantum_computing/src/QuantumState.cpp @@ -1,13 +1,13 @@ #include "QuantumState.h" -const std::vector& QuantumState::getData() const +const Vector& QuantumState::getData() const { return mState; } -std::string QuantumState::toString() const +String QuantumState::toString() const { - std::string out; + String out; for (const auto& qubit : mState) { out += "|" + qubit.toString() + "\n"; diff --git a/plugins/quantum_computing/src/QuantumState.h b/plugins/quantum_computing/src/QuantumState.h index a50c5ed..6becdad 100644 --- a/plugins/quantum_computing/src/QuantumState.h +++ b/plugins/quantum_computing/src/QuantumState.h @@ -2,8 +2,8 @@ #include "Qubit.h" -#include -#include +#include "Vector.h" +#include "String.h" class QuantumState { @@ -13,10 +13,10 @@ public: mState.push_back(data); } - const std::vector& getData() const; + const Vector& getData() const; - std::string toString() const; + String toString() const; private: - std::vector mState; + Vector mState; }; diff --git a/plugins/quantum_computing/src/Qubit.cpp b/plugins/quantum_computing/src/Qubit.cpp index 8ba0a6c..1e58b6f 100644 --- a/plugins/quantum_computing/src/Qubit.cpp +++ b/plugins/quantum_computing/src/Qubit.cpp @@ -29,9 +29,9 @@ bool Qubit::isIn1State() const return mBeta.getReal() == 1.0 && mAlpha.getMagnitude() == 0.0; } -std::string Qubit::toString(std::size_t precision) const +String Qubit::toString(size_t precision) const { - std::stringstream sstr; + Stringstream sstr; sstr.precision(precision); sstr << "alpha " << mAlpha.getReal() << " " << mAlpha.getImaginary() << "i , beta " << mBeta.getReal() << " " << mBeta.getImaginary() << "i"; return sstr.str(); diff --git a/plugins/quantum_computing/src/Qubit.h b/plugins/quantum_computing/src/Qubit.h index 51197d4..bf74e25 100644 --- a/plugins/quantum_computing/src/Qubit.h +++ b/plugins/quantum_computing/src/Qubit.h @@ -2,7 +2,7 @@ #include "ComplexNumber.h" -#include +#include "String.h" class Qubit { @@ -17,7 +17,7 @@ public: bool isIn1State() const; - std::string toString(std::size_t precision=3) const; + String toString(size_t precision=3) const; private: ComplexNumber mAlpha; ComplexNumber mBeta; diff --git a/plugins/quantum_computing/src/circuit_elements/QuantumCircuitElement.h b/plugins/quantum_computing/src/circuit_elements/QuantumCircuitElement.h index bcbefac..e0b55cf 100644 --- a/plugins/quantum_computing/src/circuit_elements/QuantumCircuitElement.h +++ b/plugins/quantum_computing/src/circuit_elements/QuantumCircuitElement.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Pointer.h" class QuantumCircuitElement { diff --git a/plugins/quantum_computing/src/circuit_elements/QuantumGate.cpp b/plugins/quantum_computing/src/circuit_elements/QuantumGate.cpp index 8ac8dbc..156f0b7 100644 --- a/plugins/quantum_computing/src/circuit_elements/QuantumGate.cpp +++ b/plugins/quantum_computing/src/circuit_elements/QuantumGate.cpp @@ -1,6 +1,6 @@ #include "QuantumGate.h" -NInMOutQuantumGate::NInMOutQuantumGate(std::size_t numIn, std::size_t numOut, std::vector inputs, std::vector outputs) +NInMOutQuantumGate::NInMOutQuantumGate(size_t numIn, size_t numOut, Vector inputs, Vector outputs) : QuantumGate(), mNumIn(numIn), mNumOut(numOut) @@ -11,7 +11,7 @@ NInMOutQuantumGate::NInMOutQuantumGate(std::size_t numIn, std::size_t numOut, st } else { - mInputs = std::vector(numIn, nullptr); + mInputs = Vector(numIn, nullptr); } if (outputs.size() == mNumOut) @@ -20,21 +20,21 @@ NInMOutQuantumGate::NInMOutQuantumGate(std::size_t numIn, std::size_t numOut, st } else { - mOutputs = std::vector(numOut, nullptr); + mOutputs = Vector(numOut, nullptr); } } -std::size_t NInMOutQuantumGate::getNumInputs() const +size_t NInMOutQuantumGate::getNumInputs() const { return mNumIn; } -std::size_t NInMOutQuantumGate::getNumOutputs() const +size_t NInMOutQuantumGate::getNumOutputs() const { return mNumOut; } -AbstractQuantumWire* NInMOutQuantumGate::getInput(std::size_t idx) const +AbstractQuantumWire* NInMOutQuantumGate::getInput(size_t idx) const { if (idx < mNumIn) { @@ -46,7 +46,7 @@ AbstractQuantumWire* NInMOutQuantumGate::getInput(std::size_t idx) const } } -AbstractQuantumWire* NInMOutQuantumGate::getOutput(std::size_t idx) const +AbstractQuantumWire* NInMOutQuantumGate::getOutput(size_t idx) const { if (idx < mNumOut) { @@ -58,7 +58,7 @@ AbstractQuantumWire* NInMOutQuantumGate::getOutput(std::size_t idx) const } } -void NInMOutQuantumGate::setAtInput(std::size_t idx, AbstractQuantumWire* value) +void NInMOutQuantumGate::setAtInput(size_t idx, AbstractQuantumWire* value) { if (idx < mInputs.size()) { @@ -66,7 +66,7 @@ void NInMOutQuantumGate::setAtInput(std::size_t idx, AbstractQuantumWire* value) } } -void NInMOutQuantumGate::setAtOutput(std::size_t idx, AbstractQuantumWire* value) +void NInMOutQuantumGate::setAtOutput(size_t idx, AbstractQuantumWire* value) { if (idx < mOutputs.size()) { diff --git a/plugins/quantum_computing/src/circuit_elements/QuantumGate.h b/plugins/quantum_computing/src/circuit_elements/QuantumGate.h index 704db82..2e73e32 100644 --- a/plugins/quantum_computing/src/circuit_elements/QuantumGate.h +++ b/plugins/quantum_computing/src/circuit_elements/QuantumGate.h @@ -4,7 +4,7 @@ #include "QuantumWire.h" -#include +#include "Vector.h" class QuantumGate : public QuantumCircuitElement { @@ -20,17 +20,17 @@ public: }; virtual ~QuantumGate() = default; - virtual std::size_t getNumInputs() const = 0; + virtual size_t getNumInputs() const = 0; - virtual std::size_t getNumOutputs() const = 0; + virtual size_t getNumOutputs() const = 0; - virtual AbstractQuantumWire* getInput(std::size_t idx) const = 0; + virtual AbstractQuantumWire* getInput(size_t idx) const = 0; - virtual AbstractQuantumWire* getOutput(std::size_t idx) const = 0; + virtual AbstractQuantumWire* getOutput(size_t idx) const = 0; - virtual void setAtInput(std::size_t idx, AbstractQuantumWire* value) = 0; + virtual void setAtInput(size_t idx, AbstractQuantumWire* value) = 0; - virtual void setAtOutput(std::size_t idx, AbstractQuantumWire* value) = 0; + virtual void setAtOutput(size_t idx, AbstractQuantumWire* value) = 0; virtual GateType getGateType() const = 0; @@ -39,27 +39,27 @@ public: return Type::GATE; } }; -using QuantumGatePtr = std::unique_ptr; +using QuantumGatePtr = Ptr; class NInMOutQuantumGate : public QuantumGate { public: - NInMOutQuantumGate(std::size_t numIn, std::size_t numOut, std::vector inputs = {}, std::vector outputs = {}); + NInMOutQuantumGate(size_t numIn, size_t numOut, Vector inputs = {}, Vector outputs = {}); virtual ~NInMOutQuantumGate() = default; - std::size_t getNumInputs() const override; + size_t getNumInputs() const override; - std::size_t getNumOutputs() const override; + size_t getNumOutputs() const override; - AbstractQuantumWire* getInput(std::size_t idx) const override; + AbstractQuantumWire* getInput(size_t idx) const override; - AbstractQuantumWire* getOutput(std::size_t idx) const override; + AbstractQuantumWire* getOutput(size_t idx) const override; - void setAtInput(std::size_t idx, AbstractQuantumWire* value) override; + void setAtInput(size_t idx, AbstractQuantumWire* value) override; - void setAtOutput(std::size_t idx, AbstractQuantumWire* value) override; + void setAtOutput(size_t idx, AbstractQuantumWire* value) override; bool isFullyConnected() const override { @@ -82,11 +82,11 @@ public: } private: - std::size_t mNumIn{ 1 }; - std::size_t mNumOut{ 1 }; + size_t mNumIn{ 1 }; + size_t mNumOut{ 1 }; - std::vector mInputs; - std::vector mOutputs; + Vector mInputs; + Vector mOutputs; }; class TwoInOneOutQuantumGate : public NInMOutQuantumGate diff --git a/plugins/quantum_computing/src/circuit_elements/QuantumTerminal.cpp b/plugins/quantum_computing/src/circuit_elements/QuantumTerminal.cpp index 0cf2f02..acfa240 100644 --- a/plugins/quantum_computing/src/circuit_elements/QuantumTerminal.cpp +++ b/plugins/quantum_computing/src/circuit_elements/QuantumTerminal.cpp @@ -1,6 +1,6 @@ #include "QuantumTerminal.h" -QuantumTerminal::QuantumTerminal(TerminalType type, const std::string& label) +QuantumTerminal::QuantumTerminal(TerminalType type, const String& label) : mLabel(label), mType(type) { diff --git a/plugins/quantum_computing/src/circuit_elements/QuantumTerminal.h b/plugins/quantum_computing/src/circuit_elements/QuantumTerminal.h index 0f320b4..1111926 100644 --- a/plugins/quantum_computing/src/circuit_elements/QuantumTerminal.h +++ b/plugins/quantum_computing/src/circuit_elements/QuantumTerminal.h @@ -3,8 +3,8 @@ #include "QuantumCircuitElement.h" #include "Qubit.h" -#include -#include +#include "String.h" +#include "Pointer.h" class QuantumWire; @@ -17,7 +17,7 @@ public: OUTPUT }; - QuantumTerminal(TerminalType type, const std::string& label = {}); + QuantumTerminal(TerminalType type, const String& label = {}); QuantumWire* getConnection() const; @@ -40,9 +40,9 @@ public: void setValue(const Qubit& value); private: - std::string mLabel; + String mLabel; TerminalType mType; Qubit mValue; QuantumWire* mConnection{ nullptr }; }; -using QuantumTerminalPtr = std::unique_ptr; +using QuantumTerminalPtr = Ptr; diff --git a/plugins/quantum_computing/src/circuit_elements/QuantumWire.h b/plugins/quantum_computing/src/circuit_elements/QuantumWire.h index 91473d7..43a95d0 100644 --- a/plugins/quantum_computing/src/circuit_elements/QuantumWire.h +++ b/plugins/quantum_computing/src/circuit_elements/QuantumWire.h @@ -38,7 +38,7 @@ public: Type getType() const override; WireType getWireType() const override; }; -using QuantumWirePtr = std::unique_ptr; +using QuantumWirePtr = Ptr; class ClassicalWire : public AbstractQuantumWire { diff --git a/plugins/quantum_computing/src/visuals/BlochSphereNode.cpp b/plugins/quantum_computing/src/visuals/BlochSphereNode.cpp index 31059b8..112c84c 100644 --- a/plugins/quantum_computing/src/visuals/BlochSphereNode.cpp +++ b/plugins/quantum_computing/src/visuals/BlochSphereNode.cpp @@ -41,7 +41,7 @@ void BlochSphereNode::update(SceneInfo*) mOuterCircle = std::make_unique(loc, mSize/2.0); const auto end_point_x = Point2(loc.getX() + 1.2 * mSize / 2.0, loc.getY()); - const std::vector points{end_point_x }; + const Vector points{end_point_x }; mXAxis = std::make_unique(loc, points); mCentreCircle = std::make_unique(loc, mSize / 50.0); diff --git a/plugins/quantum_computing/src/visuals/BlochSphereNode.h b/plugins/quantum_computing/src/visuals/BlochSphereNode.h index 6109610..00f0aa9 100644 --- a/plugins/quantum_computing/src/visuals/BlochSphereNode.h +++ b/plugins/quantum_computing/src/visuals/BlochSphereNode.h @@ -2,7 +2,7 @@ #include "AbstractVisualNode.h" -#include +#include "Pointer.h" class BlochSphere; class CircleNode; @@ -23,12 +23,12 @@ private: bool mContentDirty{ true }; BlochSphere* mContent{ nullptr }; - std::unique_ptr mOuterCircle; - std::unique_ptr mInnerCircle; - std::unique_ptr mCentreCircle; - std::unique_ptr mStateMarkerCircle; - std::unique_ptr mXAxis; - std::unique_ptr mYAxis; - std::unique_ptr mZAxis; - std::unique_ptr mStateVector; + Ptr mOuterCircle; + Ptr mInnerCircle; + Ptr mCentreCircle; + Ptr mStateMarkerCircle; + Ptr mXAxis; + Ptr mYAxis; + Ptr mZAxis; + Ptr mStateVector; }; diff --git a/plugins/quantum_computing/src/visuals/QuantumCircuitNode.cpp b/plugins/quantum_computing/src/visuals/QuantumCircuitNode.cpp index 9d6fcc1..7e0f1d2 100644 --- a/plugins/quantum_computing/src/visuals/QuantumCircuitNode.cpp +++ b/plugins/quantum_computing/src/visuals/QuantumCircuitNode.cpp @@ -45,12 +45,12 @@ void QuantumCircuitNode::buildWireConnections() for (auto gate : mContent->getLogicGates()) { - for (std::size_t idx = 0; idx < gate->getNumInputs(); idx++) + for (size_t idx = 0; idx < gate->getNumInputs(); idx++) { mWireInputConnections[gate->getInput(idx)] = gate; } - for (std::size_t idx = 0; idx < gate->getNumOutputs(); idx++) + for (size_t idx = 0; idx < gate->getNumOutputs(); idx++) { mWireOutputConnections[gate->getOutput(idx)] = gate; } diff --git a/plugins/quantum_computing/src/visuals/QuantumCircuitNode.h b/plugins/quantum_computing/src/visuals/QuantumCircuitNode.h index 2aad470..ef61314 100644 --- a/plugins/quantum_computing/src/visuals/QuantumCircuitNode.h +++ b/plugins/quantum_computing/src/visuals/QuantumCircuitNode.h @@ -2,7 +2,7 @@ #include "AbstractVisualNode.h" -#include +#include Map.h class QuantumCircuit; class QuantumCircuitElement; @@ -29,13 +29,13 @@ private: bool mContentDirty{ true }; QuantumCircuit* mContent{ nullptr }; - std::vector > mInputTerminalNodes; - std::vector > mOutputTerminalNodes; - std::vector > mGateNodes; - std::vector > mWireNodes; + Vector > mInputTerminalNodes; + Vector > mOutputTerminalNodes; + Vector > mGateNodes; + Vector > mWireNodes; - std::unordered_map mWireInputConnections; - std::unordered_map mWireOutputConnections; + Map mWireInputConnections; + Map mWireOutputConnections; - std::unordered_map mNodesForContent; + Map mNodesForContent; }; \ No newline at end of file diff --git a/plugins/quantum_computing/src/visuals/QuantumGateNode.cpp b/plugins/quantum_computing/src/visuals/QuantumGateNode.cpp index eb9716a..b58b9f3 100644 --- a/plugins/quantum_computing/src/visuals/QuantumGateNode.cpp +++ b/plugins/quantum_computing/src/visuals/QuantumGateNode.cpp @@ -44,7 +44,7 @@ void QuantumGateNode::createOrUpdateGeometry(SceneInfo*) { mLabel = std::make_unique(Point(mBodyWidth /3.0, mBodyHeight / 3.0)); - std::string label_content; + String label_content; if (mContent->getGateType() == QuantumGate::GateType::X) { label_content = "X"; @@ -75,9 +75,9 @@ void QuantumGateNode::createOrUpdateGeometry(SceneInfo*) Point2 QuantumGateNode::getConnectionLocation(AbstractQuantumWire* wire) const { bool is_input{ false }; - //std::size_t connection_id{ 0 }; + //size_t connection_id{ 0 }; - for (std::size_t idx = 0; idx < mContent->getNumInputs(); idx++) + for (size_t idx = 0; idx < mContent->getNumInputs(); idx++) { if (mContent->getInput(idx) == wire) { @@ -87,7 +87,7 @@ Point2 QuantumGateNode::getConnectionLocation(AbstractQuantumWire* wire) const } } - for (std::size_t idx = 0; idx < mContent->getNumOutputs(); idx++) + for (size_t idx = 0; idx < mContent->getNumOutputs(); idx++) { if (mContent->getOutput(idx) == wire) { diff --git a/plugins/quantum_computing/src/visuals/QuantumGateNode.h b/plugins/quantum_computing/src/visuals/QuantumGateNode.h index 289153d..b2987cf 100644 --- a/plugins/quantum_computing/src/visuals/QuantumGateNode.h +++ b/plugins/quantum_computing/src/visuals/QuantumGateNode.h @@ -25,10 +25,10 @@ private: QuantumGate* mContent{ nullptr }; bool mContentDirty{ true }; - std::unique_ptr mBody; + Ptr mBody; double mBodyWidth = 30; double mBodyHeight = 24; - std::unique_ptr mLabelExpression; - std::unique_ptr mLabel; + Ptr mLabelExpression; + Ptr mLabel; }; \ No newline at end of file diff --git a/plugins/quantum_computing/src/visuals/QuantumTerminalNode.cpp b/plugins/quantum_computing/src/visuals/QuantumTerminalNode.cpp index d581c4e..6ae1e34 100644 --- a/plugins/quantum_computing/src/visuals/QuantumTerminalNode.cpp +++ b/plugins/quantum_computing/src/visuals/QuantumTerminalNode.cpp @@ -30,7 +30,7 @@ void QuantumTerminalNode::createOrUpdateGeometry(SceneInfo*) if (!mLabel && mContent->getTerminalType() != QuantumTerminal::TerminalType::OUTPUT) { const auto value = mContent->getValue(); - std::string label; + String label; if (value.isIn0State()) { label = "\\ket{0}"; diff --git a/plugins/quantum_computing/src/visuals/QuantumTerminalNode.h b/plugins/quantum_computing/src/visuals/QuantumTerminalNode.h index 0744649..524b3ea 100644 --- a/plugins/quantum_computing/src/visuals/QuantumTerminalNode.h +++ b/plugins/quantum_computing/src/visuals/QuantumTerminalNode.h @@ -25,6 +25,6 @@ private: double mWidth = 20.0; double mHeight = 10.0; - std::unique_ptr mLabelExpression; - std::unique_ptr mLabel; + Ptr mLabelExpression; + Ptr mLabel; }; \ No newline at end of file diff --git a/plugins/quantum_computing/src/visuals/QuantumWireNode.cpp b/plugins/quantum_computing/src/visuals/QuantumWireNode.cpp index 34b96c7..92d5584 100644 --- a/plugins/quantum_computing/src/visuals/QuantumWireNode.cpp +++ b/plugins/quantum_computing/src/visuals/QuantumWireNode.cpp @@ -54,7 +54,7 @@ void QuantumWireNode::createOrUpdateGeometry(SceneInfo*) auto loc = mOutputLocation; loc.moveBy(-mInputLocation.getX(), -mInputLocation.getY(), -mInputLocation.getZ()); - std::vector points; + Vector points; if (loc.getY() == 0.0) { diff --git a/plugins/quantum_computing/src/visuals/QuantumWireNode.h b/plugins/quantum_computing/src/visuals/QuantumWireNode.h index c703ea7..fe3da7e 100644 --- a/plugins/quantum_computing/src/visuals/QuantumWireNode.h +++ b/plugins/quantum_computing/src/visuals/QuantumWireNode.h @@ -29,5 +29,5 @@ private: Point2 mInputLocation; Point2 mOutputLocation; - std::unique_ptr mLine; + Ptr mLine; }; \ No newline at end of file diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt deleted file mode 100644 index bc9ba8a..0000000 --- a/src/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -add_subdirectory(base) -add_subdirectory(console) -add_subdirectory(media) -add_subdirectory(publishing) -add_subdirectory(rendering) -add_subdirectory(ui) -add_subdirectory(web) diff --git a/src/base/CMakeLists.txt b/src/base/CMakeLists.txt deleted file mode 100644 index 4e4caef..0000000 --- a/src/base/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_subdirectory(compiler) -add_subdirectory(compression) -add_subdirectory(core) -add_subdirectory(database) -add_subdirectory(geometry) -add_subdirectory(network) diff --git a/src/base/compiler/CMakeLists.txt b/src/base/compiler/CMakeLists.txt deleted file mode 100644 index c56514a..0000000 --- a/src/base/compiler/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -set(MODULE_NAME compiler) - -list(APPEND HEADERS - Lexer.h - template_engine/TemplatingEngine.h - template_engine/TemplateFile.h - template_engine/TemplateNode.h - template_engine/TemplateElements.h - ) - -list(APPEND SOURCES - Lexer.cpp - template_engine/TemplatingEngine.cpp - template_engine/TemplateFile.cpp - template_engine/TemplateNode.cpp - template_engine/TemplateElements.cpp - ) - -add_library(${MODULE_NAME} SHARED ${HEADERS} ${SOURCES}) - -target_include_directories(${MODULE_NAME} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/template_engine - ) -target_link_libraries( ${MODULE_NAME} PUBLIC core) - -set_target_properties( ${MODULE_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON ) -set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src/base) diff --git a/src/base/compiler/KScope.cpp b/src/base/compiler/KScope.cpp new file mode 100644 index 0000000..ea1d70f --- /dev/null +++ b/src/base/compiler/KScope.cpp @@ -0,0 +1,78 @@ +#include "KScope.h" + +#include + +void KScopeLexer::run(const FileSystemPath& path) +{ + printf("Before read"); + File f(path); + + const auto content = f<.readText(); + printf("Content is: %s\n", content); + fflush(stdout); + + Vector tokens; + for(const auto c : content.data()) + { + printf("Char is: %c\n", c); + if (CharUtils::is_space(c)) + { + if (m_working_token.is_identifier() || m_working_token.is_number()) + { + on_token_finished(tokens); + } + } + else if (CharUtils::is_alpha(c)) + { + if (m_working_token.is_number()) + { + on_token_finished(tokens); + m_working_token = Token(); + m_working_token.set_is_identifier(); + } + else if (!m_working_token.is_identifier()) + { + m_working_token = Token(); + m_working_token.set_is_identifier(); + } + m_working_token.m_value += c; + } + else if (CharUtils::is_digit(c)) + { + if (m_working_token.is_number() || m_working_token.is_identifier()) + { + m_working_token.m_value += c; + } + else + { + m_working_token = Token(); + m_working_token.set_is_number(); + m_working_token.m_value += c; + } + } + else + { + if (m_working_token.is_identifier() || m_working_token.is_number()) + { + on_token_finished(tokens); + } + + m_working_token.set_is_literal(); + m_working_token.m_value += c; + on_token_finished(tokens); + } + } + on_token_finished(tokens); +} + +void KScopeLexer::on_token_finished(Vector& tokens) +{ + if (m_working_token.m_type == TokenT::NONE) + { + return; + } + + m_working_token.on_finished(); + tokens.push_back(m_working_token); + m_working_token = Token(); +} \ No newline at end of file diff --git a/src/base/compiler/KScope.h b/src/base/compiler/KScope.h new file mode 100644 index 0000000..243ec7b --- /dev/null +++ b/src/base/compiler/KScope.h @@ -0,0 +1,86 @@ +#pragma once + +#include "String.h" +#include "File.h" +#include "Vector.h" +#include "CharUtils.h" + +class KScopeLexer +{ +public: + enum class TokenT + { + NONE, + DEF, // LANG COMMANDS + EXTERN, + IDENTIFIER ,// GENERAL + LITERAL, + NUMBER + }; + + struct Token + { + bool is_identifier() const + { + return m_type == TokenT::IDENTIFIER; + } + + bool is_number() const + { + return m_type == TokenT::NUMBER; + } + + void set_is_identifier() + { + m_type = TokenT::IDENTIFIER; + } + + void set_is_number() + { + m_type = TokenT::NUMBER; + } + + void set_is_literal() + { + m_type = TokenT::LITERAL; + } + + void on_identifier_finished() + { + if (m_value == "def") + { + m_type = TokenT::DEF; + } + else if (m_value == "extern") + { + m_type = TokenT::EXTERN; + } + } + + void on_number_finished() + { + + } + + void on_finished() + { + if (is_identifier()) + { + on_identifier_finished(); + } + else if(is_number()) + { + on_number_finished(); + } + } + + TokenT m_type{TokenT::NONE}; + String m_value; + }; + + void run(const FileSystemPath& path); + + void on_token_finished(Vector& tokens); + + Token m_working_token; +}; \ No newline at end of file diff --git a/src/base/compiler/Lexer.cpp b/src/base/compiler/Lexer.cpp index 869505f..dceba0b 100644 --- a/src/base/compiler/Lexer.cpp +++ b/src/base/compiler/Lexer.cpp @@ -1,6 +1,6 @@ #include "Lexer.h" -bool Lexer::matchPattern(const std::string& pattern, const std::string& checkString, char delimiter, std::vector& hitSequence) +bool Lexer::matchPattern(const String& pattern, const String& checkString, char delimiter, Vector& hitSequence) { if (checkString.empty()) { @@ -16,8 +16,8 @@ bool Lexer::matchPattern(const std::string& pattern, const std::string& checkStr unsigned check_idx = 0; unsigned pattern_idx = 0; - std::vector hits; - std::string working_hit; + Vector hits; + String working_hit; while(check_idx < checkString.size()) { if (pattern_idx == pattern.size()) diff --git a/src/base/compiler/Lexer.h b/src/base/compiler/Lexer.h index 7f04304..21f4bcc 100644 --- a/src/base/compiler/Lexer.h +++ b/src/base/compiler/Lexer.h @@ -1,11 +1,11 @@ #pragma once -#include -#include +#include "String.h" +#include "Vector.h" class Lexer { public: // e.g. Pattern [@](@) returns for input: [source](tag) and delimiter @ - static bool matchPattern(const std::string& pattern, const std::string& checkString, char delimiter, std::vector& hitSequence); + static bool matchPattern(const String& pattern, const String& checkString, char delimiter, Vector& hitSequence); }; diff --git a/src/base/compiler/buildsystem/BuildBinary.cpp b/src/base/compiler/buildsystem/BuildBinary.cpp new file mode 100644 index 0000000..9537947 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildBinary.cpp @@ -0,0 +1,121 @@ +#include "BuildBinary.h" + +#include "Directory.h" +#include "Logger.h" +#include "Process.h" + +BuildBinary::BuildBinary(BuildTargetType binary_type) + : BuildTarget(binary_type) +{ +} + +BuildBinary::BuildBinary(Ptr config) + : BuildTarget(std::move(config)) +{ +} + +const Vector& BuildBinary::get_sources() const +{ + return m_sources; +} + +Status BuildBinary::populate_sources_dirs() +{ + return Directory::getFilesWithExtension(get_directory(), + ".cpp", + m_sources, + true); +} + +Status BuildBinary::build() +{ + for(auto target : m_dependencies) + { + target->build(); + } + + if (const auto rc = compile_sources(); !rc.ok()) + { + return rc; + } + + if (const auto rc = create_archive(); !rc.ok()) + { + return rc; + } + return {}; +} + +Status BuildBinary::configure(const BuildEnvironment& env) +{ + if(const auto rc = BuildTarget::configure(env); !rc.ok()) + { + return rc; + } + STATUS_CHECK(populate_sources_dirs(), + "Error collecting source files"); + + m_compiler_flags = env.get_compiler_flags(); + m_compiler_command = env.get_compiler_command(); + m_archive_command = env.get_archive_command(); + m_build_dir = env.get_build_dir(); + return {}; +} + +Status BuildBinary::compile_sources() +{ + for(const auto& src : m_sources) + { + if (const auto rc = compile_file(src); !rc.ok()) + { + return rc; + } + } + return {}; +} + +void BuildBinary::add_include_dirs(Vector& args) +{ + Vector dirs; + get_public_include_dirs(dirs); + for(const auto& dir : dirs) + { + args.push_back("-I" + dir.str()); + } +} + +Status BuildBinary::compile_file(const FileSystemPath& source) +{ + Vector args = m_compiler_flags; + args.push_back("-c"); + + add_include_dirs(args); + + args.push_back(source.str()); + + const auto output_path = m_build_dir / source.file_name(); + args.push_back("-o"); + args.push_back(output_path.str() + ".o"); + LOG_INFO("Compiling " << source.file_name()); + return Process::launch(m_compiler_command, args); +} + +Status BuildBinary::create_archive() +{ + Vector args; + args.push_back("rcs"); + + auto name = "lib" + get_name() + ".a"; + args.push_back(name); + + for(const auto& src : get_sources()) + { + const auto output_path = m_build_dir / src.file_name(); + const auto output_file = output_path.str() + ".o"; + args.push_back(output_file); + } + + LOG_INFO("Archiving " << name); + return Process::launch(m_archive_command, args); +} + diff --git a/src/base/compiler/buildsystem/BuildBinary.h b/src/base/compiler/buildsystem/BuildBinary.h new file mode 100644 index 0000000..a749c78 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildBinary.h @@ -0,0 +1,37 @@ +#pragma once + +#include "BuildTarget.h" + +class BuildBinary : public BuildTarget +{ +public: + BuildBinary(BuildTargetType binary_type); + + BuildBinary(Ptr config); + + virtual ~BuildBinary() = default; + + Status build() override; + + Status configure(const BuildEnvironment& env) override; + + const Vector& get_sources() const; + +private: + void add_include_dirs(Vector& args); + + Status populate_sources_dirs(); + + Status create_archive(); + + Status compile_sources(); + + Status compile_file(const FileSystemPath& source); + + Vector m_compiler_flags; + String m_compiler_command; + String m_archive_command; + FileSystemPath m_build_dir; + Vector m_public_header_dependencies; + Vector m_sources; +}; \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildConfig.cpp b/src/base/compiler/buildsystem/BuildConfig.cpp new file mode 100644 index 0000000..8d69236 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildConfig.cpp @@ -0,0 +1,33 @@ +#include "BuildConfig.h" + +#include "YamlParser.h" + +BuildConfig::BuildConfig(const FileSystemPath& path) + : m_path(path) +{ +} + +Status BuildConfig::load() +{ + YamlParser yaml_parser; + if (const auto rc = yaml_parser.parse(m_path, m_content); !rc.ok()) + { + return rc; + } + return {}; +} + +FileSystemPath BuildConfig::get_directory() const +{ + return m_path.parent_path(); +} + +String BuildConfig::get_directory_name() const +{ + return get_directory().stem().str(); +} + +BuildTargetType BuildConfig::get_target_type() const +{ + return m_type; +} \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildConfig.h b/src/base/compiler/buildsystem/BuildConfig.h new file mode 100644 index 0000000..d8742f7 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildConfig.h @@ -0,0 +1,27 @@ +#pragma once + +#include "FileSystemPath.h" +#include "YamlDocuments.h" +#include "Error.h" +#include "BuildTargetType.h" + +class BuildConfig +{ +public: + BuildConfig() = default; + + BuildConfig(const FileSystemPath& path); + + Status load(); + + FileSystemPath get_directory() const; + + String get_directory_name() const; + + BuildTargetType get_target_type() const; + +private: + BuildTargetType m_type{BuildTargetType::STATIC_LIBRARY}; + YamlDocuments m_content; + FileSystemPath m_path; +}; \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildEnvironment.cpp b/src/base/compiler/buildsystem/BuildEnvironment.cpp new file mode 100644 index 0000000..f4cf86d --- /dev/null +++ b/src/base/compiler/buildsystem/BuildEnvironment.cpp @@ -0,0 +1,46 @@ +#include "BuildEnvironment.h" + +BuildEnvironment::BuildEnvironment(const FileSystemPath& source_dir, + const FileSystemPath& build_dir) + : m_build_dir(build_dir), + m_source_dir(source_dir) +{ + m_compiler_flags.push_back("-g"); + m_compiler_flags.push_back("-fno-exceptions"); + m_compiler_flags.push_back("-fno-rtti"); +} + +const Vector& BuildEnvironment::get_compiler_flags() const +{ + return m_compiler_flags; +} + +const String& BuildEnvironment::get_compiler_command() const +{ + return m_compiler_command; +} + +const String& BuildEnvironment::get_archive_command() const +{ + return m_archive_command; +} + +const FileSystemPath& BuildEnvironment::get_build_dir() const +{ + return m_build_dir; +} + +const FileSystemPath& BuildEnvironment::get_source_dir() const +{ + return m_source_dir; +} + +FileSystemPath BuildEnvironment::get_test_dir() const +{ + return m_source_dir / "test"; +} + +void BuildEnvironment::set_build_dir(const FileSystemPath& dir) +{ + m_build_dir = dir; +} \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildEnvironment.h b/src/base/compiler/buildsystem/BuildEnvironment.h new file mode 100644 index 0000000..3c921e0 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildEnvironment.h @@ -0,0 +1,31 @@ +#pragma once + +#include "Vector.h" +#include "FileSystemPath.h" + +class BuildEnvironment +{ +public: + BuildEnvironment(const FileSystemPath& source_dir, const FileSystemPath& build_dir = {}); + + const Vector& get_compiler_flags() const; + + const String& get_compiler_command() const; + + const String& get_archive_command() const; + + const FileSystemPath& get_build_dir() const; + + const FileSystemPath& get_source_dir() const; + + FileSystemPath get_test_dir() const; + + void set_build_dir(const FileSystemPath& dir); + +private: + String m_compiler_command{"/usr/bin/g++"}; + String m_archive_command{"/usr/bin/ar"}; + Vector m_compiler_flags; + FileSystemPath m_build_dir; + FileSystemPath m_source_dir; +}; \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildExecutable.cpp b/src/base/compiler/buildsystem/BuildExecutable.cpp new file mode 100644 index 0000000..345ff27 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildExecutable.cpp @@ -0,0 +1,6 @@ +#include "BuildExecutable.h" + +BuildExecutable::BuildExecutable(Ptr config) + : BuildBinary(std::move(config)) +{ +} \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildExecutable.h b/src/base/compiler/buildsystem/BuildExecutable.h new file mode 100644 index 0000000..ba089e7 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildExecutable.h @@ -0,0 +1,13 @@ +#pragma once + +#include "BuildBinary.h" + +class BuildExecutable : public BuildBinary +{ +public: + BuildExecutable() = default; + + BuildExecutable(Ptr config); + + virtual ~BuildExecutable() = default; +}; \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildLibrary.cpp b/src/base/compiler/buildsystem/BuildLibrary.cpp new file mode 100644 index 0000000..4477ef2 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildLibrary.cpp @@ -0,0 +1,17 @@ +#include "BuildLibrary.h" + +BuildLibrary::BuildLibrary(BuildTargetType lib_type) + : BuildBinary(lib_type) +{ + +} + +BuildLibrary::BuildLibrary(Ptr config) + : BuildBinary(std::move(config)) +{ +} + +Status BuildLibrary::build() +{ + return BuildBinary::build(); +} \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildLibrary.h b/src/base/compiler/buildsystem/BuildLibrary.h new file mode 100644 index 0000000..01cd79f --- /dev/null +++ b/src/base/compiler/buildsystem/BuildLibrary.h @@ -0,0 +1,15 @@ +#pragma once + +#include "BuildBinary.h" + +class BuildLibrary : public BuildBinary +{ +public: + BuildLibrary(BuildTargetType lib_type); + + BuildLibrary(Ptr config); + + virtual ~BuildLibrary() = default; + + Status build() override; +}; \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildSession.cpp b/src/base/compiler/buildsystem/BuildSession.cpp new file mode 100644 index 0000000..0160e3d --- /dev/null +++ b/src/base/compiler/buildsystem/BuildSession.cpp @@ -0,0 +1,86 @@ +#include "BuildSession.h" + +#include "Logger.h" +#include "Directory.h" + +BuildSession::BuildSession(const FileSystemPath& source_dir, + const FileSystemPath& build_dir) + : m_build_environment(source_dir) +{ + auto working_build_dir = build_dir; + if (working_build_dir.is_empty().value()) + { + working_build_dir = FileSystemPath::current_dir().value(); + } + m_build_environment.set_build_dir(working_build_dir / "build"); +} + +Status BuildSession::configure() +{ + LOG_INFO("Configuring project at:" << m_build_environment.get_source_dir()); + Vector yaml_files; + STATUS_CHECK(Directory::getFilesWithExtension( + m_build_environment.get_source_dir(), + ".yaml", + yaml_files, + true), "Error looking for build files"); + for(const auto& yaml_file : yaml_files) + { + if (yaml_file.file_name() == "build") + { + STATUS_CHECK(add_target(yaml_file), + "Error adding target at: " + yaml_file.stem().str()); + } + } + return configure_tests(); +} + +Status BuildSession::add_target(const FileSystemPath& config_path) +{ + LOG_INFO("Adding target at: " << config_path); + auto target = BuildTarget::create(config_path); + STATUS_CHECK(target->configure(m_build_environment), "Error configuring target"); + m_targets.push_back(std::move(target)); + return {}; +} + +Status BuildSession::configure_tests() +{ + const auto test_dir = m_build_environment.get_test_dir(); + LOG_INFO("Scanning test files at:" << test_dir); + Vector candidate_test_files; + STATUS_CHECK(Directory::getFilesWithExtension( + test_dir, + ".cpp", + candidate_test_files, + true), "Error looking for test files"); + + Vector test_files; + for(const auto& test_file : candidate_test_files) + { + if (test_file.stem().starts_with("Test")) + { + if (test_file.contains("core")) + { + LOG_INFO("Adding " << test_file); + test_files.push_back(test_file); + } + } + } + return {}; +} + +Status BuildSession::build() +{ + LOG_INFO("Starting build at: " << m_build_environment.get_build_dir()); + Directory::create(m_build_environment.get_build_dir(), true); + for(auto& target : m_targets) + { + auto run_status = target->build(); + if (!run_status.ok()) + { + return run_status; + } + } + return {}; +} diff --git a/src/base/compiler/buildsystem/BuildSession.h b/src/base/compiler/buildsystem/BuildSession.h new file mode 100644 index 0000000..e21a492 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildSession.h @@ -0,0 +1,26 @@ +#pragma once + +#include "BuildEnvironment.h" +#include "BuildTarget.h" +#include "FileSystemPath.h" +#include "Error.h" +#include "Pointer.h" + +class BuildSession +{ +public: + BuildSession(const FileSystemPath& source_dir, + const FileSystemPath& build_dir = {}); + + Status build(); + + Status configure(); + +private: + Status add_target(const FileSystemPath& config_path); + + Status configure_tests(); + + BuildEnvironment m_build_environment; + Vector > m_targets; +}; \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildTarget.cpp b/src/base/compiler/buildsystem/BuildTarget.cpp new file mode 100644 index 0000000..41ee013 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildTarget.cpp @@ -0,0 +1,105 @@ +#include "BuildTarget.h" + +#include "Logger.h" +#include "Directory.h" +#include "YamlParser.h" + +#include "BuildLibrary.h" +#include "BuildExecutable.h" + +Ptr BuildTarget::create(const FileSystemPath& build_config_path) +{ + auto build_config = Ptr::create(build_config_path); + build_config->load(); + auto build_type = build_config->get_target_type(); + if (build_type == BuildTargetType::SHARED_LIBRARY || build_type == BuildTargetType::SHARED_LIBRARY) + { + Ptr target_type; + target_type = Ptr::create(std::move(build_config)); + return std::move(target_type); + } + else + { + Ptr target_type; + target_type = Ptr::create(std::move(build_config)); + return std::move(target_type); + } +} + +BuildTarget::BuildTarget(BuildTargetType target_type) + : m_type(target_type) +{ +} + +BuildTarget::BuildTarget(Ptr config) + : m_build_config(std::move(config)), + m_type(m_build_config->get_target_type()) +{ +} + +void BuildTarget::add_dependency(BuildTarget* dependency) +{ + m_dependencies.push_back(dependency); +} + +BuildTargetType BuildTarget::get_type() const +{ + return m_type; +} + +const Vector& BuildTarget::get_dependencies() const +{ + return m_dependencies; +} + +const Vector& BuildTarget::get_dependency_names() const +{ + return m_dependency_names; +} + +const String& BuildTarget::get_name() const +{ + return m_name; +} + +void BuildTarget::get_public_include_dirs(Vector& dirs) const +{ + dirs.extend(m_include_dirs); + for(auto target : m_dependencies) + { + target->get_public_include_dirs(dirs); + } +} + +Status BuildTarget::load_config() +{ + STATUS_CHECK(m_build_config->load(), "Failed to load build config."); + m_name = m_build_config->get_directory_name(); + return {}; +} + +FileSystemPath BuildTarget::get_directory() const +{ + return m_build_config->get_directory(); +} + +Status BuildTarget::populate_include_dirs() +{ + const auto search_dir = get_directory(); + m_include_dirs.push_back(search_dir); + return Directory::getAllSubDirectories(search_dir, m_include_dirs); +} + +Status BuildTarget::configure(const BuildEnvironment& env) +{ + for(auto target : m_dependencies) + { + target->configure(env); + } + + const auto search_dir = get_directory(); + LOG_INFO("Scanning build file at: " << search_dir); + + STATUS_CHECK(populate_include_dirs(), "Error populating include dirs"); + return {}; +} \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildTarget.h b/src/base/compiler/buildsystem/BuildTarget.h new file mode 100644 index 0000000..1bf1ce0 --- /dev/null +++ b/src/base/compiler/buildsystem/BuildTarget.h @@ -0,0 +1,52 @@ +#pragma once + +#include "BuildConfig.h" +#include "FileSystemPath.h" +#include "String.h" +#include "Vector.h" + +#include "BuildEnvironment.h" + +class BuildTarget +{ +public: + BuildTarget(BuildTargetType target_type); + + BuildTarget(Ptr config); + + static Ptr create(const FileSystemPath& build_config_path); + + virtual ~BuildTarget() = default; + + virtual Status build() = 0; + + void add_dependency(BuildTarget* dependency); + + virtual Status configure(const BuildEnvironment& env); + + BuildTargetType get_type() const; + + void get_public_include_dirs(Vector& dirs) const; + + const String& get_name() const; + + const Vector& get_dependencies() const; + + const Vector& get_dependency_names() const; + +protected: + FileSystemPath get_directory() const; + + Vector m_dependencies; + +private: + Status populate_include_dirs(); + + Status load_config(); + + Vector m_dependency_names; + Ptr m_build_config; + Vector m_include_dirs; + String m_name; + BuildTargetType m_type{BuildTargetType::UNSET}; +}; \ No newline at end of file diff --git a/src/base/compiler/buildsystem/BuildTargetType.h b/src/base/compiler/buildsystem/BuildTargetType.h new file mode 100644 index 0000000..7694a5e --- /dev/null +++ b/src/base/compiler/buildsystem/BuildTargetType.h @@ -0,0 +1,9 @@ +#pragma once + +enum class BuildTargetType +{ + UNSET, + SHARED_LIBRARY, + STATIC_LIBRARY, + EXECUTABLE +}; \ No newline at end of file diff --git a/src/base/compiler/template_engine/TemplateElements.cpp b/src/base/compiler/template_engine/TemplateElements.cpp index 46e6577..9a2c4ef 100644 --- a/src/base/compiler/template_engine/TemplateElements.cpp +++ b/src/base/compiler/template_engine/TemplateElements.cpp @@ -5,50 +5,50 @@ #include -TemplateExtends::TemplateExtends(TemplateNode* parent, const std::string& path) +TemplateExtends::TemplateExtends(TemplateNode* parent, const String& path) : TemplateNode(parent) { mPath = StringUtils::stripQuotes(path); }; -std::string TemplateExtends::getRawContent() const +String TemplateExtends::getRawContent() const { return "TemplateExtends: " + mPath; } -std::string TemplateExtends::getPath() const +String TemplateExtends::getPath() const { return mPath; } -TemplateBlock::TemplateBlock(TemplateNode* parent, const std::string& name) +TemplateBlock::TemplateBlock(TemplateNode* parent, const String& name) : TemplateNode(parent), mName(name) { } -void TemplateBlock::addLine(const std::string& line) +void TemplateBlock::addLine(const String& line) { mBody.push_back(line); } -std::string TemplateBlock::getRawContent() const +String TemplateBlock::getRawContent() const { - std::string content = "TemplateBlock: " + mName + " - Start \n"; + String content = "TemplateBlock: " + mName + " - Start \n"; content += TemplateNode::getRawContent(); content += "TemplateBlock: " + mName + " - End"; return content; } -std::string TemplateBlock::getIdentifier() const +String TemplateBlock::getIdentifier() const { return mName; } -std::string TemplateBlock::renderAsParent(TemplateSubstitutionContext* substitutions, TemplateBlock* base) +String TemplateBlock::renderAsParent(TemplateSubstitutionContext* substitutions, TemplateBlock* base) { - std::string content; + String content; for (auto& child : mChildren) { if (child->getType() == Type::EXPRESSION) @@ -67,9 +67,9 @@ std::string TemplateBlock::renderAsParent(TemplateSubstitutionContext* substitut return content; } -std::string TemplateBlock::renderAsLeaf(TemplateSubstitutionContext* substitutions) +String TemplateBlock::renderAsLeaf(TemplateSubstitutionContext* substitutions) { - std::string content; + String content; for (auto& child : mChildren) { if(child->getType() == Type::TEXT_BODY) @@ -80,9 +80,9 @@ std::string TemplateBlock::renderAsLeaf(TemplateSubstitutionContext* substitutio return content; } -std::string TemplateBlock::render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext) +String TemplateBlock::render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext) { - std::string content; + String content; if (parentContext) { if (auto parent_node = parentContext->getFirstChildShallow(Type::BLOCK, getIdentifier())) @@ -101,19 +101,19 @@ std::string TemplateBlock::render(TemplateSubstitutionContext* substitutions, Te return content; } -TemplateExpression::TemplateExpression(TemplateNode* parent, const std::string& content) +TemplateExpression::TemplateExpression(TemplateNode* parent, const String& content) : TemplateNode(parent), mContent(content) { } -const std::string& TemplateExpression::getContent() const +const String& TemplateExpression::getContent() const { return mContent; } -std::string TemplateExpression::render(TemplateSubstitutionContext* substitutions, TemplateNode*) +String TemplateExpression::render(TemplateSubstitutionContext* substitutions, TemplateNode*) { if (substitutions && substitutions->hasSubstitution(mContent)) { @@ -122,7 +122,7 @@ std::string TemplateExpression::render(TemplateSubstitutionContext* substitution return {}; } -std::string TemplateExpression::getRawContent() const +String TemplateExpression::getRawContent() const { return "TemplateExpression: " + mContent; } @@ -133,7 +133,7 @@ TemplateTextBody::TemplateTextBody(TemplateNode* parent) } -void TemplateTextBody::addLine(const std::string& content) +void TemplateTextBody::addLine(const String& content) { mContent.push_back(content); } @@ -143,9 +143,9 @@ bool TemplateTextBody::hasContent() const return !mContent.empty(); } -std::string TemplateTextBody::render(TemplateSubstitutionContext*, TemplateNode*) +String TemplateTextBody::render(TemplateSubstitutionContext*, TemplateNode*) { - std::string content; + String content; for(unsigned idx=0; idx mBody; + String mName; + Vector mBody; }; class TemplateExpression : public TemplateNode { public: - TemplateExpression(TemplateNode* parent, const std::string& content); + TemplateExpression(TemplateNode* parent, const String& content); virtual ~TemplateExpression() = default; - std::string getRawContent() const override; + String getRawContent() const override; - const std::string& getContent() const; + const String& getContent() const; Type getType() const override { return Type::EXPRESSION; } - std::string render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext) override; + String render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext) override; private: - std::string mContent; + String mContent; }; class TemplateTextBody : public TemplateNode @@ -79,18 +79,18 @@ public: virtual ~TemplateTextBody() = default; - void addLine(const std::string& content); + void addLine(const String& content); - std::string getRawContent() const override; + String getRawContent() const override; bool hasContent() const; - std::string render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext) override; + String render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext) override; Type getType() const override { return Type::TEXT_BODY; } private: - std::vector mContent; + Vector mContent; }; diff --git a/src/base/compiler/template_engine/TemplateFile.cpp b/src/base/compiler/template_engine/TemplateFile.cpp index bde3cf6..40cdb32 100644 --- a/src/base/compiler/template_engine/TemplateFile.cpp +++ b/src/base/compiler/template_engine/TemplateFile.cpp @@ -19,7 +19,7 @@ TemplateFile::~TemplateFile() } -std::string TemplateFile::getName() const +String TemplateFile::getName() const { return mPath.stem().string(); } @@ -53,7 +53,7 @@ void TemplateFile::loadContent() mHasLoaded = true; } -std::string TemplateFile::dumpContent() +String TemplateFile::dumpContent() { return mRootNode->getRawContent(); } @@ -73,15 +73,15 @@ void TemplateFile::onTextSpanFinished() mWorkingLineContent.clear(); } -std::size_t TemplateFile::checkForStatement(const std::string& lineSection) +size_t TemplateFile::checkForStatement(const String& lineSection) { if (lineSection.empty()) { return 0; } - std::vector hits; - std::size_t hit_size{0}; + Vector hits; + size_t hit_size{0}; if (Lexer::matchPattern("{%@%}", lineSection, '@', hits)) { if (hits.size() == 1) @@ -97,15 +97,15 @@ std::size_t TemplateFile::checkForStatement(const std::string& lineSection) return hit_size; } -std::size_t TemplateFile::checkForExpression(const std::string& lineSection) +size_t TemplateFile::checkForExpression(const String& lineSection) { if (lineSection.empty()) { return 0; } - std::vector hits; - std::size_t hit_size{0}; + Vector hits; + size_t hit_size{0}; if (Lexer::matchPattern("{{@}}", lineSection, '@', hits)) { if (hits.size() == 1) @@ -121,9 +121,9 @@ std::size_t TemplateFile::checkForExpression(const std::string& lineSection) return hit_size; } -void TemplateFile::processLine(const std::string& line) +void TemplateFile::processLine(const String& line) { - std::size_t line_position = 0; + size_t line_position = 0; mWorkingLineContent.clear(); while(line_position < line.size()) { @@ -150,7 +150,7 @@ void TemplateFile::processLine(const std::string& line) } } -void TemplateFile::onFoundStatement(const std::string& statement_string) +void TemplateFile::onFoundStatement(const String& statement_string) { const auto statement_elements = StringUtils::split(statement_string); if (statement_elements.size() == 0) @@ -172,14 +172,14 @@ void TemplateFile::onFoundStatement(const std::string& statement_string) } } -void TemplateFile::onFoundExpression(const std::string& expression_string) +void TemplateFile::onFoundExpression(const String& expression_string) { const auto stripped = StringUtils::stripSurroundingWhitepsace(expression_string); auto expression = std::make_unique(mWorkingNode, stripped); mWorkingNode->addChild(std::move(expression)); } -void TemplateFile::onFoundBlock(const std::vector args) +void TemplateFile::onFoundBlock(const Vector args) { if (args.size() != 2) { @@ -191,12 +191,12 @@ void TemplateFile::onFoundBlock(const std::vector args) mWorkingNode = temp; } -void TemplateFile::onFoundEndBlock(const std::vector) +void TemplateFile::onFoundEndBlock(const Vector) { mWorkingNode = mWorkingNode->getParent(); } -void TemplateFile::onFoundExtends(const std::vector args) +void TemplateFile::onFoundExtends(const Vector args) { if (args.size() != 2) { diff --git a/src/base/compiler/template_engine/TemplateFile.h b/src/base/compiler/template_engine/TemplateFile.h index 717d73b..184f0d7 100644 --- a/src/base/compiler/template_engine/TemplateFile.h +++ b/src/base/compiler/template_engine/TemplateFile.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Vector.h" +#include "String.h" #include class TemplateNode; @@ -16,9 +16,9 @@ public: ~TemplateFile(); - std::string dumpContent(); + String dumpContent(); - std::string getName() const; + String getName() const; TemplateNode* getContent() const; @@ -27,32 +27,32 @@ public: void loadContent(); private: - std::size_t checkForStatement(const std::string& lineSection); + size_t checkForStatement(const String& lineSection); - std::size_t checkForExpression(const std::string& lineSection); + size_t checkForExpression(const String& lineSection); void onTextSpanFinished(); - void onFoundStatement(const std::string& statement_string); + void onFoundStatement(const String& statement_string); - void onFoundExpression(const std::string& expression_string); + void onFoundExpression(const String& expression_string); - void onFoundBlock(const std::vector args); + void onFoundBlock(const Vector args); - void onFoundEndBlock(const std::vector args); + void onFoundEndBlock(const Vector args); - void onFoundExtends(const std::vector args); + void onFoundExtends(const Vector args); - void processLine(const std::string& line); + void processLine(const String& line); Path mPath; - std::string mParentName; - std::vector mRawContent; + String mParentName; + Vector mRawContent; bool mHasLoaded{false}; - std::unique_ptr mRootNode; + Ptr mRootNode; TemplateNode* mWorkingNode{ nullptr }; - std::string mWorkingLineContent; - std::unique_ptr mWorkingTextSpan; + String mWorkingLineContent; + Ptr mWorkingTextSpan; }; diff --git a/src/base/compiler/template_engine/TemplateNode.cpp b/src/base/compiler/template_engine/TemplateNode.cpp index 9f76817..d97a09a 100644 --- a/src/base/compiler/template_engine/TemplateNode.cpp +++ b/src/base/compiler/template_engine/TemplateNode.cpp @@ -13,17 +13,17 @@ TemplateNode* TemplateNode::getParent() const return mParent; } -void TemplateNode::addChild(std::unique_ptr child) +void TemplateNode::addChild(Ptr child) { mChildren.push_back(std::move(child)); } -std::size_t TemplateNode::getNumChildren() const +size_t TemplateNode::getNumChildren() const { return mChildren.size(); } -TemplateNode* TemplateNode::getFirstChildShallow(Type type, const std::string& identifier) const +TemplateNode* TemplateNode::getFirstChildShallow(Type type, const String& identifier) const { for (const auto& child : mChildren) { @@ -50,19 +50,19 @@ TemplateNode::Type TemplateNode::getType() const return Type::NONE; } -std::string TemplateNode::getIdentifier() const +String TemplateNode::getIdentifier() const { return {}; } -TemplateNode* TemplateNode::getChild(std::size_t index) const +TemplateNode* TemplateNode::getChild(size_t index) const { return mChildren[index].get(); } -std::string TemplateNode::getRawContent() const +String TemplateNode::getRawContent() const { - std::string content; + String content; for (const auto& child : mChildren) { content += child->getRawContent() + "\n"; @@ -80,7 +80,7 @@ void TemplateNode::setExtensionBase(TemplateNode* base) mExtensionBase = base; } -std::string TemplateNode::render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext) +String TemplateNode::render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext) { if (mExtensionBase) { @@ -92,7 +92,7 @@ std::string TemplateNode::render(TemplateSubstitutionContext* substitutions, Tem parentContext = mExtensionParent; } - std::string content; + String content; for (size_t idx = 0; idx < mChildren.size(); idx++) { content += mChildren[idx]->render(substitutions, parentContext); diff --git a/src/base/compiler/template_engine/TemplateNode.h b/src/base/compiler/template_engine/TemplateNode.h index ab573ad..6a9b14e 100644 --- a/src/base/compiler/template_engine/TemplateNode.h +++ b/src/base/compiler/template_engine/TemplateNode.h @@ -1,8 +1,8 @@ #pragma once -#include -#include -#include +#include "Pointer.h" +#include "String.h" +#include "Vector.h" class TemplateSubstitutionContext; @@ -22,33 +22,33 @@ public: virtual ~TemplateNode() = default; - virtual void addChild(std::unique_ptr child); + virtual void addChild(Ptr child); - TemplateNode* getChild(std::size_t index) const; + TemplateNode* getChild(size_t index) const; - TemplateNode* getFirstChildShallow(Type type, const std::string& identifier = {}) const; + TemplateNode* getFirstChildShallow(Type type, const String& identifier = {}) const; - virtual std::string getIdentifier() const; + virtual String getIdentifier() const; - std::size_t getNumChildren() const; + size_t getNumChildren() const; TemplateNode* getParent() const; - virtual std::string getRawContent() const; + virtual String getRawContent() const; virtual Type getType() const; - virtual std::string render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext = nullptr); + virtual String render(TemplateSubstitutionContext* substitutions, TemplateNode* parentContext = nullptr); void setExtensionParent(TemplateNode* parent); void setExtensionBase(TemplateNode* base); protected: - std::vector > mChildren; + Vector > mChildren; TemplateNode* mParent{ nullptr }; TemplateNode* mExtensionParent{ nullptr }; TemplateNode* mExtensionBase{ nullptr }; }; -using TemplateNodePtr = std::unique_ptr; +using TemplateNodePtr = Ptr; diff --git a/src/base/compiler/template_engine/TemplateSubstitutionContext.h b/src/base/compiler/template_engine/TemplateSubstitutionContext.h index c125e1a..d68fec5 100644 --- a/src/base/compiler/template_engine/TemplateSubstitutionContext.h +++ b/src/base/compiler/template_engine/TemplateSubstitutionContext.h @@ -1,23 +1,23 @@ #pragma once -#include -#include +#include "String.h" +#include Map.h class TemplateSubstitutionContext { public: - void addSubstitution(const std::string& key, const std::string& value) + void addSubstitution(const String& key, const String& value) { mSubstitutions[key] = value; } - bool hasSubstitution(const std::string& key) const + bool hasSubstitution(const String& key) const { return mSubstitutions.find(key) != mSubstitutions.end(); } - std::string getSubstitution(const std::string& key) const + String getSubstitution(const String& key) const { auto iter = mSubstitutions.find(key); if(iter != mSubstitutions.end()) @@ -31,5 +31,5 @@ public: } private: - std::unordered_map mSubstitutions; + Map mSubstitutions; }; diff --git a/src/base/compiler/template_engine/TemplatingEngine.cpp b/src/base/compiler/template_engine/TemplatingEngine.cpp index 4f62684..d4a942d 100644 --- a/src/base/compiler/template_engine/TemplatingEngine.cpp +++ b/src/base/compiler/template_engine/TemplatingEngine.cpp @@ -14,7 +14,7 @@ TemplatingEngine::TemplatingEngine(const Path& workingDirectory) } -std::string TemplatingEngine::renderTemplate(const std::string& name, TemplateSubstitutionContext* substitutionContext) +String TemplatingEngine::renderTemplate(const String& name, TemplateSubstitutionContext* substitutionContext) { if (mTemplateFiles.empty()) { @@ -53,7 +53,7 @@ TemplateFile* TemplatingEngine::getTemplateFile(const Path& path) return getTemplateFile(path.stem().string()); } -TemplateFile* TemplatingEngine::getTemplateFile(const std::string& name) +TemplateFile* TemplatingEngine::getTemplateFile(const String& name) { return mTemplateFiles[name].get(); } diff --git a/src/base/compiler/template_engine/TemplatingEngine.h b/src/base/compiler/template_engine/TemplatingEngine.h index e622847..091fbe3 100644 --- a/src/base/compiler/template_engine/TemplatingEngine.h +++ b/src/base/compiler/template_engine/TemplatingEngine.h @@ -3,10 +3,10 @@ #include "File.h" #include "TemplateFile.h" -#include -#include -#include -#include +#include "Vector.h" +#include "String.h" +#include "Pointer.h" +#include Map.h class TemplateSubstitutionContext; @@ -15,16 +15,16 @@ class TemplatingEngine public: TemplatingEngine(const Path& workingDirectory); - std::string renderTemplate(const std::string& name, TemplateSubstitutionContext* substitutionContext); + String renderTemplate(const String& name, TemplateSubstitutionContext* substitutionContext); private: - TemplateFile* getTemplateFile(const std::string& name); + TemplateFile* getTemplateFile(const String& name); TemplateFile* getTemplateFile(const Path& path); void loadTemplateFiles(); void processTemplate(TemplateFile* file, TemplateNode* parent = nullptr); - std::unordered_map > mTemplateFiles; + Map > mTemplateFiles; Path mWorkingDirectory; - std::string mTemplateExtension{ ".html" }; + String mTemplateExtension{ ".html" }; }; diff --git a/src/base/compression/AbstractEncoder.h b/src/base/compression/AbstractEncoder.h index 6e59c3c..5e161a3 100644 --- a/src/base/compression/AbstractEncoder.h +++ b/src/base/compression/AbstractEncoder.h @@ -2,7 +2,7 @@ #include "AbstractChecksumCalculator.h" -#include +#include "Vector.h" class BitStream; @@ -28,7 +28,7 @@ public: protected: - std::vector mChecksumCalculators; + Vector mChecksumCalculators; BitStream* mInputStream{nullptr}; BitStream* mOutputStream{nullptr}; }; diff --git a/src/base/compression/CMakeLists.txt b/src/base/compression/CMakeLists.txt deleted file mode 100644 index 6eff2f6..0000000 --- a/src/base/compression/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -set(MODULE_NAME compression) - -list(APPEND SOURCES - StreamCompressor.cpp - huffman/HuffmanEncoder.cpp - huffman/HuffmanStream.cpp - huffman/HuffmanCodeLengthTable.cpp - huffman/HuffmanTree.cpp - RunLengthEncoder.cpp - ZlibEncoder.cpp - deflate/DeflateEncoder.cpp - deflate/DeflateBlock.cpp - Lz77Encoder.cpp - CyclicRedundancyChecker.cpp - ) - -add_library(${MODULE_NAME} SHARED ${SOURCES}) - -target_include_directories(${MODULE_NAME} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/deflate - ${CMAKE_CURRENT_SOURCE_DIR}/huffman - ) - -target_link_libraries(${MODULE_NAME} PUBLIC core) -set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src/base) -set_target_properties( ${MODULE_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON ) diff --git a/src/base/compression/CyclicRedundancyChecker.cpp b/src/base/compression/CyclicRedundancyChecker.cpp index 97f518b..bf51244 100644 --- a/src/base/compression/CyclicRedundancyChecker.cpp +++ b/src/base/compression/CyclicRedundancyChecker.cpp @@ -2,9 +2,9 @@ void CyclicRedundancyChecker::createTable() { - mTable = std::vector(TABLE_SIZE, 0); + mTable = Vector(TABLE_SIZE, 0); unsigned long c{0}; - for (std::size_t n = 0; n < TABLE_SIZE; n++) + for (size_t n = 0; n < TABLE_SIZE; n++) { c = (unsigned long) n; for (int k = 0; k < 8; k++) diff --git a/src/base/compression/CyclicRedundancyChecker.h b/src/base/compression/CyclicRedundancyChecker.h index a20a1cf..9aa4446 100644 --- a/src/base/compression/CyclicRedundancyChecker.h +++ b/src/base/compression/CyclicRedundancyChecker.h @@ -2,7 +2,7 @@ #include "AbstractChecksumCalculator.h" -#include +#include "Vector.h" class CyclicRedundancyChecker : public AbstractChecksumCalculator { @@ -19,6 +19,6 @@ private: uint32_t mLastValue{0xffffffffL}; - static const std::size_t TABLE_SIZE{ 256 }; - std::vector mTable; + static const size_t TABLE_SIZE{ 256 }; + Vector mTable; }; diff --git a/src/base/compression/Lz77Encoder.cpp b/src/base/compression/Lz77Encoder.cpp index e5f649b..3db7198 100644 --- a/src/base/compression/Lz77Encoder.cpp +++ b/src/base/compression/Lz77Encoder.cpp @@ -2,7 +2,7 @@ #include "StringUtils.h" #include "BitStream.h" -#include "ByteUtils.h" +#include "Bits.h" #include "HuffmanEncoder.h" #include @@ -15,7 +15,7 @@ Lz77Encoder::Lz77Encoder(BitStream* inputStream, BitStream* outputStream) } -void Lz77Encoder::setPrefixCodeGenerator(std::unique_ptr generator) +void Lz77Encoder::setPrefixCodeGenerator(Ptr generator) { mCodeGenerator = std::move(generator); } @@ -35,7 +35,7 @@ void Lz77Encoder::populateSearchBuffer(const Hit& hit) } else { - std::vector new_items(distance, 0); + Vector new_items(distance, 0); for(unsigned idx=0 ;idx& Lz77Encoder::getHitBuffer() const +const Vector& Lz77Encoder::getHitBuffer() const { return mHitBuffer; } @@ -234,7 +234,7 @@ void Lz77Encoder::flushHitBuffer() if (length == 0) { code = *mCodeGenerator->getLiteralValue(next_char); - std::cout << "Writing symbol " << static_cast(next_char) << " with code " << ByteUtils::toString(code.getData(), code.getLength()) << "\n"; + std::cout << "Writing symbol " << static_cast(next_char) << " with code " << Bits::toString(code.getData(), code.getLength()) << "\n"; mOutputStream->writeNBits(code.getData(), code.getLength()); } @@ -243,16 +243,16 @@ void Lz77Encoder::flushHitBuffer() code = *mCodeGenerator->getLengthValue(length); const auto distance_code = mCodeGenerator->getDistanceValue(distance); - std::cout << "Writing length " << length << " with code " << ByteUtils::toString(code.getData(), code.getLength()) << "\n"; + std::cout << "Writing length " << length << " with code " << Bits::toString(code.getData(), code.getLength()) << "\n"; mOutputStream->writeNBits(code.getData(), code.getLength()); - std::cout << "Writing distance " << distance << " with code " << ByteUtils::toString(distance_code.getData(), distance_code.getLength()) << "\n"; + std::cout << "Writing distance " << distance << " with code " << Bits::toString(distance_code.getData(), distance_code.getLength()) << "\n"; mOutputStream->writeNBits(distance_code.getData(), distance_code.getLength()); } } auto eos_code = mCodeGenerator->getEndOfStreamValue(); - std::cout << "Writing EOS value with code " << ByteUtils::toString(eos_code->getData(), eos_code->getLength()) << "\n"; + std::cout << "Writing EOS value with code " << Bits::toString(eos_code->getData(), eos_code->getLength()) << "\n"; mOutputStream->writeNBits(eos_code->getData(), eos_code->getLength()); } @@ -261,7 +261,7 @@ void Lz77Encoder::flushHitBuffer() bool Lz77Encoder::decode() { /* - std::string ret; + String ret; unsigned loc{0}; while(loc < stream.size()) @@ -272,7 +272,7 @@ bool Lz77Encoder::decode() unsigned loc_working = loc; auto remainder = stream.size() - loc; - std::string offset; + String offset; unsigned length_loc{0}; for(unsigned jdx=0; jdx< remainder; jdx++) @@ -292,7 +292,7 @@ bool Lz77Encoder::decode() } unsigned offset_amount = std::stoul(offset); - std::string length; + String length; remainder = stream.size() - loc; for(unsigned jdx=0; jdx< remainder; jdx++) diff --git a/src/base/compression/Lz77Encoder.h b/src/base/compression/Lz77Encoder.h index 0d3ec85..e0555d7 100644 --- a/src/base/compression/Lz77Encoder.h +++ b/src/base/compression/Lz77Encoder.h @@ -4,9 +4,9 @@ #include "HuffmanEncoder.h" #include "CircleBuffer.h" -#include -#include -#include +#include "String.h" +#include "Vector.h" +#include "Pointer.h" #include class PrefixCodeGenerator; @@ -22,19 +22,19 @@ public: bool decode() override; - const std::vector& getHitBuffer() const; + const Vector& getHitBuffer() const; void setSearchBufferSize(unsigned size); void setLookAheadBufferSize(unsigned size); - void setPrefixCodeGenerator(std::unique_ptr generator); + void setPrefixCodeGenerator(Ptr generator); bool hitBufferFull() const; private: - bool lookAheadSourceEmpty() const; + unsigned char getSearchBufferItem(unsigned index) const; unsigned lookAheadForMatchingChars(unsigned searchIndex); @@ -46,7 +46,7 @@ private: void populateSearchBuffer(const Hit& hit); unsigned mMaxHitBufferSize{32000}; - std::vector mHitBuffer; + Vector mHitBuffer; unsigned mSearchBufferSize{32000}; CircleBuffer mSearchBuffer; @@ -56,5 +56,5 @@ private: unsigned mMinLengthMatchSize{1}; CircleBuffer mLookaheadBuffer; - std::unique_ptr mCodeGenerator; + Ptr mCodeGenerator; }; diff --git a/src/base/compression/RunLengthEncoder.cpp b/src/base/compression/RunLengthEncoder.cpp index 88444d1..62526eb 100644 --- a/src/base/compression/RunLengthEncoder.cpp +++ b/src/base/compression/RunLengthEncoder.cpp @@ -1,8 +1,8 @@ #include "RunLengthEncoder.h" -std::vector RunLengthEncoder::encode(const std::vector& input) +Vector RunLengthEncoder::encode(const Vector& input) { - std::vector ret; + Vector ret; if (input.empty()) { return ret; @@ -34,9 +34,9 @@ std::vector RunLengthEncoder::encode(const std::vector RunLengthEncoder::decode(const std::vector& input) +Vector RunLengthEncoder::decode(const Vector& input) { - std::vector ret; + Vector ret; if (input.empty()) { return ret; diff --git a/src/base/compression/RunLengthEncoder.h b/src/base/compression/RunLengthEncoder.h index d8a7a95..9316169 100644 --- a/src/base/compression/RunLengthEncoder.h +++ b/src/base/compression/RunLengthEncoder.h @@ -1,15 +1,15 @@ #pragma once -#include +#include "Vector.h" class RunLengthEncoder { public: using Hit = std::pair; - std::vector encode(const std::vector& input); + Vector encode(const Vector& input); - std::vector decode(const std::vector& input); + Vector decode(const Vector& input); private: }; diff --git a/src/base/compression/ZlibEncoder.cpp b/src/base/compression/ZlibEncoder.cpp index 17af59e..64b7f81 100644 --- a/src/base/compression/ZlibEncoder.cpp +++ b/src/base/compression/ZlibEncoder.cpp @@ -1,6 +1,6 @@ #include "ZlibEncoder.h" -#include "ByteUtils.h" +#include "Bits.h" #include "DeflateEncoder.h" #include "FileLogger.h" #include "BitStream.h" @@ -27,7 +27,7 @@ void ZlibEncoder::setWindowSize(unsigned size) mWindowSize = size; } -std::string ZlibEncoder::toString(CompressionLevel level) const +String ZlibEncoder::toString(CompressionLevel level) const { switch(level) { @@ -44,7 +44,7 @@ std::string ZlibEncoder::toString(CompressionLevel level) const } } -std::string ZlibEncoder::toString(CompressionMethod method) const +String ZlibEncoder::toString(CompressionMethod method) const { return method == CompressionMethod::DEFLATE ? "DEFLATE" : "UNKNOWN"; } @@ -52,8 +52,8 @@ std::string ZlibEncoder::toString(CompressionMethod method) const void ZlibEncoder::parseCompressionMethod(unsigned char method) { //std::cout << "Got compression input " << static_cast(method) << std::endl; - mCompressionMethod = static_cast(ByteUtils::getLowerNBits(method, 4)); - auto compression_info = ByteUtils::getHigherNBits(method, 4); + mCompressionMethod = static_cast(Bits::getLowerNBits(method, 4)); + auto compression_info = Bits::getHigherNBits(method, 4); if (mCompressionMethod == CompressionMethod::DEFLATE) { @@ -71,14 +71,14 @@ void ZlibEncoder::parseExtraFlags(unsigned char extraFlags, unsigned char compre //std::cout << "Invalid header. Mod is " << mod << std::endl; } - mFlagCheck = ByteUtils::getLowerNBits(extraFlags, 5); - mUseDictionary = bool(ByteUtils::getBitN(extraFlags, 5)); - mFlagLevel = static_cast(ByteUtils::getHigherNBits(extraFlags, 2)); + mFlagCheck = Bits::getLowerNBits(extraFlags, 5); + mUseDictionary = bool(Bits::getBitN(extraFlags, 5)); + mFlagLevel = static_cast(Bits::getHigherNBits(extraFlags, 2)); } -std::string ZlibEncoder::getData() const +String ZlibEncoder::getData() const { - std::stringstream sstream; + Stringstream sstream; sstream << "ZlibEncoder data \n"; sstream << "Compression method: " << toString(mCompressionMethod) << '\n'; sstream << "Window size: " << mWindowSize << '\n'; diff --git a/src/base/compression/ZlibEncoder.h b/src/base/compression/ZlibEncoder.h index 931c382..bc1eab4 100644 --- a/src/base/compression/ZlibEncoder.h +++ b/src/base/compression/ZlibEncoder.h @@ -4,8 +4,8 @@ #include "DeflateElements.h" -#include -#include +#include "Pointer.h" +#include "Vector.h" class AbstractChecksumCalculator; @@ -38,9 +38,9 @@ public: bool encode() override; bool decode() override; - std::string getData() const; - std::string toString(CompressionLevel level) const; - std::string toString(CompressionMethod method) const; + String getData() const; + String toString(CompressionLevel level) const; + String toString(CompressionMethod method) const; private: void parseCompressionMethod(unsigned char method); @@ -54,6 +54,6 @@ private: bool mUseDictionary{false}; CompressionLevel mFlagLevel{CompressionLevel::DEFAULT}; - std::unique_ptr mChecksumCalculator; - std::unique_ptr mWorkingEncoder; + Ptr mChecksumCalculator; + Ptr mWorkingEncoder; }; diff --git a/src/base/compression/deflate/DeflateBlock.cpp b/src/base/compression/deflate/DeflateBlock.cpp index 6b2d4b2..dfe3892 100644 --- a/src/base/compression/deflate/DeflateBlock.cpp +++ b/src/base/compression/deflate/DeflateBlock.cpp @@ -1,6 +1,6 @@ #include "DeflateBlock.h" -#include "ByteUtils.h" +#include "Bits.h" #include "AbstractChecksumCalculator.h" #include @@ -14,9 +14,9 @@ DeflateBlock::DeflateBlock(BitStream* inputStream, BitStream* outputStream) } -std::string DeflateBlock::getMetaData() const +String DeflateBlock::getMetaData() const { - std::stringstream sstr; + Stringstream sstr; sstr << "DeflateBlock Metadata \n"; sstr << "Final block: " << mInFinalBlock << '\n'; @@ -72,16 +72,16 @@ bool DeflateBlock::readUncompressedStream() auto byte1 = *mInputStream->readNextByte(); mUncompressedBlockLength = (byte0 << 8) | byte1; - std::cout << "Check block 0: " << ByteUtils::toString(byte0) << std::endl; - std::cout << "Check block 1: " << ByteUtils::toString(byte1) << std::endl; + std::cout << "Check block 0: " << Bits::toString(byte0) << std::endl; + std::cout << "Check block 1: " << Bits::toString(byte1) << std::endl; auto byte2 = *mInputStream->readNextByte(); auto byte3 = *mInputStream->readNextByte(); uint16_t len_check = (byte2 << 8) | byte3; (void) len_check; - //std::cout << "Check block 2: " << ByteUtils::toString(byte2) << std::endl; - //std::cout << "Check block 3: " << ByteUtils::toString(byte3) << std::endl; + //std::cout << "Check block 2: " << Bits::toString(byte2) << std::endl; + //std::cout << "Check block 3: " << Bits::toString(byte3) << std::endl; //if (!(byte0 ==(~byte2) && byte1 ==(~byte3))) //{ //std::cout << "Uncompressed block length check failed - aborting." << std::endl; @@ -141,13 +141,13 @@ void DeflateBlock::write(uint16_t datalength) void DeflateBlock::writeUncompressedStream(unsigned char working_byte, uint16_t datalength) { - //std::cout << "Writing compression block header " << ByteUtils::toString(working_byte) << std::endl; + //std::cout << "Writing compression block header " << Bits::toString(working_byte) << std::endl; mOutputStream->writeByte(working_byte); - //std::cout << "Writing data length " << mUncompressedBlockLength << " " << ByteUtils::toString(mUncompressedBlockLength) << std::endl; + //std::cout << "Writing data length " << mUncompressedBlockLength << " " << Bits::toString(mUncompressedBlockLength) << std::endl; mOutputStream->writeWord(datalength); - //std::cout << "Writing iverse data length " << ~mUncompressedBlockLength << " " << ByteUtils::toString(~mUncompressedBlockLength) << std::endl; + //std::cout << "Writing iverse data length " << ~mUncompressedBlockLength << " " << Bits::toString(~mUncompressedBlockLength) << std::endl; mOutputStream->writeWord(static_cast(~mUncompressedBlockLength)); for(unsigned idx=0; idx +#include "Pointer.h" class AbstractChecksumCalculator; @@ -14,7 +14,7 @@ class DeflateBlock public: DeflateBlock(BitStream* inputStream, BitStream* outputStream); - std::string getMetaData() const; + String getMetaData() const; bool isFinalBlock() const; @@ -38,7 +38,7 @@ private: BitStream* mInputStream; BitStream* mOutputStream; - std::unique_ptr mHuffmanStream; + Ptr mHuffmanStream; uint16_t mUncompressedBlockLength{0}; bool mInFinalBlock{false}; diff --git a/src/base/compression/deflate/DeflateElements.h b/src/base/compression/deflate/DeflateElements.h index 9cbc146..fd0118a 100644 --- a/src/base/compression/deflate/DeflateElements.h +++ b/src/base/compression/deflate/DeflateElements.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "String.h" namespace Deflate { @@ -12,7 +12,7 @@ namespace Deflate ERROR }; - inline std::string toString(CompressionMethod method) + inline String toString(CompressionMethod method) { switch (method) { diff --git a/src/base/compression/deflate/DeflateEncoder.cpp b/src/base/compression/deflate/DeflateEncoder.cpp index 60ffdeb..3b61ebd 100644 --- a/src/base/compression/deflate/DeflateEncoder.cpp +++ b/src/base/compression/deflate/DeflateEncoder.cpp @@ -1,7 +1,7 @@ #include "DeflateEncoder.h" #include "BitStream.h" -#include "ByteUtils.h" +#include "Bits.h" #include "DeflateBlock.h" #include "BufferBitStream.h" @@ -22,7 +22,7 @@ bool DeflateEncoder::encode() { uint16_t count = 0; BufferBitStream stream; - std::unique_ptr working_block = std::make_unique(&stream, mOutputStream); + Ptr working_block = std::make_unique(&stream, mOutputStream); working_block->setCompressionMethod(mCompressionMethod); if (mChecksumCalculators.size() > 0) @@ -45,7 +45,7 @@ bool DeflateEncoder::encode() if (auto byte = mInputStream->readNextByte()) { - //std::cout << "Adding byte " << ByteUtils::toString(*byte) << " to deflate block input" << std::endl; + //std::cout << "Adding byte " << Bits::toString(*byte) << " to deflate block input" << std::endl; stream.writeByte(*byte); } else diff --git a/src/base/compression/deflate/DeflateEncoder.h b/src/base/compression/deflate/DeflateEncoder.h index 9d74cc0..eb5164f 100644 --- a/src/base/compression/deflate/DeflateEncoder.h +++ b/src/base/compression/deflate/DeflateEncoder.h @@ -3,8 +3,8 @@ #include "AbstractEncoder.h" #include "DeflateElements.h" -#include -#include +#include "Vector.h" +#include "Pointer.h" class DeflateBlock; @@ -27,7 +27,7 @@ public: private: uint16_t mMaxBlockSize{65535}; Deflate::CompressionMethod mCompressionMethod{Deflate::CompressionMethod::NONE}; - std::unique_ptr mLastBlock; + Ptr mLastBlock; }; diff --git a/src/base/compression/huffman/HuffmanCodeLengthTable.cpp b/src/base/compression/huffman/HuffmanCodeLengthTable.cpp index d2c3ef3..71298d4 100644 --- a/src/base/compression/huffman/HuffmanCodeLengthTable.cpp +++ b/src/base/compression/huffman/HuffmanCodeLengthTable.cpp @@ -1,6 +1,6 @@ #include "HuffmanCodeLengthTable.h" -#include "ByteUtils.h" +#include "Bits.h" #include "RunLengthEncoder.h" #include "BitStream.h" @@ -25,15 +25,15 @@ void HuffmanCodeLengthTable::buildCompressedLengthSequence() const auto count = entry.second; if (count < 3) { - for(std::size_t idx=0; idx(19, 0); + mCompressedLengthCounts = Vector(19, 0); for (const auto& entry : mCompressedLengthSequence) { mCompressedLengthCounts[entry.first]++; } } -const std::vector& HuffmanCodeLengthTable::getCompressedLengthSequence() const +const Vector& HuffmanCodeLengthTable::getCompressedLengthSequence() const { return mCompressedLengthSequence; } -const std::vector HuffmanCodeLengthTable::getCompressedLengthCounts() const +const Vector HuffmanCodeLengthTable::getCompressedLengthCounts() const { return mCompressedLengthCounts; } -std::optional HuffmanCodeLengthTable::getCodeForSymbol(unsigned symbol) const +Optional HuffmanCodeLengthTable::getCodeForSymbol(unsigned symbol) const { return mTree.getCode(symbol); } @@ -106,7 +106,7 @@ bool HuffmanCodeLengthTable::readNextSymbol(unsigned& result, BitStream* stream) return false; } - std::size_t working_index{0}; + size_t working_index{0}; auto length = getCodeLength(working_index); auto delta = length; @@ -118,11 +118,11 @@ bool HuffmanCodeLengthTable::readNextSymbol(unsigned& result, BitStream* stream) while(!found) { stream->readNextNBits(delta, buffer); - //std::cout << "Got buffer " << ByteUtils::toString(buffer) << std::endl;; + //std::cout << "Got buffer " << Bits::toString(buffer) << std::endl;; unsigned hold = buffer; working_bits = working_bits | (hold << (length - delta)); - //std::cout << "Read " << delta << " bits with length " << length << " and value " << ByteUtils::toString(working_bits) << std::endl; + //std::cout << "Read " << delta << " bits with length " << length << " and value " << Bits::toString(working_bits) << std::endl; if (const auto symbol = findMatch(working_index, working_bits)) { @@ -146,13 +146,13 @@ bool HuffmanCodeLengthTable::readNextSymbol(unsigned& result, BitStream* stream) if (found) { result = working_symbol; - // std::cout << "Found symbol " << working_symbol << " with bits " << ByteUtils::toString(working_bits) << std::endl; + // std::cout << "Found symbol " << working_symbol << " with bits " << Bits::toString(working_bits) << std::endl; // std::cout << "At Byte offset " << stream->getCurrentByteOffset() << " and bit offset " << stream->getCurrentBitOffset() << std::endl; return true; } else { - //std::cout << "SYMBOL NOT FOUND " << " with bits " << ByteUtils::toString(working_bits) << " and index " << working_index << std::endl; + //std::cout << "SYMBOL NOT FOUND " << " with bits " << Bits::toString(working_bits) << " and index " << working_index << std::endl; return false; } } @@ -165,7 +165,7 @@ void HuffmanCodeLengthTable::buildPrefixCodes() } unsigned char max_length = *std::max_element(mInputLengthSequence.begin(), mInputLengthSequence.end()); - std::vector counts(max_length+1, 0); + Vector counts(max_length+1, 0); for (const auto length : mInputLengthSequence) { counts[length]++; @@ -173,15 +173,15 @@ void HuffmanCodeLengthTable::buildPrefixCodes() counts[0] = 0; uint32_t code{0}; - std::vector next_code(max_length + 1, 0); + Vector next_code(max_length + 1, 0); for (unsigned bits = 1; bits <= max_length; bits++) { code = (code + counts[bits-1]) << 1; - //std::cout << "Start code for bit " << bits << " is " << ByteUtils::toString(code) << " | dec " << code << " count " << counts[bits-1] << std::endl; + //std::cout << "Start code for bit " << bits << " is " << Bits::toString(code) << " | dec " << code << " count " << counts[bits-1] << std::endl; next_code[bits] = code; } - for(std::size_t idx=0; idx= DEFLATE_PERMUTATION_SIZE) { @@ -218,29 +218,29 @@ std::size_t HuffmanCodeLengthTable::mapToDeflateIndex(std::size_t index) const } } -std::size_t HuffmanCodeLengthTable::getNumCodeLengths() const +size_t HuffmanCodeLengthTable::getNumCodeLengths() const { return mTree.getNumCodeLengths(); } -std::optional HuffmanCodeLengthTable::findMatch(std::size_t treeIndex, uint32_t code) const +Optional HuffmanCodeLengthTable::findMatch(size_t treeIndex, uint32_t code) const { return mTree.findMatch(treeIndex, code); } -unsigned HuffmanCodeLengthTable::getCodeLength(std::size_t index) const +unsigned HuffmanCodeLengthTable::getCodeLength(size_t index) const { return mTree.getCodeLength(index); } -void HuffmanCodeLengthTable::setInputLengthSequence(const std::vector& sequence, bool targetDeflate) +void HuffmanCodeLengthTable::setInputLengthSequence(const Vector& sequence, bool targetDeflate) { mTargetDeflate = targetDeflate; if (targetDeflate) { - mInputLengthSequence = std::vector(DEFLATE_PERMUTATION_SIZE, 0); - for(std::size_t idx=0; idx(DEFLATE_PERMUTATION_SIZE, 0); + for(size_t idx=0; idx(sequence[idx]) << std::endl; diff --git a/src/base/compression/huffman/HuffmanCodeLengthTable.h b/src/base/compression/huffman/HuffmanCodeLengthTable.h index 50a1226..4d89ca7 100644 --- a/src/base/compression/huffman/HuffmanCodeLengthTable.h +++ b/src/base/compression/huffman/HuffmanCodeLengthTable.h @@ -2,8 +2,8 @@ #include "HuffmanTree.h" -#include -#include +#include "Vector.h" +#include "String.h" #include class BitStream; @@ -15,28 +15,28 @@ public: void buildCompressedLengthSequence(); - std::string dumpPrefixCodes() const; + String dumpPrefixCodes() const; - std::optional findMatch(std::size_t treeIndex, uint32_t code) const; + Optional findMatch(size_t treeIndex, uint32_t code) const; const HuffmanTree& getTree() const; - const PrefixCode& getCode(std::size_t index) const; + const PrefixCode& getCode(size_t index) const; - std::optional getCodeForSymbol(unsigned symbol) const; + Optional getCodeForSymbol(unsigned symbol) const; using CompressedSequenceEntry = std::pair; - const std::vector& getCompressedLengthSequence() const; + const Vector& getCompressedLengthSequence() const; - const std::vector getCompressedLengthCounts() const; + const Vector getCompressedLengthCounts() const; - std::size_t getNumCodeLengths() const; + size_t getNumCodeLengths() const; - unsigned getCodeLength(std::size_t treeIndex) const; + unsigned getCodeLength(size_t treeIndex) const; - std::size_t mapToDeflateIndex(std::size_t index) const; + size_t mapToDeflateIndex(size_t index) const; - void setInputLengthSequence(const std::vector& sequence, bool targetDeflate = true); + void setInputLengthSequence(const Vector& sequence, bool targetDeflate = true); bool readNextSymbol(unsigned& buffer, BitStream* stream); @@ -45,11 +45,11 @@ private: HuffmanTree mTree; bool mTargetDeflate{true}; - std::vector mInputLengthSequence; - std::vector mCodes; + Vector mInputLengthSequence; + Vector mCodes; - std::vector mCompressedLengthSequence; - std::vector mCompressedLengthCounts; + Vector mCompressedLengthSequence; + Vector mCompressedLengthCounts; static constexpr unsigned DEFLATE_PERMUTATION_SIZE{19}; static constexpr unsigned DEFLATE_PERMUTATION[DEFLATE_PERMUTATION_SIZE]{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; diff --git a/src/base/compression/huffman/HuffmanEncoder.cpp b/src/base/compression/huffman/HuffmanEncoder.cpp index 6c154ec..c458582 100644 --- a/src/base/compression/huffman/HuffmanEncoder.cpp +++ b/src/base/compression/huffman/HuffmanEncoder.cpp @@ -4,7 +4,7 @@ #include "HuffmanFixedCodes.h" -#include +#include Map.h #include #include #include @@ -19,7 +19,7 @@ void HuffmanEncoder::dumpNode(RawNode* node, unsigned depth) const auto data = node->getData(); (void)data; - std::string prefix(depth, '_'); + String prefix(depth, '_'); if (node->isLeaf()) { @@ -43,14 +43,14 @@ void HuffmanEncoder::dumpTree(const RawTree& tree) const dumpNode(tree.getRootNode(), 0); } -void HuffmanEncoder::encode(const std::vector& counts) +void HuffmanEncoder::encode(const Vector& counts) { auto cmp = [](RawNode* left, RawNode* right) { return left->getData().second > right->getData().second; }; - std::priority_queue*, std::vector* >, decltype(cmp)> q(cmp); + std::priority_queue*, Vector* >, decltype(cmp)> q(cmp); unsigned offset{0}; for (auto count : counts) { @@ -90,9 +90,9 @@ void HuffmanEncoder::encode(const std::vector& counts) //std::cout << "********" << std::endl; } -void HuffmanEncoder::encode(const std::unordered_map& counts) +void HuffmanEncoder::encode(const Map& counts) { - std::vector just_counts; + Vector just_counts; for (const auto& data: counts) { mSymbolMapping.push_back(data.first); @@ -112,32 +112,32 @@ uint32_t HuffmanEncoder::getLengthValue(unsigned) return 0; } -std::optional HuffmanEncoder::getLiteralValue(unsigned char value) const +Optional HuffmanEncoder::getLiteralValue(unsigned char value) const { return mLiteralLengthTable.getCodeForSymbol(value); } -std::optional HuffmanEncoder::getLengthValue(unsigned length) const +Optional HuffmanEncoder::getLengthValue(unsigned length) const { return mLiteralLengthTable.getCodeForSymbol(length); } -std::optional HuffmanEncoder::getDistanceValue(unsigned distance) const +Optional HuffmanEncoder::getDistanceValue(unsigned distance) const { return mDistanceTable.getCodeForSymbol(distance); } -std::optional HuffmanEncoder::getEndOfStreamValue() const +Optional HuffmanEncoder::getEndOfStreamValue() const { return mLiteralLengthTable.getCodeForSymbol(256); } -void HuffmanEncoder::initializeTrees(const std::vector& hits) +void HuffmanEncoder::initializeTrees(const Vector& hits) { initializeLiteralLengthTable(hits); } -void HuffmanEncoder::initializeLiteralLengthTable(const std::vector& hits) +void HuffmanEncoder::initializeLiteralLengthTable(const Vector& hits) { if(mUseFixedCode) { @@ -146,7 +146,7 @@ void HuffmanEncoder::initializeLiteralLengthTable(const std::vector& hits) return; } - std::vector counts(285, 0); + Vector counts(285, 0); counts[256] = 1; for (const auto& hit : hits) { diff --git a/src/base/compression/huffman/HuffmanEncoder.h b/src/base/compression/huffman/HuffmanEncoder.h index a723f13..b3b6cf9 100644 --- a/src/base/compression/huffman/HuffmanEncoder.h +++ b/src/base/compression/huffman/HuffmanEncoder.h @@ -5,19 +5,19 @@ #include "HuffmanCodeLengthTable.h" #include "HuffmanFixedCodes.h" -#include +#include "Vector.h" #include -#include +#include Map.h class PrefixCodeGenerator { public: virtual ~PrefixCodeGenerator() = default; - virtual std::optional getLiteralValue(unsigned char symbol) const = 0; - virtual std::optional getLengthValue(unsigned length) const = 0; - virtual std::optional getDistanceValue(unsigned distance) const = 0; + virtual Optional getLiteralValue(unsigned char symbol) const = 0; + virtual Optional getLengthValue(unsigned length) const = 0; + virtual Optional getDistanceValue(unsigned distance) const = 0; - virtual std::optional getEndOfStreamValue() const = 0; + virtual Optional getEndOfStreamValue() const = 0; }; class HuffmanEncoder : public PrefixCodeGenerator @@ -26,31 +26,31 @@ class HuffmanEncoder : public PrefixCodeGenerator using Hit = std::tuple; public: - void encode(const std::vector& counts); - void encode(const std::unordered_map& counts); + void encode(const Vector& counts); + void encode(const Map& counts); uint32_t getLengthValue(unsigned length); - std::optional getLiteralValue(unsigned char symbol) const override; + Optional getLiteralValue(unsigned char symbol) const override; - std::optional getLengthValue(unsigned length) const override; + Optional getLengthValue(unsigned length) const override; - std::optional getDistanceValue(unsigned distance) const override; + Optional getDistanceValue(unsigned distance) const override; - std::optional getEndOfStreamValue() const override; + Optional getEndOfStreamValue() const override; - void initializeTrees(const std::vector& hits); + void initializeTrees(const Vector& hits); void setUseFixedCode(bool useFixed); private: - void initializeLiteralLengthTable(const std::vector& hits); + void initializeLiteralLengthTable(const Vector& hits); void dumpTree(const RawTree& tree) const; void dumpNode(RawNode* node, unsigned depth) const; bool mUseFixedCode{false}; - std::vector mSymbolMapping; + Vector mSymbolMapping; HuffmanCodeLengthTable mLiteralLengthTable; HuffmanCodeLengthTable mDistanceTable; }; diff --git a/src/base/compression/huffman/HuffmanFixedCodes.h b/src/base/compression/huffman/HuffmanFixedCodes.h index f3b89fe..e3ce929 100644 --- a/src/base/compression/huffman/HuffmanFixedCodes.h +++ b/src/base/compression/huffman/HuffmanFixedCodes.h @@ -1,14 +1,14 @@ #pragma once -#include +#include "Vector.h" #include namespace HuffmanFixedCodes { - inline std::vector getDeflateFixedHuffmanCodes() + inline Vector getDeflateFixedHuffmanCodes() { - std::vector > mappings {{144, 8}, {112, 9}, {24, 7}, {8 ,8}}; - std::vector sequence; + Vector > mappings {{144, 8}, {112, 9}, {24, 7}, {8 ,8}}; + Vector sequence; for(const auto& entry : mappings) { for(unsigned idx=0;idx #include -#include +#include Map.h #include -std::vector DISTANCE_OFFSETS +Vector DISTANCE_OFFSETS { 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 258, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, @@ -77,7 +77,7 @@ bool HuffmanStream::readNextDistanceSymbol(unsigned& buffer) return true; } -void HuffmanStream::addValue(unsigned value, unsigned& count, unsigned& lastValue, std::vector& literals, unsigned, std::vector& distances) +void HuffmanStream::addValue(unsigned value, unsigned& count, unsigned& lastValue, Vector& literals, unsigned, Vector& distances) { if (count < mNumLiterals) { @@ -93,8 +93,8 @@ void HuffmanStream::addValue(unsigned value, unsigned& count, unsigned& lastValu void HuffmanStream::readCodeLengths() { - std::vector literal_lengths(288, 0); - std::vector distance_lengths(32, 0); + Vector literal_lengths(288, 0); + Vector distance_lengths(32, 0); unsigned symbol{0}; unsigned count{0}; @@ -172,7 +172,7 @@ void HuffmanStream::readCodeLengths() void HuffmanStream::copyFromBuffer(unsigned length, unsigned distance) { - std::size_t offset = mBuffer.size() - 1 - distance; + size_t offset = mBuffer.size() - 1 - distance; for(unsigned idx=0; idx(num_code_lengths, 0); + auto sequence = Vector(num_code_lengths, 0); unsigned char buffer{0}; for(unsigned idx = 0; idx< num_code_lengths; idx++) { mInputStream->readNextNBits(3, buffer); - //std::cout << "Got coding table value " << idx << " | " << static_cast(buffer) << " | " << ByteUtils::toString(buffer) << std::endl; + //std::cout << "Got coding table value " << idx << " | " << static_cast(buffer) << " | " << Bits::toString(buffer) << std::endl; sequence[idx] = buffer; } diff --git a/src/base/compression/huffman/HuffmanStream.h b/src/base/compression/huffman/HuffmanStream.h index d636493..7dc4a99 100644 --- a/src/base/compression/huffman/HuffmanStream.h +++ b/src/base/compression/huffman/HuffmanStream.h @@ -3,8 +3,8 @@ #include "BitStream.h" #include "HuffmanCodeLengthTable.h" -#include -#include +#include "Vector.h" +#include "String.h" class HuffmanStream @@ -17,7 +17,7 @@ public: void generateFixedCodeMapping(); - void setCodeLengthAlphabetLengths(const std::vector& lengths); + void setCodeLengthAlphabetLengths(const Vector& lengths); private: void readCodingsTable(); @@ -34,12 +34,12 @@ private: bool readNextCodeLengthSymbol(unsigned& buffer); - void addValue(unsigned value, unsigned& count, unsigned& lastValue, std::vector& literals, unsigned numLiterals, std::vector& distances); + void addValue(unsigned value, unsigned& count, unsigned& lastValue, Vector& literals, unsigned numLiterals, Vector& distances); BitStream* mInputStream; BitStream* mOutputStream; - std::vector mBuffer; + Vector mBuffer; unsigned mNumLiterals{0}; // HLIT + 257 unsigned mNumDistances{0}; // HDIST + 1 diff --git a/src/base/compression/huffman/HuffmanTree.cpp b/src/base/compression/huffman/HuffmanTree.cpp index bde4878..21842e5 100644 --- a/src/base/compression/huffman/HuffmanTree.cpp +++ b/src/base/compression/huffman/HuffmanTree.cpp @@ -1,6 +1,6 @@ #include "HuffmanTree.h" -#include "ByteUtils.h" +#include "Bits.h" #include #include @@ -9,7 +9,7 @@ PrefixCode::PrefixCode(uint32_t data, unsigned length) : mLength(length) { - mData = ByteUtils::mirror(data, length); + mData = Bits::mirror(data, length); } bool PrefixCode::matches(unsigned length, uint32_t code) const @@ -17,28 +17,28 @@ bool PrefixCode::matches(unsigned length, uint32_t code) const return (mLength == length) && (mData == code); } -std::string PrefixCode::toString(bool bitsAsRightToLeft) const +String PrefixCode::toString(bool bitsAsRightToLeft) const { if (bitsAsRightToLeft) { if (mLength <=8 ) { - return ByteUtils::toString(mData).substr(8 - mLength, mLength); + return Bits::toString(mData).substr(8 - mLength, mLength); } else { - return ByteUtils::toString(mData, mLength); + return Bits::toString(mData, mLength); } } else { if (mLength <=8 ) { - return ByteUtils::toString(ByteUtils::mirror(mData, mLength)).substr(0, mLength); + return Bits::toString(Bits::mirror(mData, mLength)).substr(0, mLength); } else { - return ByteUtils::toString(mData, mLength); + return Bits::toString(mData, mLength); } } } @@ -67,12 +67,12 @@ void HuffmanTree::sortTable() std::sort(mTable.begin(), mTable.end(), [](CodeLengthData a, CodeLengthData b){return a.first < b.first;}); } -std::optional HuffmanTree::findMatch(std::size_t treeIndex, uint32_t code) const +Optional HuffmanTree::findMatch(size_t treeIndex, uint32_t code) const { const auto& legth_data = mTable[treeIndex]; for(const auto& entry : legth_data.second) { - //std::cout << "Checking if " << entry.second << " matches code " << ByteUtils::toString(code) << std::endl;; + //std::cout << "Checking if " << entry.second << " matches code " << Bits::toString(code) << std::endl;; if (entry.first.matches(legth_data.first, code)) { return entry.second; @@ -81,7 +81,7 @@ std::optional HuffmanTree::findMatch(std::size_t treeIndex, return std::nullopt; } -std::optional HuffmanTree::getCode(Symbol symbol) const +Optional HuffmanTree::getCode(Symbol symbol) const { for(const auto& entry : mTable) { @@ -96,19 +96,19 @@ std::optional HuffmanTree::getCode(Symbol symbol) const return std::nullopt; } -std::size_t HuffmanTree::getNumCodeLengths() const +size_t HuffmanTree::getNumCodeLengths() const { return mTable.size(); } -unsigned HuffmanTree::getCodeLength(std::size_t idx) const +unsigned HuffmanTree::getCodeLength(size_t idx) const { return mTable[idx].first; } -std::string HuffmanTree::dump(bool bitsAsRightToLeft) const +String HuffmanTree::dump(bool bitsAsRightToLeft) const { - std::stringstream sstr; + Stringstream sstr; for (const auto& code_length_data : mTable) { sstr << "Prefix table for Code Length " << code_length_data.first << " has vals: \n"; diff --git a/src/base/compression/huffman/HuffmanTree.h b/src/base/compression/huffman/HuffmanTree.h index cf5fef7..36ac994 100644 --- a/src/base/compression/huffman/HuffmanTree.h +++ b/src/base/compression/huffman/HuffmanTree.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Vector.h" +#include "String.h" #include #include @@ -10,7 +10,7 @@ class PrefixCode public: PrefixCode(uint32_t data, unsigned length); - std::string toString(bool bitsAsRightToLeft = true) const; + String toString(bool bitsAsRightToLeft = true) const; bool matches(unsigned length, uint32_t code) const; @@ -35,21 +35,21 @@ public: using Symbol = unsigned; using CodeLength = unsigned; using CodeSymbolPair = std::pair; - using CodeLengthData = std::pair >; + using CodeLengthData = std::pair >; void addCodeLengthEntry(unsigned length, const CodeSymbolPair& data); - std::string dump(bool bitsAsRightToLeft = true) const; + String dump(bool bitsAsRightToLeft = true) const; - std::optional findMatch(std::size_t treeIndex, uint32_t code) const; + Optional findMatch(size_t treeIndex, uint32_t code) const; - std::size_t getNumCodeLengths() const; + size_t getNumCodeLengths() const; - unsigned getCodeLength(std::size_t idx) const; + unsigned getCodeLength(size_t idx) const; - std::optional getCode(Symbol symbol) const; + Optional getCode(Symbol symbol) const; void sortTable(); private: - std::vector mTable; + Vector mTable; }; diff --git a/src/base/core/CMakeLists.txt b/src/base/core/CMakeLists.txt deleted file mode 100644 index d3c607d..0000000 --- a/src/base/core/CMakeLists.txt +++ /dev/null @@ -1,90 +0,0 @@ -set(MODULE_NAME core) - -list(APPEND HEADERS - AbstractApp.h - AbstractNamedItem.h - AbstractWebApp.h - Dictionary.h - Event.h - Color.h - CommandLineArgs.h - data_structures/RawTree.h - data_structures/List.h - data_structures/Tree.h - encoding/ByteUtils.h - encoding/StringUtils.h - encoding/UnicodeUtils.h - loggers/FileLogger.h - file_utilities/Directory.h - file_utilities/File.h - file_utilities/FileFormats.h - file_utilities/PathUtils.h - http/HttpResponse.h - http/HttpHeader.h - http/HttpRequest.h - http/HttpParser.h - http/HttpPreamble.h - serializers/TomlReader.h - Win32BaseIncludes.h - ThreadCollection.h - xml/XmlParser.h - xml/XmlDocument.h - xml/XmlWriter.h - xml/xml-elements/XmlElement.h - xml/xml-elements/XmlAttribute.h - xml/xml-elements/XmlProlog.h -) - -list(APPEND SOURCES - Event.cpp - Dictionary.cpp - Color.cpp - CommandLineArgs.cpp - data_structures/RawTree.cpp - data_structures/Tree.cpp - loggers/FileLogger.cpp - file_utilities/Directory.cpp - file_utilities/File.cpp - file_utilities/FileFormats.cpp - file_utilities/PathUtils.cpp - memory/SharedMemory.cpp - RandomUtils.cpp - encoding/StringUtils.cpp - encoding/ByteUtils.cpp - encoding/UnicodeUtils.cpp - streams/BinaryStream.cpp - streams/BitStream.cpp - streams/InputBitStream.cpp - streams/OutputBitStream.cpp - streams/BufferBitStream.cpp - http/HttpResponse.cpp - http/HttpHeader.cpp - http/HttpRequest.cpp - http/HttpParser.cpp - serializers/TomlReader.cpp - ThreadCollection.cpp - xml/XmlParser.cpp - xml/XmlDocument.cpp - xml/XmlWriter.cpp - xml/xml-elements/XmlElement.cpp - xml/xml-elements/XmlAttribute.cpp - xml/xml-elements/XmlProlog.cpp - ) - -add_library(${MODULE_NAME} SHARED ${SOURCES} ${HEADERS}) - -target_include_directories(${MODULE_NAME} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/encoding - ${CMAKE_CURRENT_SOURCE_DIR}/file_utilities - ${CMAKE_CURRENT_SOURCE_DIR}/loggers - ${CMAKE_CURRENT_SOURCE_DIR}/memory - ${CMAKE_CURRENT_SOURCE_DIR}/streams - ${CMAKE_CURRENT_SOURCE_DIR}/http - ${CMAKE_CURRENT_SOURCE_DIR}/data_structures - ${CMAKE_CURRENT_SOURCE_DIR}/serializers - ${CMAKE_CURRENT_SOURCE_DIR}/xml - ${CMAKE_CURRENT_SOURCE_DIR}/xml/xml-elements - ) -set_target_properties( ${MODULE_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON ) -set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src/base) \ No newline at end of file diff --git a/src/base/core/Color.cpp b/src/base/core/Color.cpp deleted file mode 100644 index 2fd35da..0000000 --- a/src/base/core/Color.cpp +++ /dev/null @@ -1,75 +0,0 @@ -#include "Color.h" - -Color::Color(unsigned char r, unsigned char g, unsigned char b, double a) - : mR(r), - mG(g), - mB(b), - mAlpha(a) -{ - -} - -Color::Color(const std::string& hexString) -{ - if (hexString.size() < 7) - { - return; - } - if (hexString[0] != '#') - { - return; - } - mR = toDecimal(hexString.substr(1, 2)); - mG = toDecimal(hexString.substr(3, 2)); - mB = toDecimal(hexString.substr(5, 2)); -} - -unsigned char Color::toDecimal(const std::string& hex) const -{ - return static_cast(std::stoul("0x" + hex, nullptr, 16)); -} - -std::unique_ptr Color::Create(unsigned char r, unsigned char g, unsigned char b, double a ) -{ - return std::make_unique(r, g, b, a); -} - -std::unique_ptr Color::Create(const Color& color) -{ - return std::make_unique(color); -} - -unsigned char Color::getR() const -{ - return mR; -} - -unsigned char Color::getG() const -{ - return mG; -} - -unsigned char Color::getB() const -{ - return mB; -} - -double Color::getAlpha() const -{ - return mAlpha; -} - -std::vector Color::getAsVectorDouble() const -{ - return { mR / 255.0, mG / 255.0, mB / 255.0, mAlpha }; -} - -uint32_t Color::getAsUInt32() const -{ - return static_cast(mB + (mG << 8) + (mR << 16)); -} - -std::string Color::toString() const -{ - return std::to_string(static_cast(mR)) + "," + std::to_string(static_cast(mG)) + "," + std::to_string(static_cast(mB)); -} \ No newline at end of file diff --git a/src/base/core/Color.h b/src/base/core/Color.h deleted file mode 100644 index ea70540..0000000 --- a/src/base/core/Color.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#include -#include -#include - -class Color -{ -public: - - Color(const std::string& hexString); - Color(unsigned char r = 0, unsigned char g = 0, unsigned char b = 0, double a = 1.0); - - static std::unique_ptr Create(unsigned char r, unsigned char g, unsigned char b, double a = 1.0); - static std::unique_ptr Create(const Color& color); - - unsigned char getR() const; - unsigned char getG() const; - unsigned char getB() const; - double getAlpha() const; - - std::vector getAsVectorDouble() const; - - uint32_t getAsUInt32() const; - - std::string toString() const; - - void setAlpha(float alpha) - { - mAlpha = static_cast(alpha); - } - - bool operator==(const Color& rhs) const - { - return (mR == rhs.mR) - && (mG == rhs.mG) - && (mB == rhs.mB) - && (mAlpha == rhs.mAlpha); - } - - bool operator!=(const Color& rhs) const - { - return !operator==(rhs); - } - -private: - unsigned char toDecimal(const std::string& hex) const; - - unsigned char mR{0}; - unsigned char mG{0}; - unsigned char mB{0}; - double mAlpha{0.0}; -}; - -using ColorPtr = std::shared_ptr; -using ColorUPtr = std::unique_ptr; diff --git a/src/base/core/CommandLineArgs.h b/src/base/core/CommandLineArgs.h deleted file mode 100644 index 9a39346..0000000 --- a/src/base/core/CommandLineArgs.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -class CommandLineArgs -{ -public: - CommandLineArgs(); - - static std::unique_ptr Create(); - - std::filesystem::path getLaunchPath(); - - const std::vector getArgs() const; - - std::vector getUserArgs() const; - - static void initialize(CommandLineArgs* args); - - void process(int argc, char *argv[]); - - void process(const std::vector& args); - - void recordLaunchPath(); -private: - std::vector mArugments; - std::filesystem::path mLaunchPath; -}; - -using CommandLineArgsUPtr = std::unique_ptr; diff --git a/src/base/core/Dictionary.cpp b/src/base/core/Dictionary.cpp deleted file mode 100644 index 4268458..0000000 --- a/src/base/core/Dictionary.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "Dictionary.h" - -bool Dictionary::hasKey(const std::string& key) const -{ - return hasStringKey(key) || hasDictKey(key); -} - -bool Dictionary::hasStringKey(const std::string& key) const -{ - return mStringData.count(key) > 0; -} - -bool Dictionary::hasDictKey(const std::string& key) const -{ - return mDictData.count(key) > 0; -} - -std::vector Dictionary::getStringKeys() const -{ - std::vector keys; - for (const auto& item : mStringData) - { - keys.push_back(item.first); - } - return keys; -} - -std::vector Dictionary::getDictKeys() const -{ - std::vector keys; - for (const auto& item : mDictData) - { - keys.push_back(item.first); - } - return keys; -} - -Dictionary* Dictionary::getDict(const std::string& key) const -{ - return mDictData.at(key).get(); -} - -std::string Dictionary::getItem(const std::string& key) const -{ - return mStringData.at(key); -} - -void Dictionary::addStringItem(const std::string& key, const std::string& item) -{ - mStringData[key] = item; -} - -void Dictionary::addDictItem(const std::string& key, std::unique_ptr dict) -{ - mDictData[key] = std::move(dict); -} diff --git a/src/base/core/Dictionary.h b/src/base/core/Dictionary.h deleted file mode 100644 index c26468e..0000000 --- a/src/base/core/Dictionary.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once -#include -#include -#include -#include - -class Dictionary -{ -public: - Dictionary() = default; - virtual ~Dictionary() = default; - - void addStringItem(const std::string& key, const std::string& item); - - void addDictItem(const std::string& key, std::unique_ptr dict); - - Dictionary* getDict(const std::string& key) const; - - std::vector getDictKeys() const; - - std::vector getStringKeys() const; - - std::string getItem(const std::string& key) const; - - bool hasKey(const std::string& key) const; - - bool hasStringKey(const std::string& key) const; - - bool hasDictKey(const std::string& key) const; -protected: - - std::map mStringData; - std::map > mDictData; -}; diff --git a/src/base/core/RandomUtils.h b/src/base/core/RandomUtils.h deleted file mode 100644 index 062bd34..0000000 --- a/src/base/core/RandomUtils.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -class RandomUtils -{ -public: - - static std::vector getRandomVecUnsigned(std::size_t size); -}; diff --git a/src/base/core/base_types/Byte.h b/src/base/core/base_types/Byte.h new file mode 100644 index 0000000..b739fbd --- /dev/null +++ b/src/base/core/base_types/Byte.h @@ -0,0 +1,12 @@ +#pragma once + +#include "Vector.h" + +#include + +using Byte = uint8_t; +using VecBytes = Vector; + +using Word = uint16_t; +using DWord = uint32_t; +using QWord = uint64_t; \ No newline at end of file diff --git a/src/base/core/base_types/Char.cpp b/src/base/core/base_types/Char.cpp new file mode 100644 index 0000000..61a23e9 --- /dev/null +++ b/src/base/core/base_types/Char.cpp @@ -0,0 +1,47 @@ +#include "Char.h" + +bool Char::is_alpha_upper(char c) +{ + const auto unsigned_c = static_cast(c); + return unsigned_c >= 65 && unsigned_c <= 90; +} + +bool Char::is_alpha_lower(char c) +{ + const auto unsigned_c = static_cast(c); + return unsigned_c >= 97 && unsigned_c <= 122; +} + +bool Char::is_alpha(char c) +{ + return is_alpha_upper(c) || is_alpha_lower(c); +} + +bool Char::is_alnum(char c) +{ + return is_alpha(c) || is_digit(c); +} + +bool Char::is_digit(char c) +{ + const auto unsigned_c = static_cast(c); + return unsigned_c >= 48 && unsigned_c <= 57; +} + +bool Char::is_space(char c) +{ + return c == ' ' || c == '\f' || c == '\n' + || c == '\r' || c == '\t' || c == '\v'; +} + +char Char::to_lower(char c) +{ + if (is_alpha_upper(c)) + { + return c + 32; + } + else + { + return c; + } +} \ No newline at end of file diff --git a/src/base/core/base_types/Char.h b/src/base/core/base_types/Char.h new file mode 100644 index 0000000..d7d4215 --- /dev/null +++ b/src/base/core/base_types/Char.h @@ -0,0 +1,29 @@ +#pragma once + +class Char +{ +public: + static constexpr char LEFT_BRACKET = '<'; + static constexpr char RIGHT_BRACKET = '>'; + static constexpr char FORWARD_SLASH = '/'; + static constexpr char BACK_SLASH = '\\'; + static constexpr char QUESTION_MARK = '?'; + static constexpr char EQUALS = '='; + static constexpr char DOUBLE_QUOTE = '"'; + static constexpr char SINGLE_QUOTE = '\''; + static constexpr char COLON = ':'; + + static bool is_alpha_upper(char c); + + static bool is_alpha_lower(char c); + + static bool is_alpha(char c); + + static bool is_alnum(char c); + + static bool is_digit(char c); + + static bool is_space(char c); + + static char to_lower(char c); +}; \ No newline at end of file diff --git a/src/base/core/base_types/Color.cpp b/src/base/core/base_types/Color.cpp new file mode 100644 index 0000000..b50d3fc --- /dev/null +++ b/src/base/core/base_types/Color.cpp @@ -0,0 +1,147 @@ +#include "Color.h" + +Color::Color(unsigned char r, unsigned char g, unsigned char b, double a) + : mR(r), + mG(g), + mB(b), + mAlpha(a) +{ + +} + +Color::Color(const String& hexString) +{ + if (hexString.size() < 7) + { + return; + } + if (hexString[0] != '#') + { + return; + } + /* + mR = toDecimal(hexString.substr(1, 2)); + mG = toDecimal(hexString.substr(3, 2)); + mB = toDecimal(hexString.substr(5, 2)); + */ +} + +unsigned char Color::toDecimal(const String& hex) const +{ + //return static_cast(std::stoul("0x" + hex, nullptr, 16)); + return 0; +} + +Ptr Color::Create(unsigned char r, unsigned char g, unsigned char b, double a ) +{ + //return Ptr::create(r, g, b, a); + return {}; +} + +size_t Color::getSize() const +{ + return getSize(mFormat, mBitDepth); +} + +size_t Color::getSize(Format format, unsigned bitDepth) +{ + return getNumChannels(format) * bitDepth / 8; +} + +size_t Color::getNumChannels(Format format) +{ + if (format == Format::GRAYSCALE || format == Format::LUT) + { + return 1; + } + else + { + return 4; + } +} + +uint8_t Color::getByte(size_t index) const +{ + if (mFormat == Format::GRAYSCALE || mFormat == Format::LUT) + { + return mValue; + } + else if (mFormat == Format::ARGB) + { + switch(index) + { + case 0: + return mAlpha * 255; + case 1: + return mR; + case 2: + return mG; + case 3: + return mB; + default: + return mR; + } + } + else + { + switch(index) + { + case 0: + return mR; + case 1: + return mG; + case 2: + return mB; + case 3: + return mAlpha * 255; + default: + return mR; + } + } +} + +void Color::setAlpha(float alpha) +{ + mAlpha = static_cast(alpha); +} + +Ptr Color::Create(const Color& color) +{ + return Ptr::create(color); +} + +unsigned char Color::getR() const +{ + return mR; +} + +unsigned char Color::getG() const +{ + return mG; +} + +unsigned char Color::getB() const +{ + return mB; +} + +double Color::getAlpha() const +{ + return mAlpha; +} + +Vector Color::getAsVectorDouble() const +{ + //return { mR / 255.0, mG / 255.0, mB / 255.0, mAlpha }; + return {}; +} + +uint32_t Color::getAsUInt32() const +{ + return static_cast(mB + (mG << 8) + (mR << 16)); +} + +String Color::toString() const +{ + return String::to_string(static_cast(mR)) + "," + String::to_string(static_cast(mG)) + "," + String::to_string(static_cast(mB)); +} \ No newline at end of file diff --git a/src/base/core/base_types/Color.h b/src/base/core/base_types/Color.h new file mode 100644 index 0000000..9c76a43 --- /dev/null +++ b/src/base/core/base_types/Color.h @@ -0,0 +1,70 @@ +#pragma once + +#include "Pointer.h" +#include "Vector.h" +#include "String.h" + +class Color +{ +public: + enum class Format + { + GRAYSCALE, + GRAYSCALE_ALPHA, + LUT, + RGB, + ARGB, + RGBA + }; + + Color(const String& hexString); + Color(unsigned char r = 0, unsigned char g = 0, unsigned char b = 0, double a = 1.0); + + static Ptr Create(unsigned char r, unsigned char g, unsigned char b, double a = 1.0); + static Ptr Create(const Color& color); + + unsigned char getR() const; + unsigned char getG() const; + unsigned char getB() const; + double getAlpha() const; + + Vector getAsVectorDouble() const; + + uint32_t getAsUInt32() const; + + String toString() const; + + size_t getSize() const; + + static size_t getNumChannels(Format format); + + static size_t getSize(Format format, unsigned bitDepth); + + uint8_t getByte(size_t index) const; + + void setAlpha(float alpha); + + bool operator==(const Color& rhs) const + { + return (mR == rhs.mR) + && (mG == rhs.mG) + && (mB == rhs.mB) + && (mAlpha == rhs.mAlpha); + } + + bool operator!=(const Color& rhs) const + { + return !operator==(rhs); + } + +private: + unsigned char toDecimal(const String& hex) const; + + unsigned char mR{0}; + unsigned char mG{0}; + unsigned char mB{0}; + unsigned char mValue{0}; + double mAlpha{0.0}; + unsigned mBitDepth{8}; + Format mFormat{Format::RGBA}; +}; diff --git a/src/base/core/base_types/Error.cpp b/src/base/core/base_types/Error.cpp new file mode 100644 index 0000000..b0f7949 --- /dev/null +++ b/src/base/core/base_types/Error.cpp @@ -0,0 +1,62 @@ +#include "Error.h" + +#include +#include + +Error::Error(const String& msg) + : m_message(msg) +{ +} + +const String& Error::msg() const +{ + return m_message; +} + +String Error::from_errno() +{ + return ::strerror(errno); +} + +Status::Status(const Error& err) + : m_error(err), + m_ok(false) +{ + +} + +Status Status::with_errno(const String& prefix_msg) +{ + Status ret; + ret.on_errno(prefix_msg); + return ret; +} + +void Status::on_errno(const String& prefix_msg) +{ + String errno_msg(::strerror(errno)); + m_error = Error(prefix_msg + " | " + errno_msg); + m_ok = false; +} + +const Error& Status::error() const +{ + return m_error; +} + +bool Status::ok() const +{ + return m_ok; +} + +String Status::str() const +{ + if (!m_ok) + { + return m_error.msg(); + } + else + { + return {}; + } +} \ No newline at end of file diff --git a/src/base/core/base_types/Error.h b/src/base/core/base_types/Error.h new file mode 100644 index 0000000..5e5b49d --- /dev/null +++ b/src/base/core/base_types/Error.h @@ -0,0 +1,64 @@ +#pragma once + +#include "String.h" + +#define IF_OK_AND_TRUE(PRED) \ + const auto _result = PRED; \ + if (!_result.ok()){return Status(_result.error());} \ + if (_result.value()) + +#define ERROR_IF_NOT_OK_OR_TRUE(PRED, msg) \ + {const auto _result = PRED; \ + if (!_result.ok()){return {_result.error()};} \ + if (!_result.value()){return {Error(msg)};}} + +#define ON_ERRNO(msg) \ + {Status _status; \ + _status.on_errno("Failed to get directory content in opendir"); \ + return _status;} \ + +#define ON_ERRNO_RESULT(msg) \ + return {Error(_s(msg) + " | " + Error::from_errno())}; + +#define STATUS_CHECK(PRED, error_msg) \ + {const auto _status = PRED; \ + if (!_status.ok()){ \ + const auto message = _s(error_msg) + "|" + _status.error().msg(); \ + return Status(Error(message)); \ + }} + +class Error +{ +public: + Error(const String& msg); + + Error() = default; + + const String& msg() const; + + static String from_errno(); +private: + String m_message; +}; + +class Status +{ +public: + Status() = default; + + Status(const Error& err); + + const Error& error() const; + + static Status with_errno(const String& prefix_msg); + + void on_errno(const String& prefix_msg); + + bool ok() const; + + String str() const; + +private: + Error m_error; + bool m_ok{true}; +}; \ No newline at end of file diff --git a/src/base/core/base_types/Index.cpp b/src/base/core/base_types/Index.cpp new file mode 100644 index 0000000..fad50ac --- /dev/null +++ b/src/base/core/base_types/Index.cpp @@ -0,0 +1,17 @@ +#include "Index.h" + +Index::Index(size_t value) + : m_value(value), + m_valid(true) +{ +} + +bool Index::valid() const +{ + return m_valid; +} + +size_t Index::value() const +{ + return m_value; +} \ No newline at end of file diff --git a/src/base/core/base_types/Index.h b/src/base/core/base_types/Index.h new file mode 100644 index 0000000..f6b8f58 --- /dev/null +++ b/src/base/core/base_types/Index.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +class Index +{ +public: + Index() = default; + + Index(size_t value); + + bool valid() const; + + size_t value() const; + +private: + size_t m_value{0}; + bool m_valid{false}; +}; \ No newline at end of file diff --git a/src/base/core/base_types/Number.h b/src/base/core/base_types/Number.h new file mode 100644 index 0000000..9d12877 --- /dev/null +++ b/src/base/core/base_types/Number.h @@ -0,0 +1,20 @@ +#pragma once + +class Number +{ +public: + enum class Type + { + HEX, + INT, + FLOAT, + FRACTION, + EXPONENT + }; + + Number() = default; + +private: + Type m_type{Type::INT}; + unsigned m_value{0}; +}; \ No newline at end of file diff --git a/src/base/core/base_types/Result.h b/src/base/core/base_types/Result.h new file mode 100644 index 0000000..bac9d7b --- /dev/null +++ b/src/base/core/base_types/Result.h @@ -0,0 +1,52 @@ +#pragma once + +#include "Error.h" + +template +class Result +{ +public: + Result(const T& val = T()) + : m_value(val) + { + + } + + Result(const Error& error) + : m_error(error), + m_ok(false) + { + + } + + void on_error(const Error& error) + { + m_error = error; + m_ok = false; + } + + const Error& error() const + { + return m_error; + } + + bool ok() const + { + return m_ok; + } + + const T& value() const + { + return m_value; + } + + T& value() + { + return m_value; + } + +private: + T m_value; + Error m_error; + bool m_ok{true}; +}; \ No newline at end of file diff --git a/src/base/core/data_structures/RawTree.cpp b/src/base/core/build.yaml similarity index 100% rename from src/base/core/data_structures/RawTree.cpp rename to src/base/core/build.yaml diff --git a/src/base/core/data_structures/CircleBuffer.h b/src/base/core/data_structures/CircleBuffer.h index 8b83f8b..bcab357 100644 --- a/src/base/core/data_structures/CircleBuffer.h +++ b/src/base/core/data_structures/CircleBuffer.h @@ -1,14 +1,12 @@ #pragma once -#include - -#include +#include "Vector.h" template class CircleBuffer { public: - CircleBuffer(std::size_t size) + CircleBuffer(size_t size) : mData(size) { @@ -35,12 +33,12 @@ public: } } - std::size_t getNumItems() const + size_t getNumItems() const { return mEndPointer; } - const T& getItem(std::size_t index) const + const T& getItem(size_t index) const { if (mEndPointer < mData.size()) { @@ -58,7 +56,7 @@ public: } private: - std::size_t mStartPointer{0}; - std::size_t mEndPointer{0}; - std::vector mData; + size_t mStartPointer{0}; + size_t mEndPointer{0}; + Vector mData; }; diff --git a/src/base/core/data_structures/Dictionary.cpp b/src/base/core/data_structures/Dictionary.cpp new file mode 100644 index 0000000..1e7bfcc --- /dev/null +++ b/src/base/core/data_structures/Dictionary.cpp @@ -0,0 +1,65 @@ +#include "Dictionary.h" + +Dictionary::Dictionary(const String& item) + : mType(Type::SCALAR), + mScalarType(ScalarType::STRING), + mStringVal(item) +{ +} + +void Dictionary::addItem(const String& key, Ptr dict) +{ + mMapVal.insert(key, std::move(dict)); +} + +void Dictionary::addItem(const String& key, const String& item) +{ + mMapVal.insert(key, Ptr::create(item)); +} + +Vector Dictionary::getKeys() const +{ + Vector keys; + for (const auto& item : mMapVal) + { + keys.push_back(item.key()); + } + return keys; +} + +Dictionary* Dictionary::getItemAsMap(const String& key) const +{ + if (isMap()) + { + return (*mMapVal.find(key)).value().get(); + } + return nullptr; +} + +Optional Dictionary::getItemAsString(const String& key) const +{ + if (isString()) + { + return mStringVal; + } + return {}; +} + +bool Dictionary::hasKey(const String& key) const +{ + return mMapVal.has_key(key); +} + +bool Dictionary::isMap() const +{ + return mType == Type::MAP; +} + +bool Dictionary::isString() const +{ + return mType == Type::SCALAR && mScalarType == ScalarType::STRING; +} + + + + diff --git a/src/base/core/data_structures/Dictionary.h b/src/base/core/data_structures/Dictionary.h new file mode 100644 index 0000000..64af598 --- /dev/null +++ b/src/base/core/data_structures/Dictionary.h @@ -0,0 +1,57 @@ +#pragma once + +#include "String.h" +#include "Number.h" +#include "Vector.h" +#include "Map.h" +#include "Pointer.h" +#include "Optional.h" + +class Dictionary +{ +public: + enum class Type + { + MAP, + SEQUENCE, + SCALAR + }; + + enum class ScalarType + { + STRING, + NUMBER, + BOOLEAN, + NULLT + }; + + Dictionary() = default; + Dictionary(const String& item); + + virtual ~Dictionary() = default; + + void addItem(const String& key, const String& item); + + void addItem(const String& key, Ptr dict); + + Dictionary* getItemAsMap(const String& key) const; + + Optional getItemAsString(const String& key) const; + + Vector getKeys() const; + + bool hasKey(const String& key) const; + + bool isMap() const; + + bool isString() const; + +protected: + Type mType{Type::MAP}; + ScalarType mScalarType{ScalarType::STRING}; + String mStringVal; + bool mBoolVal{false}; + Number mNumberVal; + Vector> mSequenceVal; + Map > mMapVal; +}; diff --git a/src/base/core/data_structures/List.h b/src/base/core/data_structures/List.h index 86354f5..abee3dd 100644 --- a/src/base/core/data_structures/List.h +++ b/src/base/core/data_structures/List.h @@ -1,69 +1,195 @@ #pragma once -#include -#include -#include +#include "Error.h" +#include "Pointer.h" +#include "Vector.h" +#include "Optional.h" -class AbstractList -{ -public: - virtual ~AbstractList() = default; - - virtual std::size_t getLength() const = 0; -}; +#include template -class List : public AbstractList +class List { public: - List() = default; - - void initializeTo(std::size_t size, T value) + List(const T& item) + : m_item(item) { - mData = std::vector(size, value); } - const T* getDataPtr() const + List(T&& item) + : m_item(std::move(item)) { - return mData.data(); } - const std::vector& getData() const + List* next() { - return mData; + return m_next.get(); } - T getItem(std::size_t index) const + const List* next() const { - if (index < mData.size()) + return m_next.get(); + } + + const List* end() const + { + if (is_end()) { - return mData[index]; + return this; } - else + auto next_entry = next(); + while(next_entry) { - const auto msg = "Tried to access out of range index: " + std::to_string(index) + " with size " + std::to_string(mData.size()); - throw std::out_of_range(msg); + if(!next_entry->is_end()) + { + next_entry = next_entry->next(); + } + else + { + break; + } + } + return next_entry; + } + + using onItemFunc = std::function; + void forEach(onItemFunc item_func) const + { + if (is_end()) + { + return; + } + auto next_entry = next(); + while(next_entry) + { + if (!item_func(next_entry->item())) + { + return; + } + next_entry = next_entry->next(); } } - void setData(const std::vector& data) + List* end() { - mData = data; - } - - void setItem(std::size_t index, T item) - { - if (index < mData.size()) + if (is_end()) { - mData[index] = item; + return this; } + auto next_entry = next(); + while(next_entry) + { + if(!next_entry->is_end()) + { + next_entry = next_entry->next(); + } + else + { + break; + } + } + return next_entry; } - std::size_t getLength() const override + const List* find(const T& item) const { - return mData.size(); + if (m_item == item) + { + return this; + } + auto next_entry = next(); + while(next_entry) + { + if (next_entry->m_item == item) + { + return next_entry; + } + next_entry = next_entry->next(); + } + return nullptr; + } + + Optional find_index(const T& item) const + { + if (item == m_item) + { + return {0}; + } + auto next_entry = next(); + size_t count = 1; + while(next_entry) + { + if (next_entry->m_item == item) + { + return {count}; + } + next_entry = next_entry->next(); + count++; + } + return {}; + } + + size_t size() const + { + auto next_entry = next(); + size_t count = 1; + while(next_entry) + { + next_entry = next_entry->next(); + count++; + } + return count; + } + + void insert(const T& item) + { + auto end_entry = end(); + end_entry->set_next(Ptr::create(item)); + } + + void insert(T&& item) + { + auto end_entry = end(); + end_entry->set_next(Ptr::create(std::move(item))); + } + + const T& item() const + { + return m_item; + } + + T& item() + { + return m_item; + } + + bool empty() const + { + return is_end(); + } + + bool is_end() const + { + return !bool(m_next); + } + + void flatten(Vector& items) const + { + items.push_back(m_item); + auto next_entry = next(); + while(next_entry) + { + items.push_back(next_entry->item()); + next_entry = next_entry->next(); + } } private: - std::vector mData; + void set_next(Ptr entry) + { + m_next = std::move(entry); + } + + T m_item; + Ptr m_next; }; diff --git a/src/base/core/data_structures/Map.h b/src/base/core/data_structures/Map.h new file mode 100644 index 0000000..94a4d37 --- /dev/null +++ b/src/base/core/data_structures/Map.h @@ -0,0 +1,363 @@ +#pragma once + +#include "String.h" +#include "List.h" +#include "Pair.h" +#include "Optional.h" + +#include +#include + +template +class Map{ + +public: + struct KvPair + { + KvPair() = default; + + KvPair(const K& key) + :m_key(key) + { + } + + KvPair(const K& key, const T& value) + : m_key(key), + m_value(value) + { + } + + KvPair(const K& key, T&& value) + : m_key(key), + m_value(std::move(value)) + { + } + + bool operator==(const KvPair& other) const + { + return m_key == other.m_key; + } + + const K& key() const + { + return m_key; + } + + const T& value() const + { + return m_value; + } + + T& value() + { + return m_value; + } + + K m_key; + T m_value; + }; + + Map() = default; + + void insert(const K& key, const T& value) + { + auto& map_entry = m_buffer[(hash(key))]; + if (!map_entry.is_set()) + { + map_entry.init(KvPair(key, value)); + } + else + { + map_entry.m_list->insert(KvPair(key, value)); + } + } + + void insert(const K& key, T&& value) + { + auto& map_entry = m_buffer[(hash(key))]; + if (!map_entry.is_set()) + { + map_entry.init(std::move(KvPair(key, std::move(value)))); + } + else + { + map_entry.m_list->insert(std::move(KvPair(key, std::move(value)))); + } + } + + using onItemFunc = std::function; + void forEach(onItemFunc item_func) + { + for(size_t idx=0; idx& value(const K& key) const + { + const auto& map_entry = m_buffer[(hash(key))]; + if (!map_entry.is_set()) + { + return {}; + } + KvPair search_term(key); + if (auto list_item = map_entry.find(search_term); list_item != nullptr) + { + return list_item->value(); + } + return {}; + } + + bool has_key(const K& key) const + { + const auto& map_entry = m_buffer[(hash(key))]; + if (!map_entry.is_set()) + { + return false; + } + KvPair search_term(key); + if (auto list_item = map_entry.m_list->find(search_term); list_item != nullptr) + { + return true; + } + return false; + } + + Vector items() const + { + Vector ret; + for(size_t idx=0; idxflatten(ret); + } + } + return ret; + } + + class MapIter + { + public: + MapIter(const Map* container, int index = -1) + : m_index(index), m_container(container) + { + } + + bool operator!=(const MapIter& other) const + { + return m_index != other.m_index; + } + + const KvPair& operator*() const + { + bool found{false}; + return m_container->get_item(m_index, found); + } + + void operator++() + { + m_index++; + } + + private: + int m_index{-1}; + const Map* m_container{nullptr}; + }; + + MapIter begin() const + { + if (empty()) + { + return MapIter(this, -1); + } + else + { + return MapIter(this, 0); + } + } + + MapIter end() const + { + if (empty()) + { + return MapIter(this, -1); + } + else + { + return MapIter(this, size()); + } + } + + MapIter find(const K& key) const + { + if (empty()) + { + return MapIter(this, -1); + } + size_t count{0}; + for(size_t idx=0; idxfind_index(key); + if (loc_index.is_set()) + { + return MapIter(this, count + loc_index.value()); + } + else + { + count += map_entry.m_list->size(); + } + } + } + return MapIter(this, -1); + } + + size_t size() const + { + size_t count{0}; + for(size_t kdx=0; kdxnext(); + while(next_item) + { + next_item = next_item->next(); + count++; + } + } + } + return count; + } + +private: + struct MapEntry + { + bool is_set() const + { + return bool(m_list); + } + void init(const KvPair& kv) + { + m_list = Ptr >::create(kv); + } + void init(KvPair&& kv) + { + m_list = Ptr >::create(std::move(kv)); + } + void clear() + { + m_list.reset(); + } + Ptr > m_list; + }; + + size_t hash(const K& key) const + { + size_t result{0}; + for(const auto c : key.data()) + { + result += static_cast(c); + } + return result / BUFFER_SIZE; + } + + const KvPair& get_item(size_t idx, bool& found) const + { + static KvPair s_bad_item; + + size_t count{0}; + for(size_t kdx=0; kdxitem(); + } + count++; + auto next_item = map_entry.m_list->next(); + while(next_item) + { + if (idx == count) + { + found = true; + return next_item->item(); + } + next_item = next_item->next(); + count++; + } + } + } + return s_bad_item; + } + + KvPair& get_item(size_t idx, bool& found) + { + static KvPair s_bad_item; + + size_t count{0}; + for(size_t kdx=0; kdxitem(); + } + count++; + auto next_item = map_entry.m_list->next(); + while(next_item) + { + if (idx == count) + { + found = true; + return next_item->item(); + } + next_item = next_item->next(); + count++; + } + } + } + return s_bad_item; + } + + static constexpr size_t BUFFER_SIZE{5000}; + MapEntry m_buffer[BUFFER_SIZE]; +}; \ No newline at end of file diff --git a/src/base/core/data_structures/Optional.h b/src/base/core/data_structures/Optional.h new file mode 100644 index 0000000..1825985 --- /dev/null +++ b/src/base/core/data_structures/Optional.h @@ -0,0 +1,34 @@ +#pragma once + +template +class Optional{ + +public: + Optional() = default; + + Optional(const T& value) + : m_is_set(true), + m_value(value) + { + + } + + const T& value() const + { + return m_value; + } + + bool is_set() const + { + return m_is_set; + } + + operator bool() const + { + return m_is_set; + } + +private: + bool m_is_set{false}; + T m_value; +}; \ No newline at end of file diff --git a/src/base/core/data_structures/Pair.h b/src/base/core/data_structures/Pair.h new file mode 100644 index 0000000..180c384 --- /dev/null +++ b/src/base/core/data_structures/Pair.h @@ -0,0 +1,29 @@ +#pragma once + +template +class Pair +{ +public: + Pair() = default; + + Pair(const T& t, const U& u) + : m_first(t), + m_second(u) + { + + } + + const T& first() const + { + return m_first; + } + + const U& second() const + { + return m_second; + } + +private: + T m_first; + U m_second; +}; \ No newline at end of file diff --git a/src/base/core/data_structures/RawTree.h b/src/base/core/data_structures/RawTree.h index 633473e..ef05a20 100644 --- a/src/base/core/data_structures/RawTree.h +++ b/src/base/core/data_structures/RawTree.h @@ -1,7 +1,5 @@ #pragma once -#include - template class RawNode { diff --git a/src/base/core/data_structures/Stack.h b/src/base/core/data_structures/Stack.h new file mode 100644 index 0000000..307bb12 --- /dev/null +++ b/src/base/core/data_structures/Stack.h @@ -0,0 +1,71 @@ +#pragma once + +#include "Pointer.h" +#include "Optional.h" + +template +class Stack +{ + struct StackItem + { + StackItem(const T& value, Ptr prev) + : m_value(value), + m_previous(std::move(prev)) + { + } + + T m_value; + Ptr m_previous; + }; + +public: + + bool empty() const + { + return !bool(m_end); + } + + Optional pop() + { + if (!m_end) + { + return {}; + } + auto end_tmp = m_end->m_value; + remove_end(); + return end_tmp; + } + + T* top() + { + if (!m_end) + { + return nullptr; + } + return &(m_end->m_value); + } + + void push(const T& value) + { + //auto new_end = Ptr::create(value, std::move(m_end)); + //m_end = std::move(new_end); + } + +private: + void remove_end() + { + if (m_end) + { + if (m_end->m_previous) + { + m_end = std::move(m_end->m_previous); + } + else + { + m_end.reset(); + } + } + } + + Ptr m_end; +}; \ No newline at end of file diff --git a/src/base/core/data_structures/String.cpp b/src/base/core/data_structures/String.cpp new file mode 100644 index 0000000..ec36fc1 --- /dev/null +++ b/src/base/core/data_structures/String.cpp @@ -0,0 +1,459 @@ +#include "String.h" + +#include "Char.h" +#include +#include + +String::String() +{ + m_data.push_back('\0'); +} + +String::String(size_t size, char c) +{ + m_data.resize(size, c); + m_data.push_back('\0'); +} + +String::String(const Vector& data) +{ + append(data); +} + +String::String(const char* data) +{ + append(data); +} + +bool String::contains(const String& term) const +{ + if (empty() || term.empty()) + { + return false; + } + + if (term.size() > size()) + { + return false; + } + + size_t match_idx{0}; + for(std::size_t idx=0; idx& String::data() const +{ + return m_data; +} + +bool String::empty() const +{ + return m_data.empty() || m_data[0] == '\0'; +} + +void String::to_bytes(Vector& bytes) const +{ + if (m_data.empty()) + { + return; + } + for(size_t idx=0; idx& data) +{ + if (data.empty()) + { + m_data.push_back('\0'); + return; + } + + if (m_data.size() == 1 && m_data[0] == '\0') + { + m_data.clear(); + } + + for(const auto c : data) + { + if(c == '\0') + { + break; + } + else + { + m_data.push_back(static_cast(c)); + } + } + m_data.push_back('\0'); +} + +Pair String::rsplit(char c) const +{ + if (const auto index = rindex(c); index.valid()) + { + String left; + slice(0, index.value(), left); + + String right; + slice(index.value() + 1, size(), right); + return {left, right}; + } + return {*this, {}}; +} + +bool String::slice(size_t idx, String& out) const +{ + if (idx >= m_data.size()) + { + return false; + } + auto ok = m_data.slice(idx, out.m_data); + if (!ok) + { + return ok; + } + out.m_data.push_back('\0'); + return true; +} + +bool String::slice(size_t start, size_t end, String& out) const +{ + if (end >= m_data.size()) + { + return false; + } + auto ok = m_data.slice(start, end, out.m_data); + if (!ok) + { + return ok; + } + out.m_data.push_back('\0'); + return true; +} + +Index String::rindex(char c) const +{ + if (m_data.size() <= 2) + { + return {}; + } + for(size_t idx=m_data.size()-2; idx >= 0; idx--) + { + if (m_data[idx] == c) + { + return Index(idx); + } + } + return {}; +} + +const char* String::raw() const +{ + return m_data.data(); +} + +size_t String::size() const +{ + return m_data.size() - 1; +} + +void String::reverse() +{ + if (m_data.size() == 1) + { + return; + } + for(size_t idx=0; idx<(m_data.size()-1)/2; idx++) + { + const auto ridx = m_data.size() - 2 - idx; + const auto tmp0 = m_data[idx]; + m_data[idx] = m_data[ridx]; + m_data[ridx] = tmp0; + } +} + +void String::split(Vector& output, char delimiter) const +{ + String working_string; + bool last_was_non_delimiter{ false }; + for (size_t idx = 0; idx 0) + { + const auto rem = input_cpy % 10; + conv += static_cast(48 + rem); + input_cpy /= 10; + } + conv.reverse(); + return conv; +} + +char String::operator[](size_t idx) const +{ + return m_data[idx]; +} + +String& String::operator<<(const char* body) +{ + append(body); + return *this; +} + +String& String::operator<<(const String& body) +{ + *this += body; + return *this; +} + +bool String::operator==(const String& other) const +{ + return m_data == other.m_data; +} + +bool String::operator!=(const String& other) const +{ + return !(*this == other); +} + +String& String::operator<<(size_t idx) +{ + *this += to_string(idx); + return *this; +} + +String& String::operator<<(const int idx) +{ + *this += to_string(idx); + return *this; +} + +void String::push_back(char c) +{ + if (m_data.empty()) + { + m_data.push_back('\0'); + } + m_data.push_back('\0'); + m_data[m_data.size()-2] = c; +} + +void String::to_lower() +{ + if (empty()) + { + return; + } + for(size_t idx=0; idx + +class String +{ +public: + String(); + + String(const Vector& data); + + String(const char* data); + + String(size_t size, char c); + + static String fmt(const char* fmt, ...); + + void append(const Vector& data); + + bool contains(const String& term) const; + + const Vector& data() const; + + bool empty() const; + + using erasePredicate = std::function; + void eraseIf(erasePredicate func); + + static size_t length(const char* arr); + + bool is_whitespace() const; + + void push_back(char c); + + const char* raw() const; + + Pair rsplit(char c) const; + + Index rindex(char c) const; + + void reverse(); + + size_t size() const; + + bool slice(size_t idx, String& out) const; + + bool slice(size_t start, size_t end, String& out) const; + + void split(Vector& output, char delimiter = ' ') const; + + bool starts_with(const String& prefix) const; + + static String to_string(size_t input); + + void to_bytes(Vector& bytes) const; + + void to_lower(); + + static String to_lower(const String& input); + + char operator[](size_t idx) const; + + String& operator<<(const String& body); + + String& operator<<(const char* body); + + String& operator<<(size_t idx); + + String& operator<<(const int idx); + + template + String& operator<<(const T& stringable) + { + *this += stringable.str(); + return *this; + } + + String& operator+=(const String& str); + + String& operator+=(char c); + + String operator+(const String& str) const; + + bool operator==(const String& other) const; + + bool operator!=(const String& other) const; + + class StringIter + { + public: + StringIter(const String* container, int index = -1) + : m_index(index), m_container(container) + { + } + + bool operator!=(const StringIter& other) const + { + return m_index != other.m_index; + } + + char operator*() const + { + return (*m_container)[m_index]; + } + + void operator++() + { + m_index++; + } + + private: + int m_index{-1}; + const String* m_container{nullptr}; + }; + + StringIter begin() const + { + if (empty()) + { + return StringIter(this, -1); + } + else + { + return StringIter(this, 0); + } + } + + StringIter end() const + { + if (empty()) + { + return StringIter(this, -1); + } + else + { + return StringIter(this, size()); + } + } + +private: + void append(const char* data); + + Vector m_data; +}; + +inline String operator+(const char* str, const String& s) +{ + String ret(str); + ret += s; + return ret; +} + +using _s = String; \ No newline at end of file diff --git a/src/base/core/data_structures/Tree.h b/src/base/core/data_structures/Tree.h index 7b19016..5b85435 100644 --- a/src/base/core/data_structures/Tree.h +++ b/src/base/core/data_structures/Tree.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Pointer.h" template class Node @@ -10,7 +10,7 @@ public: : mData(data) {} - void addChild(std::unique_ptr child) + void addChild(Ptr child) { if(!mLeftChild) { @@ -45,12 +45,12 @@ public: private: T mData; unsigned char mTag{0}; - std::unique_ptr mLeftChild; - std::unique_ptr mRightChild; + Ptr mLeftChild; + Ptr mRightChild; }; template -using NodePtr = std::unique_ptr >; +using NodePtr = Ptr >; template class Tree diff --git a/src/base/core/data_structures/Vector.h b/src/base/core/data_structures/Vector.h new file mode 100644 index 0000000..2c1e6cd --- /dev/null +++ b/src/base/core/data_structures/Vector.h @@ -0,0 +1,254 @@ +#pragma once + +#include "Allocator.h" +#include + +template +class Vector +{ +public: + Vector() = default; + + Vector(size_t size) + { + resize(size); + } + + Vector(const Vector& v) + { + *this = v; + } + + ~Vector() + { + clear(); + } + + T* begin() const + { + return m_data; + } + + T* end() const + { + return m_data + m_size; + } + + const T* data() const + { + return m_data; + } + + T* data() + { + return m_data; + } + + bool slice(size_t slice_idx, Vector& v) const + { + if (slice_idx >= m_size) + { + return false; + } + v.resize(slice_idx); + for(size_t idx=0; idx m_size) + { + return false; + } + v.resize(slice_end - slice_start); + for(size_t idx=slice_start; idx remaining_capacity()) + { + resize_delta = other.m_size - remaining_capacity(); + resize_capacity(m_capacity + resize_delta); + } + for(size_t idx=0;idx= m_capacity) + { + const size_t new_size = 1.5*m_size; + resize_capacity(new_size); + } + m_data[m_size] = item; + m_size++; + } + + void push_back(T&& item) + { + if (!has_allocated()) + { + resize_capacity(10); + } + else if (m_size >= m_capacity) + { + const size_t new_size = 1.5*m_size; + resize_capacity(new_size); + } + m_data[m_size] = std::move(item); + m_size++; + } + + const T& operator[] (const size_t idx) const + { + return m_data[idx]; + } + + T& operator[] (const size_t idx) + { + return m_data[idx]; + } + + Vector& operator=(const Vector& v) + { + resize(v.size()); + for(size_t idx=0; idx& other) const + { + if (m_size != other.m_size) + { + return false; + } + for(size_t idx=0; idx 0; + } + + size_t remaining_capacity() const + { + return m_capacity - m_size; + } + + void resize_capacity(size_t new_capacity) + { + if (!has_allocated()) + { + m_data = m_allocator.alloc_array(new_capacity); + m_capacity = new_capacity; + } + else if (new_capacity != m_capacity) + { + auto temp = m_allocator.alloc_array(new_capacity); + auto min_capacity = new_capacity; + if (m_capacity < min_capacity) + { + min_capacity = m_capacity; + } + for(size_t idx=0; idx m_allocator; + size_t m_size{0}; + size_t m_capacity{0}; +}; \ No newline at end of file diff --git a/src/base/core/encoding/ByteUtils.cpp b/src/base/core/encoding/Bits.cpp similarity index 62% rename from src/base/core/encoding/ByteUtils.cpp rename to src/base/core/encoding/Bits.cpp index 61f943f..5d164e7 100644 --- a/src/base/core/encoding/ByteUtils.cpp +++ b/src/base/core/encoding/Bits.cpp @@ -1,32 +1,31 @@ -#include "ByteUtils.h" +#include "Bits.h" - -bool ByteUtils::MostSignificantBitIsOne(char c) +bool Bits::MostSignificantBitIsOne(Byte c) { return c & (1 << 7); } -ByteUtils::Word ByteUtils::GetWordFirstBit(const Word word) +Word Bits::GetWordFirstBit(const Word word) { - return word & ByteUtils::WORD_FIRST_BIT; + return word & Bits::WORD_FIRST_BIT; }; -ByteUtils::Word ByteUtils::GetWordLastByte(const Word word) +Word Bits::GetWordLastByte(const Word word) { - return word & ByteUtils::WORD_LAST_BYTE; + return word & Bits::WORD_LAST_BYTE; } -unsigned char ByteUtils::getHigherNBits(unsigned char input, unsigned num) +unsigned char Bits::getHigherNBits(Byte input, size_t num) { return input >> (8 - num); } -unsigned char ByteUtils::getByteN(uint32_t input, unsigned n) +unsigned char Bits::getByteN(DWord input, size_t n) { return (input << 8*n) >> 24; } -uint32_t ByteUtils::mirror(uint32_t byte, unsigned length) +uint32_t Bits::mirror(DWord byte, size_t length) { uint32_t ret{0}; for(unsigned idx=0; idx> n; } -unsigned char ByteUtils::getMBitsAtN(unsigned char input, unsigned m, unsigned n) +unsigned char Bits::getMBitsAtN(Byte input, size_t m, size_t n) { switch (m) { @@ -94,16 +93,16 @@ unsigned char ByteUtils::getMBitsAtN(unsigned char input, unsigned m, unsigned n } } -bool ByteUtils::getBitN(uint32_t input, unsigned n) +bool Bits::getBitN(DWord input, size_t n) { return input & (1 << n); } -unsigned char ByteUtils::getFromString(const std::string& string) +unsigned char Bits::getFromString(const String& string) { unsigned char ret{0}; - if (string.length() < 8) + if (string.size() < 8) { return ret; } @@ -118,9 +117,9 @@ unsigned char ByteUtils::getFromString(const std::string& string) return ret; } -std::string ByteUtils::toString(uint32_t input, unsigned length) +String Bits::toString(DWord input, size_t length) { - std::string ret; + String ret; if (length > 8) { unsigned overshoot = length - 8; @@ -144,7 +143,7 @@ std::string ByteUtils::toString(uint32_t input, unsigned length) return ret; } -void ByteUtils::ReverseBuffer(char* buffer, char* reverse, unsigned size, unsigned targetSize) +void Bits::ReverseBuffer(Byte* buffer, char* reverse, size_t size, size_t targetSize) { for(unsigned idx=0; idx(buffer, reverse); } -ByteUtils::DWord ByteUtils::ToDWord(char* buffer, bool reverse) +DWord Bits::ToDWord(Byte* buffer, bool reverse) { return ToType(buffer, reverse); } -ByteUtils::QWord ByteUtils::ToQWord(char* buffer, bool reverse) +QWord Bits::ToQWord(Byte* buffer, bool reverse) { return ToType(buffer, reverse); } -bool ByteUtils::Compare(char* buffer, const char* tag, unsigned size) +bool Bits::Compare(Byte* buffer, const char* tag, size_t size) { for(unsigned idx=0; idx + static T ToType(Byte* buffer, bool reverse = true) + { + T result {0}; + if(reverse) + { + char reversed[sizeof(T)]; + ReverseBuffer(buffer, reversed, sizeof(T), sizeof(T)); + //std::memcpy(&result, reversed, sizeof(T)); + } + else + { + //std::memcpy(&result, buffer, sizeof(T)); + } + return result; + } + + static Word ToWord(Byte* buffer, bool reverse = true); + + static DWord ToDWord(Byte* buffer, bool reverse = true); + + static QWord ToQWord(Byte* buffer, bool reverse = true); + + static bool Compare(Byte* buffer, const char* tag, size_t size); + + static bool CompareDWords(Byte* buffer, DWord target); + + static bool CompareWords(Byte* buffer, Word target); + + static const int BYTE_FIRST_BIT = 0x40; // 1000 0000 + static const Word WORD_FIRST_BIT = static_cast(0x8000); // 1000 0000 - 0000 0000 + static const Word WORD_LAST_BYTE = 0x00FF; // 0000 0000 - 1111 1111 +}; diff --git a/src/base/core/encoding/ByteUtils.h b/src/base/core/encoding/ByteUtils.h deleted file mode 100644 index cb15b22..0000000 --- a/src/base/core/encoding/ByteUtils.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#include -#include -#include - -class ByteUtils -{ -public: - using Word = int16_t; - using DWord = int32_t; - using QWord = int64_t; - - static bool MostSignificantBitIsOne(char c); - - static Word GetWordFirstBit(const Word word); - - static Word GetWordLastByte(const Word word); - - static unsigned char getByteN(uint32_t input, unsigned n); - - static unsigned char getHigherNBits(unsigned char input, unsigned num); - - static unsigned char getLowerNBits(uint32_t input, unsigned num); - - static unsigned char getTwoBitsAtN(unsigned char input, unsigned n); - - static unsigned char getMBitsAtN(unsigned char input, unsigned m, unsigned n); - - static bool getBitN(uint32_t input, unsigned n); - - static unsigned char getFromString(const std::string& string); - - static std::string toString(uint32_t input, unsigned length = 8); - - static uint32_t mirror(uint32_t input, unsigned length=0); - - static void ReverseBuffer(char* buffer, char* reverse, unsigned size, unsigned targetSize); - - template - static T ToType(char* buffer, bool reverse = true) - { - T result {0}; - if(reverse) - { - char reversed[sizeof(T)]; - ReverseBuffer(buffer, reversed, sizeof(T), sizeof(T)); - std::memcpy(&result, reversed, sizeof(T)); - } - else - { - std::memcpy(&result, buffer, sizeof(T)); - } - return result; - } - - static Word ToWord(char* buffer, bool reverse = true); - - static DWord ToDWord(char* buffer, bool reverse = true); - - static QWord ToQWord(char* buffer, bool reverse = true); - - static bool Compare(char* buffer, const char* tag, unsigned size); - - static bool CompareDWords(char* buffer, const char* tag); - - static bool CompareWords(char* buffer, const char* tag); - - static const int BYTE_FIRST_BIT = 0x40; // 1000 0000 - static const Word WORD_FIRST_BIT = static_cast(0x8000); // 1000 0000 - 0000 0000 - static const Word WORD_LAST_BYTE = 0x00FF; // 0000 0000 - 1111 1111 -}; diff --git a/src/base/core/encoding/StringUtils.cpp b/src/base/core/encoding/StringUtils.cpp index e1e56e3..853328b 100644 --- a/src/base/core/encoding/StringUtils.cpp +++ b/src/base/core/encoding/StringUtils.cpp @@ -1,69 +1,24 @@ #include "StringUtils.h" +#include "Char.h" + #include #include #include #include -bool StringUtils::isAlphaNumeric(char c) -{ - return std::isalnum(c); -} - -bool StringUtils::isSpace(char c) -{ - return std::isspace(c); -} - -bool StringUtils::isAlphabetical(char c) -{ - return std::isalpha(c); -} - -std::vector StringUtils::toBytes(const std::string& input) -{ - return {input.begin(), input.end()}; -} - -std::string StringUtils::toString(const std::vector& bytes) -{ - return {bytes.begin(), bytes.end()}; -} - -std::vector StringUtils::toLines(const std::string& input) -{ - auto result = std::vector{}; - auto ss = std::stringstream{input}; - for (std::string line; std::getline(ss, line, '\n');) - { - result.push_back(line); - } - return result; -} - -bool StringUtils::isWhitespaceOnly(const std::string& input) -{ - if (input.empty()) - { - return true; - } - else - { - return std::all_of(input.cbegin(), input.cend(), [](char c){ return std::isspace(c); }); - } -} - -std::size_t StringUtils::countFirstConsecutiveHits(const std::string& input, char c) +size_t StringUtils::countFirstConsecutiveHits(const String& input, char c) { + /* auto found_id = input.find(c); - if(found_id == std::string::npos) + if(found_id == String::npos) { return 0; } else { - std::size_t count = 1; - for(std::size_t idx=found_id+1; idx 0; idx--) + for (size_t idx = last_nonspace; idx > 0; idx--) { if (!std::isspace(input[idx])) { @@ -110,60 +68,30 @@ std::string StringUtils::stripSurroundingWhitepsace(const std::string& input) } } return input.substr(first_nonspace, last_nonspace-first_nonspace + 1); + + */ + return {}; } -std::vector StringUtils::split(const std::string& input) +String StringUtils::toPaddedString(unsigned numBytes, unsigned entry) { - std::vector substrings; - std::string working_string; - std::locale loc; - bool last_was_nonspace{ false }; - for (auto c : input) - { - if (std::isspace(c, loc)) - { - if (last_was_nonspace) - { - substrings.push_back(working_string); - working_string = ""; - last_was_nonspace = false; - } - } - else - { - last_was_nonspace = true; - working_string += c; - } - } - if (!working_string.empty()) - { - substrings.push_back(working_string); - } - return substrings; -} - -std::string StringUtils::toLower(const std::string& s) -{ - std::string ret; - std::transform(s.begin(), s.end(), ret.begin(), [](unsigned char c){ return std::tolower(c); }); - return ret; -} - -std::string StringUtils::toPaddedString(unsigned numBytes, unsigned entry) -{ - std::stringstream sstr; + /* + Stringstream sstr; sstr << std::setfill('0') << std::setw(numBytes) << entry; return sstr.str(); + */ + return {}; } -std::string StringUtils::stripQuotes(const std::string& input) +String StringUtils::stripQuotes(const String& input) { + /* if (input.size() < 3) { return input; } - std::size_t start_index = 0; - std::size_t end_index = input.size()-1; + size_t start_index = 0; + size_t end_index = input.size()-1; if (input[start_index] == '"') { start_index = 1; @@ -173,12 +101,15 @@ std::string StringUtils::stripQuotes(const std::string& input) end_index = end_index - 1; } return input.substr(start_index, end_index - start_index + 1); + */ + return {}; } -std::string StringUtils::removeUpTo(const std::string& input, const std::string& prefix) +String StringUtils::removeUpTo(const String& input, const String& prefix) { - std::size_t found = input.find(prefix); - if (found != std::string::npos) + /* + size_t found = input.find(prefix); + if (found != String::npos) { return input.substr(found + prefix.size(), input.size()-found); } @@ -186,14 +117,17 @@ std::string StringUtils::removeUpTo(const std::string& input, const std::string& { return input; } + */ + return {}; } -bool StringUtils::startsWith(const std::string& input, const std::string& prefix, bool ignoreWhitespace) +bool StringUtils::startsWith(const String& input, const String& prefix, bool ignoreWhitespace) { + /* if(ignoreWhitespace) { const auto loc = input.find(prefix); - if (loc == std::string::npos) + if (loc == String::npos) { return false; } @@ -206,4 +140,6 @@ bool StringUtils::startsWith(const std::string& input, const std::string& prefix { return input.find(prefix) == 0; } + */ + return false; } diff --git a/src/base/core/encoding/StringUtils.h b/src/base/core/encoding/StringUtils.h index e91010b..c091bdc 100644 --- a/src/base/core/encoding/StringUtils.h +++ b/src/base/core/encoding/StringUtils.h @@ -1,48 +1,22 @@ #pragma once -#include -#include +#include "Byte.h" + +#include "String.h" +#include "Vector.h" class StringUtils { public: - static constexpr char LEFT_BRACKET = '<'; - static constexpr char RIGHT_BRACKET = '>'; - static constexpr char FORWARD_SLASH = '/'; - static constexpr char BACK_SLASH = '\\'; - static constexpr char QUESTION_MARK = '?'; - static constexpr char EQUALS = '='; - static constexpr char DOUBLE_QUOTE = '"'; - static constexpr char SINGLE_QUOTE = '\''; - static constexpr char COLON = ':'; + static size_t countFirstConsecutiveHits(const String& input, char c); - static std::size_t countFirstConsecutiveHits(const std::string& input, char c); + static String removeUpTo(const String& input, const String& prefix); - static bool isAlphaNumeric(char c); + static bool startsWith(const String& input, const String& prefix, bool ignoreWhitespace = false); - static bool isAlphabetical(char c); + static String stripSurroundingWhitepsace(const String& input); - static bool isSpace(char c); + static String stripQuotes(const String& input); - static bool isWhitespaceOnly(const std::string& input); - - static std::string removeUpTo(const std::string& input, const std::string& prefix); - - static std::vector split(const std::string& input); - - static bool startsWith(const std::string& input, const std::string& prefix, bool ignoreWhitespace = false); - - static std::string stripSurroundingWhitepsace(const std::string& input); - - static std::string stripQuotes(const std::string& input); - - static std::vector toBytes(const std::string& input); - - static std::string toLower(const std::string& s); - - static std::vector toLines(const std::string& input); - - static std::string toPaddedString(unsigned numBytes, unsigned entry); - - static std::string toString(const std::vector& bytes); + static String toPaddedString(unsigned numBytes, unsigned entry); }; diff --git a/src/base/core/encoding/UnicodeUtils.cpp b/src/base/core/encoding/Unicode.cpp similarity index 71% rename from src/base/core/encoding/UnicodeUtils.cpp rename to src/base/core/encoding/Unicode.cpp index fe02353..0b2cd91 100644 --- a/src/base/core/encoding/UnicodeUtils.cpp +++ b/src/base/core/encoding/Unicode.cpp @@ -1,30 +1,33 @@ -#include "UnicodeUtils.h" +#include "Unicode.h" #include "Win32BaseIncludes.h" -#include +#include "Vector.h" #include #include -std::string UnicodeUtils::utf16ToUtf8String(const std::wstring& input) +/* +String UnicodeUtils::utf16ToUtf8String(const std::wstring& input) { if (input.empty()) { - return std::string(); + return String(); } #ifdef _WIN32 const auto size = ::WideCharToMultiByte(CP_UTF8, 0, &input[0], static_cast(input.size()), nullptr, 0, nullptr, nullptr); - std::string result(size, 0); + String result(size, 0); ::WideCharToMultiByte(CP_UTF8, 0, &input[0], static_cast(input.size()), &result[0], size, nullptr, nullptr); return result; #else throw std::logic_error("Not implemented"); #endif } +*/ -std::wstring UnicodeUtils::utf8ToUtf16WString(const std::string& input) +/* +std::wstring UnicodeUtils::utf8ToUtf16WString(const String& input) { if (input.empty()) { @@ -33,20 +36,22 @@ std::wstring UnicodeUtils::utf8ToUtf16WString(const std::string& input) #ifdef _WIN32 const auto charsNeeded = ::MultiByteToWideChar(CP_UTF8, 0, input.data(), static_cast(input.size()), nullptr, 0); - std::vector buffer(charsNeeded); + Vector buffer(charsNeeded); const auto charsConverted = ::MultiByteToWideChar(CP_UTF8, 0, input.data(), static_cast(input.size()), &buffer[0], static_cast(buffer.size())); return std::wstring(&buffer[0], charsConverted); #else throw std::logic_error("Not implemented"); #endif } +*/ -std::vector UnicodeUtils::utf8ToUtf32(const std::string& input) +Vector Unicode::utf8ToUtf32(const String& input) { - const auto utf_16 = utf8ToUtf16WString(input); + //const auto utf_16 = utf8ToUtf16WString(input); - std::vector output; - std::size_t pos = 0; + Vector output; + /* + size_t pos = 0; while (pos < utf_16.size()) { const auto c = utf_16[pos]; @@ -68,25 +73,26 @@ std::vector UnicodeUtils::utf8ToUtf32(const std::string& input) } } } + */ return output; } -bool UnicodeUtils::isSurrogate(wchar_t c) +bool Unicode::isSurrogate(wchar_t c) { return (c - 0xd800u) < 2048u; } -bool UnicodeUtils::isHighSurrogate(wchar_t c) +bool Unicode::isHighSurrogate(wchar_t c) { return (c & 0xfffffc00) == 0xd800; } -bool UnicodeUtils::isLowSurrogate(wchar_t c) +bool Unicode::isLowSurrogate(wchar_t c) { return (c & 0xfffffc00) == 0xdc00; } -uint32_t UnicodeUtils::surrogateToUtf32(wchar_t high, wchar_t low) +uint32_t Unicode::surrogateToUtf32(wchar_t high, wchar_t low) { return (high << 10) + low - 0x35fdc00; } diff --git a/src/base/core/encoding/Unicode.h b/src/base/core/encoding/Unicode.h new file mode 100644 index 0000000..e50863f --- /dev/null +++ b/src/base/core/encoding/Unicode.h @@ -0,0 +1,21 @@ +#pragma once + +#include "String.h" +#include "Vector.h" +#include + +class Unicode +{ +public: + //static String utf16ToUtf8String(const std::wstring& input); + + //static std::wstring utf8ToUtf16WString(const String& input); + + static Vector utf8ToUtf32(const String& input); + +private: + static bool isSurrogate(wchar_t c); + static bool isHighSurrogate(wchar_t c); + static bool isLowSurrogate(wchar_t c); + static uint32_t surrogateToUtf32(wchar_t high, wchar_t low); +}; diff --git a/src/base/core/encoding/UnicodeUtils.h b/src/base/core/encoding/UnicodeUtils.h deleted file mode 100644 index 4c3d2d4..0000000 --- a/src/base/core/encoding/UnicodeUtils.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include -#include -#include - -class UnicodeUtils -{ -public: - static std::string utf16ToUtf8String(const std::wstring& input); - - static std::wstring utf8ToUtf16WString(const std::string& input); - - static std::vector utf8ToUtf32(const std::string& input); - -private: - static bool isSurrogate(wchar_t c); - static bool isHighSurrogate(wchar_t c); - static bool isLowSurrogate(wchar_t c); - static uint32_t surrogateToUtf32(wchar_t high, wchar_t low); -}; diff --git a/src/base/core/Event.cpp b/src/base/core/events/Event.cpp similarity index 100% rename from src/base/core/Event.cpp rename to src/base/core/events/Event.cpp diff --git a/src/base/core/Event.h b/src/base/core/events/Event.h similarity index 100% rename from src/base/core/Event.h rename to src/base/core/events/Event.h diff --git a/src/base/core/file_utilities/Directory.cpp b/src/base/core/file_utilities/Directory.cpp deleted file mode 100644 index 49aac5a..0000000 --- a/src/base/core/file_utilities/Directory.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "Directory.h" - -std::vector Directory::getFilesWithExtension(const Path& path, const std::string& extension, bool recursive) -{ - std::vector paths; - if (std::filesystem::is_directory(path)) - { - for (const auto& entry : std::filesystem::directory_iterator(path)) - { - if (std::filesystem::is_regular_file(entry) && entry.path().extension() == extension) - { - paths.push_back(entry.path()); - } - else if(recursive && std::filesystem::is_directory(entry)) - { - const auto child_paths = getFilesWithExtension(entry, extension, recursive); - paths.insert(paths.end(), child_paths.begin(), child_paths.end()); - } - } - } - return paths; -} - -void Directory::createIfNotExisting(const Path& path) -{ - Path working_path; - if (std::filesystem::is_directory(path)) - { - working_path = path; - } - else - { - working_path = path.parent_path(); - } - - if (!std::filesystem::exists(working_path)) - { - std::filesystem::create_directories(working_path); - } -} diff --git a/src/base/core/file_utilities/Directory.h b/src/base/core/file_utilities/Directory.h deleted file mode 100644 index a225f32..0000000 --- a/src/base/core/file_utilities/Directory.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include - -using Path = std::filesystem::path; - -class Directory -{ -public: - static void createIfNotExisting(const Path& path); - - static std::vector getFilesWithExtension(const Path& path, const std::string& extension, bool recursive=false); -}; diff --git a/src/base/core/file_utilities/File.cpp b/src/base/core/file_utilities/File.cpp deleted file mode 100644 index e09fc47..0000000 --- a/src/base/core/file_utilities/File.cpp +++ /dev/null @@ -1,220 +0,0 @@ -#include "File.h" - -#include "FileLogger.h" -#include "ByteUtils.h" - -#include -#include - -File::File(std::filesystem::path path) - : mFullPath(path), - mInHandle(), - mOutHandle() -{ - -} - -File::~File() -{ - close(); -} - -std::string File::getExtension() const -{ - return mFullPath.extension().string(); -} - -std::string File::dumpBinary() -{ - open(AccessMode::Read); - - std::stringstream sstr; - sstr << "Count | Binary | Decimal | ASCII \n"; - unsigned count = 0; - while(mInHandle->peek() != EOF) - { - const unsigned char val = static_cast(mInHandle->get()); - const unsigned char ascii_val = std::isalpha(val) ? val : '.'; - sstr << count << " | " << ByteUtils::toString(val) << " | " << static_cast(val) << " | " << ascii_val << '\n'; - if (count % 10 == 0) - { - sstr << "\n"; - } - count++; - } - const auto out = sstr.str(); - close(); - return out; -} - -std::ifstream* File::getInHandle() const -{ - return mInHandle.get(); -} - -std::ofstream* File::getOutHandle() const -{ - return mOutHandle.get(); -} - -std::optional File::readNextByte() -{ - if (!mInHandle) - { - if (!open(AccessMode::Read)) - { - return std::nullopt; - } - } - - if (mInHandle->good()) - { - if (auto val = mInHandle->get(); val == EOF) - { - return std::nullopt; - } - else - { - return val; - } - } - else - { - return std::nullopt; - } -} - -bool File::open(AccessMode accessMode) -{ - if (mFullPath.is_absolute() && !std::filesystem::exists(mFullPath.parent_path())) - { - std::filesystem::create_directories(mFullPath.parent_path()); - } - - if(accessMode == AccessMode::Read) - { - auto flags = std::ifstream::in; - mInHandle = std::make_unique(); - mInHandle->open(mFullPath, flags); - if (!mInHandle->is_open()) - { - MLOG_ERROR("Failed to open file at :" << mFullPath); - return false; - } - } - else - { - auto flags = std::ofstream::out; - mOutHandle = std::make_unique(); - mOutHandle->open(mFullPath, flags); - if (!mOutHandle->is_open()) - { - MLOG_ERROR("Failed to open file at :" << mFullPath); - return false; - } - } - return true; -} - -void File::close() -{ - if(mOutHandle) - { - mOutHandle->close(); - } - if(mInHandle) - { - mInHandle->close(); - } -} - -FileFormat::Format File::inferFormat() const -{ - const auto extension = getExtension(); - return FileFormat::inferFormat(extension); -} - -void File::writeText(const std::string& text) -{ - bool had_to_open{false}; - if (!mOutHandle) - { - had_to_open = true; - if (!open(File::AccessMode::Write)) - { - return; - } - } - - (*mOutHandle) << text; - - if (had_to_open) - { - close(); - } -} - -std::vector File::readLines() -{ - std::vector content; - - if (!pathExists()) - { - return {}; - } - - if(!open(AccessMode::Read)) - { - return {}; - } - - std::string str; - while(std::getline(*mInHandle, str)) - { - content.push_back(str); - } - - close(); - return content; -} - -std::string File::read() -{ - if (!pathExists()) - { - return {}; - } - - if(!open(AccessMode::Read)) - { - return {}; - } - - std::stringstream buffer; - buffer << mInHandle->rdbuf(); - - close(); - return buffer.str(); -} - -std::string File::readText() -{ - if (!pathExists()) - { - return {}; - } - - if(!open(AccessMode::Read)) - { - return {}; - } - - std::string str((std::istreambuf_iterator(*mInHandle)), - std::istreambuf_iterator()); - return str; -} - -bool File::pathExists() const -{ - return std::filesystem::exists(mFullPath); -} diff --git a/src/base/core/file_utilities/File.h b/src/base/core/file_utilities/File.h deleted file mode 100644 index b2cb3f0..0000000 --- a/src/base/core/file_utilities/File.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once - -#include "FileFormats.h" - -#include -#include -#include -#include -#include -#include - -using Path = std::filesystem::path; - -class File -{ -public: - enum class AccessMode{ - Read, - Write - }; - -public: - File(std::filesystem::path fullPath); - - ~File(); - - void close(); - - std::string dumpBinary(); - - std::string getExtension() const; - - std::ifstream* getInHandle() const; - - std::ofstream* getOutHandle() const; - - FileFormat::Format inferFormat() const; - - std::string readText(); - - std::vector readLines(); - - std::string read(); - - bool pathExists() const; - - bool open(AccessMode mode); - - std::optional readNextByte(); - - void writeText(const std::string& text); - -private: - std::filesystem::path mFullPath; - std::unique_ptr mInHandle; - std::unique_ptr mOutHandle; -}; diff --git a/src/base/core/file_utilities/FileFormats.cpp b/src/base/core/file_utilities/FileFormats.cpp deleted file mode 100644 index 925b28d..0000000 --- a/src/base/core/file_utilities/FileFormats.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "FileFormats.h" - -#include "StringUtils.h" - -FileFormat::ExtensionMap FileFormat::mExtensions = [] -{ - ExtensionMap ret; - ret[Format::Markdown] = ".md"; - ret[Format::Html] = ".html"; - ret[Format::Wav] = ".wav"; - return ret; -}(); - -bool FileFormat::isFormat(const std::string& extension, Format format) -{ - return StringUtils::toLower(extension) == mExtensions[format]; -} - -FileFormat::Format FileFormat::inferFormat(const std::string& query) -{ - for(const auto& extension : mExtensions) - { - if(extension.second == query) - { - return extension.first; - } - } - return Format::Unknown; -} - -std::string FileFormat::getExtension(Format format) -{ - return mExtensions[format]; -} diff --git a/src/base/core/file_utilities/PathUtils.cpp b/src/base/core/file_utilities/PathUtils.cpp deleted file mode 100644 index a56c0bb..0000000 --- a/src/base/core/file_utilities/PathUtils.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "PathUtils.h" - - -std::string PathUtils::getBaseFilename(const Path& path) -{ - return path.stem().string(); -} - -Path PathUtils::getRelativePath(const Path& input, const Path& relativeTo) -{ - return std::filesystem::relative(input, relativeTo); -} - -std::string PathUtils::getPathDelimited(const Path& path, char delimiter) -{ - std::string name; - - unsigned count = 0; - for(const auto& element : path) - { - if (count == 0) - { - name += element.stem().string(); - } - else - { - name += delimiter + element.stem().string(); - } - count++; - } - - return name; -} diff --git a/src/base/core/file_utilities/PathUtils.h b/src/base/core/file_utilities/PathUtils.h deleted file mode 100644 index 5c59dea..0000000 --- a/src/base/core/file_utilities/PathUtils.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include -#include -#include - -using Path = std::filesystem::path; - -class PathUtils -{ -public: - static std::string getBaseFilename(const Path& path); - - static Path getRelativePath(const Path& path, const Path& relativeTo); - - static std::string getPathDelimited(const Path& path, char delimiter='-'); -}; diff --git a/src/base/core/filesystem/BinaryFile.cpp b/src/base/core/filesystem/BinaryFile.cpp new file mode 100644 index 0000000..30eef63 --- /dev/null +++ b/src/base/core/filesystem/BinaryFile.cpp @@ -0,0 +1,31 @@ +#include "BinaryFile.h" + +Status BinaryFile::to_readable(InputStream& input, + OutputStream& output) +{ + String sstr; + sstr << "Count | Binary | Decimal | Hex | ASCII \n"; + + Byte b{0}; + while(input.get(b)) + { + unsigned count = 0; + } + + /* + for(const auto byte : buffer) + { + const auto ascii_val = std::isalpha(byte) ? byte : '.'; + String hex_sstr; + hex_sstr << std::setfill('0') << std::setw(2) << std::hex << static_cast(byte); + + sstr << count << " | " << Bits::toString(byte) << " | " << static_cast(byte) << " | " << hex_sstr.str() << " | " << ascii_val << '\n'; + if (count % 10 == 0) + { + sstr << "\n"; + } + count++; + } + */ + return {}; +} \ No newline at end of file diff --git a/src/base/core/filesystem/BinaryFile.h b/src/base/core/filesystem/BinaryFile.h new file mode 100644 index 0000000..b2f935d --- /dev/null +++ b/src/base/core/filesystem/BinaryFile.h @@ -0,0 +1,12 @@ +#pragma once + +#include "IOStream.h" +#include "Byte.h" +#include "Error.h" + +class BinaryFile +{ +public: + static Status to_readable(InputStream& input, + OutputStream& output); +}; \ No newline at end of file diff --git a/src/base/core/filesystem/Directory.cpp b/src/base/core/filesystem/Directory.cpp new file mode 100644 index 0000000..bd49b6b --- /dev/null +++ b/src/base/core/filesystem/Directory.cpp @@ -0,0 +1,186 @@ +#include "Directory.h" +#include "ConsoleLogger.h" + +#include +#include +#include + +#include + +Status Directory::getDirectoryContents(const FileSystemPath& path, + Vector& ret, bool directoryOnly) +{ + Status status; + errno = 0; + auto dirp = ::opendir(path.str().raw()); + if (dirp == nullptr) + { + ON_ERRNO("Failed to get directory content in opendir"); + } + + while(auto ep = ::readdir(dirp)) + { + auto rel_path = String(ep->d_name); + if (rel_path == "." || rel_path == "..") + { + continue; + } + + const auto full_path = path.join(rel_path); + if (directoryOnly) + { + IF_OK_AND_TRUE(full_path.is_directory()) + { + ret.push_back(full_path); + } + } + else + { + IF_OK_AND_TRUE(full_path.is_regular_file_or_directory()) + { + ret.push_back(full_path); + } + } + } + String errno_msg; + if (errno != 0) + { + errno_msg = "Failed traversing dirp structure | "; + errno_msg += Error::from_errno(); + } + errno = 0; + const auto rc = ::closedir(dirp); + if (rc != 0) + { + errno_msg += "Failed to close dirp"; + errno_msg += Error::from_errno(); + } + if (!errno_msg.empty()) + { + return Status(errno_msg); + } + return {}; +} + +Status Directory::getAllSubDirectories(const FileSystemPath& path, + Vector& ret) +{ + const auto is_dir = path.is_directory(); + if (!is_dir.ok()) + { + return Status(is_dir.error()); + } + if (!is_dir.value()) + { + return {}; + } + + Vector dir_contents; + STATUS_CHECK(getDirectoryContents(path, dir_contents, true), + "Failed to get directory contents"); + + for (const auto& entry : dir_contents) + { + IF_OK_AND_TRUE(entry.is_directory()) + { + ret.push_back(entry); + STATUS_CHECK(getAllSubDirectories(entry, ret), + "Failed to get subdirectories"); + } + } + return {}; +} + +Status Directory::getFiles(const FileSystemPath& path, + Vector& ret, + bool recursive, + const String& extension) +{ + const auto is_dir = path.is_directory(); + if (!is_dir.ok()) + { + return Status(is_dir.error()); + } + if (!is_dir.value()) + { + return {}; + } + + Vector dir_contents; + STATUS_CHECK(getDirectoryContents(path, dir_contents), + "Failed to get directory contents"); + + for (const auto& entry : dir_contents) + { + IF_OK_AND_TRUE(entry.is_regular_file()) + { + if (!extension.empty()) + { + if (entry.extension() == extension) + { + ret.push_back(entry); + } + } + else + { + ret.push_back(entry); + } + } + else if(recursive) + { + IF_OK_AND_TRUE(entry.is_directory()) + { + Vector child_paths; + STATUS_CHECK(getFiles(entry, child_paths, recursive, extension), "Failed to get files"); + ret.extend(child_paths); + } + } + } + return {}; +} + +Status Directory::getFilesWithExtension(const FileSystemPath& path, + const String& extension, + Vector& ret, + bool recursive) +{ + return getFiles(path, ret, recursive, extension); +} + +Status Directory::create(const FileSystemPath& path, bool existsOk) +{ + FileSystemPath working_path; + if (path.is_directory().value()) + { + working_path = path; + } + else + { + working_path = path.parent_path(); + } + + if (working_path.exists()) + { + if (!existsOk) + { + return Status(Error( + "Attempted to create existing directory." + )); + } + return {}; + } + else + { + errno = 0; + mode_t mode{S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH}; + Status status; + const auto rc = ::mkdir(working_path.str().raw(), + mode); + if (rc !=0) + { + status.on_errno("Failed to create directory."); + } + return status; + } + return {}; +} diff --git a/src/base/core/filesystem/Directory.h b/src/base/core/filesystem/Directory.h new file mode 100644 index 0000000..ec9d283 --- /dev/null +++ b/src/base/core/filesystem/Directory.h @@ -0,0 +1,27 @@ +#pragma once + +#include "Vector.h" +#include "FileSystemPath.h" +#include "Result.h" + +class Directory +{ +public: + static Status getDirectoryContents(const FileSystemPath& path, + Vector& content, bool directoryOnly=false); + + static Status create(const FileSystemPath& path, bool existsOK = false); + + static Status getAllSubDirectories(const FileSystemPath& path, + Vector& content); + + static Status getFiles(const FileSystemPath& path, + Vector& content, + bool recursive=false, + const String& extension = {}); + + static Status getFilesWithExtension(const FileSystemPath& path, + const String& extension, + Vector& content, + bool recursive=false); +}; diff --git a/src/base/core/filesystem/File.cpp b/src/base/core/filesystem/File.cpp new file mode 100644 index 0000000..be2cd39 --- /dev/null +++ b/src/base/core/filesystem/File.cpp @@ -0,0 +1,142 @@ +#include "File.h" + +#include "Char.h" +#include "Directory.h" +#include "Result.h" +#include "FilePosixImpl.h" + +File::File(const FileSystemPath& path) + : m_impl(Ptr::create()), + m_path(path) +{ +} + +File::~File() +{ + close(); +} + +Status File::close() +{ + return m_impl->do_close(); +} + +bool File::exists() const +{ + return m_path.exists(); +} + +String File::getExtension() const +{ + return m_path.extension(); +} + +FileFormat::Format File::inferFormat() const +{ + const auto extension = getExtension(); + return FileFormat::inferFormat(extension); +} + +Status File::open(AccessMode accessMode) +{ + if (m_path.is_absolute() && !m_path.parent_path().exists()) + { + Directory::create(m_path.parent_path(), true); + } + return m_impl->do_open(m_path, accessMode); +} + +Status File::read(VecBytes& buffer) +{ + if (const auto rc = open(AccessMode::Read); !rc.ok()) + { + return rc; + } + + if (const auto rc = m_impl->update_size(); !rc.ok()) + { + return rc; + } + + buffer.resize(m_impl->m_size); + const auto result = m_impl->do_read(buffer); + if (!result.ok()) + { + return Status(result.error()); + } + buffer.resize(result.value()); + return {}; +} + +Status File::read(String& ret) +{ + if (const auto rc = open(AccessMode::Read); !rc.ok()) + { + return rc; + } + + VecBytes buffer; + if (const auto rc = m_impl->update_size(); rc.ok() && m_impl->m_size > 0) + { + buffer.resize(m_impl->m_size); + const auto result = m_impl->do_read(buffer); + if (!result.ok()) + { + return Status(result.error()); + } + buffer.resize(result.value()); + ret.append(buffer); + } + else + { + buffer.resize(1024); + while(true) + { + const auto result = m_impl->do_read(buffer); + if (!result.ok()) + { + return Status(result.error()); + } + if (result.value() < 1024) + { + if (result.value() > 0) + { + buffer.resize(result.value()); + ret.append(buffer); + } + break; + } + else + { + ret.append(buffer); + } + } + } + return {}; +} + +Status File::write(const String& text) +{ + bool had_to_open{false}; + Status status; + if (!m_impl->is_open_for_write()) + { + had_to_open = true; + status = m_impl->do_open(m_path, File::AccessMode::Write); + if (!status.ok()) + { + return status; + } + } + const auto result = m_impl->do_write(text.data(), text.data().size() - 1); + if (!result.ok()) + { + return Status(result.error()); + } + + if (had_to_open) + { + status = m_impl->do_close(); + } + return status; +} \ No newline at end of file diff --git a/src/base/core/filesystem/File.h b/src/base/core/filesystem/File.h new file mode 100644 index 0000000..335b8bd --- /dev/null +++ b/src/base/core/filesystem/File.h @@ -0,0 +1,48 @@ +#pragma once + +#include "FileFormats.h" +#include "FileSystemPath.h" +#include "String.h" +#include "Byte.h" +#include "Pointer.h" + +class FilePosixImpl; + +class File +{ +public: + enum class AccessMode{ + Read, + Write + }; + +public: + File(const FileSystemPath& path); + + ~File(); + + Status close(); + + bool exists() const; + + bool finished() const; + + String getExtension() const; + + FileFormat::Format inferFormat() const; + + Status open(AccessMode mode); + + Status read(VecBytes& bytes); + + Status read(String& buffer); + + Status write(const String& buffer); + + Status write(const VecBytes& bytes); + +private: + Ptr m_impl; + FileSystemPath m_path; + bool mGotEndOfFile{false}; +}; diff --git a/src/base/core/filesystem/FileFormats.cpp b/src/base/core/filesystem/FileFormats.cpp new file mode 100644 index 0000000..5bfa34b --- /dev/null +++ b/src/base/core/filesystem/FileFormats.cpp @@ -0,0 +1,34 @@ +#include "FileFormats.h" + +#include "StringUtils.h" + +FileFormat::ExtensionMap FileFormat::mExtensions = [] +{ + ExtensionMap ret; + //ret.insert(Format::Markdown, ".md"); + //ret.insert(Format::Html, ".html"); + //ret.insert(Format::Wav, ".wav"); + return ret; +}(); + +bool FileFormat::isFormat(const String& extension, Format format) +{ + return String::to_lower(extension) == (*mExtensions.find(format)).value(); +} + +FileFormat::Format FileFormat::inferFormat(const String& query) +{ + for(const auto& extension : mExtensions) + { + if(extension.value() == query) + { + return extension.key(); + } + } + return Format::Unknown; +} + +String FileFormat::getExtension(Format format) +{ + return (*mExtensions.find(format)).value(); +} diff --git a/src/base/core/file_utilities/FileFormats.h b/src/base/core/filesystem/FileFormats.h similarity index 55% rename from src/base/core/file_utilities/FileFormats.h rename to src/base/core/filesystem/FileFormats.h index 0dccf8f..1aeb124 100644 --- a/src/base/core/file_utilities/FileFormats.h +++ b/src/base/core/filesystem/FileFormats.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Map.h" +#include "String.h" class FileFormat{ @@ -24,13 +24,13 @@ public: Unknown }; - using ExtensionMap = std::map; + using ExtensionMap = Map; public: - static bool isFormat(const std::string& extension, Format format); + static bool isFormat(const String& extension, Format format); - static Format inferFormat(const std::string& query); + static Format inferFormat(const String& query); - static std::string getExtension(Format format); + static String getExtension(Format format); private: static ExtensionMap mExtensions; diff --git a/src/base/core/filesystem/FileSystemPath.cpp b/src/base/core/filesystem/FileSystemPath.cpp new file mode 100644 index 0000000..06794ae --- /dev/null +++ b/src/base/core/filesystem/FileSystemPath.cpp @@ -0,0 +1,184 @@ +#include "FileSystemPath.h" + +#include +#include +#include +#include + +FileSystemPath::FileSystemPath() +{ +} + +FileSystemPath::FileSystemPath(const String& path) + : m_path(path) +{ +} + +FileSystemPath::FileSystemPath(const char* path) + : m_path(path) +{ + +} + +const String& FileSystemPath::str() const +{ + return m_path; +} + +Result FileSystemPath::is_empty() const +{ + ERROR_IF_NOT_OK_OR_TRUE(is_regular_file(), + "Requested empty check but target is not regular file."); + const auto size_result = get_size(); + if (!size_result.ok()) + { + return {size_result.error().msg()}; + } + return {size_result.value() == 0}; +} + +Result FileSystemPath::get_size() const +{ + ERROR_IF_NOT_OK_OR_TRUE(is_regular_file(), + "Requested size check but target is not regular file."); + + struct stat buf; + errno = 0; + const auto rc = ::stat(m_path.raw(), &buf); + if (rc != 0) + { + ON_ERRNO_RESULT("Failed to stat file"); + } + return buf.st_size; +} + +Result FileSystemPath::current_dir() +{ + errno = 0; + const auto path_max = ::pathconf(".", _PC_PATH_MAX); + size_t size{0}; + if (path_max == -1) + { + size = 1024; + } + else if(path_max > 10240) + { + size = 10240; + } + else + { + size = path_max; + } + + Vector buffer(path_max); + errno = 0; + const auto ret = ::getcwd(buffer.data(), path_max); + if (ret == nullptr) + { + ON_ERRNO_RESULT("Failed to get cwd"); + } + return FileSystemPath(String(buffer.data())); +} + +Result FileSystemPath::is_regular_file() const +{ + struct stat path_stat; + const auto rc = ::stat(m_path.raw(), &path_stat); + if (rc != 0) + { + ON_ERRNO_RESULT("Failed to stat file"); + } + return S_ISREG(path_stat.st_mode); +} + +Result FileSystemPath::is_directory() const +{ + struct stat path_stat; + const auto rc = ::stat(m_path.raw(), &path_stat); + if (rc != 0) + { + ON_ERRNO_RESULT("Failed to stat file"); + } + return S_ISDIR(path_stat.st_mode); +} + +Result FileSystemPath::is_regular_file_or_directory() const +{ + struct stat path_stat; + const auto rc = ::stat(m_path.raw(), &path_stat); + if (rc != 0) + { + ON_ERRNO_RESULT("Failed to stat file"); + } + return S_ISREG(path_stat.st_mode) || S_ISDIR(path_stat.st_mode); +} + +bool FileSystemPath::is_absolute() const +{ + return false; +} + +FileSystemPath FileSystemPath::parent_path() const +{ + const auto split = m_path.rsplit('/'); + return FileSystemPath(split.first()); +} + +String FileSystemPath::extension() const +{ + const auto split = m_path.rsplit('.'); + String result("."); + result += split.second(); + return result; +} + +FileSystemPath FileSystemPath::stem() const +{ + const auto split = m_path.rsplit('/'); + if (split.second().empty()) + { + return split.first(); + } + else + { + return split.second(); + } +} + +bool FileSystemPath::starts_with(const String& prefix) const +{ + return m_path.starts_with(prefix); +} + +bool FileSystemPath::contains(const String& term) const +{ + return m_path.contains(term); +} + +String FileSystemPath::file_name() const +{ + String name_and_ext; + const auto split = m_path.rsplit('/'); + if (split.second().empty()) + { + name_and_ext = split.first(); + } + else + { + name_and_ext = split.second(); + } + return name_and_ext.rsplit('.').first(); +} + +bool FileSystemPath::exists() const +{ + return ::access(m_path.raw(), F_OK) == 0; +} + +FileSystemPath FileSystemPath::join(const String& entry) const +{ + auto new_path = *this; + new_path.m_path += m_delimiter; + new_path.m_path += entry; + return new_path; +} \ No newline at end of file diff --git a/src/base/core/filesystem/FileSystemPath.h b/src/base/core/filesystem/FileSystemPath.h new file mode 100644 index 0000000..4b8772b --- /dev/null +++ b/src/base/core/filesystem/FileSystemPath.h @@ -0,0 +1,64 @@ +#pragma once + +#include "String.h" +#include "Result.h" + +class FileSystemPath +{ +public: + FileSystemPath(); + + FileSystemPath(const String& path); + + FileSystemPath(const char* path); + + const String& str() const; + + static Result current_dir(); + + String extension() const; + + String file_name() const; + + bool exists() const; + + Result is_empty() const; + + Result get_size() const; + + FileSystemPath join(const String& entry) const; + + Result is_regular_file() const; + + Result is_directory() const; + + Result is_regular_file_or_directory() const; + + bool is_absolute() const; + + FileSystemPath parent_path() const; + + FileSystemPath stem() const; + + bool contains(const String& term) const; + + bool starts_with(const String& prefix) const; + + FileSystemPath operator/ (const char* body) const + { + String ret = m_path; + ret += m_delimiter + String(body); + return ret; + } + + FileSystemPath operator/ (const String& body) const + { + String ret = m_path; + ret += m_delimiter + body; + return ret; + } + +private: + String m_delimiter{"/"}; + String m_path; +}; \ No newline at end of file diff --git a/src/base/core/filesystem/PathUtils.cpp b/src/base/core/filesystem/PathUtils.cpp new file mode 100644 index 0000000..190952b --- /dev/null +++ b/src/base/core/filesystem/PathUtils.cpp @@ -0,0 +1,37 @@ +#include "PathUtils.h" + + +String PathUtils::getBaseFilename(const FileSystemPath& path) +{ + //return path.stem().string(); + return {}; +} + +FileSystemPath PathUtils::getRelativePath(const FileSystemPath& input, const FileSystemPath& relativeTo) +{ + //return std::filesystem::relative(input, relativeTo); + return input; +} + +String PathUtils::getPathDelimited(const FileSystemPath& path, char delimiter) +{ + String name; + /* + + unsigned count = 0; + for(const auto& element : path) + { + if (count == 0) + { + name += element.stem().string(); + } + else + { + name += delimiter + element.stem().string(); + } + count++; + } + */ + + return name; +} diff --git a/src/base/core/filesystem/PathUtils.h b/src/base/core/filesystem/PathUtils.h new file mode 100644 index 0000000..1feb44b --- /dev/null +++ b/src/base/core/filesystem/PathUtils.h @@ -0,0 +1,15 @@ +#pragma once + +#include "FileSystemPath.h" +#include "String.h" +#include "Vector.h" + +class PathUtils +{ +public: + static String getBaseFilename(const FileSystemPath& path); + + static FileSystemPath getRelativePath(const FileSystemPath& path, const FileSystemPath& relativeTo); + + static String getPathDelimited(const FileSystemPath& path, char delimiter='-'); +}; diff --git a/src/base/core/filesystem/posix/FilePosixImpl.cpp b/src/base/core/filesystem/posix/FilePosixImpl.cpp new file mode 100644 index 0000000..438da5f --- /dev/null +++ b/src/base/core/filesystem/posix/FilePosixImpl.cpp @@ -0,0 +1,121 @@ +#include "FilePosixImpl.h" + +#include +#include +#include +#include +#include +#include +#include + +Status FilePosixImpl::do_open(const FileSystemPath& path, File::AccessMode accessMode) +{ + int flags{0}; + if (accessMode == File::AccessMode::Read) + { + flags |= O_RDONLY; + } + else + { + flags |= O_WRONLY; + flags |= O_CREAT; + } + errno = 0; + m_fd = ::open(path.str().raw(), flags); + if (m_fd < 0) + { + return Status::with_errno("Failed to open file with"); + } + + if (accessMode == File::AccessMode::Read) + { + m_open_for_read = true; + } + else + { + m_open_for_write = true; + } + return {}; +} + +Status FilePosixImpl::do_close() +{ + errno = 0; + if (const auto rc = ::close(m_fd); rc < 0) + { + Status::with_errno("Failed to close file with"); + } + m_open_for_read = false; + m_open_for_write = false; + return {}; +} + +bool FilePosixImpl::is_ok() const +{ + return m_valid; +} + +bool FilePosixImpl::is_open_for_read() const +{ + return m_open_for_read; +} + +bool FilePosixImpl::is_open_for_write() const +{ + return m_open_for_write; +} + +Result FilePosixImpl::do_read(VecBytes& bytes) +{ + errno = 0; + const auto rc = ::read(m_fd, bytes.data(), bytes.capacity()); + if (rc < 0) + { + const auto msg = _s("Error in read impl | ") + Error::from_errno(); + return Result(Error(msg)); + } + return Result(rc); +} + +Result FilePosixImpl::do_write(const VecBytes& bytes) +{ + errno = 0; + const auto rc = ::write(m_fd, bytes.data(), bytes.size()); + if (rc < 0) + { + const auto msg = _s("Error in write impl | ") + Error::from_errno(); + return Result(Error(msg)); + } + return Result(rc); +} + +Result FilePosixImpl::do_write(const Vector& bytes, int size) +{ + errno = 0; + int rc = 0; + if (size > -1) + { + rc = ::write(m_fd, bytes.data(), size); + } + else + { + rc = ::write(m_fd, bytes.data(), bytes.size()); + } + if (rc < 0) + { + const auto msg = _s("Error in write impl | ") + Error::from_errno(); + return Result(Error(msg)); + } + return Result(rc); +} + +Status FilePosixImpl::update_size() +{ + struct stat buf; + if (const auto rc = ::fstat(m_fd, &buf); rc != 0) + { + return Status::with_errno("Failed to get size with fstat"); + } + m_size = buf.st_size; + return {}; +} \ No newline at end of file diff --git a/src/base/core/filesystem/posix/FilePosixImpl.h b/src/base/core/filesystem/posix/FilePosixImpl.h new file mode 100644 index 0000000..0409ac1 --- /dev/null +++ b/src/base/core/filesystem/posix/FilePosixImpl.h @@ -0,0 +1,34 @@ +#pragma once + +#include "FileSystemPath.h" +#include "File.h" + +class FilePosixImpl +{ +public: + Status do_open(const FileSystemPath& path, + File::AccessMode accessMode); + + Status do_close(); + + bool is_ok() const; + + bool is_open_for_read() const; + + bool is_open_for_write() const; + + Result do_read(VecBytes& bytes); + + Result do_write(const VecBytes& bytes); + + Result do_write(const Vector& bytes, int size = -1); + + Status update_size(); + + bool m_open_for_write{false}; + bool m_open_for_read{false}; + bool m_valid{false}; + size_t m_size{0}; + bool m_is_open{false}; + int m_fd{-1}; +}; \ No newline at end of file diff --git a/src/base/core/http/HttpHeader.h b/src/base/core/http/HttpHeader.h deleted file mode 100644 index d9b231d..0000000 --- a/src/base/core/http/HttpHeader.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -#include - -class HttpHeader -{ -public: - HttpHeader(); - void parse(const std::vector& message); - - std::string getContentType() const; - - std::string getHttpVersion() const; - -private: - std::string mHttpVersion; - std::string mContentType; - std::string mHost; - std::string mUserAgent; - std::string mAccept; - std::string mAcceptLanguage; - std::string mAcceptEncoding; - std::string mConnection; - std::string mReferer; - std::string mSecFetchDest; - std::string mSecFetchMode; - std::string mSecFetchSite; - - std::map mOtherFields; -}; diff --git a/src/base/core/http/HttpParser.h b/src/base/core/http/HttpParser.h deleted file mode 100644 index 78ec0d1..0000000 --- a/src/base/core/http/HttpParser.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "HttpPreamble.h" - -class HttpParser -{ -public: - static bool parsePreamble(const std::string& line, HttpPreamble& preamble); -}; \ No newline at end of file diff --git a/src/base/core/http/HttpPreamble.h b/src/base/core/http/HttpPreamble.h deleted file mode 100644 index c92d9c7..0000000 --- a/src/base/core/http/HttpPreamble.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -struct HttpPreamble -{ - std::string mMethod; - std::string mPath; - std::string mVersion; -}; \ No newline at end of file diff --git a/src/base/core/http/HttpResponse.cpp b/src/base/core/http/HttpResponse.cpp deleted file mode 100644 index 6f3a0d5..0000000 --- a/src/base/core/http/HttpResponse.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#include "HttpResponse.h" - -#include "StringUtils.h" -#include "HttpParser.h" - -#include - -HttpResponse::HttpResponse() - : mStatusCode(200), - mResponseReason("OK"), - mBody() -{ - -} - -HttpResponse::~HttpResponse() -{ - -} - -const HttpHeader& HttpResponse::getHeader() const -{ - return mHeader; -} - -unsigned short HttpResponse::getStatusCode() const -{ - return mStatusCode; -} - -const std::string& HttpResponse::getBody() const -{ - return mBody; -} - -void HttpResponse::setBody(const std::string& body) -{ - mBody = body; -} - -void HttpResponse::fromMessage(const std::string& message) -{ - std::stringstream ss(message); - - std::string buffer; - bool firstLine{ true }; - - std::vector headers; - while (std::getline(ss, buffer, '\n')) - { - if (firstLine) - { - HttpParser::parsePreamble(buffer, mPreamble); - firstLine = false; - } - else - { - headers.push_back(buffer); - } - } - mHeader.parse(headers); -} - -unsigned HttpResponse::getBodyLength() const -{ - return unsigned(mBody.length()); -} - -void HttpResponse::setClientError(const ClientError& error) -{ - mClientError = error; -} - -std::string HttpResponse::getHeaderString() const -{ - std::string header = "HTTP/" + mHeader.getHttpVersion() + " " + std::to_string(mStatusCode) + " " + mResponseReason + "\n"; - header += "Content-Type: " + mHeader.getContentType() + "\n"; - header += "Content-Length: " + std::to_string(getBodyLength()) + "\n"; - return header; -} - -const std::string& HttpResponse::getResponseReason() const -{ - return mResponseReason; -} - -std::string HttpResponse::toString() const -{ - return getHeaderString() + "\n\n" + mBody; -} - -void HttpResponse::setStatusCode(unsigned short code) -{ - mStatusCode = code; -} - -void HttpResponse::setResponseReason(const std::string& reason) -{ - mResponseReason = reason; -} diff --git a/src/base/core/loggers/FileLogger.cpp b/src/base/core/loggers/FileLogger.cpp deleted file mode 100644 index d9330b9..0000000 --- a/src/base/core/loggers/FileLogger.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include "FileLogger.h" - -#include -#include -#include -#include - -FileLogger::~FileLogger() -{ - -} - -void FileLogger::SetWorkDirectory(const std::string& workDir) -{ - mWorkDirectory = workDir; -} - -void FileLogger::SetFileName(const std::string& fileName) -{ - mFileName = fileName; -} - -void FileLogger::Open() -{ - if (mWorkDirectory.empty()) - { - mWorkDirectory = std::filesystem::current_path().string(); - } - mFileStream.open(mWorkDirectory + "/" + mFileName); -} - -void FileLogger::Close() -{ - mFileStream.close(); -} - -void FileLogger::LogLine(const std::ostringstream& line) -{ - if (mDisabled) - { - return; - } - - if (!mFileStream.is_open()) - { - Open(); - } - mFileStream << line.str() << std::endl; -} - -void FileLogger::disable() -{ - mDisabled = true; -} - -void FileLogger::LogLine(const std::string& logType, const std::ostringstream& line, const std::string& fileName, const std::string& functionName, int lineNumber) -{ - if (mDisabled) - { - return; - } - - std::time_t t = std::time(nullptr); - const std::string cleanedFileName = fileName.substr(fileName.find_last_of("/\\") + 1); - std::tm time_buf{ }; -#ifdef WIN32 - gmtime_s(&time_buf, &t); -#else - gmtime_r(&t, &time_buf); -#endif - std::cout << logType << "|" << std::put_time(&time_buf, "%T") << "|" << cleanedFileName << "::" << functionName << "::" << lineNumber << "|" << line.str() << std::endl; - mFileStream << logType << "|" << std::put_time(&time_buf, "%T") << "|" << cleanedFileName << "::" << functionName << "::" << lineNumber << "|" << line.str() << std::endl; -} diff --git a/src/base/core/loggers/FileLogger.h b/src/base/core/loggers/FileLogger.h deleted file mode 100644 index 1d73311..0000000 --- a/src/base/core/loggers/FileLogger.h +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once - -#define MLOG_ALL(msg, level) {std::ostringstream mt_logstream;\ - mt_logstream << msg; \ - FileLogger::GetInstance().LogLine(level, mt_logstream, __FILE__, __FUNCTION__, __LINE__);}; - -#define MLOG_INFO(msg) MLOG_ALL(msg, "Info"); -#define MLOG_ERROR(msg) MLOG_ALL(msg, "Error"); - -#include -#include -#include -#include - -class FileLogger -{ - FileLogger() - :mWorkDirectory(), - mFileName("MT_Log.txt"), - mFileStream() - { - - } - -public: - static FileLogger& GetInstance() - { - static FileLogger instance; - return instance; - } - - FileLogger(FileLogger const&) = delete; - void operator=(FileLogger const&) = delete; - - ~FileLogger(); - - void disable(); - - void SetWorkDirectory(const std::string& workDir); - - void SetFileName(const std::string& fileName); - - void Open(); - - void Close(); - - void LogLine(const std::ostringstream& line); - - void LogLine(const std::string& logType, const std::ostringstream& line, const std::string& fileName = "", const std::string& functionName = "", int lineNumber=-1); -private: - bool mDisabled{false}; - std::string mWorkDirectory; - std::string mFileName; - std::ofstream mFileStream; -}; - -using FileLoggerPtr = std::shared_ptr; diff --git a/src/base/core/logging/ConsoleLogger.cpp b/src/base/core/logging/ConsoleLogger.cpp new file mode 100644 index 0000000..b06b73b --- /dev/null +++ b/src/base/core/logging/ConsoleLogger.cpp @@ -0,0 +1,24 @@ +#include "ConsoleLogger.h" + +#include + +void ConsoleLogger::log_line(Level level, + const String& msg, + const String& fileName, + const String& functionName, + int lineNumber) +{ + const auto log_msg = build_log_message(level, + msg, + fileName, + functionName, + lineNumber); + if (level == Level::INFO) + { + printf("%s\n", log_msg.raw()); + } + else + { + fprintf(stderr, "%s\n", log_msg.raw()); + } +} \ No newline at end of file diff --git a/src/base/core/logging/ConsoleLogger.h b/src/base/core/logging/ConsoleLogger.h new file mode 100644 index 0000000..9790e5a --- /dev/null +++ b/src/base/core/logging/ConsoleLogger.h @@ -0,0 +1,13 @@ +#pragma once + +#include "Logger.h" + +class ConsoleLogger : public Logger +{ +public: + void log_line(Level level, + const String& line, + const String& fileName, + const String& functionName, + int lineNumber) override; +}; \ No newline at end of file diff --git a/src/base/core/logging/FileLogger.cpp b/src/base/core/logging/FileLogger.cpp new file mode 100644 index 0000000..f5305ab --- /dev/null +++ b/src/base/core/logging/FileLogger.cpp @@ -0,0 +1,70 @@ +#include "FileLogger.h" + +#include "FileSystemPath.h" + +FileLogger::FileLogger() + :mWorkDirectory(), + mFileName("MT_Log.txt") +{ + +} + +FileLogger::~FileLogger() +{ + +} + +void FileLogger::SetWorkDirectory(const String& workDir) +{ + mWorkDirectory = workDir; +} + +void FileLogger::SetFileName(const String& fileName) +{ + mFileName = fileName; +} + +void FileLogger::Open() +{ + if (mWorkDirectory.empty()) + { + mWorkDirectory = FileSystemPath::current_dir().value().str(); + } + //mFileStream.open(mWorkDirectory + "/" + mFileName); +} + +void FileLogger::Close() +{ + //mFileStream.close(); +} + +void FileLogger::disable() +{ + mDisabled = true; +} + +void FileLogger::log_line(Level level, + const String& line, + const String& fileName, + const String& functionName, + int lineNumber) +{ + if (mDisabled) + { + return; + } + + const auto log_msg = build_log_message(level, + line, + fileName, + functionName, + lineNumber); + if (level == Level::INFO) + { + //printf("%s\n", log_msg.raw()); + } + else + { + //fprintf(stderr, "%s\n", log_msg.raw()); + } +} diff --git a/src/base/core/logging/FileLogger.h b/src/base/core/logging/FileLogger.h new file mode 100644 index 0000000..92f8e9c --- /dev/null +++ b/src/base/core/logging/FileLogger.h @@ -0,0 +1,30 @@ +#pragma once + +#include "Logger.h" + +class FileLogger : public Logger +{ + FileLogger(); + + ~FileLogger(); + + void disable(); + + void SetWorkDirectory(const String& workDir); + + void SetFileName(const String& fileName); + + void Open(); + + void Close(); + + void log_line(Level level, + const String& line, + const String& fileName, + const String& functionName, + int lineNumber) override; +private: + bool mDisabled{false}; + String mWorkDirectory; + String mFileName; +}; \ No newline at end of file diff --git a/src/base/core/logging/Logger.cpp b/src/base/core/logging/Logger.cpp new file mode 100644 index 0000000..3cc76e2 --- /dev/null +++ b/src/base/core/logging/Logger.cpp @@ -0,0 +1,48 @@ +#include "Logger.h" + +#include "Time.h" +#include "ConsoleLogger.h" + +static Ptr s_logger; + +Logger* Logger::get_instance() +{ + if (s_logger.get() == nullptr) + { + s_logger = Ptr::create(); + } + return s_logger.get(); +} + +String Logger::build_log_message(Level level, + const String& msg, + const String& fileName, + const String& functionName, + int lineNumber) +{ + String log_msg; + if (level == Level::INFO) + { + log_msg += "Info|"; + } + else if (level == Level::ERROR) + { + log_msg += "Error|"; + } + log_msg += Time::get_now_str() + "|"; + + String cleaned_filename; + if (auto index = fileName.rindex('/'); index.valid()) + { + fileName.slice(index.value()+1, fileName.size(), cleaned_filename); + } + else + { + cleaned_filename = fileName; + } + log_msg += cleaned_filename + "::"; + log_msg += functionName + "::"; + log_msg += String::to_string(lineNumber) + "|"; + log_msg += msg; + return log_msg; +} \ No newline at end of file diff --git a/src/base/core/logging/Logger.h b/src/base/core/logging/Logger.h new file mode 100644 index 0000000..a8d6430 --- /dev/null +++ b/src/base/core/logging/Logger.h @@ -0,0 +1,36 @@ +#pragma once + +#include "String.h" +#include "Pointer.h" + +#define LOG_ALL(msg, level) {String mt_logstream;\ + mt_logstream << msg; \ + Logger::get_instance()->log_line(level, mt_logstream, __FILE__, __FUNCTION__, __LINE__);}; +#define LOG_INFO(msg) LOG_ALL(msg, Logger::Level::INFO); +#define LOG_ERROR(msg) LOG_ALL(msg, Logger::Level::ERROR); + +class Logger +{ +public: + enum class Level + { + INFO, + ERROR + }; + + virtual ~Logger() = default; + virtual void log_line(Level level, + const String& line, + const String& fileName, + const String& functionName, + int lineNumber){}; + + static Logger* get_instance(); + +protected: + static String build_log_message(Level level, + const String& line, + const String& fileName, + const String& functionName, + int lineNumber); +}; \ No newline at end of file diff --git a/src/base/core/memory/Allocator.h b/src/base/core/memory/Allocator.h new file mode 100644 index 0000000..26ef3cb --- /dev/null +++ b/src/base/core/memory/Allocator.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +template +class Allocator +{ +public: + template + T* allocate(U&& u) + { + return new T(std::forward(u)); + } + + T* allocate() + { + return new T(); + } + + void do_delete(T* p) + { + delete p; + } + + T* alloc_array(size_t size) + { + return new T[size]; + } + + void delete_array(T*& arr) + { + delete[] arr; + } +}; \ No newline at end of file diff --git a/src/base/core/memory/Pointer.h b/src/base/core/memory/Pointer.h new file mode 100644 index 0000000..3214e70 --- /dev/null +++ b/src/base/core/memory/Pointer.h @@ -0,0 +1,101 @@ +#pragma once + +#include "Allocator.h" +#include + +template +class Ptr +{ +public: + Ptr() + { + } + + template + static Ptr create(U&& u) + { + Ptr p; + p.allocate(std::forward(u)); + return std::move(p); + } + + static Ptr create() + { + Ptr p; + p.allocate(); + return std::move(p); + } + + template + void allocate(U&& u) + { + m_raw = m_allocator.allocate(std::forward(u)); + } + + void allocate() + { + m_raw = m_allocator.allocate(); + } + + ~Ptr() + { + reset(); + } + + void reset() + { + if (m_raw != nullptr) + { + m_allocator.do_delete(m_raw); + } + } + + Ptr(const Ptr& other) = delete; + + Ptr(Ptr&& other) + { + *this = std::move(other); + } + + void clear_raw() + { + m_raw = nullptr; + } + + T* get() const + { + return m_raw; + } + + Ptr& operator=(const Ptr& other) = delete; + + template + Ptr& operator=(Ptr&& other) + { + if (this->m_raw != other.get()) + { + this->m_raw = dynamic_cast(other.get()); + other.clear_raw(); + } + return *this; + } + + const T* operator->() const + { + return m_raw; + } + + T* operator->() + { + return m_raw; + } + + operator bool() const + { + return m_raw != nullptr; + } + +private: + Allocator m_allocator; + T* m_raw{nullptr}; +}; \ No newline at end of file diff --git a/src/base/core/memory/SharedMemory.cpp b/src/base/core/memory/SharedMemory.cpp index 5cb9901..2ec3cc3 100644 --- a/src/base/core/memory/SharedMemory.cpp +++ b/src/base/core/memory/SharedMemory.cpp @@ -4,13 +4,15 @@ #ifdef __linux__ #include +#include +#include #include #include #include #include #endif -void SharedMemory::allocate(const std::string& namePrefix, std::size_t size) +void SharedMemory::allocate(const String& namePrefix, size_t size) { createFile(namePrefix); @@ -45,7 +47,7 @@ bool SharedMemory::isValid() const return mIsValid; } -void SharedMemory::createFile(const std::string& namePrefix) +void SharedMemory::createFile(const String& namePrefix) { #ifdef __linux__ unsigned retries = 100; @@ -53,10 +55,10 @@ void SharedMemory::createFile(const std::string& namePrefix) const auto name = getRandomName(namePrefix); --retries; - const int fd = shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600); + const int fd = shm_open(name.raw(), O_RDWR | O_CREAT | O_EXCL, 0600); if (fd >= 0) { - shm_unlink(name.c_str()); + shm_unlink(name.raw()); mFileDescriptor = fd; mIsValid = true; break; @@ -67,12 +69,12 @@ void SharedMemory::createFile(const std::string& namePrefix) #endif } -std::string SharedMemory::getRandomName(const std::string& namePrefix) const +String SharedMemory::getRandomName(const String& namePrefix) const { - std::string randomSuffix; + String randomSuffix; for (const auto entry : RandomUtils::getRandomVecUnsigned(6)) { - randomSuffix += std::to_string(entry); + randomSuffix += String::to_string(entry); } return namePrefix + randomSuffix; } diff --git a/src/base/core/memory/SharedMemory.h b/src/base/core/memory/SharedMemory.h index d483438..4a9d30b 100644 --- a/src/base/core/memory/SharedMemory.h +++ b/src/base/core/memory/SharedMemory.h @@ -1,11 +1,11 @@ #pragma once -#include +#include "String.h" class SharedMemory { public: - void allocate(const std::string& namePrefix, std::size_t size); + void allocate(const String& namePrefix, size_t size); int getFileDescriptor() const; @@ -13,9 +13,9 @@ public: private: - void createFile(const std::string& namePrefix); + void createFile(const String& namePrefix); - std::string getRandomName(const std::string& namePrefix) const; + String getRandomName(const String& namePrefix) const; int mFileDescriptor{0}; bool mIsValid{false}; diff --git a/src/base/core/http/HttpHeader.cpp b/src/base/core/protocol/HttpHeader.cpp similarity index 79% rename from src/base/core/http/HttpHeader.cpp rename to src/base/core/protocol/HttpHeader.cpp index f4c84bc..b1147c5 100644 --- a/src/base/core/http/HttpHeader.cpp +++ b/src/base/core/protocol/HttpHeader.cpp @@ -1,5 +1,5 @@ #include "HttpHeader.h" -#include "StringUtils.h" +#include "Char.h" HttpHeader::HttpHeader() @@ -9,27 +9,27 @@ HttpHeader::HttpHeader() } -std::string HttpHeader::getContentType() const +String HttpHeader::getContentType() const { return mContentType; } -std::string HttpHeader::getHttpVersion() const +String HttpHeader::getHttpVersion() const { return mHttpVersion; } -void HttpHeader::parse(const std::vector& message) +void HttpHeader::parse(const Vector& message) { - std::string tag; - std::string value; + String tag; + String value; bool foundDelimiter{false}; for (const auto& line : message) { - for(std::size_t idx = 0; idx< line.size(); idx++) + for(size_t idx = 0; idx< line.size(); idx++) { const auto c = line[idx]; - if (c == StringUtils::COLON) + if (c == Char::COLON) { foundDelimiter = true; } @@ -91,7 +91,7 @@ void HttpHeader::parse(const std::vector& message) } else { - mOtherFields[tag] = value; + mOtherFields.insert(tag, value); } } diff --git a/src/base/core/protocol/HttpHeader.h b/src/base/core/protocol/HttpHeader.h new file mode 100644 index 0000000..b47551e --- /dev/null +++ b/src/base/core/protocol/HttpHeader.h @@ -0,0 +1,32 @@ +#pragma once + +#include "String.h" +#include "Vector.h" +#include "Map.h" + +class HttpHeader +{ +public: + HttpHeader(); + void parse(const Vector& message); + + String getContentType() const; + + String getHttpVersion() const; + +private: + String mHttpVersion; + String mContentType; + String mHost; + String mUserAgent; + String mAccept; + String mAcceptLanguage; + String mAcceptEncoding; + String mConnection; + String mReferer; + String mSecFetchDest; + String mSecFetchMode; + String mSecFetchSite; + + Map mOtherFields; +}; diff --git a/src/base/core/http/HttpParser.cpp b/src/base/core/protocol/HttpParser.cpp similarity index 79% rename from src/base/core/http/HttpParser.cpp rename to src/base/core/protocol/HttpParser.cpp index 6b66639..8c5832b 100644 --- a/src/base/core/http/HttpParser.cpp +++ b/src/base/core/protocol/HttpParser.cpp @@ -1,8 +1,9 @@ #include "HttpParser.h" -#include "StringUtils.h" +#include "Char.h" -bool HttpParser::parsePreamble(const std::string& line, HttpPreamble& preamble) +bool HttpParser::parsePreamble(const String& line, + HttpPreamble& preamble) { bool inPath{ false }; bool inMethod{ true }; @@ -12,7 +13,7 @@ bool HttpParser::parsePreamble(const std::string& line, HttpPreamble& preamble) { if (inPath) { - if (StringUtils::isSpace(c)) + if (Char::is_space(c)) { inPath = false; inMethod = true; @@ -24,7 +25,7 @@ bool HttpParser::parsePreamble(const std::string& line, HttpPreamble& preamble) } else if (inMethod) { - if (StringUtils::isSpace(c)) + if (Char::is_space(c)) { inMethod = false; inProtocol = true; diff --git a/src/base/core/protocol/HttpParser.h b/src/base/core/protocol/HttpParser.h new file mode 100644 index 0000000..bb2c530 --- /dev/null +++ b/src/base/core/protocol/HttpParser.h @@ -0,0 +1,10 @@ +#pragma once + +#include "HttpPreamble.h" + +class HttpParser +{ +public: + static bool parsePreamble(const String& line, + HttpPreamble& preamble); +}; \ No newline at end of file diff --git a/src/base/core/protocol/HttpPreamble.h b/src/base/core/protocol/HttpPreamble.h new file mode 100644 index 0000000..8cf321b --- /dev/null +++ b/src/base/core/protocol/HttpPreamble.h @@ -0,0 +1,10 @@ +#pragma once + +#include "String.h" + +struct HttpPreamble +{ + String mMethod; + String mPath; + String mVersion; +}; \ No newline at end of file diff --git a/src/base/core/http/HttpRequest.cpp b/src/base/core/protocol/HttpRequest.cpp similarity index 51% rename from src/base/core/http/HttpRequest.cpp rename to src/base/core/protocol/HttpRequest.cpp index ce813a1..d534245 100644 --- a/src/base/core/http/HttpRequest.cpp +++ b/src/base/core/protocol/HttpRequest.cpp @@ -3,9 +3,7 @@ #include "StringUtils.h" #include "HttpParser.h" -#include - -HttpRequest::HttpRequest(Verb verb, const std::string& path) +HttpRequest::HttpRequest(Verb verb, const String& path) : mVerb(verb) { mPreamble.mPath = path; @@ -16,14 +14,14 @@ HttpRequest::Verb HttpRequest::getVerb() const return mVerb; } -std::string HttpRequest::getPath() const +String HttpRequest::getPath() const { return mPreamble.mPath; } -std::string HttpRequest::toString(const std::string& host) const +String HttpRequest::toString(const String& host) const { - std::string out; + String out; if (mVerb == Verb::GET) { @@ -31,30 +29,30 @@ std::string HttpRequest::toString(const std::string& host) const } auto path = mPreamble.mPath; - out += " /" + path + " HTTP/" + mHeader.getHttpVersion() + "\n"; - out += "Host: " + host + "\n"; + out += _s(" /") + path + _s(" HTTP/") + mHeader.getHttpVersion() + _s("\n"); + out += _s("Host: ") + host + _s("\n"); out += "Accept - Encoding: \n"; return out; } -void HttpRequest::fromString(const std::string& message) +void HttpRequest::fromString(const String& message) { - std::stringstream ss(message); - - std::string buffer; + String buffer; bool firstLine{ true }; - std::vector headers; - while (std::getline(ss, buffer, '\n')) + Vector headers; + Vector lines; + message.split(lines, '\n'); + for(const auto& line : lines) { if (firstLine) { - HttpParser::parsePreamble(buffer, mPreamble); + HttpParser::parsePreamble(line, mPreamble); firstLine = false; } else { - headers.push_back(buffer); + headers.push_back(line); } } if (mPreamble.mMethod == "GET") @@ -66,7 +64,7 @@ void HttpRequest::fromString(const std::string& message) mRequiredBytes = 0; } -std::size_t HttpRequest::requiredBytes() const +size_t HttpRequest::requiredBytes() const { return mRequiredBytes; } diff --git a/src/base/core/http/HttpRequest.h b/src/base/core/protocol/HttpRequest.h similarity index 61% rename from src/base/core/http/HttpRequest.h rename to src/base/core/protocol/HttpRequest.h index f54371d..3f468ef 100644 --- a/src/base/core/http/HttpRequest.h +++ b/src/base/core/protocol/HttpRequest.h @@ -3,7 +3,7 @@ #include "HttpHeader.h" #include "HttpPreamble.h" -#include +#include "String.h" class HttpRequest { @@ -21,17 +21,17 @@ public: HttpRequest() = default; - HttpRequest(Verb verb, const std::string& path = {}); + HttpRequest(Verb verb, const String& path = {}); Verb getVerb() const; - std::string getPath() const; + String getPath() const; - void fromString(const std::string& string); + void fromString(const String& string); - std::string toString(const std::string& host) const; + String toString(const String& host) const; - std::size_t requiredBytes() const; + size_t requiredBytes() const; private: Verb mVerb = Verb::UNKNOWN; diff --git a/src/base/core/protocol/HttpResponse.cpp b/src/base/core/protocol/HttpResponse.cpp new file mode 100644 index 0000000..eda80dd --- /dev/null +++ b/src/base/core/protocol/HttpResponse.cpp @@ -0,0 +1,98 @@ +#include "HttpResponse.h" + +#include "StringUtils.h" +#include "HttpParser.h" + +HttpResponse::HttpResponse() + : mStatusCode(200), + mResponseReason("OK"), + mBody() +{ + +} + +HttpResponse::~HttpResponse() +{ + +} + +const HttpHeader& HttpResponse::getHeader() const +{ + return mHeader; +} + +unsigned short HttpResponse::getStatusCode() const +{ + return mStatusCode; +} + +const String& HttpResponse::getBody() const +{ + return mBody; +} + +void HttpResponse::setBody(const String& body) +{ + mBody = body; +} + +void HttpResponse::fromMessage(const String& message) +{ + String buffer; + bool firstLine{ true }; + + Vector headers; + Vector lines; + message.split(lines, '\n'); + for(const auto& line : lines) + { + if (firstLine) + { + HttpParser::parsePreamble(line, mPreamble); + firstLine = false; + } + else + { + headers.push_back(line); + } + } + mHeader.parse(headers); +} + +unsigned HttpResponse::getBodyLength() const +{ + return unsigned(mBody.size()); +} + +void HttpResponse::setClientError(const ClientError& error) +{ + mClientError = error; +} + +String HttpResponse::getHeaderString() const +{ + String header = _s("HTTP/") + mHeader.getHttpVersion() + _s(" ") + String::to_string(mStatusCode) + _s(" ") + mResponseReason + _s("\n"); + header += _s("Content-Type: ") + mHeader.getContentType() + _s("\n"); + header += _s("Content-Length: ") + String::to_string(getBodyLength()) + _s("\n"); + return header; +} + +const String& HttpResponse::getResponseReason() const +{ + return mResponseReason; +} + +String HttpResponse::toString() const +{ + return getHeaderString() + _s("\n\n") + mBody; +} + +void HttpResponse::setStatusCode(unsigned short code) +{ + mStatusCode = code; +} + +void HttpResponse::setResponseReason(const String& reason) +{ + mResponseReason = reason; +} diff --git a/src/base/core/http/HttpResponse.h b/src/base/core/protocol/HttpResponse.h similarity index 57% rename from src/base/core/http/HttpResponse.h rename to src/base/core/protocol/HttpResponse.h index 80dd903..4a06746 100644 --- a/src/base/core/http/HttpResponse.h +++ b/src/base/core/protocol/HttpResponse.h @@ -3,14 +3,14 @@ #include "HttpHeader.h" #include "HttpPreamble.h" -#include +#include "String.h" class HttpResponse { public: struct ClientError { - std::string mMessage; + String mMessage; int mCode{ -1 }; }; @@ -18,27 +18,27 @@ public: ~HttpResponse(); - void fromMessage(const std::string& message); + void fromMessage(const String& message); unsigned getBodyLength() const; - const std::string& getBody() const; + const String& getBody() const; const HttpHeader& getHeader() const; - std::string getHeaderString() const; + String getHeaderString() const; - std::string toString() const; + String toString() const; unsigned short getStatusCode() const; - const std::string& getResponseReason() const; + const String& getResponseReason() const; void setStatusCode(unsigned short code); - void setResponseReason(const std::string& reason); + void setResponseReason(const String& reason); - void setBody(const std::string& body); + void setBody(const String& body); void setClientError(const ClientError& error); @@ -48,6 +48,6 @@ private: ClientError mClientError; unsigned short mStatusCode{ 200 }; - std::string mResponseReason{ }; - std::string mBody; + String mResponseReason{ }; + String mBody; }; diff --git a/src/base/core/RandomUtils.cpp b/src/base/core/random/RandomUtils.cpp similarity index 78% rename from src/base/core/RandomUtils.cpp rename to src/base/core/random/RandomUtils.cpp index fa31fab..9c0fdb7 100644 --- a/src/base/core/RandomUtils.cpp +++ b/src/base/core/random/RandomUtils.cpp @@ -4,7 +4,7 @@ #include #include -std::vector RandomUtils::getRandomVecUnsigned(std::size_t size) +Vector RandomUtils::getRandomVecUnsigned(size_t size) { std::random_device rnd_device; @@ -16,7 +16,7 @@ std::vector RandomUtils::getRandomVecUnsigned(std::size_t size) return dist(mersenne_engine); }; - std::vector vec(size); + Vector vec(size); std::generate(std::begin(vec), std::end(vec), generator); return vec; } diff --git a/src/base/core/random/RandomUtils.h b/src/base/core/random/RandomUtils.h new file mode 100644 index 0000000..582e069 --- /dev/null +++ b/src/base/core/random/RandomUtils.h @@ -0,0 +1,10 @@ +#pragma once + +#include "Vector.h" + +class RandomUtils +{ +public: + + static Vector getRandomVecUnsigned(size_t size); +}; diff --git a/src/base/core/AbstractNamedItem.h b/src/base/core/serialization/AbstractNamedItem.h similarity index 60% rename from src/base/core/AbstractNamedItem.h rename to src/base/core/serialization/AbstractNamedItem.h index e68dca8..7f07073 100644 --- a/src/base/core/AbstractNamedItem.h +++ b/src/base/core/serialization/AbstractNamedItem.h @@ -1,12 +1,12 @@ #pragma once -#include +#include "String.h" class AbstractNamedItem { public: ~AbstractNamedItem() = default; protected: - std::string mName; - std::string mSymbol; + String mName; + String mSymbol; }; \ No newline at end of file diff --git a/src/base/core/serialization/Serializeable.h b/src/base/core/serialization/Serializeable.h new file mode 100644 index 0000000..6f0213b --- /dev/null +++ b/src/base/core/serialization/Serializeable.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +class Serializeable +{ +public: + virtual size_t getSize() const = 0; + + virtual uint8_t getByte(size_t index) const = 0; +}; \ No newline at end of file diff --git a/src/base/core/data_structures/Tree.cpp b/src/base/core/serialization/json/JsonDocument.cpp similarity index 100% rename from src/base/core/data_structures/Tree.cpp rename to src/base/core/serialization/json/JsonDocument.cpp diff --git a/src/base/core/serialization/json/JsonDocument.h b/src/base/core/serialization/json/JsonDocument.h new file mode 100644 index 0000000..9eff431 --- /dev/null +++ b/src/base/core/serialization/json/JsonDocument.h @@ -0,0 +1,15 @@ +#pragma once + +#include "Dictionary.h" + +class JsonDocument +{ +public: + const Dictionary& get_data() const + { + return mData; + } + +private: + Dictionary mData; +}; \ No newline at end of file diff --git a/src/base/core/serialization/json/JsonParser.cpp b/src/base/core/serialization/json/JsonParser.cpp new file mode 100644 index 0000000..308cc91 --- /dev/null +++ b/src/base/core/serialization/json/JsonParser.cpp @@ -0,0 +1,11 @@ +#include "JsonParser.h" + +Ptr JsonParser::read(const FileSystemPath& input_file) +{ + return {}; +} + +Ptr JsonParser::read(InputStream& stream) +{ + return {}; +} \ No newline at end of file diff --git a/src/base/core/serialization/json/JsonParser.h b/src/base/core/serialization/json/JsonParser.h new file mode 100644 index 0000000..b8c214a --- /dev/null +++ b/src/base/core/serialization/json/JsonParser.h @@ -0,0 +1,23 @@ +#pragma once + +#include "FileSystemPath.h" +#include "IOStream.h" +#include "JsonDocument.h" + +class JsonParser +{ +public: + Ptr read(const FileSystemPath& input_file); + + Ptr read(InputStream& stream); + +private: + enum class State + { + READY, + IN_OBJECT, + IN_ARRAY, + IN_STRING, + IN_NUMBER + }; +}; \ No newline at end of file diff --git a/src/base/core/serializers/TomlReader.cpp b/src/base/core/serialization/toml/TomlReader.cpp similarity index 56% rename from src/base/core/serializers/TomlReader.cpp rename to src/base/core/serialization/toml/TomlReader.cpp index 3693a4f..aff7c05 100644 --- a/src/base/core/serializers/TomlReader.cpp +++ b/src/base/core/serialization/toml/TomlReader.cpp @@ -1,10 +1,8 @@ #include "TomlReader.h" -#include -#include -#include +#include "Char.h" -TomlTable::TomlTable(const std::string& header) +TomlTable::TomlTable(const String& header) : mHeader(header) { @@ -15,34 +13,34 @@ void TomlTable::addComment(const Comment& comment) mComments.push_back(comment); } -void TomlTable::addTable(std::unique_ptr table) +void TomlTable::addTable(Ptr table) { - mTables[table->getHeader()] = std::move(table); + mTables.insert(table->getHeader(), std::move(table)); } -void TomlTable::addKeyValuePair(const std::string& key, const std::string& value) +void TomlTable::addKeyValuePair(const String& key, const String& value) { - mMap[key] = value; + mMap.insert(key, value); } -std::string TomlTable::getHeader() const +String TomlTable::getHeader() const { return mHeader; } -TomlTable* TomlTable::getTable(const std::string& path) +TomlTable* TomlTable::getTable(const String& path) const { - return mTables[path].get(); + return (*mTables.find(path)).value().get(); } -TomlTable::KeyValuePairs TomlTable::getKeyValuePairs() const +const TomlTable::KeyValuePairs& TomlTable::getKeyValuePairs() const { return mMap; } TomlContent::TomlContent() - : mRootTable(std::make_unique("root")) + : mRootTable(Ptr::create("root")) { } @@ -52,13 +50,13 @@ TomlTable* TomlContent::getRootTable() const return mRootTable.get(); } -TomlTable* TomlContent::getTable(const std::string& path) const +TomlTable* TomlContent::getTable(const String& path) const { return mRootTable->getTable(path); } TomlReader::TomlReader() - : mContent(std::make_unique()) + : mContent(Ptr::create()) { } @@ -68,9 +66,15 @@ TomlContent* TomlReader::getContent() const return mContent.get(); } -void TomlReader::read(const Path& input_path) +void TomlReader::read(const FileSystemPath& input_path) { - const auto lines = File(input_path).readLines(); + Vector lines; + File input_file(input_path); + + String buffer; + input_file.read(buffer); + buffer.split(lines, '\n'); + mLastSectionOffset = 0; mWorkingTable = mContent->getRootTable(); @@ -83,13 +87,13 @@ void TomlReader::read(const Path& input_path) mWorkingTable = nullptr; } -void TomlReader::processLine(const std::string& line) +void TomlReader::processLine(const String& line) { bool in_comment{ false }; bool in_header{ false }; bool found_key{ false }; - std::string working_string; - std::string key_string; + String working_string; + String key_string; for (auto c : line) { if (c == '#' && !in_comment) @@ -126,26 +130,26 @@ void TomlReader::processLine(const std::string& line) } else if (found_key) { - key_string.erase(std::remove_if(key_string.begin(), key_string.end(), [](char c) {return std::isspace(c); }), key_string.end()); - working_string.erase(std::remove_if(working_string.begin(), working_string.end(), [](char c) {return std::isspace(c); }), working_string.end()); + key_string.eraseIf([](char c) {return Char::is_space(c); }); + working_string.eraseIf([](char c) {return Char::is_space(c); }); if (working_string.size()>2 && working_string[0] == '"' && working_string[working_string.size() - 1] == '"') { - working_string = working_string.substr(1, working_string.size() - 2); + working_string.slice(1, working_string.size() - 2, working_string); } onKeyValuePair(key_string, working_string); } } -void TomlReader::onHeader(const std::string& header) +void TomlReader::onHeader(const String& header) { - auto new_table = std::make_unique(header); + auto new_table = Ptr::create(header); auto table_temp = new_table.get(); mWorkingTable->addTable(std::move(new_table)); mWorkingTable = table_temp; } -void TomlReader::onKeyValuePair(const std::string key, const std::string value) +void TomlReader::onKeyValuePair(const String key, const String value) { mWorkingTable->addKeyValuePair(key, value); } diff --git a/src/base/core/serialization/toml/TomlReader.h b/src/base/core/serialization/toml/TomlReader.h new file mode 100644 index 0000000..6d88699 --- /dev/null +++ b/src/base/core/serialization/toml/TomlReader.h @@ -0,0 +1,68 @@ +#pragma once + +#include "File.h" +#include "FileSystemPath.h" +#include "Pointer.h" +#include "Map.h" +#include "String.h" + +class TomlTable +{ +public: + using Comment = Pair; + using KeyValuePairs = Map; + + TomlTable(const String& header); + + void addComment(const Comment& comment); + + void addTable(Ptr table); + + void addKeyValuePair(const String& key, const String& value); + + String getHeader() const; + + TomlTable* getTable(const String& path) const; + + const KeyValuePairs& getKeyValuePairs() const; + +private: + String mHeader; + Map > mTables; + KeyValuePairs mMap; + Vector mComments; +}; + +class TomlContent +{ +public: + TomlContent(); + + TomlTable* getRootTable() const; + + TomlTable* getTable(const String& path) const; + +private: + Ptr mRootTable; +}; + +class TomlReader +{ +public: + TomlReader(); + + TomlContent* getContent() const; + + void read(const FileSystemPath& input_path); + + void processLine(const String& line); + + void onHeader(const String& header); + + void onKeyValuePair(const String key, const String value); + +private: + unsigned mLastSectionOffset{ 0 }; + Ptr mContent; + TomlTable* mWorkingTable{nullptr}; +}; diff --git a/src/base/core/serialization/xml/XmlDocument.cpp b/src/base/core/serialization/xml/XmlDocument.cpp new file mode 100644 index 0000000..97e67ad --- /dev/null +++ b/src/base/core/serialization/xml/XmlDocument.cpp @@ -0,0 +1,38 @@ +#include "XmlDocument.h" + +XmlDocument::XmlDocument() + : mProlog(XmlProlog::Create("xml")) +{ + +} + +XmlDocument::~XmlDocument() +{ + +} + +void XmlDocument::setProlog(Ptr prolog) +{ + mProlog = std::move(prolog); +} + +const XmlProlog* XmlDocument::getProlog() const +{ + return mProlog.get(); +} + +XmlProlog* XmlDocument::getProlog() +{ + return mProlog.get(); +} + +void XmlDocument::setRoot(Ptr root) +{ + mRoot = std::move(root); +} + +const XmlElement* XmlDocument::getRoot() const +{ + return mRoot.get(); +} + diff --git a/src/base/core/serialization/xml/XmlDocument.h b/src/base/core/serialization/xml/XmlDocument.h new file mode 100644 index 0000000..d00f3c2 --- /dev/null +++ b/src/base/core/serialization/xml/XmlDocument.h @@ -0,0 +1,24 @@ +#pragma once + +#include "Pointer.h" +#include "String.h" + +#include "XmlElement.h" +#include "XmlProlog.h" + +class XmlDocument +{ +public: + XmlDocument(); + virtual ~XmlDocument(); + + const XmlProlog* getProlog() const; + XmlProlog* getProlog(); + const XmlElement* getRoot() const; + + void setProlog(Ptr prolog); + void setRoot(Ptr root); +private: + Ptr mProlog; + Ptr mRoot; +}; diff --git a/src/base/core/xml/XmlParser.cpp b/src/base/core/serialization/xml/XmlParser.cpp similarity index 86% rename from src/base/core/xml/XmlParser.cpp rename to src/base/core/serialization/xml/XmlParser.cpp index 9760e86..dacf39b 100644 --- a/src/base/core/xml/XmlParser.cpp +++ b/src/base/core/serialization/xml/XmlParser.cpp @@ -1,47 +1,45 @@ #include "XmlParser.h" -#include "StringUtils.h" +#include "Char.h" #include "XmlDocument.h" #include "XmlElement.h" #include "XmlAttribute.h" -#include - using LS = XmlParser::LineState; using DS = XmlParser::DocumentState; XmlParser::XmlParser() : mDocumentState(XmlParser::DocumentState::Await_Prolog), mLineState(XmlParser::LineState::Await_Tag_Open), - mDocument(XmlDocument::Create()), + mDocument(Ptr::create()), mWorkingElements() { } -void XmlParser::processLine(const std::string& input) +void XmlParser::processLine(const String& input) { - for (std::size_t idx=0; idxsetText(mWorkingText); + (*mWorkingElements.top())->setText(mWorkingText); } void XmlParser::onElementTagEnd() @@ -318,7 +316,7 @@ void XmlParser::onElementTagEnd() void XmlParser::onTagNameStart(char c) { - mWorkingTagName = c; + mWorkingTagName += c; mLineState = LS::Await_Tag_Name_End; if(mDocumentState != DS::Build_Prolog && mDocumentState != DS::Close_Element) { @@ -344,7 +342,7 @@ void XmlParser::onTagNameEnd() } else { - mWorkingElements.top()->addChild(std::move(new_element)); + (*mWorkingElements.top())->addChild(std::move(new_element)); } mWorkingElements.push(working_element); mLineState = LS::Await_Attribute_Name; @@ -353,7 +351,7 @@ void XmlParser::onTagNameEnd() void XmlParser::onAttributeNameStart(char c) { - mWorkingAttributeName = c; + mWorkingAttributeName += c; mLineState = LS::Await_Attribute_Name_End; } @@ -366,7 +364,7 @@ void XmlParser::onAttributeNameEnd() } else if(mDocumentState == DS::Build_Element) { - mWorkingElements.top()->addAttribute(std::move(attribute)); + (*mWorkingElements.top())->addAttribute(std::move(attribute)); } mLineState = LS::Await_Attribute_Value; } @@ -385,7 +383,7 @@ void XmlParser::onAttributeValueEnd() } else if(mDocumentState == DS::Build_Element) { - mWorkingElements.top()->getAttribute(mWorkingAttributeName)->setValue(mWorkingAttributeValue); + (*mWorkingElements.top())->getAttribute(mWorkingAttributeName)->setValue(mWorkingAttributeValue); } mLineState = LS::Await_Attribute_Name; } @@ -403,7 +401,7 @@ void XmlParser::onFinishProlog() mLineState = LS::Await_Tag_Open; } -XmlDocumentPtr XmlParser::getDocument() +Ptr XmlParser::getDocument() { return std::move(mDocument); } diff --git a/src/base/core/xml/XmlParser.h b/src/base/core/serialization/xml/XmlParser.h similarity index 76% rename from src/base/core/xml/XmlParser.h rename to src/base/core/serialization/xml/XmlParser.h index 3007641..636f12f 100644 --- a/src/base/core/xml/XmlParser.h +++ b/src/base/core/serialization/xml/XmlParser.h @@ -1,12 +1,10 @@ #pragma once -#include -#include -#include +#include "String.h" +#include "Stack.h" +#include "Pointer.h" class XmlDocument; -using XmlDocumentPtr = std::unique_ptr; - class XmlElement; class XmlParser @@ -38,9 +36,9 @@ public: public: XmlParser(); - void processLine(const std::string& input); + Ptr getDocument(); - XmlDocumentPtr getDocument(); + void processLine(const String& input); private: void onLeftBracket(); @@ -92,11 +90,11 @@ private: private: DocumentState mDocumentState; LineState mLineState; - XmlDocumentPtr mDocument; - std::stack mWorkingElements; + Ptr mDocument; + Stack mWorkingElements; - std::string mWorkingAttributeName; - std::string mWorkingTagName; - std::string mWorkingAttributeValue; - std::string mWorkingText; + String mWorkingAttributeName; + String mWorkingTagName; + String mWorkingAttributeValue; + String mWorkingText; }; diff --git a/src/base/core/serialization/xml/XmlWriter.cpp b/src/base/core/serialization/xml/XmlWriter.cpp new file mode 100644 index 0000000..b5a3986 --- /dev/null +++ b/src/base/core/serialization/xml/XmlWriter.cpp @@ -0,0 +1,23 @@ +#include "XmlWriter.h" + +#include "XmlDocument.h" +#include "XmlAttribute.h" + +Status XmlWriter::toString(XmlDocument* document, String& output) +{ + if (auto prolog = document->getProlog()) + { + output += "getAttributes()) + { + output += _s(" ") + attribute->getName() + _s("=\"") + attribute->getValue() + _s("\""); + } + output += "?>\n"; + } + + if (auto root = document->getRoot()) + { + output += root->toString(); + } + return {}; +} diff --git a/src/base/core/xml/XmlWriter.h b/src/base/core/serialization/xml/XmlWriter.h similarity index 52% rename from src/base/core/xml/XmlWriter.h rename to src/base/core/serialization/xml/XmlWriter.h index 0b9869d..d02afcc 100644 --- a/src/base/core/xml/XmlWriter.h +++ b/src/base/core/serialization/xml/XmlWriter.h @@ -1,6 +1,7 @@ #pragma once -#include +#include "String.h" +#include "Error.h" class XmlDocument; class XmlElement; @@ -10,5 +11,5 @@ class XmlWriter public: XmlWriter() = default; - std::string toString(XmlDocument* document); + Status toString(XmlDocument* document, String& output); }; diff --git a/src/base/core/serialization/xml/xml-elements/XmlAttribute.cpp b/src/base/core/serialization/xml/xml-elements/XmlAttribute.cpp new file mode 100644 index 0000000..d80eb71 --- /dev/null +++ b/src/base/core/serialization/xml/xml-elements/XmlAttribute.cpp @@ -0,0 +1,28 @@ +#include "XmlAttribute.h" + +XmlAttribute::XmlAttribute(const String& name) + : mName(name), + mValue() +{ + +} + +Ptr XmlAttribute::Create(const String& name) +{ + return Ptr::create(name); +} + +const String& XmlAttribute::getName() const +{ + return mName; +} + +const String& XmlAttribute::getValue() const +{ + return mValue; +} + +void XmlAttribute::setValue(const String& value) +{ + mValue = value; +} diff --git a/src/base/core/serialization/xml/xml-elements/XmlAttribute.h b/src/base/core/serialization/xml/xml-elements/XmlAttribute.h new file mode 100644 index 0000000..3589517 --- /dev/null +++ b/src/base/core/serialization/xml/xml-elements/XmlAttribute.h @@ -0,0 +1,21 @@ +#pragma once + +#include "Pointer.h" +#include "String.h" + +class XmlAttribute +{ +public: + XmlAttribute(const String& name); + + static Ptr Create(const String& name); + + const String& getName() const; + + const String& getValue() const; + + void setValue(const String& value); +private: + String mName; + String mValue; +}; diff --git a/src/base/core/serialization/xml/xml-elements/XmlElement.cpp b/src/base/core/serialization/xml/xml-elements/XmlElement.cpp new file mode 100644 index 0000000..6d1a499 --- /dev/null +++ b/src/base/core/serialization/xml/xml-elements/XmlElement.cpp @@ -0,0 +1,154 @@ +#include "XmlElement.h" + +#include "XmlAttribute.h" + +XmlElement::XmlElement(const String& tagName) + : mTagName(tagName), + mChildren() +{ + +} + +XmlElement::~XmlElement() +{ + +} + +Ptr XmlElement::Create(const String& tagName) +{ + return Ptr::create(tagName); +} + +void XmlElement::setTagName(const String& tagName) +{ + mTagName = tagName; +} + +void XmlElement::addChild(Ptr child) +{ + mChildren.push_back(std::move(child)); +} + +void XmlElement::addAttribute(Ptr attribute) +{ + mAttributes.insert(attribute->getName(), std::move(attribute)); +} + +void XmlElement::addAttribute(const String& name, const String& value) +{ + auto attr = Ptr::create(name); + attr->setValue(value); + addAttribute(std::move(attr)); +} + +const String& XmlElement::getTagName() const +{ + return mTagName; +} + +const String& XmlElement::getText() const +{ + return mText; +} + +void XmlElement::setText(const String& text) +{ + mText = text; +} + +XmlElement* XmlElement::getFirstChildWithTagName(const String& tag) +{ + for(auto& child : mChildren) + { + if (child->getTagName() == tag) + { + return child.get(); + } + } + + return nullptr; +} + +bool XmlElement::hasAttribute(const String& attribute) const +{ + return (bool)(getAttribute(attribute)); +} + +const XmlAttribute* XmlElement::getAttribute(const String& attributeName) const +{ + if (auto iter = mAttributes.find(attributeName); iter != mAttributes.end()) + { + return (*iter).value().get(); + } + return nullptr; +} + +XmlAttribute* XmlElement::getAttribute(const String& attributeName) +{ + if (auto iter = mAttributes.find(attributeName); iter != mAttributes.end()) + { + //return (*iter).value().get(); + } + return nullptr; +} + +void XmlElement::forEachAttribute(eachAttrFunc func) const +{ + +} + +const Map >& XmlElement::getAttributes() const +{ + return mAttributes; +} + +const Vector >& XmlElement::getChildren() const +{ + return mChildren; +} + +String XmlElement::toString(unsigned depth, bool keepInline) const +{ + const auto prefix = String(2*depth, ' '); + + String line_ending = keepInline ? "" : "\n"; + + auto content = prefix + "<" + getTagName(); + for (const auto& [key, attribute] : getAttributes()) + { + content += _s(" ") + attribute->getName() + _s("=\"") + attribute->getValue() + _s("\""); + } + + const auto num_children = mChildren.size(); + if (num_children == 0 && getText().empty()) + { + content += _s("/>") + line_ending; + return content; + } + else + { + content += _s(">"); + } + + if (!getText().empty()) + { + content += getText(); + } + + if (num_children>0) + { + content += line_ending; + } + + for(const auto& child : mChildren) + { + content += child->toString(depth+1, keepInline); + } + if (num_children>0) + { + content += prefix; + } + + content += _s("") + line_ending; + return content; +} diff --git a/src/base/core/serialization/xml/xml-elements/XmlElement.h b/src/base/core/serialization/xml/xml-elements/XmlElement.h new file mode 100644 index 0000000..e4d064a --- /dev/null +++ b/src/base/core/serialization/xml/xml-elements/XmlElement.h @@ -0,0 +1,49 @@ +#pragma once + +#include "Pointer.h" +#include "String.h" +#include "Map.h" + +class XmlAttribute; + +class XmlElement +{ +public: + XmlElement(const String& tagName); + virtual ~XmlElement(); + + static Ptr Create(const String& tagName); + + void addAttribute(Ptr attribute); + void addAttribute(const String& name, const String& value); + void addChild(Ptr child); + + const String& getTagName() const; + const String& getText() const; + + using eachAttrFunc = std::function; + void forEachAttribute(eachAttrFunc func) const; + + const XmlAttribute* getAttribute(const String& attribute) const; + XmlAttribute* getAttribute(const String& attribute); + + const Map >& getAttributes() const; + + const Vector >& getChildren() const; + + XmlElement* getFirstChildWithTagName(const String& tag); + + bool hasAttribute(const String& attribute) const; + + void setText(const String& text); + void setTagName(const String& tagName); + + virtual String toString(unsigned depth = 0, bool keepInline = false) const; + +protected: + String mTagName; + String mText; + + Map > mAttributes; + Vector > mChildren; +}; diff --git a/src/base/core/xml/xml-elements/XmlProlog.cpp b/src/base/core/serialization/xml/xml-elements/XmlProlog.cpp similarity index 73% rename from src/base/core/xml/xml-elements/XmlProlog.cpp rename to src/base/core/serialization/xml/xml-elements/XmlProlog.cpp index eb9f622..c03f760 100644 --- a/src/base/core/xml/xml-elements/XmlProlog.cpp +++ b/src/base/core/serialization/xml/xml-elements/XmlProlog.cpp @@ -2,7 +2,7 @@ #include "XmlAttribute.h" -XmlProlog::XmlProlog(const std::string& tagName) +XmlProlog::XmlProlog(const String& tagName) : XmlElement(tagName), mVersion(XmlProlog::Version::V1_0), mEncoding(XmlProlog::Encoding::UTF8) @@ -10,9 +10,9 @@ XmlProlog::XmlProlog(const std::string& tagName) } -XmlPrologPtr XmlProlog::Create(const std::string& tagName) +Ptr XmlProlog::Create(const String& tagName) { - return std::make_unique(tagName); + return Ptr::create(tagName); } XmlProlog::Encoding XmlProlog::getEncoding() const @@ -25,7 +25,7 @@ XmlProlog::Version XmlProlog::getVersion() const return mVersion; } -void XmlProlog::setEncoding(const std::string& encoding) +void XmlProlog::setEncoding(const String& encoding) { if(encoding == "UTF-8") { @@ -33,7 +33,7 @@ void XmlProlog::setEncoding(const std::string& encoding) } } -void XmlProlog::setVersion(const std::string& version) +void XmlProlog::setVersion(const String& version) { if(version == "1.0") { diff --git a/src/base/core/xml/xml-elements/XmlProlog.h b/src/base/core/serialization/xml/xml-elements/XmlProlog.h similarity index 51% rename from src/base/core/xml/xml-elements/XmlProlog.h rename to src/base/core/serialization/xml/xml-elements/XmlProlog.h index 8a30288..5d4a967 100644 --- a/src/base/core/xml/xml-elements/XmlProlog.h +++ b/src/base/core/serialization/xml/xml-elements/XmlProlog.h @@ -2,8 +2,8 @@ #include "XmlElement.h" -#include -#include +#include "Pointer.h" +#include "Vector.h" class XmlProlog : public XmlElement { @@ -17,20 +17,18 @@ public: }; public: - XmlProlog(const std::string& tagName); + XmlProlog(const String& tagName); - static std::unique_ptr Create(const std::string& tagName); + static Ptr Create(const String& tagName); Encoding getEncoding() const; Version getVersion() const; - void setEncoding(const std::string& encoding); - void setVersion(const std::string& version); + void setEncoding(const String& encoding); + void setVersion(const String& version); void update(); private: Version mVersion; Encoding mEncoding; -}; - -using XmlPrologPtr = std::unique_ptr; +}; \ No newline at end of file diff --git a/src/base/core/serialization/yaml/YamlDocument.cpp b/src/base/core/serialization/yaml/YamlDocument.cpp new file mode 100644 index 0000000..e69de29 diff --git a/src/base/core/serialization/yaml/YamlDocument.h b/src/base/core/serialization/yaml/YamlDocument.h new file mode 100644 index 0000000..a7a8f1a --- /dev/null +++ b/src/base/core/serialization/yaml/YamlDocument.h @@ -0,0 +1,14 @@ +#pragma once + +#include "Dictionary.h" +#include "Pointer.h" + +class YamlDocument +{ +public: + YamlDocument() + { + } + + Ptr m_root; +}; \ No newline at end of file diff --git a/src/base/core/serialization/yaml/YamlDocuments.cpp b/src/base/core/serialization/yaml/YamlDocuments.cpp new file mode 100644 index 0000000..7a5c022 --- /dev/null +++ b/src/base/core/serialization/yaml/YamlDocuments.cpp @@ -0,0 +1,11 @@ +#include "YamlDocuments.h" + +void YamlDocuments::add_document(Ptr doc) +{ + m_documents.push_back(std::move(doc)); +} + +const Vector >& YamlDocuments::get_documents() const +{ + return m_documents; +} \ No newline at end of file diff --git a/src/base/core/serialization/yaml/YamlDocuments.h b/src/base/core/serialization/yaml/YamlDocuments.h new file mode 100644 index 0000000..317a45c --- /dev/null +++ b/src/base/core/serialization/yaml/YamlDocuments.h @@ -0,0 +1,17 @@ +#pragma once + +#include "Vector.h" +#include "Pointer.h" +#include "YamlDocument.h" + +class YamlDocuments +{ +public: + + void add_document(Ptr doc); + + const Vector >& get_documents() const; + +private: + Vector > m_documents; +}; \ No newline at end of file diff --git a/src/base/core/serialization/yaml/YamlParser.cpp b/src/base/core/serialization/yaml/YamlParser.cpp new file mode 100644 index 0000000..ab22174 --- /dev/null +++ b/src/base/core/serialization/yaml/YamlParser.cpp @@ -0,0 +1,14 @@ +#include "YamlParser.h" + +#include "FileStream.h" + +Status YamlParser::parse(const FileSystemPath& path, YamlDocuments& result) +{ + InputFileStream f(path); + return parse(f, result); +} + +Status YamlParser::parse(InputStream& input, YamlDocuments& result) +{ + return {}; +} \ No newline at end of file diff --git a/src/base/core/serialization/yaml/YamlParser.h b/src/base/core/serialization/yaml/YamlParser.h new file mode 100644 index 0000000..4b20481 --- /dev/null +++ b/src/base/core/serialization/yaml/YamlParser.h @@ -0,0 +1,13 @@ +#pragma once + +#include "IOStream.h" +#include "YamlDocuments.h" +#include "FileSystemPath.h" + +class YamlParser +{ +public: + Status parse(const FileSystemPath& path, YamlDocuments& result); + + Status parse(InputStream& input, YamlDocuments& result); +}; \ No newline at end of file diff --git a/src/base/core/serializers/TomlReader.h b/src/base/core/serializers/TomlReader.h deleted file mode 100644 index 7e4dfa5..0000000 --- a/src/base/core/serializers/TomlReader.h +++ /dev/null @@ -1,71 +0,0 @@ -#pragma once - -#include "File.h" - -#include -#include -#include -#include - -using Path = std::filesystem::path; - -class TomlTable -{ -public: - using Comment = std::pair; - using KeyValuePairs = std::unordered_map; - - TomlTable(const std::string& header); - - void addComment(const Comment& comment); - - void addTable(std::unique_ptr table); - - void addKeyValuePair(const std::string& key, const std::string& value); - - std::string getHeader() const; - - TomlTable* getTable(const std::string& path); - - KeyValuePairs getKeyValuePairs() const; - -private: - std::string mHeader; - std::unordered_map > mTables; - KeyValuePairs mMap; - std::vector mComments; -}; - -class TomlContent -{ -public: - TomlContent(); - - TomlTable* getRootTable() const; - - TomlTable* getTable(const std::string& path) const; - -private: - std::unique_ptr mRootTable; -}; - -class TomlReader -{ -public: - TomlReader(); - - TomlContent* getContent() const; - - void read(const Path& input_path); - - void processLine(const std::string& line); - - void onHeader(const std::string& header); - - void onKeyValuePair(const std::string key, const std::string value); - -private: - unsigned mLastSectionOffset{ 0 }; - std::unique_ptr mContent; - TomlTable* mWorkingTable{nullptr}; -}; diff --git a/src/base/core/streams/BinaryStream.cpp b/src/base/core/streams/BinaryStream.cpp index aee7ac2..b4886e2 100644 --- a/src/base/core/streams/BinaryStream.cpp +++ b/src/base/core/streams/BinaryStream.cpp @@ -1,16 +1,18 @@ #include "BinaryStream.h" -std::optional BinaryStream::getNextByteAsInt(std::basic_istream* stream) +#include "Bits.h" + +bool BinaryStream::getNextByte(InputStream& stream, Byte& ret) { - return stream->get(); + return stream.get(ret); } -bool BinaryStream::getNextNBytes(std::basic_istream* stream, char* buffer, unsigned number) +bool BinaryStream::getNextNBytes(InputStream& stream, Byte* buffer, size_t number) { - char c; - for(unsigned idx=0; idxget(c)) + if(stream.get(c)) { buffer[idx] = c; } @@ -22,72 +24,72 @@ bool BinaryStream::getNextNBytes(std::basic_istream* stream, char* buffer, return true; } -bool BinaryStream::getNextWord(std::basic_istream* stream, char* buffer) +bool BinaryStream::getNextWord(InputStream& stream, Byte* buffer) { - return getNextNBytes(stream, buffer, sizeof(ByteUtils::Word)); + return getNextNBytes(stream, buffer, sizeof(Word)); } -bool BinaryStream::getNextDWord(std::basic_istream* stream, char* buffer) +bool BinaryStream::getNextDWord(InputStream& stream, Byte* buffer) { - return getNextNBytes(stream, buffer, sizeof(ByteUtils::DWord)); + return getNextNBytes(stream, buffer, sizeof(DWord)); } -bool BinaryStream::getNextQWord(std::basic_istream* stream, char* buffer) +bool BinaryStream::getNextQWord(InputStream& stream, Byte* buffer) { - return getNextNBytes(stream, buffer, sizeof(ByteUtils::QWord)); + return getNextNBytes(stream, buffer, sizeof(QWord)); } -std::optional BinaryStream::getNextWord(std::basic_istream* stream, bool reverse) +Optional BinaryStream::getNextWord(InputStream& stream, bool reverse) { - char buffer[sizeof(ByteUtils::Word)]; - if(!BinaryStream::getNextWord(stream, buffer)) + Byte buffer[sizeof(Word)]; + if(!getNextWord(stream, buffer)) { return false; } - return ByteUtils::ToWord(buffer, reverse); + return Bits::ToWord(buffer, reverse); } -std::optional BinaryStream::getNextDWord(std::basic_istream* stream) +Optional BinaryStream::getNextDWord(InputStream& stream) { - char buffer[sizeof(ByteUtils::DWord)]; + Byte buffer[sizeof(DWord)]; if(!BinaryStream::getNextDWord(stream, buffer)) { return false; } - return ByteUtils::ToDWord(buffer);; + return Bits::ToDWord(buffer); } -std::optional BinaryStream::getNextQWord(std::basic_istream* stream) +Optional BinaryStream::getNextQWord(InputStream& stream) { - char buffer[sizeof(ByteUtils::QWord)]; - if(!BinaryStream::getNextQWord(stream, buffer)) + Byte buffer[sizeof(QWord)]; + if(!getNextQWord(stream, buffer)) { return false; } - return ByteUtils::ToQWord(buffer);; + return Bits::ToQWord(buffer); } -bool BinaryStream::checkNextDWord(std::basic_istream* stream, const char* target) +bool BinaryStream::checkNextDWord(InputStream& stream, DWord target) { - char buffer[sizeof(ByteUtils::DWord)]; - if(!BinaryStream::getNextDWord(stream, buffer)) + Byte buffer[sizeof(DWord)]; + if(!getNextDWord(stream, buffer)) { return false; } - if(!ByteUtils::CompareDWords(buffer, target)) + if(!Bits::CompareDWords(buffer, target)) { return false; } return true; } -bool BinaryStream::getNextString(std::basic_istream* stream, std::string& target, unsigned numBytes) +bool BinaryStream::getNextString(InputStream& stream, String& target, size_t numBytes) { - char c; - for(unsigned idx=0; idxget(c)) + if(!stream.get(c)) { return false; } diff --git a/src/base/core/streams/BinaryStream.h b/src/base/core/streams/BinaryStream.h index 33df8fe..651c6be 100644 --- a/src/base/core/streams/BinaryStream.h +++ b/src/base/core/streams/BinaryStream.h @@ -1,40 +1,37 @@ #pragma once -#include -#include -#include -#include - -#include "ByteUtils.h" +#include "IOStream.h" +#include "String.h" +#include "Optional.h" +#include "Byte.h" class BinaryStream { public: - template - static bool write(std::basic_ostream* stream, T data) + static bool write(OutputStream* stream, T data) { - stream->write(reinterpret_cast(&data), sizeof(data)); + stream->write(reinterpret_cast(&data), sizeof(data)); return true; } - static std::optional getNextByteAsInt(std::basic_istream* stream); + static bool getNextByte(InputStream& stream, Byte& ret); - static bool getNextNBytes(std::basic_istream* stream, char* buffer, unsigned numBytes); + static bool getNextNBytes(InputStream& stream, Byte* buffer, size_t numBytes); - static bool getNextWord(std::basic_istream* stream, char* buffer); + static bool getNextWord(InputStream& stream, Byte* buffer); - static bool getNextDWord(std::basic_istream* stream, char* buffer); + static bool getNextDWord(InputStream& stream, Byte* buffer); - static bool getNextQWord(std::basic_istream* stream, char* buffer); + static bool getNextQWord(InputStream& stream, Byte* buffer); - static std::optional getNextWord(std::basic_istream* stream, bool reverse = true); + static Optional getNextWord(InputStream& stream, bool reverse = true); - static std::optional getNextDWord(std::basic_istream* stream); + static Optional getNextDWord(InputStream& stream); - static std::optional getNextQWord(std::basic_istream* stream); + static Optional getNextQWord(InputStream& stream); - static bool checkNextDWord(std::basic_istream* stream, const char* target); + static bool checkNextDWord(InputStream& stream, DWord target); - static bool getNextString(std::basic_istream* stream, std::string& target, unsigned numBytes); + static bool getNextString(InputStream& stream, String& target, size_t numBytes); }; diff --git a/src/base/core/streams/BitStream.cpp b/src/base/core/streams/BitStream.cpp index 28afdb6..b827845 100644 --- a/src/base/core/streams/BitStream.cpp +++ b/src/base/core/streams/BitStream.cpp @@ -1,37 +1,34 @@ #include "BitStream.h" -#include "ByteUtils.h" - -#include -#include +#include "Bits.h" BitStream::~BitStream() { } -unsigned char BitStream::getCurrentByte() +Byte BitStream::getCurrentByte() { if (mByteOffset < 0) { - readNextByte(); + Byte buffer; + readNextByte(buffer); } return mCurrentByte; } -void BitStream::write(uint32_t data) +void BitStream::write(DWord data) { - unsigned num_bytes = sizeof(uint32_t); - for(unsigned idx=0; idx(data >> 8); - const auto byte1 = static_cast((data << 8) >> 8); + const auto byte0 = static_cast(data >> 8); + const auto byte1 = static_cast((data << 8) >> 8); writeByte(byte0); writeByte(byte1); } @@ -41,53 +38,55 @@ int BitStream::getCurrentByteOffset() const return mByteOffset; } -unsigned BitStream::getCurrentBitOffset() const +size_t BitStream::getCurrentBitOffset() const { return mBitOffset; } -std::string BitStream::logLocation() +String BitStream::logLocation() { - std::stringstream sstr; - sstr << "Byte offset " << mByteOffset<< " | Bit offset " << mBitOffset; - sstr << " | Working byte " << ByteUtils::toString(getCurrentByte()) << '\n'; - return sstr.str(); + String ret; + ret << _s("Byte offset ") << mByteOffset<< _s(" | Bit offset ") << mBitOffset; + ret << _s(" | Working byte ") << Bits::toString(getCurrentByte()) << _s('\n'); + return ret; } -std::string BitStream::logNextNBytes(unsigned n) const +String BitStream::logNextNBytes(size_t n) const { - std::stringstream sstr; - unsigned count{0}; - for(auto byte : peekNextNBytes(n)) + String sstr; + size_t count{0}; + VecBytes bytes; + peekNextNBytes(n, bytes); + for(auto byte : bytes) { - sstr << mByteOffset + count << " | " << ByteUtils::toString(byte) + '\n'; + sstr << mByteOffset + count << _s(" | ") << Bits::toString(byte) + _s('\n'); count++; } - return sstr.str(); + return sstr; } -void BitStream::writeNBits(uint32_t data, unsigned length) +void BitStream::writeNBits(DWord data, size_t length) { const auto num_left = 8 - mBitOffset; const int overshoot = length - num_left; if (overshoot > 0) { - unsigned char lower_bits = ByteUtils::getLowerNBits(data, num_left); + Byte lower_bits = Bits::getLowerNBits(data, num_left); mCurrentByte |= lower_bits << mBitOffset; writeByte(mCurrentByte, false); - unsigned num_bytes = overshoot / 8; - for (unsigned idx=0; idx< num_bytes; idx++) + size_t num_bytes = overshoot / 8; + for (size_t idx=0; idx< num_bytes; idx++) { - mCurrentByte = ByteUtils::getMBitsAtN(static_cast(data), overshoot, idx*8 + num_left); + mCurrentByte = Bits::getMBitsAtN(static_cast(data), overshoot, idx*8 + num_left); writeByte(mCurrentByte, false); } if (const auto remainder = overshoot % 8; remainder > 0) { - mCurrentByte = ByteUtils::getMBitsAtN(static_cast(data), remainder, num_bytes*8 + num_left); + mCurrentByte = Bits::getMBitsAtN(static_cast(data), remainder, num_bytes*8 + num_left); mBitOffset = remainder; } else @@ -98,7 +97,7 @@ void BitStream::writeNBits(uint32_t data, unsigned length) } else { - mCurrentByte |= (static_cast(data) << mBitOffset); + mCurrentByte |= (static_cast(data) << mBitOffset); mBitOffset += length; if (mBitOffset == 8) { @@ -107,14 +106,14 @@ void BitStream::writeNBits(uint32_t data, unsigned length) mBitOffset = 0; } } - } -bool BitStream::readNextNBits(unsigned n, unsigned char& buffer) +bool BitStream::readNextNBits(size_t n, Byte& buffer) { + Byte internal_buffer; if (mByteOffset < 0) { - if (!readNextByte()) + if (!readNextByte(internal_buffer)) { return false; } @@ -123,15 +122,15 @@ bool BitStream::readNextNBits(unsigned n, unsigned char& buffer) int overshoot = n + mBitOffset - 8; if (overshoot > 0) { - unsigned char last_byte = mCurrentByte; - if (!readNextByte()) + const auto last_byte = mCurrentByte; + if (!readNextByte(internal_buffer)) { return false; } auto num_lower = 8 - mBitOffset; - char lower_bits = ByteUtils::getHigherNBits(last_byte, num_lower); - char higher_bits = ByteUtils::getLowerNBits(mCurrentByte, overshoot); + const auto lower_bits = Bits::getHigherNBits(last_byte, num_lower); + const auto higher_bits = Bits::getLowerNBits(mCurrentByte, overshoot); buffer = (higher_bits << num_lower) | lower_bits; @@ -140,8 +139,49 @@ bool BitStream::readNextNBits(unsigned n, unsigned char& buffer) } else { - buffer = ByteUtils::getMBitsAtN(mCurrentByte, n, mBitOffset); + buffer = Bits::getMBitsAtN(mCurrentByte, n, mBitOffset); mBitOffset += n; return true; } } + +void BitStream::resetOffsets() +{ + mEndByteOffset = mByteOffset; + mEndBitOffset = mBitOffset; + mEndByte = mCurrentByte; + + mCurrentByte = 0; + mByteOffset = -1; + mBitOffset = 0; +} + +void BitStream::reset() +{ + resetOffsets(); + mCurrentByte = 0; +} + +void BitStream::flushRemainingBits() +{ + if (mBitOffset > 0) + { + writeByte(mCurrentByte, false); + mBitOffset = 0; + } +} + +Pair BitStream::getRemainingBits() const +{ + return {mEndByte, mEndBitOffset}; +} + +void BitStream::setChecksumCalculator(AbstractChecksumCalculator* calc) +{ + mChecksumCalculator = calc; +} + +void BitStream::clearChecksumCalculator() +{ + mChecksumCalculator = nullptr; +} diff --git a/src/base/core/streams/BitStream.h b/src/base/core/streams/BitStream.h index 9cef91a..973701d 100644 --- a/src/base/core/streams/BitStream.h +++ b/src/base/core/streams/BitStream.h @@ -1,92 +1,63 @@ #pragma once #include "AbstractChecksumCalculator.h" - -#include -#include -#include +#include "Byte.h" +#include "String.h" +#include "Optional.h" +#include "Pair.h" class BitStream { public: virtual ~BitStream(); - unsigned char getCurrentByte(); + Byte getCurrentByte(); int getCurrentByteOffset() const; - unsigned getCurrentBitOffset() const; + size_t getCurrentBitOffset() const; virtual bool isFinished() const = 0; - std::string logNextNBytes(unsigned n) const; + String logNextNBytes(size_t n) const; - std::string logLocation(); + String logLocation(); - virtual std::vector peekNextNBytes(unsigned n) const = 0; + virtual void peekNextNBytes(size_t n, VecBytes& bytes) const = 0; - virtual bool readNextNBits(unsigned n, unsigned char& buffer); + virtual bool readNextNBits(size_t n, Byte& buffer); - virtual std::optional readNextByte() = 0; + virtual bool readNextByte(Byte& ret) = 0; - virtual void writeNBits(uint32_t data, unsigned length); + virtual void writeNBits(DWord data, size_t length); - virtual void writeByte(unsigned char data, bool checkOverflow = true) = 0; + virtual void writeByte(Byte data, bool checkOverflow = true) = 0; - void write(uint32_t data); + void write(DWord data); - void writeWord(uint16_t data); + void writeWord(Word data); - virtual void writeBytes(const std::vector data) = 0; + virtual void writeBytes(const VecBytes& data) = 0; - void resetOffsets() - { - mEndByteOffset = mByteOffset; - mEndBitOffset = mBitOffset; - mEndByte = mCurrentByte; + void resetOffsets(); - mCurrentByte = 0; - mByteOffset = -1; - mBitOffset = 0; - } + virtual void reset(); - virtual void reset() - { - resetOffsets(); - mCurrentByte = 0; - } + void flushRemainingBits(); - void flushRemainingBits() - { - if (mBitOffset > 0) - { - writeByte(mCurrentByte, false); - mBitOffset = 0; - } - } + Pair getRemainingBits() const; - std::pair getRemainingBits() const - { - return {mEndByte, mEndBitOffset}; - } + void setChecksumCalculator(AbstractChecksumCalculator* calc); - void setChecksumCalculator(AbstractChecksumCalculator* calc) - { - mChecksumCalculator = calc; - } - - void clearChecksumCalculator() - { - mChecksumCalculator = nullptr; - } + void clearChecksumCalculator(); protected: int mByteOffset{-1}; - unsigned mBitOffset{0}; - unsigned char mCurrentByte{0}; + size_t mBitOffset{0}; + Byte mCurrentByte{0}; int mEndByteOffset{-1}; - unsigned mEndBitOffset{0}; - unsigned char mEndByte{0}; + size_t mEndBitOffset{0}; + Byte mEndByte{0}; AbstractChecksumCalculator* mChecksumCalculator{nullptr}; }; diff --git a/src/base/core/streams/BufferBitStream.cpp b/src/base/core/streams/BufferBitStream.cpp index 5f9d3f2..92db816 100644 --- a/src/base/core/streams/BufferBitStream.cpp +++ b/src/base/core/streams/BufferBitStream.cpp @@ -1,18 +1,16 @@ #include "BufferBitStream.h" -#include "ByteUtils.h" - -#include +#include "Bits.h" bool BufferBitStream::isFinished() const { return mByteOffset == static_cast(mBuffer.size()) - 1; } -std::vector BufferBitStream::peekNextNBytes(unsigned n) const +void BufferBitStream::peekNextNBytes(size_t n, VecBytes& ret) const { - std::vector ret (n, 0); - unsigned count = 0; + ret.resize(n, 0); + size_t count = 0; int start = mByteOffset; if (start<0) @@ -28,39 +26,39 @@ std::vector BufferBitStream::peekNextNBytes(unsigned n) const } ret[count] = mBuffer[idx]; - count ++; + count++; } - return ret; } -std::optional BufferBitStream::readNextByte() +bool BufferBitStream::readNextByte(Byte& byte) { if (mByteOffset + 1 == static_cast(mBuffer.size())) { - return std::nullopt; + return false; } else { mByteOffset++; mCurrentByte = mBuffer[mByteOffset]; - return mCurrentByte; + byte = mCurrentByte; + return true; } } -void BufferBitStream::setBuffer(const std::vector& data) +void BufferBitStream::setBuffer(const VecBytes& data) { mBuffer = data; } -void BufferBitStream::writeByte(unsigned char data, bool checkOverflow) +void BufferBitStream::writeByte(Byte data, bool checkOverflow) { - unsigned char out_byte{0}; + Byte out_byte{0}; if (checkOverflow && mBitOffset > 0) { - out_byte = ByteUtils::getLowerNBits(mCurrentByte, mBitOffset); + out_byte = Bits::getLowerNBits(mCurrentByte, mBitOffset); out_byte |= data << mBitOffset; - mCurrentByte = ByteUtils::getHigherNBits(data, mBitOffset); + mCurrentByte = Bits::getHigherNBits(data, mBitOffset); } else { @@ -71,17 +69,17 @@ void BufferBitStream::writeByte(unsigned char data, bool checkOverflow) { mChecksumCalculator->addValue(out_byte); } - //std::cout << "Writing byte " << ByteUtils::toString(out_byte) << " had bitoffset of " << mBitOffset << std::endl; + //std::cout << "Writing byte " << Bits::toString(out_byte) << " had bitoffset of " << mBitOffset << std::endl; mBuffer.push_back(out_byte); } -void BufferBitStream::writeBytes(const std::vector data) +void BufferBitStream::writeBytes(const VecBytes& data) { - std::copy(data.begin(), data.end(), std::back_inserter(mBuffer)); + mBuffer = data; } -const std::vector& BufferBitStream::getBuffer() const +const VecBytes& BufferBitStream::getBuffer() const { return mBuffer; } diff --git a/src/base/core/streams/BufferBitStream.h b/src/base/core/streams/BufferBitStream.h index 6acde9a..5960087 100644 --- a/src/base/core/streams/BufferBitStream.h +++ b/src/base/core/streams/BufferBitStream.h @@ -2,28 +2,25 @@ #include "BitStream.h" -#include -#include - class BufferBitStream : public BitStream { public: - const std::vector& getBuffer() const; + const VecBytes& getBuffer() const; bool isFinished() const override; - std::vector peekNextNBytes(unsigned n) const override; + void peekNextNBytes(size_t n, VecBytes& bytes) const override; - std::optional readNextByte() override; + bool readNextByte(Byte& byte) override; void reset() override; - void setBuffer(const std::vector& data); + void setBuffer(const VecBytes& data); - void writeByte(unsigned char data, bool checkOverflow = true) override; + void writeByte(Byte data, bool checkOverflow = true) override; - void writeBytes(const std::vector data) override; + void writeBytes(const VecBytes& data) override; private: - std::vector mBuffer; + VecBytes mBuffer; }; diff --git a/src/base/core/streams/ByteStream.cpp b/src/base/core/streams/ByteStream.cpp new file mode 100644 index 0000000..e69de29 diff --git a/src/base/core/streams/ByteStream.h b/src/base/core/streams/ByteStream.h new file mode 100644 index 0000000..7842e17 --- /dev/null +++ b/src/base/core/streams/ByteStream.h @@ -0,0 +1,11 @@ +#pragma once + +#include "IOStream.h" +#include "String.h" + +using OutputByteStream = OutputByteStream; + +inline void operator<<(OutputByteStream& stream, const char* string) +{ + +} \ No newline at end of file diff --git a/src/base/core/streams/FileStream.cpp b/src/base/core/streams/FileStream.cpp new file mode 100644 index 0000000..57948bf --- /dev/null +++ b/src/base/core/streams/FileStream.cpp @@ -0,0 +1,58 @@ +#include "FileStream.h" + +InputFileStream::InputFileStream(const FileSystemPath& path) + : m_file(path), + m_buffer(Vector(m_buffer_size)) +{ + +} + +bool InputFileStream::finished() const +{ + return m_end_of_stream == true; +} + +bool InputFileStream::get(Byte& item) +{ + if (m_buffer_offset >= m_buffer_current_size) + { + if (m_end_of_file) + { + m_end_of_stream = true; + return false; + } + + m_buffer_offset = 0; + if (const auto rc = m_file.read(m_buffer); !rc.ok()) + { + on_error(rc); + return false; + } + m_buffer_current_size = m_buffer.size(); + if (m_buffer_current_size < m_buffer_size) + { + m_end_of_file = true; + } + if (m_buffer_current_size == 0) + { + m_end_of_stream = true; + return false; + } + item = m_buffer[m_buffer_offset]; + m_buffer_offset++; + return true; + } + else + { + item = m_buffer[m_buffer_offset]; + m_buffer_offset++; + return true; + } +} + +bool InputFileStream::good() const +{ + return !m_end_of_stream && Stream::good(); +} + + diff --git a/src/base/core/streams/FileStream.h b/src/base/core/streams/FileStream.h new file mode 100644 index 0000000..6dc2cd3 --- /dev/null +++ b/src/base/core/streams/FileStream.h @@ -0,0 +1,29 @@ +#pragma once + +#include "Byte.h" +#include "IOStream.h" +#include "FileSystemPath.h" +#include "File.h" +#include "Vector.h" + +class InputFileStream : public InputStream +{ +public: + InputFileStream(const FileSystemPath& path); + + bool finished() const; + + bool good() const override; + + bool get(Byte& item); + +private: + File m_file; + bool m_end_of_file{false}; + bool m_end_of_stream{false}; + size_t m_buffer_offset{0}; + size_t m_buffer_current_size{0}; + size_t m_buffer_size{4096}; + Vector m_buffer; + Status mStatus; +}; \ No newline at end of file diff --git a/src/base/core/streams/IOStream.h b/src/base/core/streams/IOStream.h new file mode 100644 index 0000000..ed462dc --- /dev/null +++ b/src/base/core/streams/IOStream.h @@ -0,0 +1,41 @@ +#pragma once + +#include "Vector.h" +#include "Stream.h" + +template +class InputStream : public Stream +{ +public: + virtual bool get(T& item) = 0; + + virtual int get(Vector& items) + { + size_t count = 0; + T item; + while(good() && count < items.size()) + { + if (const auto ok = get(item); !ok) + { + break; + } + items[count] = item; + count++; + } + if (has_error()) + { + return -1; + } + else + { + return count; + } + } +}; + +template +class OutputStream : public Stream +{ +public: + virtual int write(T* data, size_t size) = 0; +}; \ No newline at end of file diff --git a/src/base/core/streams/InputBitStream.cpp b/src/base/core/streams/InputBitStream.cpp index 8568853..4a6776c 100644 --- a/src/base/core/streams/InputBitStream.cpp +++ b/src/base/core/streams/InputBitStream.cpp @@ -1,6 +1,6 @@ #include "InputBitStream.h" -InputBitStream::InputBitStream(std::basic_istream* stream) +InputBitStream::InputBitStream(InputStream* stream) : BitStream(), mStream(stream) { @@ -12,24 +12,23 @@ bool InputBitStream::isFinished() const return mStream->good(); } -std::vector InputBitStream::peekNextNBytes(unsigned) const +void InputBitStream::peekNextNBytes(size_t, VecBytes&) const { - return {}; } -std::optional InputBitStream::readNextByte() +bool InputBitStream::readNextByte(Byte& buffer) { if (mStream->good()) { - return static_cast(mStream->get()); + return mStream->get(buffer); } else { - return std::nullopt; + return false; } } -void InputBitStream::writeByte(unsigned char, bool) +void InputBitStream::writeByte(Byte, bool) { } diff --git a/src/base/core/streams/InputBitStream.h b/src/base/core/streams/InputBitStream.h index 03d3fb1..221dbf0 100644 --- a/src/base/core/streams/InputBitStream.h +++ b/src/base/core/streams/InputBitStream.h @@ -1,26 +1,25 @@ #pragma once #include "BitStream.h" - -#include +#include "IOStream.h" +#include "Byte.h" class InputBitStream : public BitStream { - InputBitStream(std::basic_istream* stream); + InputBitStream(InputStream* stream); bool isFinished() const override; - std::vector peekNextNBytes(unsigned n) const override; + void peekNextNBytes(size_t n, VecBytes& bytes) const override; - std::optional readNextByte() override; + bool readNextByte(Byte& buffer) override; - void writeByte(unsigned char data, bool checkOverflow = true) override; + void writeByte(Byte data, bool checkOverflow = true) override; - void writeBytes(const std::vector) override + void writeBytes(const VecBytes&) override { - } private: - std::basic_istream* mStream{nullptr}; + InputStream* mStream{nullptr}; }; diff --git a/src/base/core/streams/OutputBitStream.cpp b/src/base/core/streams/OutputBitStream.cpp index 2579e24..a1c1acc 100644 --- a/src/base/core/streams/OutputBitStream.cpp +++ b/src/base/core/streams/OutputBitStream.cpp @@ -1,6 +1,6 @@ #include "OutputBitStream.h" -OutputBitStream::OutputBitStream(std::basic_ostream* stream) +OutputBitStream::OutputBitStream(OutputStream* stream) : BitStream(), mStream(stream) { @@ -12,22 +12,22 @@ bool OutputBitStream::isFinished() const return true; } -std::vector OutputBitStream::peekNextNBytes(unsigned) const +void OutputBitStream::peekNextNBytes(size_t, VecBytes&) const { - return {}; + } -std::optional OutputBitStream::readNextByte() +bool OutputBitStream::readNextByte(Byte& buffer) { - return std::nullopt; + return false; } -void OutputBitStream::writeByte(unsigned char data, bool) +void OutputBitStream::writeByte(Byte data, bool) { - (*mStream) << data; + //(*mStream) << data; } -void OutputBitStream::writeBytes(const std::vector data) +void OutputBitStream::writeBytes(const VecBytes& data) { for(auto byte : data) { diff --git a/src/base/core/streams/OutputBitStream.h b/src/base/core/streams/OutputBitStream.h index 75215d3..5b827de 100644 --- a/src/base/core/streams/OutputBitStream.h +++ b/src/base/core/streams/OutputBitStream.h @@ -1,24 +1,24 @@ #pragma once #include "BitStream.h" - -#include +#include "IOStream.h" +#include "Byte.h" class OutputBitStream : public BitStream { public: - OutputBitStream(std::basic_ostream* stream); + OutputBitStream(OutputStream* stream); bool isFinished() const override; - std::vector peekNextNBytes(unsigned n) const override; + void peekNextNBytes(size_t n, VecBytes& bytes) const override; - std::optional readNextByte() override; + bool readNextByte(Byte& buffer) override; - void writeByte(unsigned char data, bool checkOverflow = true) override; + void writeByte(Byte data, bool checkOverflow = true) override; - void writeBytes(const std::vector data) override; + void writeBytes(const VecBytes& data) override; private: - std::basic_ostream* mStream{nullptr}; + OutputStream* mStream{nullptr}; }; diff --git a/src/base/core/streams/Stream.cpp b/src/base/core/streams/Stream.cpp new file mode 100644 index 0000000..c8cd101 --- /dev/null +++ b/src/base/core/streams/Stream.cpp @@ -0,0 +1,23 @@ +#include "Stream.h" + +bool Stream::good() const +{ + return m_has_error; +} + +const Status& Stream::get_last_error() const +{ + return m_last_error; +} + +void Stream::on_error(const String& msg) +{ + m_has_error = true; + m_last_error = Status(Error(msg)); +} + +void Stream::on_error(const Status& status) +{ + m_has_error = true; + m_last_error = status; +} \ No newline at end of file diff --git a/src/base/core/streams/Stream.h b/src/base/core/streams/Stream.h new file mode 100644 index 0000000..d75ba64 --- /dev/null +++ b/src/base/core/streams/Stream.h @@ -0,0 +1,25 @@ +#pragma once + +#include "Error.h" + +class Stream +{ +public: + const Status& get_last_error() const; + + virtual bool good() const; + + bool has_error() const + { + return m_has_error; + } + +protected: + void on_error(const String& msg); + + void on_error(const Status& status); + + bool m_has_error{false}; + Status m_last_error; +}; + diff --git a/src/base/core/streams/StringStream.cpp b/src/base/core/streams/StringStream.cpp new file mode 100644 index 0000000..f517eb1 --- /dev/null +++ b/src/base/core/streams/StringStream.cpp @@ -0,0 +1,32 @@ +#include "StringStream.h" + +StringStream::StringStream(const String& str) +{ + str.to_bytes(m_buffer); +} + +bool StringStream::finished() const +{ + return m_end_of_stream; +} + +bool StringStream::good() const +{ + return !m_end_of_stream && InputStream::good(); +} + +bool StringStream::get(Byte& item) +{ + if (m_end_of_stream) + { + return false; + } + if (m_offset >= m_buffer.size()) + { + m_end_of_stream = true; + return false; + } + item = m_buffer[m_offset]; + m_offset++; + return true; +} \ No newline at end of file diff --git a/src/base/core/streams/StringStream.h b/src/base/core/streams/StringStream.h new file mode 100644 index 0000000..bd1aa94 --- /dev/null +++ b/src/base/core/streams/StringStream.h @@ -0,0 +1,21 @@ +#pragma once + +#include "IOStream.h" +#include "String.h" + +class StringStream : public InputStream +{ +public: + StringStream(const String& str); + + bool finished() const; + + bool good() const override; + + bool get(Byte& item); + +private: + bool m_end_of_stream{false}; + size_t m_offset{0}; + VecBytes m_buffer; +}; \ No newline at end of file diff --git a/src/base/core/Win32BaseIncludes.h b/src/base/core/system/Win32BaseIncludes.h similarity index 100% rename from src/base/core/Win32BaseIncludes.h rename to src/base/core/system/Win32BaseIncludes.h diff --git a/src/base/core/AbstractApp.h b/src/base/core/system/process/AbstractApp.h similarity index 71% rename from src/base/core/AbstractApp.h rename to src/base/core/system/process/AbstractApp.h index ab34aa4..42e4599 100644 --- a/src/base/core/AbstractApp.h +++ b/src/base/core/system/process/AbstractApp.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Pointer.h" class IApplicationContext { @@ -20,7 +20,7 @@ public: return mApplicationContext.get(); } protected: - std::unique_ptr mApplicationContext{ nullptr }; + Ptr mApplicationContext{ nullptr }; }; -using AbstractAppPtr = std::unique_ptr; +using AbstractAppPtr = Ptr; diff --git a/src/base/core/AbstractWebApp.h b/src/base/core/system/process/AbstractWebApp.h similarity index 100% rename from src/base/core/AbstractWebApp.h rename to src/base/core/system/process/AbstractWebApp.h diff --git a/src/base/core/CommandLineArgs.cpp b/src/base/core/system/process/CommandLineArgs.cpp similarity index 57% rename from src/base/core/CommandLineArgs.cpp rename to src/base/core/system/process/CommandLineArgs.cpp index 26ef06c..48faf22 100644 --- a/src/base/core/CommandLineArgs.cpp +++ b/src/base/core/system/process/CommandLineArgs.cpp @@ -1,8 +1,10 @@ #include "CommandLineArgs.h" -#include "UnicodeUtils.h" +#include "Unicode.h" +#ifdef _WIN32 #include "Win32BaseIncludes.h" +#endif CommandLineArgs::CommandLineArgs() : mArugments(), @@ -21,10 +23,10 @@ void CommandLineArgs::initialize(CommandLineArgs* args) return; } - std::vector windowsArgs(nArgs); + Vector windowsArgs(nArgs); for (int idx = 0; idx < nArgs; idx++) { - windowsArgs[idx] = UnicodeUtils::utf16ToUtf8String(szArglist[idx]); + windowsArgs[idx] = Unicode::utf16ToUtf8String(szArglist[idx]); } ::LocalFree(szArglist); @@ -34,37 +36,37 @@ void CommandLineArgs::initialize(CommandLineArgs* args) #endif } -std::unique_ptr CommandLineArgs::Create() +Ptr CommandLineArgs::Create() { - return std::make_unique(); + return Ptr::create(); } -std::filesystem::path CommandLineArgs::getLaunchPath() +FileSystemPath CommandLineArgs::getLaunchPath() { return mLaunchPath; } void CommandLineArgs::recordLaunchPath() { - mLaunchPath = std::filesystem::current_path(); + mLaunchPath = FileSystemPath::current_dir().value(); } void CommandLineArgs::process(int argc, char *argv[]) { for(int idx=0; idx& args) +void CommandLineArgs::process(const Vector& args) { mArugments = args; } -std::vector CommandLineArgs::getUserArgs() const +Vector CommandLineArgs::getUserArgs() const { - std::vector user_args; + Vector user_args; for(unsigned idx=1; idx CommandLineArgs::getUserArgs() const return user_args; } -const std::vector CommandLineArgs::getArgs() const +const Vector CommandLineArgs::getArgs() const { return mArugments; } diff --git a/src/base/core/system/process/CommandLineArgs.h b/src/base/core/system/process/CommandLineArgs.h new file mode 100644 index 0000000..b3d9614 --- /dev/null +++ b/src/base/core/system/process/CommandLineArgs.h @@ -0,0 +1,31 @@ +#pragma once + +#include "Pointer.h" +#include "Vector.h" +#include "String.h" +#include "FileSystemPath.h" + +class CommandLineArgs +{ +public: + CommandLineArgs(); + + static Ptr Create(); + + FileSystemPath getLaunchPath(); + + const Vector getArgs() const; + + Vector getUserArgs() const; + + static void initialize(CommandLineArgs* args); + + void process(int argc, char *argv[]); + + void process(const Vector& args); + + void recordLaunchPath(); +private: + Vector mArugments; + FileSystemPath mLaunchPath; +}; \ No newline at end of file diff --git a/src/base/core/system/process/Process.cpp b/src/base/core/system/process/Process.cpp new file mode 100644 index 0000000..9bb9f37 --- /dev/null +++ b/src/base/core/system/process/Process.cpp @@ -0,0 +1,70 @@ +#include "Process.h" + +#include "Logger.h" +#include "File.h" + +#include +#include +#include + +Status Process::launch(const String& command, + const Vector& args) +{ + const auto pid = fork(); + if (pid < 0) + { + ON_ERRNO("Failed to fork"); + } + + if (pid == 0) + { + char* exe_args[args.size()+2]; + exe_args[0] = const_cast(command.raw()); + for(size_t idx = 1; idx(args[idx-1].raw()); + } + exe_args[args.size()+1] = nullptr; + errno = 0; + auto rc = execv(command.raw(), exe_args); + if (rc != 0) + { + LOG_ERROR("External proc failed: " << Error::from_errno()); + exit(EXIT_FAILURE); + } + exit(EXIT_SUCCESS); + } + else + { + int status; + auto rc = wait(&status); + if (rc < 0) + { + ON_ERRNO("Failed to wait"); + } + if (!WIFEXITED(status)) + { + return Status(Error("Process child did not termintate normally")); + } + if (WEXITSTATUS(status) != EXIT_SUCCESS) + { + return Status(Error("Process child terminated with failure")); + } + } + return {}; +} + +Result Process::get_self_name() +{ + FileSystemPath path(String("/proc/self/cmdline")); + File sys_file(path); + + Result ret; + const auto rc = sys_file.read(ret.value()); + if (!rc.ok()) + { + ret.on_error(rc.error()); + } + return ret; +} \ No newline at end of file diff --git a/src/base/core/system/process/Process.h b/src/base/core/system/process/Process.h new file mode 100644 index 0000000..db11a91 --- /dev/null +++ b/src/base/core/system/process/Process.h @@ -0,0 +1,13 @@ +#pragma once + +#include "String.h" +#include "Result.h" + +class Process +{ +public: + static Result get_self_name(); + + static Status launch(const String& command, + const Vector& args); +}; \ No newline at end of file diff --git a/src/base/core/ThreadCollection.cpp b/src/base/core/thread/ThreadCollection.cpp similarity index 75% rename from src/base/core/ThreadCollection.cpp rename to src/base/core/thread/ThreadCollection.cpp index 6394204..88c45df 100644 --- a/src/base/core/ThreadCollection.cpp +++ b/src/base/core/thread/ThreadCollection.cpp @@ -1,8 +1,6 @@ #include "ThreadCollection.h" -#include - -bool ThreadCollection::add(std::unique_ptr thread) +bool ThreadCollection::add(Ptr thread) { if (!mAccepting) { @@ -10,7 +8,7 @@ bool ThreadCollection::add(std::unique_ptr thread) } std::scoped_lock guard(mMutex); - mThreads[thread->get_id()] = std::move(thread); + //mThreads.insert(thread->get_id(), std::move(thread)); return true; } @@ -18,12 +16,12 @@ bool ThreadCollection::add(std::unique_ptr thread) void ThreadCollection::joinAndClearAll() { mAccepting = false; - std::vector threads; + Vector threads; { std::scoped_lock guard(mMutex); for (const auto& item : mThreads) { - threads.push_back(item.second.get()); + //threads.push_back(item.value().get()); } } @@ -40,9 +38,9 @@ void ThreadCollection::joinAndClearAll() mAccepting = true; } -std::size_t ThreadCollection::size() const +size_t ThreadCollection::size() const { - std::size_t size{ 0 }; + size_t size{ 0 }; { std::scoped_lock guard(mMutex); size = mThreads.size(); @@ -70,7 +68,7 @@ void ThreadCollection::_remove(std::thread::thread::id inputId) { if (auto const& it = mThreads.find(inputId); it != mThreads.end()) { - it->second->detach(); - mThreads.erase(it); + //it->value()->detach(); + //mThreads.erase(it); } } \ No newline at end of file diff --git a/src/base/core/ThreadCollection.h b/src/base/core/thread/ThreadCollection.h similarity index 54% rename from src/base/core/ThreadCollection.h rename to src/base/core/thread/ThreadCollection.h index d8412d9..a0f7c59 100644 --- a/src/base/core/ThreadCollection.h +++ b/src/base/core/thread/ThreadCollection.h @@ -1,16 +1,17 @@ #pragma once -#include -#include +#include "Map.h" +#include "Pointer.h" +#include "Vector.h" #include #include #include -#include + class ThreadCollection { public: - bool add(std::unique_ptr thread); + bool add(Ptr thread); void joinAndClearAll(); @@ -18,7 +19,7 @@ public: void removeMarked(); - std::size_t size() const; + size_t size() const; private: void _remove(std::thread::thread::id inputId); @@ -26,6 +27,6 @@ private: mutable std::mutex mMutex; std::atomic mAccepting{ true }; - std::vector mMarkedForRemoval; - std::unordered_map > mThreads; + Vector mMarkedForRemoval; + Map > mThreads; }; \ No newline at end of file diff --git a/src/base/core/time/Time.cpp b/src/base/core/time/Time.cpp new file mode 100644 index 0000000..947d92d --- /dev/null +++ b/src/base/core/time/Time.cpp @@ -0,0 +1,29 @@ +#include "Time.h" +#include + +String Time::get_now_str() +{ + time_t time_buf{0}; + ::time(&time_buf); + if (time_buf == -1) + { + return {}; + } + + struct tm tm_buf; + auto rc = ::gmtime_r(&time_buf, &tm_buf); + if (rc == nullptr) + { + return {}; + } + + String ret("T"); + ret += String::to_string(tm_buf.tm_mday) + ":"; + ret += String::to_string(tm_buf.tm_mon) + ":"; + const auto year = (tm_buf.tm_year - 100) + 2000; + ret += String::to_string(year) + "Z"; + ret += String::to_string(tm_buf.tm_hour) + ":"; + ret += String::to_string(tm_buf.tm_min) + ":"; + ret += String::to_string(tm_buf.tm_sec); + return ret; +} \ No newline at end of file diff --git a/src/base/core/time/Time.h b/src/base/core/time/Time.h new file mode 100644 index 0000000..55dad61 --- /dev/null +++ b/src/base/core/time/Time.h @@ -0,0 +1,9 @@ +#pragma once + +#include "String.h" + +class Time +{ +public: + static String get_now_str(); +}; \ No newline at end of file diff --git a/src/base/core/xml/XmlDocument.cpp b/src/base/core/xml/XmlDocument.cpp deleted file mode 100644 index f2bf626..0000000 --- a/src/base/core/xml/XmlDocument.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "XmlDocument.h" - -#include "XmlProlog.h" -#include "XmlElement.h" - -#include - -XmlDocument::XmlDocument() - :mProlog(XmlProlog::Create("xml")) -{ - -} - -XmlDocument::~XmlDocument() -{ - -} - -XmlDocumentPtr XmlDocument::Create() -{ - return std::make_unique(); -} - -void XmlDocument::setProlog(XmlPrologPtr prolog) -{ - mProlog = std::move(prolog); -} - -XmlProlog* XmlDocument::getProlog() const -{ - return mProlog.get(); -} - -void XmlDocument::setRoot(XmlElementPtr root) -{ - mRoot = std::move(root); -} - -XmlElement* XmlDocument::getRoot() const -{ - return mRoot.get(); -} - diff --git a/src/base/core/xml/XmlDocument.h b/src/base/core/xml/XmlDocument.h deleted file mode 100644 index 049b0ef..0000000 --- a/src/base/core/xml/XmlDocument.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#include -#include - -#include "XmlElement.h" -#include "XmlProlog.h" - -class XmlElement; -class XmlProlog; -using XmlPrologPtr = std::unique_ptr; -using XmlElementPtr = std::unique_ptr; - -class XmlDocument -{ -public: - XmlDocument(); - virtual ~XmlDocument(); - - static std::unique_ptr Create(); - - XmlProlog* getProlog() const; - XmlElement* getRoot() const; - - void setProlog(XmlPrologPtr prolog); - void setRoot(XmlElementPtr root); -private: - XmlPrologPtr mProlog; - XmlElementPtr mRoot; -}; - -using XmlDocumentPtr = std::unique_ptr; diff --git a/src/base/core/xml/XmlWriter.cpp b/src/base/core/xml/XmlWriter.cpp deleted file mode 100644 index a9e741f..0000000 --- a/src/base/core/xml/XmlWriter.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "XmlWriter.h" - -#include "XmlDocument.h" -#include "XmlAttribute.h" - -std::string XmlWriter::toString(XmlDocument* document) -{ - std::string content; - if (auto prolog = document->getProlog()) - { - content += "getAttributes()) - { - content += " " + attribute->getName() + "=\"" + attribute->getValue() + "\""; - } - content += "?>\n"; - } - - if (auto root = document->getRoot()) - { - content += root->toString(); - } - return content; -} diff --git a/src/base/core/xml/xml-elements/XmlAttribute.cpp b/src/base/core/xml/xml-elements/XmlAttribute.cpp deleted file mode 100644 index 7c4142e..0000000 --- a/src/base/core/xml/xml-elements/XmlAttribute.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "XmlAttribute.h" - -XmlAttribute::XmlAttribute(const std::string& name) - : mName(name), - mValue() -{ - -} - -XmlAttributePtr XmlAttribute::Create(const std::string& name) -{ - return std::make_unique(name); -} - -const std::string& XmlAttribute::getName() const -{ - return mName; -} - -const std::string& XmlAttribute::getValue() const -{ - return mValue; -} - -void XmlAttribute::setValue(const std::string& value) -{ - mValue = value; -} diff --git a/src/base/core/xml/xml-elements/XmlAttribute.h b/src/base/core/xml/xml-elements/XmlAttribute.h deleted file mode 100644 index 302c5bf..0000000 --- a/src/base/core/xml/xml-elements/XmlAttribute.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include -#include - -class XmlAttribute -{ -public: - XmlAttribute(const std::string& name); - - static std::unique_ptr Create(const std::string& name); - - const std::string& getName() const; - - const std::string& getValue() const; - - void setValue(const std::string& value); -private: - std::string mName; - std::string mValue; -}; - -using XmlAttributePtr = std::unique_ptr; diff --git a/src/base/core/xml/xml-elements/XmlElement.cpp b/src/base/core/xml/xml-elements/XmlElement.cpp deleted file mode 100644 index 7cdd4cd..0000000 --- a/src/base/core/xml/xml-elements/XmlElement.cpp +++ /dev/null @@ -1,140 +0,0 @@ -#include "XmlElement.h" - -#include "XmlAttribute.h" - -XmlElement::XmlElement(const std::string& tagName) - : mTagName(tagName), - mChildren() -{ - -} - -XmlElement::~XmlElement() -{ - -} - -XmlElementPtr XmlElement::Create(const std::string& tagName) -{ - return std::make_unique(tagName); -} - -void XmlElement::setTagName(const std::string& tagName) -{ - mTagName = tagName; -} - -void XmlElement::addChild(XmlElementPtr child) -{ - mChildren.push_back(std::move(child)); -} - -void XmlElement::addAttribute(XmlAttributePtr attribute) -{ - mAttributes[attribute->getName()] = std::move(attribute); -} - -void XmlElement::addAttribute(const std::string& name, const std::string& value) -{ - auto attr = std::make_unique(name); - attr->setValue(value); - addAttribute(std::move(attr)); -} - -const std::string& XmlElement::getTagName() const -{ - return mTagName; -} - -const std::string& XmlElement::getText() const -{ - return mText; -} - -void XmlElement::setText(const std::string& text) -{ - mText = text; -} - -XmlElement* XmlElement::getFirstChildWithTagName(const std::string& tag) -{ - for(auto& child : mChildren) - { - if (child->getTagName() == tag) - { - return child.get(); - } - } - - return nullptr; -} - -bool XmlElement::hasAttribute(const std::string& attribute) const -{ - return (bool)(getAttribute(attribute)); -} - -XmlAttribute* XmlElement::getAttribute(const std::string& attributeName) const -{ - if (auto iter = mAttributes.find(attributeName); iter != mAttributes.end()) - { - return iter->second.get(); - } - return nullptr; -} - -const std::unordered_map& XmlElement::getAttributes() const -{ - return mAttributes; -} - -const std::vector >& XmlElement::getChildren() const -{ - return mChildren; -} - -std::string XmlElement::toString(unsigned depth, bool keepInline) const -{ - const auto prefix = std::string(2*depth, ' '); - - std::string line_ending = keepInline ? "" : "\n"; - - auto content = prefix + "<" + getTagName(); - for (const auto& [key, attribute] : getAttributes()) - { - content += " " + attribute->getName() + "=\"" + attribute->getValue() + "\""; - } - - const auto num_children = mChildren.size(); - if (num_children == 0 && getText().empty()) - { - content += "/>" + line_ending; - return content; - } - else - { - content += ">"; - } - - if (!getText().empty()) - { - content += getText(); - } - - if (num_children>0) - { - content += line_ending; - } - - for(const auto& child : mChildren) - { - content += child->toString(depth+1, keepInline); - } - if (num_children>0) - { - content += prefix; - } - - content += "" + line_ending; - return content; -} diff --git a/src/base/core/xml/xml-elements/XmlElement.h b/src/base/core/xml/xml-elements/XmlElement.h deleted file mode 100644 index 1b3139f..0000000 --- a/src/base/core/xml/xml-elements/XmlElement.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -class XmlAttribute; -using XmlAttributePtr = std::unique_ptr; - -class XmlElement -{ -public: - XmlElement(const std::string& tagName); - virtual ~XmlElement(); - - static std::unique_ptr Create(const std::string& tagName); - - void addAttribute(XmlAttributePtr attribute); - void addAttribute(const std::string& name, const std::string& value); - void addChild(std::unique_ptr child); - - const std::string& getTagName() const; - const std::string& getText() const; - - bool hasAttribute(const std::string& attribute) const; - XmlAttribute* getAttribute(const std::string& attribute) const; - const std::unordered_map& getAttributes() const; - - const std::vector >& getChildren() const; - - XmlElement* getFirstChildWithTagName(const std::string& tag); - - void setText(const std::string& text); - void setTagName(const std::string& tagName); - - virtual std::string toString(unsigned depth = 0, bool keepInline = false) const; - -protected: - std::string mTagName; - std::string mText; - - std::unordered_map mAttributes; - std::vector > mChildren; -}; - -using XmlElementPtr = std::unique_ptr; diff --git a/src/base/database/CMakeLists.txt b/src/base/database/CMakeLists.txt deleted file mode 100644 index a541729..0000000 --- a/src/base/database/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -set(MODULE_NAME database) - -set(SQLite3_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/src/third_party/sqlite3") -set(SQLite3_SOURCE_FILE "${CMAKE_SOURCE_DIR}/src/third_party/sqlite3/sqlite3.c") - -list(APPEND HEADERS - Database.h - DatabaseManager.h - database_interfaces/SqliteInterface.h - ${SQLite3_SOURCE_FILE}) - -list(APPEND SOURCES - Database.cpp - DatabaseManager.cpp - database_interfaces/SqliteInterface.cpp - ${SQLite3_SOURCE_FILE}) - -add_library(${MODULE_NAME} SHARED ${SOURCES} ${HEADERS}) - -target_include_directories(${MODULE_NAME} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/database_interfaces - ${SQLite3_INCLUDE_DIR} - ) - -target_link_libraries(${MODULE_NAME} core) -set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src/base) -set_target_properties( ${MODULE_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON ) diff --git a/src/base/database/Database.cpp b/src/base/database/Database.cpp index e99e037..facf24a 100644 --- a/src/base/database/Database.cpp +++ b/src/base/database/Database.cpp @@ -11,7 +11,7 @@ Database::~Database() } -std::unique_ptr Database::Create() +Ptr Database::Create() { return std::make_unique(); } diff --git a/src/base/database/Database.h b/src/base/database/Database.h index 29e3928..9446393 100644 --- a/src/base/database/Database.h +++ b/src/base/database/Database.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Pointer.h" +#include "String.h" #include using Path = std::filesystem::path; @@ -13,7 +13,7 @@ public: ~Database(); - static std::unique_ptr Create(); + static Ptr Create(); const Path& getPath() const; @@ -23,4 +23,4 @@ private: Path mPath; }; -using DatabasePtr = std::unique_ptr; +using DatabasePtr = Ptr; diff --git a/src/base/database/DatabaseManager.cpp b/src/base/database/DatabaseManager.cpp index 4ef3017..53f233c 100644 --- a/src/base/database/DatabaseManager.cpp +++ b/src/base/database/DatabaseManager.cpp @@ -12,7 +12,7 @@ DatabaseManager::~DatabaseManager() } -std::unique_ptr DatabaseManager::Create() +Ptr DatabaseManager::Create() { return std::make_unique(); } @@ -27,7 +27,7 @@ void DatabaseManager::openDatabase(const Path& path) mDatabaseInterface->open(mDatabase.get()); } -void DatabaseManager::run(const std::string& statement) +void DatabaseManager::run(const String& statement) { mDatabaseInterface->run(statement); } diff --git a/src/base/database/DatabaseManager.h b/src/base/database/DatabaseManager.h index b8e2d61..398559f 100644 --- a/src/base/database/DatabaseManager.h +++ b/src/base/database/DatabaseManager.h @@ -3,7 +3,7 @@ #include "SqliteInterface.h" #include "Database.h" -#include +#include "Pointer.h" #include using Path = std::filesystem::path; @@ -15,11 +15,11 @@ public: ~DatabaseManager(); - static std::unique_ptr Create(); + static Ptr Create(); void openDatabase(const Path& path); - void run(const std::string& statement); + void run(const String& statement); void onShutDown(); @@ -28,4 +28,4 @@ private: SqliteInterfacePtr mDatabaseInterface; }; -using DatabaseManagerPtr = std::unique_ptr; +using DatabaseManagerPtr = Ptr; diff --git a/src/base/database/database_interfaces/SqliteInterface.cpp b/src/base/database/database_interfaces/SqliteInterface.cpp index 71ca453..62be154 100644 --- a/src/base/database/database_interfaces/SqliteInterface.cpp +++ b/src/base/database/database_interfaces/SqliteInterface.cpp @@ -14,7 +14,7 @@ SqliteInterface::~SqliteInterface() } -std::unique_ptr SqliteInterface::Create() +Ptr SqliteInterface::Create() { return std::make_unique(); } @@ -43,7 +43,7 @@ static int callback(void *, int argc, char **, char **) return 0; } -void SqliteInterface::run(const std::string& statement) +void SqliteInterface::run(const String& statement) { MLOG_INFO("Running statement: " << statement); char *zErrMsg = 0; diff --git a/src/base/database/database_interfaces/SqliteInterface.h b/src/base/database/database_interfaces/SqliteInterface.h index 5eb9bef..934fbb0 100644 --- a/src/base/database/database_interfaces/SqliteInterface.h +++ b/src/base/database/database_interfaces/SqliteInterface.h @@ -1,5 +1,5 @@ #pragma once -#include +#include "Pointer.h" #include #include "Database.h" @@ -11,16 +11,16 @@ public: ~SqliteInterface(); - static std::unique_ptr Create(); + static Ptr Create(); void open(Database* db); void close(); - void run(const std::string& statement); + void run(const String& statement); private: sqlite3* mSqliteDb; }; -using SqliteInterfacePtr = std::unique_ptr; +using SqliteInterfacePtr = Ptr; diff --git a/src/base/device/power/Battery.cpp b/src/base/device/power/Battery.cpp new file mode 100644 index 0000000..f03d73e --- /dev/null +++ b/src/base/device/power/Battery.cpp @@ -0,0 +1,11 @@ +#include "Battery.h" + +#include "File.h" + +String Battery::get_capacity() +{ + String content; + File f("/sys/class/power_supply/BAT1/capacity"); + f.readText(content); + return content; +} \ No newline at end of file diff --git a/src/base/device/power/Battery.h b/src/base/device/power/Battery.h new file mode 100644 index 0000000..50a7837 --- /dev/null +++ b/src/base/device/power/Battery.h @@ -0,0 +1,10 @@ +#pragma once + +#include "String.h" + +class Battery +{ +public: + +static String get_capacity(); +} \ No newline at end of file diff --git a/src/base/geometry/CMakeLists.txt b/src/base/geometry/CMakeLists.txt deleted file mode 100644 index a438ab1..0000000 --- a/src/base/geometry/CMakeLists.txt +++ /dev/null @@ -1,72 +0,0 @@ -set(MODULE_NAME geometry) - -list(APPEND HEADERS - AbstractGeometricItem.h - Bounds.h - Transform.h - Rotation.h - grid/AbstractGrid.h - grid/TypedGrid.h - grid/Grid.h - grid/SparseGrid.h - math/Linalg.h - math/Matrix.h - math/Vector.h - path/Curve.h - path/Line.h - path/LineSegment.h - path/Path.h - path/PathElement.h - path/Arc.h - path/QuadraticBezierCurve.h - path/CubicBezierCurve.h - points/Point.h - points/PointParser.h - points/PointCollection.h - points/DiscretePoint.h - primitives/Circle.h - primitives/Polygon.h - primitives/Rectangle.h - primitives/Triangle.h -) - -list(APPEND SOURCES - Rotation.cpp - Bounds.cpp - Transform.cpp - grid/AbstractGrid.cpp - math/Linalg.cpp - math/Matrix.cpp - math/Vector.cpp - path/Curve.cpp - path/Line.cpp - path/LineSegment.cpp - path/Path.cpp - path/PathElement.cpp - path/Arc.cpp - path/QuadraticBezierCurve.cpp - path/CubicBezierCurve.cpp - points/Point.cpp - points/PointParser.cpp - points/PointCollection.cpp - points/DiscretePoint.cpp - primitives/Circle.cpp - primitives/Polygon.cpp - primitives/Rectangle.cpp - primitives/Triangle.cpp - ) - -add_library(${MODULE_NAME} SHARED ${SOURCES} ${HEADERS}) - -target_include_directories(${MODULE_NAME} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/math - ${CMAKE_CURRENT_SOURCE_DIR}/path - ${CMAKE_CURRENT_SOURCE_DIR}/points - ${CMAKE_CURRENT_SOURCE_DIR}/primitives - ${CMAKE_CURRENT_SOURCE_DIR}/grid - ) - -target_link_libraries( ${MODULE_NAME} PUBLIC core) -set_target_properties( ${MODULE_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON ) -set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src/base) diff --git a/src/base/geometry/grid/AbstractGrid.cpp b/src/base/geometry/grid/AbstractGrid.cpp index 411dd58..fd498b6 100644 --- a/src/base/geometry/grid/AbstractGrid.cpp +++ b/src/base/geometry/grid/AbstractGrid.cpp @@ -1,6 +1,6 @@ #include "AbstractGrid.h" -AbstractGrid::AbstractGrid(const Bounds& bounds, std::size_t numPointsX, std::size_t numPointsY, std::size_t numPointsZ) +AbstractGrid::AbstractGrid(const Bounds& bounds, size_t numPointsX, size_t numPointsY, size_t numPointsZ) : mBounds(bounds), mNumX(numPointsX), mNumY(numPointsY), diff --git a/src/base/geometry/grid/AbstractGrid.h b/src/base/geometry/grid/AbstractGrid.h index c2ef52e..25843a7 100644 --- a/src/base/geometry/grid/AbstractGrid.h +++ b/src/base/geometry/grid/AbstractGrid.h @@ -2,19 +2,19 @@ #include "Bounds.h" -#include -#include +#include "Vector.h" +#include "Pointer.h" class AbstractGrid { public: - AbstractGrid(const Bounds& bounds, std::size_t numPointsX, std::size_t numPointsY, std::size_t numPointsZ = 1); + AbstractGrid(const Bounds& bounds, size_t numPointsX, size_t numPointsY, size_t numPointsZ = 1); virtual ~AbstractGrid(); const Bounds& getBounds() const; - virtual std::size_t getDataSize() const = 0; + virtual size_t getDataSize() const = 0; double getXSpacing() const; @@ -24,7 +24,7 @@ public: protected: Bounds mBounds; - std::size_t mNumX{ 0 }; - std::size_t mNumY{ 0 }; - std::size_t mNumZ{ 0 }; + size_t mNumX{ 0 }; + size_t mNumY{ 0 }; + size_t mNumZ{ 0 }; }; diff --git a/src/base/geometry/grid/Grid.h b/src/base/geometry/grid/Grid.h index 424fa8a..eb0f193 100644 --- a/src/base/geometry/grid/Grid.h +++ b/src/base/geometry/grid/Grid.h @@ -6,34 +6,71 @@ template class Grid : public TypedGrid { public: - Grid(const Bounds& bounds, std::size_t numPointsX, std::size_t numPointsY, std::size_t numPointsZ = 1) + Grid(const Bounds& bounds, size_t numPointsX, size_t numPointsY, size_t numPointsZ = 1) : TypedGrid(bounds, numPointsX, numPointsY, numPointsZ) { this->mData->initializeTo(numPointsX * numPointsY * numPointsZ, T()); } - T getItem(std::size_t idx, std::size_t jdx, std::size_t kdx) const override + T getItem(size_t idx, size_t jdx, size_t kdx = 1) const override { return this->mData->getItem(getOffset(idx, jdx, kdx)); } - std::size_t getOffset(std::size_t idx, std::size_t jdx, std::size_t kdx) const + size_t getOffset(size_t idx, size_t jdx, size_t kdx) const { return idx * this->mNumZ + jdx * this->mNumX * this->mNumZ + kdx; } - void setData(const std::vector& data) + void setData(const Vector& data) { this->mData->setData(data); } - void setItem(std::size_t idx, std::size_t jdx, std::size_t kdx, const T& value) override + void setItem(size_t idx, size_t jdx, size_t kdx, const T& value) override { this->mData->setItem(getOffset(idx, jdx, kdx), value); } - std::size_t getDataSize() const override + size_t getDataSize() const override { return this->mData->getLength(); } }; + +template +class SerializeableGrid : public Grid +{ +public: + SerializeableGrid(size_t itemSize, const Bounds& bounds, size_t numPointsX, size_t numPointsY, size_t numPointsZ = 1) + : Grid(bounds, numPointsX, numPointsY, numPointsZ), + mItemSize(itemSize) + { + } + + uint8_t getByte(size_t index) + { + const auto item_index = index/mItemSize; + const auto item_internal_index = index % mItemSize; + return this->mData->getItem(item_index).getByte(item_internal_index); + } + + void toBuffer(uint8_t* buffer, size_t bufferMaxSize) + { + size_t count{0}; + size_t item_count{0}; + while(count < bufferMaxSize && item_count < this->mData->getLength()) + { + const auto& item = this->mData->getItem(item_count); + for(size_t idx = 0; idx< item.getSize(); idx++) + { + buffer[count] = item.getByte(idx); + count++; + } + item_count++; + } + } + +private: + size_t mItemSize{1}; +}; diff --git a/src/base/geometry/grid/SparseGrid.h b/src/base/geometry/grid/SparseGrid.h index 6e3aa82..2d419ed 100644 --- a/src/base/geometry/grid/SparseGrid.h +++ b/src/base/geometry/grid/SparseGrid.h @@ -6,7 +6,7 @@ template class SparseGrid : public TypedGrid { public: - SparseGrid(const Bounds& bounds, std::size_t numPointsX, std::size_t numPointsY) + SparseGrid(const Bounds& bounds, size_t numPointsX, size_t numPointsY) : TypedGrid(bounds, numPointsX, numPointsY) { diff --git a/src/base/geometry/grid/TypedGrid.h b/src/base/geometry/grid/TypedGrid.h index 6e0df7a..5d9b6f6 100644 --- a/src/base/geometry/grid/TypedGrid.h +++ b/src/base/geometry/grid/TypedGrid.h @@ -3,13 +3,13 @@ #include "List.h" #include "AbstractGrid.h" -#include +#include "Pointer.h" template class TypedGrid : public AbstractGrid { public: - TypedGrid(const Bounds& bounds, std::size_t numPointsX, std::size_t numPointsY, std::size_t numPointsZ = 1) + TypedGrid(const Bounds& bounds, size_t numPointsX, size_t numPointsY, size_t numPointsZ = 1) : AbstractGrid(bounds, numPointsX, numPointsY, numPointsZ), mData(std::make_unique >()) { @@ -17,14 +17,14 @@ public: virtual ~TypedGrid() = default; - virtual T getItem(std::size_t idx, std::size_t jdx, std::size_t kdx) const = 0; + virtual T getItem(size_t idx, size_t jdx, size_t kdx) const = 0; - virtual void setItem(std::size_t idx, std::size_t jdx, std::size_t kdx, const T& value) = 0; + virtual void setItem(size_t idx, size_t jdx, size_t kdx, const T& value) = 0; List* getInternalData() const { return mData.get(); } protected: - std::unique_ptr > mData; + Ptr > mData; }; diff --git a/src/base/geometry/math/Linalg.cpp b/src/base/geometry/math/Linalg.cpp index c0710d9..34ff30d 100644 --- a/src/base/geometry/math/Linalg.cpp +++ b/src/base/geometry/math/Linalg.cpp @@ -1,7 +1,7 @@ #include "Linalg.h" -template +template Vector Linalg::crossProduct(const Vector& v0, const Vector& v1) { return v0.crossProduct(v1); diff --git a/src/base/geometry/math/Linalg.h b/src/base/geometry/math/Linalg.h index 9544f7f..8d2dcea 100644 --- a/src/base/geometry/math/Linalg.h +++ b/src/base/geometry/math/Linalg.h @@ -4,6 +4,6 @@ class Linalg { - template + template static Vector crossProduct(const Vector& v0, const Vector& v1); }; \ No newline at end of file diff --git a/src/base/geometry/math/Matrix.cpp b/src/base/geometry/math/Matrix.cpp index 6e3ff48..b010417 100644 --- a/src/base/geometry/math/Matrix.cpp +++ b/src/base/geometry/math/Matrix.cpp @@ -1,35 +1,35 @@ #include "Matrix.h" -#include +#include "String.h" #include -template +template Matrix::Matrix(T value) { - mData = std::vector(M * N, value); + mData = Vector(M * N, value); } -template +template Matrix::Matrix(T value, InputType inputType) { if (inputType == InputType::DIAGONAL) { - mData = std::vector(M * N, 0.0); + mData = Vector(M * N, 0.0); setDiagonals(value); } else { - mData = std::vector(M * N, value); + mData = Vector(M * N, value); } } -template +template void Matrix::applyTo(Vector&) const { } -template +template void Matrix::setDiagonals(T value) { if (!isSquare()) @@ -37,21 +37,21 @@ void Matrix::setDiagonals(T value) throw std::logic_error("Requested setting diagonals on non-square Matrix."); } - for (std::size_t idx = 0; idx < M; idx++) + for (size_t idx = 0; idx < M; idx++) { mData[getFlatIndex(idx, idx)] = value; } } -template -void Matrix::setDiagonals(const std::vector& values) +template +void Matrix::setDiagonals(const Vector& values) { if (!isSquare()) { throw std::logic_error("Requested setting diagonals on non-square Matrix."); } - for (std::size_t idx = 0; idx < values.size(); idx++) + for (size_t idx = 0; idx < values.size(); idx++) { if (idx >= M) { @@ -61,8 +61,8 @@ void Matrix::setDiagonals(const std::vector& values) } } -template -void Matrix::setItem(std::size_t rowId, std::size_t columnId, T value) +template +void Matrix::setItem(size_t rowId, size_t columnId, T value) { const auto index = getFlatIndex(rowId, columnId); if (index >= mData.size()) @@ -72,7 +72,7 @@ void Matrix::setItem(std::size_t rowId, std::size_t columnId, T value) mData[index] = value; } -template +template bool Matrix::isIdentity() const { if (!isSquare()) @@ -80,9 +80,9 @@ bool Matrix::isIdentity() const return false; } - for(std::size_t idx=0; idx::isIdentity() const return true; } -template -T Matrix::getItem(std::size_t rowId, std::size_t columnId) const +template +T Matrix::getItem(size_t rowId, size_t columnId) const { const auto index = getFlatIndex(rowId, columnId); if (index >= mData.size()) @@ -114,20 +114,20 @@ T Matrix::getItem(std::size_t rowId, std::size_t columnId) const return mData[getFlatIndex(rowId, columnId)]; } -template +template bool Matrix::isSquare() const { return M == N; } -template +template bool Matrix::isEqual(const Matrix& matrix) const { return mData == matrix.mData; } -template -std::size_t Matrix::getFlatIndex(std::size_t rowId, std::size_t columnId) const +template +size_t Matrix::getFlatIndex(size_t rowId, size_t columnId) const { return columnId + rowId*N; } diff --git a/src/base/geometry/math/Matrix.h b/src/base/geometry/math/Matrix.h index c04980d..3333dc4 100644 --- a/src/base/geometry/math/Matrix.h +++ b/src/base/geometry/math/Matrix.h @@ -2,10 +2,10 @@ #include "Vector.h" -#include +#include "Vector.h" #include -template +template class Matrix { public: @@ -21,9 +21,9 @@ public: void applyTo(Vector& v) const; - std::size_t getFlatIndex(std::size_t rowId, std::size_t columnId) const; + size_t getFlatIndex(size_t rowId, size_t columnId) const; - T getItem(std::size_t rowId, std::size_t columnId) const; + T getItem(size_t rowId, size_t columnId) const; bool isIdentity() const; @@ -33,9 +33,9 @@ public: void setDiagonals(T value); - void setDiagonals(const std::vector& values); + void setDiagonals(const Vector& values); - void setItem(std::size_t rowId, std::size_t columnId, T value); + void setItem(size_t rowId, size_t columnId, T value); bool operator==(const Matrix& rhs) const { @@ -48,7 +48,7 @@ public: } private: - std::vector mData; + Vector mData; }; using Matrix3x3 = Matrix; diff --git a/src/base/geometry/math/Vector.cpp b/src/base/geometry/math/Vector.cpp index efdcc77..15955cb 100644 --- a/src/base/geometry/math/Vector.cpp +++ b/src/base/geometry/math/Vector.cpp @@ -6,10 +6,10 @@ #include #include -template +template Vector::Vector(Primitive p) { - mData = std::vector(DIM, 0.0); + mData = Vector(DIM, 0.0); switch(p) { case Primitive::UNIT_X: @@ -33,28 +33,28 @@ Vector::Vector(Primitive p) } } -template -Vector::Vector(const std::vector& values) +template +Vector::Vector(const Vector& values) { - mData = std::vector(DIM, 0.0); + mData = Vector(DIM, 0.0); if (values.empty()) { return; } - for (std::size_t idx = 0; idx < std::min(values.size(), DIM); idx++) + for (size_t idx = 0; idx < std::min(values.size(), DIM); idx++) { mData[idx] = values[idx]; } } -template +template Vector::~Vector() { }; -template +template Vector Vector::add(const Vector& v) const { Vector result = *this; @@ -62,25 +62,25 @@ Vector Vector::add(const Vector& v) const return result; } -template +template void Vector::inPlaceAdd(const Vector& v) { std::transform(mData.begin(), mData.end(), v.mData.begin(), mData.begin(), std::plus()); } -template +template bool Vector::equals(const Vector& v) const { return mData == v.mData; } -template +template void Vector::inPlaceMultiply(double) { //std::transform(mData.begin(), mData.end(), mData.begin(), std::bind(std::multiplies(), std::placeholders::_1, v)); } -template +template Vector Vector::multiply(double v) const { Vector result = *this; @@ -88,14 +88,14 @@ Vector Vector::multiply(double v) const return result; } -template +template void Vector::reverseDirection() { inPlaceMultiply(-1.0); } -template -T Vector::getEntry(std::size_t idx) const +template +T Vector::getEntry(size_t idx) const { if (idx >= DIM) { @@ -104,34 +104,34 @@ T Vector::getEntry(std::size_t idx) const return mData[idx]; } -template +template double Vector::getLength() const { return std::sqrt(getSelfInnerProduct()); } -template +template double Vector::getSelfInnerProduct() const { return 0.0; //return std::inner_product(mData.begin(), mData.end(), mData.begin(), 0.0); } -template +template double Vector::innerPoduct(const Vector&) const { return 0.0; //return std::inner_product(mData.begin(), mData.end(), v.mData.begin(), 0.0); } -template +template Vector Vector::crossProduct(const Vector&) const { return Vector(); //return Vector(v.mY * mZ - v.mZ * mY, v.mZ * mX - v.mX * mZ, v.mX * mY - v.mY * mX); } -template +template Vector Vector::getNormalized() const { const auto length = getLength(); @@ -142,8 +142,8 @@ Vector Vector::getNormalized() const return (*this).multiply(1.0 / length); } -template -void Vector::scale(const std::vector&) +template +void Vector::scale(const Vector&) { //std::transform(mData.begin(), mData.end(), factors.begin(), mData.begin(), std::multiplies()); } diff --git a/src/base/geometry/math/Vector.h b/src/base/geometry/math/Vector.h index 333916f..699912c 100644 --- a/src/base/geometry/math/Vector.h +++ b/src/base/geometry/math/Vector.h @@ -1,9 +1,9 @@ #pragma once -#include +#include "Vector.h" #include -template +template class Vector { public: @@ -19,7 +19,7 @@ public: Vector(Primitive p); - Vector(const std::vector& values = {}); + Vector(const Vector& values = {}); ~Vector(); @@ -35,7 +35,7 @@ public: void reverseDirection(); - T getEntry(std::size_t idx) const; + T getEntry(size_t idx) const; double getLength() const; @@ -47,7 +47,7 @@ public: void inPlaceMultiply(double s); - void scale(const std::vector& factors); + void scale(const Vector& factors); Vector operator+(const Vector& v) const { @@ -79,13 +79,13 @@ public: return !operator==(rhs); } - T operator[](std::size_t idx) const + T operator[](size_t idx) const { return getEntry(idx); } private: - std::vector mData; + Vector mData; }; using Vector4 = Vector; diff --git a/src/base/geometry/path/CubicBezierCurve.cpp b/src/base/geometry/path/CubicBezierCurve.cpp index 914af4d..003379f 100644 --- a/src/base/geometry/path/CubicBezierCurve.cpp +++ b/src/base/geometry/path/CubicBezierCurve.cpp @@ -1,6 +1,6 @@ #include "CubicBezierCurve.h" -template +template CubicBezierCurve::CubicBezierCurve(const Vector& endOffset, const Vector& startControlOffset, const Vector& endControlOffset) : mEndOffset(endOffset), mStartControlOffset(startControlOffset), @@ -9,31 +9,31 @@ CubicBezierCurve::CubicBezierCurve(const Vector& endOffset, co } -template +template Vector CubicBezierCurve::getEndOffset() const { return mEndOffset; } -template +template const Vector& CubicBezierCurve::getStartControlOffset() const { return mStartControlOffset; } -template +template const Vector& CubicBezierCurve::getEndControlOffset() const { return mEndControlOffset; } -template +template Bounds CubicBezierCurve::getBounds() const { return {}; } -template +template CurveType CubicBezierCurve::getCurveType() const { return CurveType::CUBIC_BEZIER; diff --git a/src/base/geometry/path/CubicBezierCurve.h b/src/base/geometry/path/CubicBezierCurve.h index e7fc905..0cc2146 100644 --- a/src/base/geometry/path/CubicBezierCurve.h +++ b/src/base/geometry/path/CubicBezierCurve.h @@ -3,7 +3,7 @@ #include "Curve.h" #include "Vector.h" -template +template class CubicBezierCurve : public Curve { public: diff --git a/src/base/geometry/path/Curve.h b/src/base/geometry/path/Curve.h index af51d0f..11dc0c3 100644 --- a/src/base/geometry/path/Curve.h +++ b/src/base/geometry/path/Curve.h @@ -10,7 +10,7 @@ enum class CurveType UNKNOWN }; -template +template class Curve : public PathElement { public: diff --git a/src/base/geometry/path/Line.cpp b/src/base/geometry/path/Line.cpp index e8ec117..fd89179 100644 --- a/src/base/geometry/path/Line.cpp +++ b/src/base/geometry/path/Line.cpp @@ -1,18 +1,18 @@ #include "Line.h" -template +template Line::Line(const PointCollection& points) : mPoints(points) { } -template -Line::Line(InputBufferType bufferType, const std::vector& buffer) +template +Line::Line(InputBufferType bufferType, const Vector& buffer) { if (bufferType == InputBufferType::XY) { - for (std::size_t idx = 0; idx < buffer.size(); idx += 2) + for (size_t idx = 0; idx < buffer.size(); idx += 2) { const auto x = buffer[idx]; const auto y = buffer[idx + 1]; @@ -21,39 +21,39 @@ Line::Line(InputBufferType bufferType, const std::vector& buffer) } else if (bufferType == InputBufferType::HORIZONTAL) { - for (std::size_t idx = 0; idx < buffer.size(); idx ++) + for (size_t idx = 0; idx < buffer.size(); idx ++) { mPoints.addPoint(Point(buffer[idx], 0.0)); } } else if (bufferType == InputBufferType::VERTICAL) { - for (std::size_t idx = 0; idx < buffer.size(); idx++) + for (size_t idx = 0; idx < buffer.size(); idx++) { mPoints.addPoint(Point(0.0, buffer[idx])); } } } -template +template Vector Line::getEndOffset() const { return mPoints.getEndPoint().getOriginOffset(); } -template +template const PointCollection& Line::getPoints() const { return mPoints; } -template +template AbstractGeometricItem::Type Line::getType() const { return AbstractGeometricItem::Type::LINE; } -template +template Bounds Line::getBounds() const { auto bounds = mPoints.getBounds(); diff --git a/src/base/geometry/path/Line.h b/src/base/geometry/path/Line.h index 85a0466..5296ad9 100644 --- a/src/base/geometry/path/Line.h +++ b/src/base/geometry/path/Line.h @@ -3,10 +3,10 @@ #include "PathElement.h" #include "PointCollection.h" -#include -#include +#include "Vector.h" +#include "String.h" -template +template class Line : public PathElement { public: @@ -19,7 +19,7 @@ public: Line(const PointCollection& points); - Line(InputBufferType bufferType, const std::vector& buffer); + Line(InputBufferType bufferType, const Vector& buffer); const PointCollection& getPoints() const; diff --git a/src/base/geometry/path/LineSegment.cpp b/src/base/geometry/path/LineSegment.cpp index cae0bf0..755a21a 100644 --- a/src/base/geometry/path/LineSegment.cpp +++ b/src/base/geometry/path/LineSegment.cpp @@ -1,6 +1,6 @@ #include "LineSegment.h" -template +template LineSegment::LineSegment(const Point& p0, const Point& p1) : mP0(p0), mP1(p1) @@ -8,43 +8,43 @@ LineSegment::LineSegment(const Point& p0, const Point& p1) } -template -std::unique_ptr > LineSegment ::Create(const Point& p0, const Point& p1) +template +Ptr > LineSegment ::Create(const Point& p0, const Point& p1) { return std::make_unique >(p0, p1); } -template +template double LineSegment ::getLength() const { return mP0.getDistance(mP1); } -template +template const Point& LineSegment ::getPoint0() const { return mP0; } -template +template const Point& LineSegment ::getPoint1() const { return mP1; } -template +template bool LineSegment::isHorizontal() const { return mP0.getDeltaY(mP1) == 0.0; } -template +template bool LineSegment::isVertical() const { return mP0.getDeltaX(mP1) == 0.0; } -template +template Bounds LineSegment::getBounds() const { const auto minX = std::min(mP0.getX(), mP1.getX()); @@ -56,19 +56,19 @@ Bounds LineSegment::getBounds() const return {minX, maxX, minY, maxY}; } -template +template Vector LineSegment::getEndOffset() const { return getPoint1().getOriginOffset(); } -template +template AbstractGeometricItem::Type LineSegment::getType() const { return AbstractGeometricItem::Type::LINE_SEGMENT; } -template +template Vector LineSegment::asVector() const { return mP1.getDelta(mP0); diff --git a/src/base/geometry/path/LineSegment.h b/src/base/geometry/path/LineSegment.h index 5ad7e72..edd88b9 100644 --- a/src/base/geometry/path/LineSegment.h +++ b/src/base/geometry/path/LineSegment.h @@ -3,13 +3,13 @@ #include "PathElement.h" #include "Point.h" -template +template class LineSegment : public PathElement { public: LineSegment(const Point& p0, const Point& p1); - static std::unique_ptr > Create(const Point& p0, const Point& p1); + static Ptr > Create(const Point& p0, const Point& p1); double getLength() const; diff --git a/src/base/geometry/path/Path.cpp b/src/base/geometry/path/Path.cpp index 7681a18..f0b6162 100644 --- a/src/base/geometry/path/Path.cpp +++ b/src/base/geometry/path/Path.cpp @@ -5,7 +5,7 @@ GeometryPath::~GeometryPath() } -const std::vector& GeometryPath::getFeatures() const +const Vector& GeometryPath::getFeatures() const { return mFeatures; } diff --git a/src/base/geometry/path/Path.h b/src/base/geometry/path/Path.h index 308f729..294d3fb 100644 --- a/src/base/geometry/path/Path.h +++ b/src/base/geometry/path/Path.h @@ -2,11 +2,11 @@ #include "PathElement.h" -#include -#include -#include +#include "Vector.h" +#include "Pointer.h" +#include "String.h" -using PathElementPtr = std::unique_ptr >; +using PathElementPtr = Ptr >; class GeometryPathFeature { @@ -26,7 +26,7 @@ public: return mOffset; } - const std::vector& getElements() const + const Vector& getElements() const { return mElements; } @@ -44,9 +44,9 @@ public: private: Vector2 mOffset; PathOffsetType mOffsetType{PathOffsetType::RELATIVE_TO}; - std::vector mElements; + Vector mElements; }; -using GeometryPathFeaturePtr = std::unique_ptr; +using GeometryPathFeaturePtr = Ptr; class GeometryPath : public AbstractGeometricItem { @@ -59,8 +59,8 @@ public: Type getType() const override; - const std::vector& getFeatures() const; + const Vector& getFeatures() const; private: - std::vector mFeatures; + Vector mFeatures; }; diff --git a/src/base/geometry/path/PathElement.cpp b/src/base/geometry/path/PathElement.cpp index e923f44..6c3ebc5 100644 --- a/src/base/geometry/path/PathElement.cpp +++ b/src/base/geometry/path/PathElement.cpp @@ -1,6 +1,6 @@ #include "PathElement.h" -template +template PathElement::~PathElement() { diff --git a/src/base/geometry/path/PathElement.h b/src/base/geometry/path/PathElement.h index 486abf0..0458ae7 100644 --- a/src/base/geometry/path/PathElement.h +++ b/src/base/geometry/path/PathElement.h @@ -9,7 +9,7 @@ enum class PathOffsetType ABSOLUTE_TO }; -template +template class PathElement : public AbstractGeometricItem { public: diff --git a/src/base/geometry/path/QuadraticBezierCurve.cpp b/src/base/geometry/path/QuadraticBezierCurve.cpp index d96a0fd..db162da 100644 --- a/src/base/geometry/path/QuadraticBezierCurve.cpp +++ b/src/base/geometry/path/QuadraticBezierCurve.cpp @@ -1,6 +1,6 @@ #include "QuadraticBezierCurve.h" -template +template QuadraticBezierCurve::QuadraticBezierCurve(const Vector& endOffset, const Vector& controlOffset) : mEndOffset(endOffset), mControlOffset(controlOffset) @@ -8,25 +8,25 @@ QuadraticBezierCurve::QuadraticBezierCurve(const Vector& endOf } -template +template Vector QuadraticBezierCurve::getEndOffset() const { return mEndOffset; } -template +template const Vector& QuadraticBezierCurve::getControlOffset() const { return mControlOffset; } -template +template Bounds QuadraticBezierCurve::getBounds() const { return {}; } -template +template CurveType QuadraticBezierCurve::getCurveType() const { return CurveType::QUADRATIC_BEZIER; diff --git a/src/base/geometry/path/QuadraticBezierCurve.h b/src/base/geometry/path/QuadraticBezierCurve.h index 28125c2..d0b7eea 100644 --- a/src/base/geometry/path/QuadraticBezierCurve.h +++ b/src/base/geometry/path/QuadraticBezierCurve.h @@ -3,7 +3,7 @@ #include "Curve.h" #include "Point.h" -template +template class QuadraticBezierCurve : public Curve { public: diff --git a/src/base/geometry/points/DiscretePoint.h b/src/base/geometry/points/DiscretePoint.h index f87185c..d9ca8c9 100644 --- a/src/base/geometry/points/DiscretePoint.h +++ b/src/base/geometry/points/DiscretePoint.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Pointer.h" class DiscretePoint { diff --git a/src/base/geometry/points/Point.cpp b/src/base/geometry/points/Point.cpp index d436168..516e4b4 100644 --- a/src/base/geometry/points/Point.cpp +++ b/src/base/geometry/points/Point.cpp @@ -6,16 +6,16 @@ #include #include -template +template Point Point::from(const Point<2>& p) { return Point(p.getX(), p.getY()); } -template +template Point::Point(double x, double y, double z) { - mCoords = std::vector(DIM); + mCoords = Vector(DIM); if (DIM > 0) { mCoords[0] = x; @@ -30,27 +30,27 @@ Point::Point(double x, double y, double z) } } -template +template Point::Point(const Vector& v) { - mCoords = std::vector(DIM); - for (std::size_t idx = 0; idx < DIM; idx++) + mCoords = Vector(DIM); + for (size_t idx = 0; idx < DIM; idx++) { mCoords[idx] = v.getEntry(idx); } } -template +template Point::Point(const DiscretePoint& point) : Point(static_cast(point.getX()), static_cast(point.getY()), 0.0) { } -template +template Point::Point(const Point& reference, double offSetX, double offSetY, double offSetZ) { - mCoords = std::vector(DIM); + mCoords = Vector(DIM); if (DIM > 0) { mCoords[0] = reference.getX() + offSetX; @@ -65,12 +65,12 @@ Point::Point(const Point& reference, double offSetX, double offSetY, d } } -template +template Point::~Point() { }; -template +template double Point::getX() const { if (DIM > 0) @@ -83,7 +83,7 @@ double Point::getX() const } } -template +template double Point::getY() const { if (DIM > 1) @@ -96,7 +96,7 @@ double Point::getY() const } } -template +template double Point::getZ() const { if (DIM > 2) @@ -109,7 +109,7 @@ double Point::getZ() const } } -template +template double Point::getDistance(const Point& point) const { const auto deltaX = getDeltaX(point); @@ -118,50 +118,50 @@ double Point::getDistance(const Point& point) const return std::sqrt(deltaX* deltaX + deltaY* deltaY + deltaZ* deltaZ); } -template +template Vector Point::getDelta(const Point& point) const { return Vector({ point.getX() - getX(), point.getY() - getY(), point.getZ() - getZ() }); } -template +template double Point::getDeltaX(const Point& point) const { return point.getX() - getX(); } -template +template double Point::getDeltaY(const Point& point) const { return point.getY() - getY(); } -template +template double Point::getDeltaZ(const Point& point) const { return point.getZ() - getZ(); } -template +template bool Point::isAtOrigin() const { return std::accumulate(mCoords.begin(), mCoords.end(), 0.0) == 0.0; } -template +template Vector Point::getOriginOffset() const { return Vector(mCoords); } -template +template void Point::apply(const Transform& transform) { moveBy(-transform.getLocation().getX(), -transform.getLocation().getY(), -transform.getLocation().getZ()); scale(transform.getScale().mX, transform.getScale().mY, transform.getScale().mZ); } -template +template void Point::scale(double x, double y, double z) { if (DIM > 0) @@ -178,7 +178,7 @@ void Point::scale(double x, double y, double z) } } -template +template void Point::moveBy(double x, double y, double z) { if (DIM > 0) @@ -195,16 +195,16 @@ void Point::moveBy(double x, double y, double z) } } -template +template void Point::moveBy(const Vector& vector) { - for (std::size_t idx = 0; idx < DIM; idx++) + for (size_t idx = 0; idx < DIM; idx++) { mCoords[idx] += vector.getEntry(idx); } } -template +template bool Point::isEqual(const Point& rhs) const { return mCoords == rhs.mCoords; diff --git a/src/base/geometry/points/Point.h b/src/base/geometry/points/Point.h index d2e2451..9627c70 100644 --- a/src/base/geometry/points/Point.h +++ b/src/base/geometry/points/Point.h @@ -3,11 +3,11 @@ #include "DiscretePoint.h" #include "Vector.h" -#include +#include "Pointer.h" class Transform; -template +template class Point { public: @@ -78,11 +78,11 @@ public: } private: - std::vector mCoords; + Vector mCoords; }; using Point3 = Point<3>; using Point2 = Point<2>; -using PointPtr3 = std::unique_ptr >; -using PointPtr2 = std::unique_ptr >; +using PointPtr3 = Ptr >; +using PointPtr2 = Ptr >; diff --git a/src/base/geometry/points/PointCollection.cpp b/src/base/geometry/points/PointCollection.cpp index 9322094..7d388ce 100644 --- a/src/base/geometry/points/PointCollection.cpp +++ b/src/base/geometry/points/PointCollection.cpp @@ -1,13 +1,13 @@ #include "PointCollection.h" -template -PointCollection::PointCollection(const std::vector > points) +template +PointCollection::PointCollection(const Vector > points) : mPoints(points) { } -template +template void PointCollection::apply(const Transform& transform) { for (auto& point : mPoints) @@ -16,13 +16,13 @@ void PointCollection::apply(const Transform& transform) } } -template +template void PointCollection::addPoint(const Point& point) { mPoints.push_back(point); } -template +template Bounds PointCollection::getBounds() const { Bounds bounds{0.0, 0.0, 0.0, 0.0}; @@ -40,7 +40,7 @@ Bounds PointCollection::getBounds() const return bounds; } -template +template Point PointCollection::getEndPoint() const { if (mPoints.empty()) @@ -53,8 +53,8 @@ Point PointCollection::getEndPoint() const } } -template -const std::vector >& PointCollection::getPoints() const +template +const Vector >& PointCollection::getPoints() const { return mPoints; } diff --git a/src/base/geometry/points/PointCollection.h b/src/base/geometry/points/PointCollection.h index 777ba20..d8ed078 100644 --- a/src/base/geometry/points/PointCollection.h +++ b/src/base/geometry/points/PointCollection.h @@ -4,13 +4,13 @@ #include "Transform.h" #include "Bounds.h" -#include +#include "Vector.h" -template +template class PointCollection { public: - PointCollection(const std::vector > points = {}); + PointCollection(const Vector > points = {}); void addPoint(const Point& point); @@ -20,8 +20,8 @@ public: Point getEndPoint() const; - const std::vector >& getPoints() const; + const Vector >& getPoints() const; private: - std::vector > mPoints; + Vector > mPoints; }; diff --git a/src/base/geometry/points/PointParser.cpp b/src/base/geometry/points/PointParser.cpp index 82213f0..a04b0a4 100644 --- a/src/base/geometry/points/PointParser.cpp +++ b/src/base/geometry/points/PointParser.cpp @@ -2,17 +2,17 @@ #include -std::string PointParser::toString(const Point2& p, const std::string& delimiter, std::size_t precision) +String PointParser::toString(const Point2& p, const String& delimiter, size_t precision) { return toString(p.getX(), p.getY(), delimiter, precision); } -std::string PointParser::toString(const Vector2& v, const std::string& delimiter, std::size_t precision) +String PointParser::toString(const Vector2& v, const String& delimiter, size_t precision) { return toString(v.getEntry(0), v.getEntry(1), delimiter, precision); } -std::string PointParser::toString(double x, double y, const std::string& delimiter, std::size_t precision) +String PointParser::toString(double x, double y, const String& delimiter, size_t precision) { if (precision == 0) { @@ -20,14 +20,14 @@ std::string PointParser::toString(double x, double y, const std::string& delimit } else { - std::stringstream sstr; + Stringstream sstr; sstr.precision(precision); sstr << x << delimiter << y; return sstr.str(); } } -std::string PointParser::toString(double x, std::size_t precision) +String PointParser::toString(double x, size_t precision) { if (precision == 0) { @@ -35,7 +35,7 @@ std::string PointParser::toString(double x, std::size_t precision) } else { - std::stringstream sstr; + Stringstream sstr; sstr.precision(precision); sstr << x; return sstr.str(); diff --git a/src/base/geometry/points/PointParser.h b/src/base/geometry/points/PointParser.h index 6f64329..3dbd9b1 100644 --- a/src/base/geometry/points/PointParser.h +++ b/src/base/geometry/points/PointParser.h @@ -2,16 +2,16 @@ #include "Point.h" -#include +#include "String.h" class PointParser { public: - static std::string toString(const Point2& p, const std::string& delimiter = " ", std::size_t precision = 0); + static String toString(const Point2& p, const String& delimiter = " ", size_t precision = 0); - static std::string toString(const Vector2& v, const std::string& delimiter = " ", std::size_t precision = 0); + static String toString(const Vector2& v, const String& delimiter = " ", size_t precision = 0); - static std::string toString(double x, double y, const std::string& delimiter = " ", std::size_t precision = 0); + static String toString(double x, double y, const String& delimiter = " ", size_t precision = 0); - static std::string toString(double x, std::size_t precision = 0); + static String toString(double x, size_t precision = 0); }; diff --git a/src/base/geometry/primitives/Polygon.cpp b/src/base/geometry/primitives/Polygon.cpp index abdbdf1..4d924d0 100644 --- a/src/base/geometry/primitives/Polygon.cpp +++ b/src/base/geometry/primitives/Polygon.cpp @@ -1,26 +1,26 @@ #include "Polygon.h" namespace ntk { - template - Polygon::Polygon(const std::vector >& points) + template + Polygon::Polygon(const Vector >& points) : AbstractGeometricItem() { mPoints = PointCollection(points); } - template + template const PointCollection& Polygon::getPoints() const { return mPoints; } - template + template Bounds Polygon::getBounds() const { return mPoints.getBounds(); } - template + template AbstractGeometricItem::Type Polygon::getType() const { return Polygon::Type::POLYGON; diff --git a/src/base/geometry/primitives/Polygon.h b/src/base/geometry/primitives/Polygon.h index 07a005d..000341b 100644 --- a/src/base/geometry/primitives/Polygon.h +++ b/src/base/geometry/primitives/Polygon.h @@ -5,11 +5,11 @@ #include "PointCollection.h" namespace ntk{ -template +template class Polygon : public AbstractGeometricItem { public: - Polygon(const std::vector >& points); + Polygon(const Vector >& points); const PointCollection& getPoints() const; diff --git a/src/base/network/CMakeLists.txt b/src/base/network/CMakeLists.txt deleted file mode 100644 index 7cb13e4..0000000 --- a/src/base/network/CMakeLists.txt +++ /dev/null @@ -1,70 +0,0 @@ -set(MODULE_NAME network) - -set(platform_INCLUDES) -set(platform_LIBS) - -if(UNIX) -list(APPEND platform_INCLUDES - sockets/BerkeleySocket.h - sockets/BerkeleySocket.cpp - server/UnixSocketServer.h - server/UnixSocketServer.cpp - client/unix/UnixSocketClient.h - client/unix/UnixSocketClient.cpp - ) -else() -list(APPEND platform_INCLUDES - server/win32/Win32WebServer.h - server/win32/Win32WebServer.cpp - server/win32/Win32TempFile.h - server/win32/Win32TempFile.cpp - server/win32/Win32WebRequest.h - server/win32/Win32WebRequest.cpp - server/win32/Win32WebResponse.h - server/win32/Win32WebResponse.cpp - server/win32/Win32Buffer.h - server/win32/Win32Buffer.cpp - server/WinsockServer.h - server/WinsockServer.cpp - client/win32/WinsockClient.h - client/win32/WinsockClient.cpp - sockets/WinsockInterface.h - sockets/WinsockInterface.cpp - sockets/WinsockSocket.h - sockets/WinsockSocket.cpp - ) - list(APPEND platform_LIBS Httpapi.lib Ws2_32.lib) -endif() - -list(APPEND HEADERS - NetworkManager.h - client/HttpClient.h - client/PlatformSocketClient.h - server/HttpServer.h - server/PlatformSocketServer.h - sockets/Socket.h - sockets/IPlatformSocket.h - ) - -list(APPEND SOURCES - client/HttpClient.cpp - server/HttpServer.cpp - NetworkManager.cpp - sockets/Socket.cpp - ) - -add_library(${MODULE_NAME} SHARED ${SOURCES} ${platform_INCLUDES} ${HEADERS}) - -target_include_directories(${MODULE_NAME} PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/sockets - ${CMAKE_CURRENT_SOURCE_DIR}/server - ${CMAKE_CURRENT_SOURCE_DIR}/server/win32 - ${CMAKE_CURRENT_SOURCE_DIR}/client - ${CMAKE_CURRENT_SOURCE_DIR}/client/win32 - ${CMAKE_CURRENT_SOURCE_DIR}/client/unix - ) -set_target_properties( ${MODULE_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON ) -target_link_libraries( ${MODULE_NAME} PUBLIC core ${platform_LIBS}) - -set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src/base) diff --git a/src/base/network/NetworkManager.cpp b/src/base/network/NetworkManager.cpp index 2568bb0..f3e36c3 100644 --- a/src/base/network/NetworkManager.cpp +++ b/src/base/network/NetworkManager.cpp @@ -10,7 +10,7 @@ NetworkManager::~NetworkManager() } -std::unique_ptr NetworkManager::Create() +Ptr NetworkManager::Create() { return std::make_unique(); } diff --git a/src/base/network/NetworkManager.h b/src/base/network/NetworkManager.h index 2535766..9fe4eab 100644 --- a/src/base/network/NetworkManager.h +++ b/src/base/network/NetworkManager.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Pointer.h" +#include "Vector.h" #include "HttpClient.h" #include "HttpServer.h" @@ -15,15 +15,15 @@ public: ~NetworkManager(); - static std::unique_ptr Create(); + static Ptr Create(); HttpClient* getHttpClient() const; void runHttpServer(AbstractWebApp* webApp); private: - std::unique_ptr mHttpServer; - std::unique_ptr mHttpClient; + Ptr mHttpServer; + Ptr mHttpClient; }; -using NetworkManagerUPtr = std::unique_ptr; +using NetworkManagerUPtr = Ptr; diff --git a/src/base/network/client/HttpClient.h b/src/base/network/client/HttpClient.h index b689aca..9096e33 100644 --- a/src/base/network/client/HttpClient.h +++ b/src/base/network/client/HttpClient.h @@ -4,15 +4,15 @@ #include "HttpRequest.h" #include "HttpResponse.h" -#include +#include "Pointer.h" class HttpClient { public: struct Address { - std::string mPrefix; - std::string mHost; + String mPrefix; + String mHost; unsigned int mPort{ 8000 }; }; @@ -20,5 +20,5 @@ public: HttpResponse makeRequest(const HttpRequest& request, const Address& address); private: - std::unique_ptr mSocketClient; + Ptr mSocketClient; }; diff --git a/src/base/network/client/PlatformSocketClient.h b/src/base/network/client/PlatformSocketClient.h index 3e2b843..615bfe1 100644 --- a/src/base/network/client/PlatformSocketClient.h +++ b/src/base/network/client/PlatformSocketClient.h @@ -1,14 +1,14 @@ #pragma once -#include +#include "String.h" class PlatformSocketClient { public: struct Address { - std::string mPrefix; - std::string mHost; + String mPrefix; + String mHost; unsigned int mPort{8000}; }; @@ -21,10 +21,10 @@ public: }; Status mStatus{ Status::FAILED }; - std::string mErrorMessage; + String mErrorMessage; int mErrorCode{ -1 }; - std::string mBody; + String mBody; }; - virtual Result request(const Address& address, const std::string& message) = 0; + virtual Result request(const Address& address, const String& message) = 0; }; \ No newline at end of file diff --git a/src/base/network/client/unix/UnixSocketClient.cpp b/src/base/network/client/unix/UnixSocketClient.cpp index 32a3231..ab3f633 100644 --- a/src/base/network/client/unix/UnixSocketClient.cpp +++ b/src/base/network/client/unix/UnixSocketClient.cpp @@ -10,7 +10,7 @@ UnixSocketClient::~UnixSocketClient() } -UnixSocketClient::Result UnixSocketClient::request(const Address& address, const std::string& message) +UnixSocketClient::Result UnixSocketClient::request(const Address& address, const String& message) { UnixSocketClient::Result result; diff --git a/src/base/network/client/unix/UnixSocketClient.h b/src/base/network/client/unix/UnixSocketClient.h index 0451d87..17ce2c2 100644 --- a/src/base/network/client/unix/UnixSocketClient.h +++ b/src/base/network/client/unix/UnixSocketClient.h @@ -4,7 +4,7 @@ #include "PlatformSocketClient.h" -#include +#include "Vector.h" class UnixSocketClient : public PlatformSocketClient { @@ -13,5 +13,5 @@ public: virtual ~UnixSocketClient(); - Result request(const Address& address, const std::string& message); + Result request(const Address& address, const String& message); }; diff --git a/src/base/network/client/win32/WinsockClient.cpp b/src/base/network/client/win32/WinsockClient.cpp index 088bc37..e3db265 100644 --- a/src/base/network/client/win32/WinsockClient.cpp +++ b/src/base/network/client/win32/WinsockClient.cpp @@ -6,7 +6,7 @@ WinsockClient::WinsockClient() mSocketInterface->initializeWinsock(); } -WinsockClient::Result WinsockClient::request(const Address& address, const std::string& message) +WinsockClient::Result WinsockClient::request(const Address& address, const String& message) { WinsockClient::Result result; diff --git a/src/base/network/client/win32/WinsockClient.h b/src/base/network/client/win32/WinsockClient.h index 6d57c4f..ae063fa 100644 --- a/src/base/network/client/win32/WinsockClient.h +++ b/src/base/network/client/win32/WinsockClient.h @@ -5,15 +5,15 @@ #include "PlatformSocketClient.h" -#include +#include "Vector.h" class WinsockClient : public PlatformSocketClient { public: WinsockClient(); - Result request(const Address& address, const std::string& message); + Result request(const Address& address, const String& message); private: - std::unique_ptr mSocketInterface; + Ptr mSocketInterface; }; diff --git a/src/base/network/server/HttpServer.cpp b/src/base/network/server/HttpServer.cpp index 795e0ab..5370770 100644 --- a/src/base/network/server/HttpServer.cpp +++ b/src/base/network/server/HttpServer.cpp @@ -38,7 +38,7 @@ void HttpServer::onConnection(Socket* socket) HttpRequest request; request.fromString(message); - std::string extra_bytes; + String extra_bytes; if (request.requiredBytes() > 0) { extra_bytes += socket->recieve(); @@ -57,7 +57,7 @@ void HttpServer::onConnection(Socket* socket) } } -void HttpServer::onFailure(const std::string& reason) +void HttpServer::onFailure(const String& reason) { MLOG_ERROR("Connection failed: " << reason); } diff --git a/src/base/network/server/HttpServer.h b/src/base/network/server/HttpServer.h index a9af188..1de1f92 100644 --- a/src/base/network/server/HttpServer.h +++ b/src/base/network/server/HttpServer.h @@ -2,7 +2,7 @@ #include "PlatformSocketServer.h" -#include +#include "Pointer.h" class AbstractWebApp; class Socket; @@ -12,8 +12,8 @@ class HttpServer public: struct Address { - std::string mPrefix; - std::string mHost; + String mPrefix; + String mHost; unsigned int mPort{ 8000 }; }; @@ -25,8 +25,8 @@ public: private: void onConnection(Socket* socket); - void onFailure(const std::string& reason); + void onFailure(const String& reason); AbstractWebApp* mWebApp{ nullptr }; - std::unique_ptr mSocketServer; + Ptr mSocketServer; }; \ No newline at end of file diff --git a/src/base/network/server/PlatformSocketServer.h b/src/base/network/server/PlatformSocketServer.h index d0f7f41..3416efa 100644 --- a/src/base/network/server/PlatformSocketServer.h +++ b/src/base/network/server/PlatformSocketServer.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "String.h" #include class Socket; @@ -10,8 +10,8 @@ class PlatformSocketServer public: struct Address { - std::string mPrefix; - std::string mHost; + String mPrefix; + String mHost; unsigned int mPort{8000}; }; @@ -24,9 +24,9 @@ public: }; Status mStatus{ Status::FAILED }; - std::string mErrorMessage; + String mErrorMessage; int mErrorCode{ -1 }; - std::string mBody; + String mBody; }; using onConnectionSuccessFunc = std::function; diff --git a/src/base/network/server/UnixSocketServer.cpp b/src/base/network/server/UnixSocketServer.cpp index 05ba2cb..c08e040 100644 --- a/src/base/network/server/UnixSocketServer.cpp +++ b/src/base/network/server/UnixSocketServer.cpp @@ -41,7 +41,7 @@ void UnixSocketServer::shutDown() mThreads.joinAndClearAll(); } -void UnixSocketServer::onConnection(std::unique_ptr s) +void UnixSocketServer::onConnection(Ptr s) { // House-keeping first - clean up any finished threads MLOG_INFO("Before thread cleanup: " << mThreads.size()); @@ -50,7 +50,7 @@ void UnixSocketServer::onConnection(std::unique_ptr s) MLOG_INFO("After thread cleanup: " << mThreads.size()); - auto worker_func = [this](std::unique_ptr s) + auto worker_func = [this](Ptr s) { MLOG_INFO("Spawned thread for new connection"); diff --git a/src/base/network/server/UnixSocketServer.h b/src/base/network/server/UnixSocketServer.h index e4b1d8a..71a4039 100644 --- a/src/base/network/server/UnixSocketServer.h +++ b/src/base/network/server/UnixSocketServer.h @@ -3,7 +3,7 @@ #include "PlatformSocketServer.h" #include "ThreadCollection.h" -#include +#include "Pointer.h" class BerkeleySocket; @@ -17,7 +17,7 @@ public: void shutDown() override; private: - void onConnection(std::unique_ptr clientHandle); + void onConnection(Ptr clientHandle); void onThreadComplete(std::thread::id id); diff --git a/src/base/network/server/WinsockServer.cpp b/src/base/network/server/WinsockServer.cpp index 0ebc81d..942f01a 100644 --- a/src/base/network/server/WinsockServer.cpp +++ b/src/base/network/server/WinsockServer.cpp @@ -48,7 +48,7 @@ void WinsockServer::shutDown() mThreads.joinAndClearAll(); } -void WinsockServer::onConnection(std::unique_ptr s) +void WinsockServer::onConnection(Ptr s) { // House-keeping first - clean up any finished threads MLOG_INFO("Before thread cleanup: " << mThreads.size()); @@ -57,7 +57,7 @@ void WinsockServer::onConnection(std::unique_ptr s) MLOG_INFO("After thread cleanup: " << mThreads.size()); - auto worker_func = [this](std::unique_ptr s) + auto worker_func = [this](Ptr s) { MLOG_INFO("Spawned thread for new connection"); diff --git a/src/base/network/server/WinsockServer.h b/src/base/network/server/WinsockServer.h index 974a23b..b7ad956 100644 --- a/src/base/network/server/WinsockServer.h +++ b/src/base/network/server/WinsockServer.h @@ -4,7 +4,7 @@ #include "ThreadCollection.h" #include "WinsockInterface.h" -#include +#include "Pointer.h" class WinsockSocket; class WinsockInterface; @@ -19,7 +19,7 @@ public: void shutDown() override; private: - void onConnection(std::unique_ptr clientHandle); + void onConnection(Ptr clientHandle); void onThreadComplete(std::thread::id id); @@ -27,5 +27,5 @@ private: onConnectionSuccessFunc mConnectionCallback; onConnectionFailedFunc mFailedCallback; - std::unique_ptr mWinsockInterface; + Ptr mWinsockInterface; }; diff --git a/src/base/network/server/win32/Win32TempFile.h b/src/base/network/server/win32/Win32TempFile.h index 4ebdf54..ada0966 100644 --- a/src/base/network/server/win32/Win32TempFile.h +++ b/src/base/network/server/win32/Win32TempFile.h @@ -9,7 +9,7 @@ #endif #include -#include +#include "String.h" class Win32TempFile { diff --git a/src/base/network/server/win32/Win32WebRequest.cpp b/src/base/network/server/win32/Win32WebRequest.cpp index 4ea1adb..8c366d4 100644 --- a/src/base/network/server/win32/Win32WebRequest.cpp +++ b/src/base/network/server/win32/Win32WebRequest.cpp @@ -46,7 +46,7 @@ void Win32WebRequest::resizeBuffer(unsigned size) mHandle = reinterpret_cast(mBuffer.getBuffer()); } -std::string Win32WebRequest::getUrlFromRequest() const +String Win32WebRequest::getUrlFromRequest() const { return UnicodeUtils::utf16ToUtf8String(mHandle->CookedUrl.pAbsPath); } diff --git a/src/base/network/server/win32/Win32WebRequest.h b/src/base/network/server/win32/Win32WebRequest.h index cd5a75e..78ec846 100644 --- a/src/base/network/server/win32/Win32WebRequest.h +++ b/src/base/network/server/win32/Win32WebRequest.h @@ -13,8 +13,8 @@ #endif #include -#include -#include +#include "String.h" +#include "Pointer.h" #include "Win32Buffer.h" @@ -51,11 +51,11 @@ public: bool startReceiveEntity(); private: - std::string getUrlFromRequest() const; + String getUrlFromRequest() const; static const unsigned ENTITY_BUFFER_SIZE{ 2048 }; - std::unique_ptr mEntityBuffer; - std::unique_ptr mTempFile; + Ptr mEntityBuffer; + Ptr mTempFile; unsigned mEntityTotalSize{ 0 }; static const unsigned DEFAULT_BUFFER_SIZE{ sizeof(HTTP_REQUEST) + 2048 }; diff --git a/src/base/network/server/win32/Win32WebResponse.h b/src/base/network/server/win32/Win32WebResponse.h index 0ccf777..fdc3b25 100644 --- a/src/base/network/server/win32/Win32WebResponse.h +++ b/src/base/network/server/win32/Win32WebResponse.h @@ -14,7 +14,7 @@ #endif #include -#include +#include "String.h" class HttpResponse; class Win32WebRequest; @@ -32,11 +32,11 @@ private: void populateBody(const HttpResponse& response); void populateHeader(const HttpResponse& response); - std::string mResponseReason; - std::string mContentType; - std::string mBody; + String mResponseReason; + String mContentType; + String mBody; - std::string mContentLength; + String mContentLength; HTTP_RESPONSE mResponse; HTTP_DATA_CHUNK mDataChunk; }; \ No newline at end of file diff --git a/src/base/network/server/win32/Win32WebServer.h b/src/base/network/server/win32/Win32WebServer.h index 455e985..5d706c5 100644 --- a/src/base/network/server/win32/Win32WebServer.h +++ b/src/base/network/server/win32/Win32WebServer.h @@ -11,7 +11,7 @@ #endif #include -#include +#include "String.h" class AbstractWebApp; class Win32WebRequest; @@ -40,5 +40,5 @@ private: AbstractWebApp* mWebApp{ nullptr }; HANDLE mWorkingQueue{ 0 }; - std::string mListenUrl; + String mListenUrl; }; \ No newline at end of file diff --git a/src/base/network/sockets/BerkeleySocket.cpp b/src/base/network/sockets/BerkeleySocket.cpp index 6e661e0..80d54af 100644 --- a/src/base/network/sockets/BerkeleySocket.cpp +++ b/src/base/network/sockets/BerkeleySocket.cpp @@ -9,7 +9,7 @@ #include #include -BerkeleySocket::BerkeleySocket(const std::string& address, unsigned port) +BerkeleySocket::BerkeleySocket(const String& address, unsigned port) : Socket(address, port) { @@ -109,7 +109,7 @@ void BerkeleySocket::doListen(onIncomingConnectionFunc connectionFunc) } } -std::string BerkeleySocket::send(const std::string& message) +String BerkeleySocket::send(const String& message) { if (mState.mConnectStatus != Socket::State::ConnectStatus::OK) { @@ -133,7 +133,7 @@ std::string BerkeleySocket::send(const std::string& message) return{}; } - std::string response; + String response; while (mState.mConnectStatus == Socket::State::ConnectStatus::OK) { response += recieve(); @@ -143,13 +143,13 @@ std::string BerkeleySocket::send(const std::string& message) return response; } -void BerkeleySocket::respond(const std::string& message) +void BerkeleySocket::respond(const String& message) { auto result = ::write(mHandle, message.c_str(), static_cast(message.size())); (void)result; } -void BerkeleySocket::onSockerError(const std::string& message) +void BerkeleySocket::onSockerError(const String& message) { mState.mErrorCode = -1; mState.mErrorMessage = message; @@ -161,14 +161,14 @@ void BerkeleySocket::onSockerError(const std::string& message) mState.mConnectStatus = Socket::State::ConnectStatus::FAILED; } -std::string BerkeleySocket::recieve() +String BerkeleySocket::recieve() { const int BUFFER_SIZE = 512; char buffer[BUFFER_SIZE]; auto result = ::read(mHandle, buffer, BUFFER_SIZE); if (result > 0) { - return std::string(buffer); + return String(buffer); } else if (result == 0) { diff --git a/src/base/network/sockets/BerkeleySocket.h b/src/base/network/sockets/BerkeleySocket.h index da27037..eb2ac76 100644 --- a/src/base/network/sockets/BerkeleySocket.h +++ b/src/base/network/sockets/BerkeleySocket.h @@ -2,23 +2,23 @@ #include "Socket.h" -#include +#include "String.h" #include class BerkeleySocket : public Socket { public: - BerkeleySocket(const std::string& address, unsigned port); + BerkeleySocket(const String& address, unsigned port); BerkeleySocket(int handle); ~BerkeleySocket(); - std::string recieve() override; + String recieve() override; - void respond(const std::string& message) override; + void respond(const String& message) override; - std::string send(const std::string& message) override; + String send(const String& message) override; using onIncomingConnectionFunc = std::function; void doListen(onIncomingConnectionFunc connectionFunc); @@ -31,7 +31,7 @@ private: void doBind() override; - void onSockerError(const std::string& message); + void onSockerError(const String& message); int mHandle{ 0 }; }; diff --git a/src/base/network/sockets/ISocketMessageHandler.h b/src/base/network/sockets/ISocketMessageHandler.h index 5cab10b..94f3b40 100644 --- a/src/base/network/sockets/ISocketMessageHandler.h +++ b/src/base/network/sockets/ISocketMessageHandler.h @@ -1,10 +1,10 @@ #pragma once -#include +#include "String.h" class ISocketMessageHandler { public: virtual ~ISocketMessageHandler() = default; - virtual std::string onMessage(const std::string& message) = 0; + virtual String onMessage(const String& message) = 0; }; diff --git a/src/base/network/sockets/Socket.cpp b/src/base/network/sockets/Socket.cpp index e81c58d..5903a8f 100644 --- a/src/base/network/sockets/Socket.cpp +++ b/src/base/network/sockets/Socket.cpp @@ -1,6 +1,6 @@ #include "Socket.h" -Socket::Socket(const std::string& address, unsigned port) +Socket::Socket(const String& address, unsigned port) : mPort(port), mAddress(address) { @@ -22,7 +22,7 @@ unsigned Socket::getPort() const return mPort; } -std::string Socket::getAddress() const +String Socket::getAddress() const { return mAddress; } \ No newline at end of file diff --git a/src/base/network/sockets/Socket.h b/src/base/network/sockets/Socket.h index bf83477..ebc012a 100644 --- a/src/base/network/sockets/Socket.h +++ b/src/base/network/sockets/Socket.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Pointer.h" +#include "String.h" #include class Socket @@ -25,26 +25,26 @@ public: ConnectStatus mConnectStatus{ ConnectStatus::UNSET }; BindStatus mBindStatus{ BindStatus::UNSET }; - std::string mErrorMessage; + String mErrorMessage; int mErrorCode{ 0 }; - std::string mBody; + String mBody; }; - Socket(const std::string& address, unsigned port); + Socket(const String& address, unsigned port); virtual ~Socket(); - std::string getAddress() const; + String getAddress() const; unsigned getPort() const; const State& getState() const; - virtual void respond(const std::string& message) = 0; + virtual void respond(const String& message) = 0; - virtual std::string recieve() = 0; + virtual String recieve() = 0; - virtual std::string send(const std::string& message) = 0; + virtual String send(const String& message) = 0; protected: virtual void initialize() {}; @@ -56,7 +56,7 @@ protected: State mState; unsigned mPort{0}; - std::string mAddress; + String mAddress; }; -using SocketPtr = std::unique_ptr; +using SocketPtr = Ptr; diff --git a/src/base/network/sockets/WinsockSocket.cpp b/src/base/network/sockets/WinsockSocket.cpp index e53e6c9..55d62f5 100644 --- a/src/base/network/sockets/WinsockSocket.cpp +++ b/src/base/network/sockets/WinsockSocket.cpp @@ -5,7 +5,7 @@ #include "FileLogger.h" -WinsockSocket::WinsockSocket(const std::string& address, unsigned port) +WinsockSocket::WinsockSocket(const String& address, unsigned port) : Socket(address, port) { @@ -160,7 +160,7 @@ void WinsockSocket::doListen(onIncomingConnectionFunc connectionFunc) } } -std::string WinsockSocket::send(const std::string& message) +String WinsockSocket::send(const String& message) { if (mState.mConnectStatus != Socket::State::ConnectStatus::OK) { @@ -191,7 +191,7 @@ std::string WinsockSocket::send(const std::string& message) return {}; } - std::string response; + String response; while (mState.mConnectStatus == Socket::State::ConnectStatus::OK) { response += recieve(); @@ -201,7 +201,7 @@ std::string WinsockSocket::send(const std::string& message) return response; } -void WinsockSocket::respond(const std::string& message) +void WinsockSocket::respond(const String& message) { auto result = ::send(mHandle, message.c_str(), static_cast(message.size()), 0); if (result == SOCKET_ERROR) @@ -210,7 +210,7 @@ void WinsockSocket::respond(const std::string& message) } } -void WinsockSocket::onSockerError(const std::string& message) +void WinsockSocket::onSockerError(const String& message) { mState.mErrorCode = ::WSAGetLastError(); mState.mErrorMessage = message; @@ -222,14 +222,14 @@ void WinsockSocket::onSockerError(const std::string& message) mState.mConnectStatus = Socket::State::ConnectStatus::FAILED; } -std::string WinsockSocket::recieve() +String WinsockSocket::recieve() { const int BUFFER_SIZE = 512; char buffer[BUFFER_SIZE]; auto result = ::recv(mHandle, buffer, BUFFER_SIZE, 0); if (result > 0) { - return std::string(buffer); + return String(buffer); } else if (result == 0) { diff --git a/src/base/network/sockets/WinsockSocket.h b/src/base/network/sockets/WinsockSocket.h index df92c6d..5571266 100644 --- a/src/base/network/sockets/WinsockSocket.h +++ b/src/base/network/sockets/WinsockSocket.h @@ -9,17 +9,17 @@ class WinsockSocket : public Socket { public: - WinsockSocket(const std::string& address, unsigned port); + WinsockSocket(const String& address, unsigned port); WinsockSocket(SOCKET handle); ~WinsockSocket(); - std::string recieve() override; + String recieve() override; - void respond(const std::string& message) override; + void respond(const String& message) override; - std::string send(const std::string& message) override; + String send(const String& message) override; using onIncomingConnectionFunc = std::function; void doListen(onIncomingConnectionFunc connectionFunc); @@ -32,7 +32,7 @@ private: void doBind() override; - void onSockerError(const std::string& message); + void onSockerError(const String& message); SOCKET mHandle{ INVALID_SOCKET }; diff --git a/src/console/CMakeLists.txt b/src/console/CMakeLists.txt index a127f1a..5702c45 100644 --- a/src/console/CMakeLists.txt +++ b/src/console/CMakeLists.txt @@ -5,7 +5,8 @@ list(APPEND HEADERS BasicWebApp.h) list(APPEND SOURCES - BasicWebApp.cpp + TermInfo.cpp + BasicWebApp.cpp MainApplication.cpp) add_library(${MODULE_NAME} SHARED ${SOURCES} ${HEADERS}) @@ -17,4 +18,4 @@ set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src) target_link_libraries(${MODULE_NAME} PUBLIC core audio network database web graphics publishing) set_target_properties( ${MODULE_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON ) -set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src) \ No newline at end of file +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER src) diff --git a/src/console/MainApplication.cpp b/src/console/MainApplication.cpp index 62a6c18..51db8b3 100644 --- a/src/console/MainApplication.cpp +++ b/src/console/MainApplication.cpp @@ -25,7 +25,7 @@ MainApplication::MainApplication() } -std::unique_ptr MainApplication::Create() +Ptr MainApplication::Create() { return std::make_unique(); } @@ -36,7 +36,7 @@ MainApplication::~MainApplication() } -void MainApplication::initialize(CommandLineArgsUPtr commandLineArgs, std::unique_ptr applicationContext) +void MainApplication::initialize(CommandLineArgsUPtr commandLineArgs, Ptr applicationContext) { if (applicationContext) { @@ -66,14 +66,14 @@ void MainApplication::initialize(CommandLineArgsUPtr commandLineArgs, std::uniqu void MainApplication::run() { - std::string program_type; + String program_type; if(mCommandLineArgs->getArgs().size() > 1) { program_type = mCommandLineArgs->getArgs()[1]; } - std::string input_path; - std::string output_path; + String input_path; + String output_path; for(unsigned idx=1; idx< mCommandLineArgs->getArgs().size(); idx++) { auto arg = mCommandLineArgs->getArgs()[idx]; @@ -131,7 +131,7 @@ void MainApplication::playAudio() //mAudioManager->Play(); } -void MainApplication::convertDocument(const std::string& inputPath, const std::string& outputPath) +void MainApplication::convertDocument(const String& inputPath, const String& outputPath) { auto input_file = File(std::filesystem::path(inputPath)); auto output_file = File(std::filesystem::path(outputPath)); diff --git a/src/console/MainApplication.h b/src/console/MainApplication.h index 1142960..f56a70c 100644 --- a/src/console/MainApplication.h +++ b/src/console/MainApplication.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Pointer.h" #include #include "AbstractApp.h" @@ -17,9 +17,9 @@ public: ~MainApplication(); - static std::unique_ptr Create(); + static Ptr Create(); - void initialize(CommandLineArgsUPtr commandLineArgs, std::unique_ptr applicationContext=nullptr); + void initialize(CommandLineArgsUPtr commandLineArgs, Ptr applicationContext=nullptr); void run(); @@ -32,7 +32,7 @@ private: void playAudio(); - void convertDocument(const std::string& inputPath, const std::string& outputPath); + void convertDocument(const String& inputPath, const String& outputPath); CommandLineArgsUPtr mCommandLineArgs; DatabaseManagerPtr mDatabaseManager; diff --git a/src/console/TermInfo.cpp b/src/console/TermInfo.cpp new file mode 100644 index 0000000..897bc6a --- /dev/null +++ b/src/console/TermInfo.cpp @@ -0,0 +1,111 @@ +#include "TermInfo.h" + +#include "Vector.h" +#include "File.h" +#include +#include + +bool TermInfo::load_terminfo(const String& terminfo_dir, + const String& term) +{ + const auto path = std::filesystem::path(terminfo_dir); + if (!std::filesystem::is_directory(path)) + { + return false; + } + + String suffix = "/" + term; + suffix = term[0] + suffix; + + const auto file_path = path / std::filesystem::path(suffix); + + auto file = File(file_path); + + std::cout << "trying: " << file_path << std::endl; + if (!file.pathExists()) + { + return false; + } + + if (!file.open(File::AccessMode::Read)) + { + return false; + } + + Vector content; + file.readBinary(content); + short header_size = 12; + if (content.size() < static_cast(header_size)) + { + std::cerr << "terminfo file missing header: " << content.size() << std::endl; + return false; + } + + short magic_number = 256*content[1] + content[0]; + if (magic_number != 282) // octal 0432 + { + std::cerr << "unexpected magic number" << std::endl; + } + short name_size = 256*content[3] + content[2]; + //short bool_size = 256*content[5] + content[4]; + //short numbers_size = 256*content[7] + content[6]; + //short strings_size = 256*content[9] + content[8]; + //short string_table_size = 256*content[11] + content[10]; + std::cout << "got name size: " << name_size << std::endl; + + const auto bool_offset = static_cast(header_size + name_size); + if (content.size() < bool_offset) + { + std::cerr << "unexpected terminfo size" << std::endl; + } + Vector names; + String working_name; + for(size_t idx=header_size; idx common_paths = {"/usr/share/terminfo"}; + for (const auto& path : common_paths) + { + if (load_terminfo(path, term)) + { + return; + } + } + + + std::cerr << "Couldn't find terminfo" << std::endl; + } + + + diff --git a/src/console/TermInfo.h b/src/console/TermInfo.h new file mode 100644 index 0000000..e2e7bda --- /dev/null +++ b/src/console/TermInfo.h @@ -0,0 +1,17 @@ +#pragma once + +#include "String.h" + +class TermInfo +{ +// https://invisible-island.net/ncurses/ +// https://man7.org/linux/man-pages/man5/terminfo.5.html +// Best grab a coffee +public: + bool load_terminfo(const String& terminfo_dir, + const String& term); + + void load(); +}; + + diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..b7a52c4 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,27 @@ +#include "BuildSession.h" +#include "ConsoleLogger.h" +#include "FileSystemPath.h" + +int main(int argc, char** argv) +{ + if (argc <= 1) + { + LOG_ERROR("Missing arg with path to source dir"); + return -1; + } + + FileSystemPath source_path(argv[1]); + BuildSession build(source_path); + if (const auto rc = build.configure(); !rc.ok()) + { + LOG_ERROR("Configure failed with " << rc); + return -1; + } + + if (const auto rc = build.build(); !rc.ok()) + { + LOG_ERROR("Build failed with " << rc); + return -1; + } + return 0; +} diff --git a/src/media/audio/AudioDevice.cpp b/src/media/audio/AudioDevice.cpp index 3670110..5031f5e 100644 --- a/src/media/audio/AudioDevice.cpp +++ b/src/media/audio/AudioDevice.cpp @@ -15,7 +15,7 @@ AudioDevice::~AudioDevice() } -std::unique_ptr AudioDevice::Create() +Ptr AudioDevice::Create() { return std::make_unique(); } @@ -35,7 +35,7 @@ unsigned AudioDevice::getPeriod() const return mPeriod; } -std::size_t AudioDevice::getBufferSize() const +size_t AudioDevice::getBufferSize() const { return mBufferSize; } @@ -45,7 +45,7 @@ unsigned AudioDevice::getSampleRate() const return mSampleRate; } -std::string AudioDevice::getName() const +String AudioDevice::getName() const { return mName; } @@ -55,7 +55,7 @@ void AudioDevice::setSampleRate(unsigned rate) mSampleRate = rate; } -void AudioDevice::setName(const std::string& name) +void AudioDevice::setName(const String& name) { mName = name; } @@ -70,7 +70,7 @@ void AudioDevice::setPeriod(unsigned period) mPeriod = period; } -void AudioDevice::setBufferSize(std::size_t bufferSize) +void AudioDevice::setBufferSize(size_t bufferSize) { mBufferSize = bufferSize; } diff --git a/src/media/audio/AudioDevice.h b/src/media/audio/AudioDevice.h index 57e19d8..25c8d84 100644 --- a/src/media/audio/AudioDevice.h +++ b/src/media/audio/AudioDevice.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Pointer.h" +#include "String.h" class AudioDevice { @@ -11,7 +11,7 @@ public: ~AudioDevice(); - static std::unique_ptr Create(); + static Ptr Create(); unsigned getSampleRate() const; @@ -19,30 +19,30 @@ public: unsigned getPeriod() const; - std::size_t getBufferSize() const; + size_t getBufferSize() const; bool getIsOpen() const; - std::string getName() const; + String getName() const; - void setName(const std::string& name); + void setName(const String& name); void setNumChannels(unsigned numChannels); void setPeriod(unsigned period); - void setBufferSize(std::size_t bufferSize); + void setBufferSize(size_t bufferSize); void setSampleRate(unsigned rate); void setIsOpen(bool isOpen); private: - std::string mName {"unset"}; + String mName {"unset"}; unsigned mSampleRate {44100}; unsigned mNumChannels {1}; unsigned mPeriod {2}; - std::size_t mBufferSize{0}; + size_t mBufferSize{0}; bool mIsOpen{false}; }; -using AudioDevicePtr = std::unique_ptr; +using AudioDevicePtr = Ptr; diff --git a/src/media/audio/AudioManager.cpp b/src/media/audio/AudioManager.cpp index 41cb17a..2bcc3ae 100644 --- a/src/media/audio/AudioManager.cpp +++ b/src/media/audio/AudioManager.cpp @@ -26,7 +26,7 @@ AudioManager::~AudioManager() } -std::unique_ptr AudioManager::Create() +Ptr AudioManager::Create() { return std::make_unique(); } @@ -36,7 +36,7 @@ void AudioManager::addAudioDevice(AudioDevicePtr device) mAudioDevices.push_back(std::move(device)); } -std::size_t AudioManager::getNumAudioDevices() const +size_t AudioManager::getNumAudioDevices() const { return mAudioDevices.size(); } diff --git a/src/media/audio/AudioManager.h b/src/media/audio/AudioManager.h index dacef02..6ef3c12 100644 --- a/src/media/audio/AudioManager.h +++ b/src/media/audio/AudioManager.h @@ -3,8 +3,8 @@ #include "IAudioInterface.h" #include "AudioDevice.h" -#include -#include +#include "Pointer.h" +#include "Vector.h" class AudioSample; @@ -16,19 +16,19 @@ public: ~AudioManager(); - static std::unique_ptr Create(); + static Ptr Create(); void addAudioDevice(AudioDevicePtr device); - std::size_t getNumAudioDevices() const; + size_t getNumAudioDevices() const; AudioDevice* getAudioDevice(unsigned idx) const; void play(AudioSample* sample, unsigned duration); private: - std::vector mAudioDevices; + Vector mAudioDevices; IAudioInterfacePtr mAudioInterface; }; -using AudioManagerUPtr = std::unique_ptr; +using AudioManagerUPtr = Ptr; diff --git a/src/media/audio/AudioSample.cpp b/src/media/audio/AudioSample.cpp index 7a21f5c..519687f 100644 --- a/src/media/audio/AudioSample.cpp +++ b/src/media/audio/AudioSample.cpp @@ -5,12 +5,12 @@ AudioSample::AudioSample() } -std::unique_ptr AudioSample::Create() +Ptr AudioSample::Create() { return std::make_unique(); } -std::size_t AudioSample::getNumChannels() const +size_t AudioSample::getNumChannels() const { return mData.size(); } @@ -25,7 +25,7 @@ unsigned AudioSample::getBitDepth() const return mBitDepth; } -void AudioSample::setChannelData(const ChannelData& data, std::size_t channel) +void AudioSample::setChannelData(const ChannelData& data, size_t channel) { if (mData.size() == channel) { @@ -37,11 +37,11 @@ void AudioSample::setChannelData(const ChannelData& data, std::size_t channel) } } -AudioSample::ChannelData AudioSample::getChannelData(std::size_t channel) const +AudioSample::ChannelData AudioSample::getChannelData(size_t channel) const { if(mData.size() > channel) { return mData[channel]; } - return std::vector(); + return Vector(); } diff --git a/src/media/audio/AudioSample.h b/src/media/audio/AudioSample.h index 08cfc8c..0c6a836 100644 --- a/src/media/audio/AudioSample.h +++ b/src/media/audio/AudioSample.h @@ -1,28 +1,28 @@ #pragma once -#include -#include +#include "Vector.h" +#include "Pointer.h" class AudioSample { public: - using ChannelData = std::vector; + using ChannelData = Vector; AudioSample(); - static std::unique_ptr Create(); + static Ptr Create(); - ChannelData getChannelData(std::size_t channel) const; - std::size_t getNumChannels() const; + ChannelData getChannelData(size_t channel) const; + size_t getNumChannels() const; unsigned getSampleRate() const; unsigned getBitDepth() const; - void setChannelData(const ChannelData& data, std::size_t channel); + void setChannelData(const ChannelData& data, size_t channel); private: unsigned mSampleRate { 44100 }; unsigned mBitDepth{ 16 }; - std::vector mData; + Vector mData; }; -using AudioSamplePtr = std::unique_ptr; +using AudioSamplePtr = Ptr; diff --git a/src/media/audio/AudioSynth.cpp b/src/media/audio/AudioSynth.cpp index 23b9c1b..29386b2 100644 --- a/src/media/audio/AudioSynth.cpp +++ b/src/media/audio/AudioSynth.cpp @@ -14,7 +14,7 @@ AudioSamplePtr AudioSynth::getConstant(unsigned amplitude, unsigned duration) co { auto sample = AudioSample::Create(); auto num_samples = duration * sample->getSampleRate(); - sample->setChannelData(std::vector(num_samples, amplitude), 0); + sample->setChannelData(Vector(num_samples, amplitude), 0); return sample; } @@ -24,7 +24,7 @@ AudioSamplePtr AudioSynth::getSineWave(double freq, unsigned duration) const const auto sample_rate = sample->getSampleRate(); const auto num_samples = sample_rate*duration; - std::vector data(num_samples, 0); + Vector data(num_samples, 0); const double tick_duration = 1.0/sample_rate; const double pi_2 = 2.0 * M_PI; diff --git a/src/media/audio/AudioSynth.h b/src/media/audio/AudioSynth.h index e3479ce..fe98943 100644 --- a/src/media/audio/AudioSynth.h +++ b/src/media/audio/AudioSynth.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Vector.h" #include "AudioSample.h" diff --git a/src/media/audio/AudioWriter.h b/src/media/audio/AudioWriter.h index a23164b..972da1a 100644 --- a/src/media/audio/AudioWriter.h +++ b/src/media/audio/AudioWriter.h @@ -1,11 +1,11 @@ #pragma once -#include -#include +#include "String.h" +#include "Pointer.h" #include class AudioSample; -using AudioSamplePtr = std::unique_ptr; +using AudioSamplePtr = Ptr; using Path = std::filesystem::path; class AudioWriter diff --git a/src/media/audio/audio_interfaces/AlsaInterface.cpp b/src/media/audio/audio_interfaces/AlsaInterface.cpp index 7df0c53..9a9c483 100644 --- a/src/media/audio/audio_interfaces/AlsaInterface.cpp +++ b/src/media/audio/audio_interfaces/AlsaInterface.cpp @@ -5,7 +5,7 @@ #include "AudioSynth.h" -#include +#include "Vector.h" AlsaInterface::AlsaInterface() :mHandle(), @@ -20,7 +20,7 @@ AlsaInterface::~AlsaInterface() } -std::unique_ptr AlsaInterface::Create() +Ptr AlsaInterface::Create() { return std::make_unique(); } diff --git a/src/media/audio/audio_interfaces/AlsaInterface.h b/src/media/audio/audio_interfaces/AlsaInterface.h index 06c82ba..2174f24 100644 --- a/src/media/audio/audio_interfaces/AlsaInterface.h +++ b/src/media/audio/audio_interfaces/AlsaInterface.h @@ -3,7 +3,7 @@ #include "IAudioInterface.h" #include -#include +#include "Pointer.h" class AlsaInterface : public IAudioInterface { @@ -12,7 +12,7 @@ public: ~AlsaInterface(); - static std::unique_ptr Create(); + static Ptr Create(); void play(AudioDevice* device, AudioSample* sample, unsigned duration) override; @@ -36,4 +36,4 @@ private: snd_pcm_uframes_t mPeriodSize; }; -using AlsaInterfacePtr = std::unique_ptr; +using AlsaInterfacePtr = Ptr; diff --git a/src/media/audio/audio_interfaces/IAudioInterface.h b/src/media/audio/audio_interfaces/IAudioInterface.h index 8c9aa18..3cbd6dd 100644 --- a/src/media/audio/audio_interfaces/IAudioInterface.h +++ b/src/media/audio/audio_interfaces/IAudioInterface.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Pointer.h" class AudioDevice; class AudioSample; @@ -18,4 +18,4 @@ protected: virtual void openDevice(AudioDevice* device) = 0; }; -using IAudioInterfacePtr = std::unique_ptr; +using IAudioInterfacePtr = Ptr; diff --git a/src/media/audio/audio_interfaces/NullAudioInterface.cpp b/src/media/audio/audio_interfaces/NullAudioInterface.cpp index 2a05684..3cbfb0a 100644 --- a/src/media/audio/audio_interfaces/NullAudioInterface.cpp +++ b/src/media/audio/audio_interfaces/NullAudioInterface.cpp @@ -3,7 +3,7 @@ #include "AudioSynth.h" -#include +#include "Vector.h" NullAudioInterface::NullAudioInterface() { @@ -15,7 +15,7 @@ NullAudioInterface::~NullAudioInterface() } -std::unique_ptr NullAudioInterface::Create() +Ptr NullAudioInterface::Create() { return std::make_unique(); } diff --git a/src/media/audio/audio_interfaces/NullAudioInterface.h b/src/media/audio/audio_interfaces/NullAudioInterface.h index 3e47915..67ef993 100644 --- a/src/media/audio/audio_interfaces/NullAudioInterface.h +++ b/src/media/audio/audio_interfaces/NullAudioInterface.h @@ -3,7 +3,7 @@ #include "IAudioInterface.h" #include "AudioDevice.h" -#include +#include "Pointer.h" class NullAudioInterface : public IAudioInterface { @@ -13,7 +13,7 @@ public: ~NullAudioInterface(); - static std::unique_ptr Create(); + static Ptr Create(); void openDevice(AudioDevice* device) override; diff --git a/src/media/audio/audio_interfaces/WasapiInterface.cpp b/src/media/audio/audio_interfaces/WasapiInterface.cpp index eaae01c..3b86ac9 100644 --- a/src/media/audio/audio_interfaces/WasapiInterface.cpp +++ b/src/media/audio/audio_interfaces/WasapiInterface.cpp @@ -4,7 +4,7 @@ #include "AudioSynth.h" #include "AudioDevice.h" -#include +#include "Vector.h" #include #include @@ -22,7 +22,7 @@ WasapiInterface::~WasapiInterface() } -std::unique_ptr WasapiInterface::Create() +Ptr WasapiInterface::Create() { return std::make_unique(); } diff --git a/src/media/audio/audio_interfaces/WasapiInterface.h b/src/media/audio/audio_interfaces/WasapiInterface.h index b93133a..23aa35b 100644 --- a/src/media/audio/audio_interfaces/WasapiInterface.h +++ b/src/media/audio/audio_interfaces/WasapiInterface.h @@ -2,7 +2,7 @@ #include "IAudioInterface.h" -#include +#include "Pointer.h" class AudioDevice; @@ -13,7 +13,7 @@ public: ~WasapiInterface(); - static std::unique_ptr Create(); + static Ptr Create(); void play(AudioDevice* device, AudioSample* sample, unsigned duration) override; private: @@ -32,4 +32,4 @@ private: void setChannelNumber(AudioDevice* device); }; -using WasapiInterfacePtr = std::unique_ptr; +using WasapiInterfacePtr = Ptr; diff --git a/src/media/image/CMakeLists.txt b/src/media/image/CMakeLists.txt index ec4f824..5ef107f 100644 --- a/src/media/image/CMakeLists.txt +++ b/src/media/image/CMakeLists.txt @@ -4,6 +4,7 @@ set(platform_LIB_INCLUDES) list(APPEND image_HEADERS Image.h + Pixel.h IImageWriter.h PlatformImage.h PlatformImageWriter.h @@ -14,6 +15,7 @@ list(APPEND image_HEADERS list(APPEND image_LIB_INCLUDES Image.cpp + Pixel.cpp ImageBitStream.cpp PlatformImage.cpp png/BasicPngWriter.cpp @@ -21,6 +23,7 @@ list(APPEND image_LIB_INCLUDES png/PngReader.cpp png/PngHeader.cpp png/PngInfo.cpp + png/PngFilter.cpp ) if(WIN32) diff --git a/src/media/image/Image.cpp b/src/media/image/Image.cpp index c9ed06c..3a9843c 100644 --- a/src/media/image/Image.cpp +++ b/src/media/image/Image.cpp @@ -3,14 +3,16 @@ #include "Color.h" #include "Grid.h" +#include + #ifdef _WIN32 #include "Win32WicImage.h" #endif -Image::Image(unsigned width, unsigned height, DataType dataType) +Image::Image(unsigned width, unsigned height, Color::Format format) : mWidth(width), mHeight(height), - mDataType(dataType) + mFormat(format) { initialize(); } @@ -20,49 +22,37 @@ Image::~Image() } -std::unique_ptr Image::Create(unsigned width, unsigned height, DataType dataType) +Ptr Image::Create(unsigned width, unsigned height, Color::Format format) { - return std::make_unique(width, height, dataType); + return std::make_unique(width, height, format); } void Image::initialize() { Bounds bounds(0.0, mWidth, 0.0, mHeight); - if (mDataType == DataType::UCHAR) - { - mData = std::make_unique >(bounds, mWidth, mHeight, mNumChannels); - } - else - { - mData = std::make_unique >(bounds, mWidth, mHeight, mNumChannels); - } + const auto pixel_size = Color::getSize(mFormat, mBitDepth); + mGrid = std::make_unique >(pixel_size, bounds, mWidth, mHeight); } -void Image::setPixelValues(const Indices& indices, const std::vector& colors) +void Image::setPixelValues(const Indices& indices, const Vector& colors) { - if (!mData) + if (!mGrid) { initialize(); } - if (mDataType == DataType::UCHAR) + assert(indices.size() == colors.size()); + + for (size_t idx=0; idx< indices.size(); idx++) { - auto grid = getGridT(); - for (std::size_t idx=0; idx< indices.size(); idx++) - { - auto id = indices[idx]; - auto color = colors[idx]; - grid->setItem(id.first, id.second, 0, color.getR()); - grid->setItem(id.first, id.second, 1, color.getG()); - grid->setItem(id.first, id.second, 2, color.getB()); - } + const auto id = indices[idx]; + mGrid->getItem(id.first, id.second).setColor(colors[idx]); } } unsigned Image::getBytesPerRow() const { - const auto bitsPerEntry = mBitDepth <= 8 ? 1 : 2; - return mWidth * mNumChannels * bitsPerEntry; + return mWidth * Color::getSize(mFormat, mBitDepth); } unsigned Image::getWidth() const @@ -91,25 +81,29 @@ PlatformImage* Image::getPlatformImage() return mPlatformImage.get(); } -AbstractGrid* Image::getGrid() const +SerializeableGrid* Image::getGrid() const { - return mData.get(); + return mGrid.get(); } -template -Grid* Image::getGridT() const +uint8_t Image::getByte(size_t index) const { - return dynamic_cast*>(this->mData.get()); + return mGrid->getByte(index); } -Image::DataType Image::getType() const +void Image::toBuffer(uint8_t* buffer, size_t bufferMaxSize) { - return mDataType; + mGrid->toBuffer(buffer, bufferMaxSize); +} + +Color::Format Image::getFormat() const +{ + return mFormat; } unsigned Image::getNumChannels() const { - return mNumChannels; + return Color::getNumChannels(mFormat); } void Image::setWidth(unsigned width) @@ -127,8 +121,8 @@ void Image::setBitDepth(unsigned bitDepth) mBitDepth = bitDepth; } -void Image::setNumChannels(unsigned numChannels) +void Image::setFormat(Color::Format format) { - mNumChannels = numChannels; + mFormat = format; } diff --git a/src/media/image/Image.h b/src/media/image/Image.h index 817915b..a01112f 100644 --- a/src/media/image/Image.h +++ b/src/media/image/Image.h @@ -1,30 +1,25 @@ #pragma once #include "PlatformImage.h" +#include "Pixel.h" -#include -#include +#include "Pointer.h" +#include "Vector.h" class Color; -class AbstractGrid; template -class Grid; +class SerializeableGrid; class Image { public: - enum class DataType - { - UCHAR - }; + using Index = std::pair; + using Indices = Vector; - using Index = std::pair; - using Indices = std::vector; - - Image(unsigned width, unsigned height, DataType dataType = DataType::UCHAR); + Image(unsigned width, unsigned height, Color::Format format = Color::Format::RGBA); ~Image(); - static std::unique_ptr Create(unsigned width, unsigned height, DataType dataType = DataType::UCHAR); + static Ptr Create(unsigned width, unsigned height, Color::Format format = Color::Format::RGBA); unsigned getBytesPerRow() const; unsigned getWidth() const; @@ -32,28 +27,27 @@ public: unsigned getBitDepth() const; unsigned getNumChannels() const; - AbstractGrid* getGrid() const; + uint8_t getByte(size_t index) const; + SerializeableGrid* getGrid() const; - template - Grid* getGridT() const; - - DataType getType() const; + Color::Format getFormat() const; PlatformImage* getPlatformImage(); - void setPixelValues(const Indices& indices, const std::vector& colors); + void setPixelValues(const Indices& indices, const Vector& colors); void setWidth(unsigned width); void setHeight(unsigned height); void setBitDepth(unsigned bitDepth); - void setNumChannels(unsigned numChannels); + void setFormat(Color::Format format); + + void toBuffer(uint8_t* buffer, size_t bufferMaxSize); private: void initialize(); unsigned mWidth{1}; unsigned mHeight{1}; unsigned mBitDepth{8}; - unsigned mNumChannels{4}; + Color::Format mFormat{Color::Format::RGBA}; - DataType mDataType; - std::unique_ptr mData; - std::unique_ptr mPlatformImage; + Ptr > mGrid; + Ptr mPlatformImage; }; diff --git a/src/media/image/ImageBitStream.cpp b/src/media/image/ImageBitStream.cpp index a53df70..6ceb763 100644 --- a/src/media/image/ImageBitStream.cpp +++ b/src/media/image/ImageBitStream.cpp @@ -1,6 +1,7 @@ #include "ImageBitStream.h" -#include "AbstractGrid.h" +#include "Grid.h" +#include "Pixel.h" ImageBitStream::ImageBitStream(Image* image) : BitStream(), @@ -14,25 +15,22 @@ bool ImageBitStream::isFinished() const return mByteOffset == static_cast(mImage->getGrid()->getDataSize()); } -std::vector ImageBitStream::peekNextNBytes(unsigned) const +Vector ImageBitStream::peekNextNBytes(size_t) const { return {}; } -std::optional ImageBitStream::readNextByte() +Optional ImageBitStream::readNextByte() { mByteOffset++; - if (isFinished() ) { return std::nullopt; } - //const auto val = mImage->getData()->getAsUnsignedChar(mByteOffset); - //return val; - return {}; + return mImage->getByte(mByteOffset); } -void ImageBitStream::writeByte(unsigned char, bool ) +void ImageBitStream::writeByte(uint8_t, bool ) { mByteOffset++; diff --git a/src/media/image/ImageBitStream.h b/src/media/image/ImageBitStream.h index 0ad286d..d432e83 100644 --- a/src/media/image/ImageBitStream.h +++ b/src/media/image/ImageBitStream.h @@ -4,6 +4,8 @@ #include "Image.h" +#include + class ImageBitStream : public BitStream { public: @@ -11,13 +13,13 @@ public: bool isFinished() const override; - std::vector peekNextNBytes(unsigned n) const override; + Vector peekNextNBytes(size_t n) const override; - std::optional readNextByte() override; + Optional readNextByte() override; - void writeByte(unsigned char data, bool checkOverflow = true) override; + void writeByte(uint8_t data, bool checkOverflow = true) override; - void writeBytes(const std::vector) override + void writeBytes(const Vector&) override { } diff --git a/src/media/image/ImagePrimitives.h b/src/media/image/ImagePrimitives.h index 834c6cd..7a88378 100644 --- a/src/media/image/ImagePrimitives.h +++ b/src/media/image/ImagePrimitives.h @@ -24,7 +24,7 @@ public: } } - static void drawAlternatingStrips(std::vector& data, unsigned width, unsigned height, unsigned channels, unsigned bytesPerRow) + static void drawAlternatingStrips(Vector& data, unsigned width, unsigned height, unsigned channels, unsigned bytesPerRow) { for(unsigned jdx=0;jdx @@ -28,7 +28,7 @@ BasicPngWriter::~BasicPngWriter() } -std::unique_ptr BasicPngWriter::Create() +Ptr BasicPngWriter::Create() { return std::make_unique(); } @@ -88,18 +88,18 @@ void BasicPngWriter::writeHeader() auto crc = mPngHeader.getCrc(); - //std::cout << mPngHeader.toString() << "*********" << std::endl; + std::cout << mPngHeader.toString() << "*********" << std::endl; mOutStream->write(crc); } void BasicPngWriter::writeEndChunk() { - //std::cout << "Start writing end chunk" << std::endl; + std::cout << "Start writing end chunk" << std::endl; unsigned length{ 0 }; mOutStream->write(length); mOutStream->writeBytes(StringUtils::toBytes("IEND")); - std::vector char_data = StringUtils::toBytes("IEND"); + Vector char_data = StringUtils::toBytes("IEND"); CyclicRedundancyChecker crc_check; for (auto c : char_data) @@ -109,17 +109,17 @@ void BasicPngWriter::writeEndChunk() auto crc = crc_check.getChecksum(); mOutStream->write(crc); - //std::cout << "Writing end chunk" << std::endl; + std::cout << "Finishe Writing end chunk" << std::endl; } void BasicPngWriter::writeDataChunks(const BufferBitStream& buffer) { auto num_bytes = buffer.getBuffer().size(); - std::size_t max_bytes{ 32000 }; + size_t max_bytes{ 32000 }; auto num_dat_chunks = num_bytes / max_bytes + 1; - //std::size_t offset = 0; - for (std::size_t idx = 0; idx < num_dat_chunks; idx++) + //size_t offset = 0; + for (size_t idx = 0; idx < num_dat_chunks; idx++) { auto length = max_bytes; if (idx == num_dat_chunks - 1) @@ -128,10 +128,10 @@ void BasicPngWriter::writeDataChunks(const BufferBitStream& buffer) } (void)length; - //std::cout << "Writing idat length " << num_bytes << std::endl; + std::cout << "Writing idat length " << num_bytes << std::endl; mOutStream->write(static_cast(num_bytes)); - std::vector char_data = StringUtils::toBytes("IDAT"); + Vector char_data = StringUtils::toBytes("IDAT"); mOutStream->writeBytes(char_data); CyclicRedundancyChecker crc_check; @@ -148,7 +148,7 @@ void BasicPngWriter::writeDataChunks(const BufferBitStream& buffer) } auto crc = crc_check.getChecksum(); - //std::cout << "Writing idat crc" << crc << std::endl; + std::cout << "Writing idat crc: " << crc << std::endl; mOutStream->write(crc); //std::cout << "Finished Writing idat crc" << crc << std::endl; } @@ -156,9 +156,9 @@ void BasicPngWriter::writeDataChunks(const BufferBitStream& buffer) void BasicPngWriter::write(const Path& path, Image* image) { - std::unique_ptr out_file; + Ptr out_file; - if (path.empty()) + if (!path.empty()) { out_file = std::make_unique(path); out_file->open(File::AccessMode::Write); @@ -184,7 +184,7 @@ void BasicPngWriter::write(const Path& path, Image* image) filter_out_stream->resetOffsets(); - std::unique_ptr lz77_out_stream; + Ptr lz77_out_stream; if (mCompressionMethod == Deflate::CompressionMethod::NONE) { diff --git a/src/media/image/png/BasicPngWriter.h b/src/media/image/png/BasicPngWriter.h index ee2e051..1b27201 100644 --- a/src/media/image/png/BasicPngWriter.h +++ b/src/media/image/png/BasicPngWriter.h @@ -6,8 +6,8 @@ #include "Image.h" #include "DeflateElements.h" -#include -#include +#include "Pointer.h" +#include "String.h" #include using Path = std::filesystem::path; @@ -22,7 +22,9 @@ public: virtual ~BasicPngWriter(); - static std::unique_ptr Create(); + using Ptr = Ptr; + + static BasicPngWriter::Ptr Create(); void setCompressionMethod(Deflate::CompressionMethod method); @@ -41,10 +43,10 @@ private: //void writeIDatChunk(); Image* mWorkingImage{ nullptr }; - std::unique_ptr mInStream; - std::unique_ptr mOutStream; + Ptr mInStream; + Ptr mOutStream; - unsigned mPngInfoUserSet{ false }; + bool mPngInfoUserSet{ false }; PngInfo mPngInfo; PngHeader mPngHeader; diff --git a/src/media/image/png/PngFilter.cpp b/src/media/image/png/PngFilter.cpp new file mode 100644 index 0000000..35ba226 --- /dev/null +++ b/src/media/image/png/PngFilter.cpp @@ -0,0 +1,77 @@ +#include "PngFilter.h" +#include + +PngFilter::PngFilter(BitStream* inputStream, BitStream* outputStream) + : mInputStream(inputStream), + mOutputStream(outputStream) + +{ + +} + +void PngFilter::encode() +{ + auto image_stream = dynamic_cast(mInputStream); + if (!image_stream) + { + MLOG_ERROR("Expected ImageStream in PngFilter encode - aborting."); + return; + } + + const auto bytes_per_scanline = image_stream->getBytesPerScanline(); + unsigned count{0}; + if (mFilterType == FilterType::NONE) + { + while(true) + { + if (const auto byte = image_stream->readNextByte()) + { + if (count % bytes_per_scanline == 0) + { + mOutputStream->writeByte(0); + } + + mOutputStream->writeByte(*byte); + } + else + { + break; + } + count++; + } + } +} + +void PngFilter::decode() +{ + auto image_stream = dynamic_cast(mOutputStream); + if (!image_stream) + { + MLOG_ERROR("Expected ImageStream in PngFilter decode - aborting."); + return; + } + + const auto bytes_per_scanline = image_stream->getBytesPerScanline(); + unsigned count{0}; + + FilterType working_filter_type = FilterType::NONE; + while(auto byte = mInputStream->readNextByte()) + { + if (count % bytes_per_scanline == 0) + { + working_filter_type = static_cast(*byte); + } + else + { + if (working_filter_type == FilterType::NONE) + { + image_stream->writeByte(*byte); + } + else + { + //std::cout << "Got filter type " << static_cast(working_filter_type) << std::endl; + } + } + count++; + } +} \ No newline at end of file diff --git a/src/media/image/png/PngFilter.h b/src/media/image/png/PngFilter.h index 1075c66..680008e 100644 --- a/src/media/image/png/PngFilter.h +++ b/src/media/image/png/PngFilter.h @@ -19,83 +19,13 @@ public: PAETH }; - PngFilter(BitStream* inputStream, BitStream* outputStream) - : mInputStream(inputStream), - mOutputStream(outputStream) + PngFilter(BitStream* inputStream, BitStream* outputStream); - { + void encode(); - } - - void encode() - { - auto image_stream = dynamic_cast(mInputStream); - if (!image_stream) - { - MLOG_ERROR("Expected ImageStream in PngFilter encode - aborting."); - return; - } - - const auto bytes_per_scanline = image_stream->getBytesPerScanline(); - unsigned count{0}; - if (mFilterType == FilterType::NONE) - { - while(true) - { - if (const auto byte = image_stream->readNextByte()) - { - if (count % bytes_per_scanline == 0) - { - mOutputStream->writeByte(0); - } - - mOutputStream->writeByte(*byte); - } - else - { - break; - } - count++; - } - } - } - - void decode() - { - auto image_stream = dynamic_cast(mOutputStream); - if (!image_stream) - { - MLOG_ERROR("Expected ImageStream in PngFilter decode - aborting."); - return; - } - - const auto bytes_per_scanline = image_stream->getBytesPerScanline(); - unsigned count{0}; - - FilterType working_filter_type = FilterType::NONE; - while(auto byte = mInputStream->readNextByte()) - { - if (count % bytes_per_scanline == 0) - { - working_filter_type = static_cast(*byte); - } - else - { - if (working_filter_type == FilterType::NONE) - { - image_stream->writeByte(*byte); - } - else - { - //std::cout << "Got filter type " << static_cast(working_filter_type) << std::endl; - } - } - count++; - } - } + void decode(); private: - FilterType mFilterType{FilterType::NONE}; BitStream* mInputStream{nullptr}; BitStream* mOutputStream{nullptr}; diff --git a/src/media/image/png/PngHeader.cpp b/src/media/image/png/PngHeader.cpp index b9fa13b..7b7d64c 100644 --- a/src/media/image/png/PngHeader.cpp +++ b/src/media/image/png/PngHeader.cpp @@ -1,48 +1,68 @@ #include "PngHeader.h" -#include "ByteUtils.h" +#include "Bits.h" #include "StringUtils.h" #include "CyclicRedundancyChecker.h" -std::string PngHeader::toString() const +String PngHeader::toString() const { - std::stringstream sstr; + Stringstream sstr; sstr << "PngHeader" << "\n"; sstr << "width: " << mWidth << "\n"; sstr << "height: " << mHeight << "\n"; - sstr << "bitDepth: " << (int)mBitDepth << "\n"; + sstr << "bitDepth: " << static_cast(mBitDepth) << "\n"; sstr << "cached CRC: " << mCachedCrc << "\n"; sstr << mPngInfo.toString(); return sstr.str(); } -uint32_t PngHeader::getLength() const +DWord PngHeader::getWidth() const +{ + return mWidth; +} + +DWord PngHeader::getHeight() const +{ + return mHeight; +} + +Byte PngHeader::getBitDepth() const +{ + return mBitDepth; +} + +const PngInfo& PngHeader::getPngInfo() const +{ + return mPngInfo; +} + +DWord PngHeader::getLength() const { return 13; } -unsigned char PngHeader::getHighBitCheck() const +Byte PngHeader::getHighBitCheck() const { return 0x89; } -std::vector PngHeader::getSignature() const +void PngHeader::getSignature(VecBytes& sig) const { - return {13, 10, 26, 10}; + sig = {13, 10, 26, 10}; } -std::string PngHeader::getFileName() const +String PngHeader::getFileName() const { return "PNG"; } -const std::string& PngHeader::getChunkName() const +const String& PngHeader::getChunkName() const { return mName; } -const std::vector& PngHeader::getData() const +const VecBytes& PngHeader::getData() const { return mData; } @@ -50,28 +70,28 @@ const std::vector& PngHeader::getData() const void PngHeader::updateData() { mData.clear(); - unsigned num_bytes = sizeof(uint32_t); + const auto num_bytes = sizeof(DWord); - for(unsigned idx=0; idx(mPngInfo.mColorType)); - mData.push_back(static_cast(mPngInfo.mCompressionMethod)); - mData.push_back(static_cast(mPngInfo.mFilterMethod)); - mData.push_back(static_cast(mPngInfo.mInterlaceMethod)); + mData.push_back(static_cast(mPngInfo.mColorType)); + mData.push_back(static_cast(mPngInfo.mCompressionMethod)); + mData.push_back(static_cast(mPngInfo.mFilterMethod)); + mData.push_back(static_cast(mPngInfo.mInterlaceMethod)); } -uint32_t PngHeader::getCrc() +DWord PngHeader::getCrc() { CyclicRedundancyChecker crc_check; - std::vector char_data = StringUtils::toBytes(mName); + Vector char_data = StringUtils::toBytes(mName); for (auto c : char_data) { crc_check.addValue(c); diff --git a/src/media/image/png/PngHeader.h b/src/media/image/png/PngHeader.h index ba96b6b..2f9969f 100644 --- a/src/media/image/png/PngHeader.h +++ b/src/media/image/png/PngHeader.h @@ -2,62 +2,50 @@ #include "PngInfo.h" -#include +#include "Vector.h" #include class PngHeader { public: - uint32_t getLength() const; + DWord getLength() const; - uint32_t getCrc(); + DWord getCrc(); - const std::vector& getData() const; + const VecBytes& getData() const; - uint32_t getWidth() const - { - return mWidth; - } + DWord getWidth() const; - uint32_t getHeight() const - { - return mHeight; - } + DWord getHeight() const; - unsigned char getBitDepth() const - { - return mBitDepth; - } + Byte getBitDepth() const; - const PngInfo& getPngInfo() const - { - return mPngInfo; - } + const PngInfo& getPngInfo() const; - unsigned char getHighBitCheck() const; + Byte getHighBitCheck() const; - std::vector getSignature() const; + void getSignature(VecBytes& sig) const; - std::string getFileName() const; + String getFileName() const; - const std::string& getChunkName() const; + const String& getChunkName() const; void setPngInfo(const PngInfo& info); - void setImageData(uint32_t width, uint32_t height, unsigned char bitDepth); + void setImageData(DWord width, DWord height, Byte bitDepth); - std::string toString() const; + String toString() const; void updateData(); private: - uint32_t mWidth{0}; - uint32_t mHeight{0}; - unsigned char mBitDepth{0}; + DWord mWidth{0}; + DWord mHeight{0}; + Byte mBitDepth{0}; PngInfo mPngInfo; - std::string mName{"IHDR"}; + String mName{"IHDR"}; - uint32_t mCachedCrc{0}; + DWord mCachedCrc{0}; - std::vector mData; + VecBytes mData; }; diff --git a/src/media/image/png/PngInfo.cpp b/src/media/image/png/PngInfo.cpp index c505a1e..285f8ac 100644 --- a/src/media/image/png/PngInfo.cpp +++ b/src/media/image/png/PngInfo.cpp @@ -1,6 +1,6 @@ #include "PngInfo.h" -std::string PngInfo::toString(ColorType colorType) const +String PngInfo::toString(ColorType colorType) const { switch(colorType) { @@ -19,26 +19,12 @@ std::string PngInfo::toString(ColorType colorType) const } } -unsigned PngInfo::getNumChannels() const +ColorType PngInfo::ColorType() const { - switch(mColorType) - { - case ColorType::GREYSCALE: - return 1; - case ColorType::RGB: - return 3; - case ColorType::PALETTE: - return 1; - case ColorType::GREYSCALE_ALPHA: - return 2; - case ColorType::RGB_ALPHA: - return 4; - default: - return 1; - } + return mColorType; } -std::string PngInfo::toString(CompressionMethod method) const +String PngInfo::toString(CompressionMethod method) const { switch(method) { @@ -49,7 +35,7 @@ std::string PngInfo::toString(CompressionMethod method) const } } -std::string PngInfo::toString(FilterMethod method) const +String PngInfo::toString(FilterMethod method) const { switch(method) { @@ -60,7 +46,7 @@ std::string PngInfo::toString(FilterMethod method) const } } -std::string PngInfo::toString(InterlaceMethod method) const +String PngInfo::toString(InterlaceMethod method) const { switch(method) { @@ -73,7 +59,7 @@ std::string PngInfo::toString(InterlaceMethod method) const } } -bool PngInfo::bitDepthIsValid(ColorType colorType, unsigned char bitDepth) const +bool PngInfo::bitDepthIsValid(ColorType colorType, Byte bitDepth) const { switch(colorType) { @@ -92,19 +78,19 @@ bool PngInfo::bitDepthIsValid(ColorType colorType, unsigned char bitDepth) const } } -bool PngInfo::compressionMethodIsValid(unsigned char method) +bool PngInfo::compressionMethodIsValid(Byte method) { return method == 0; } -bool PngInfo::filterMethodIsValid(unsigned char method) +bool PngInfo::filterMethodIsValid(Byte method) { return method == 0; } -std::string PngInfo::toString() const +String PngInfo::toString() const { - std::stringstream sstr; + Stringstream sstr; sstr << "PngInfo" << "\n"; sstr << "colorType: " << toString(mColorType) << "\n"; sstr << "compressionMethod: " << toString(mCompressionMethod) << "\n"; diff --git a/src/media/image/png/PngInfo.h b/src/media/image/png/PngInfo.h index d6e1e08..7fcc379 100644 --- a/src/media/image/png/PngInfo.h +++ b/src/media/image/png/PngInfo.h @@ -1,12 +1,14 @@ #pragma once -#include +#include "Byte.h" + +#include "String.h" #include class PngInfo { public: - enum class ColorType : unsigned char + enum class ColorType : Byte { GREYSCALE = 0, RGB = 2, @@ -15,39 +17,39 @@ public: RGB_ALPHA = 6 }; - enum class CompressionMethod : unsigned char + enum class CompressionMethod : Byte { DEFLATE = 0 }; - enum class FilterMethod : unsigned char + enum class FilterMethod : Byte { ADAPTIVE = 0 }; - enum class InterlaceMethod : unsigned char + enum class InterlaceMethod : Byte { NONE = 0, ADAM7 = 1 }; - unsigned getNumChannels() const; + ColorType getColorType() const; - std::string toString(ColorType colorType) const; + String toString(ColorType colorType) const; - std::string toString(CompressionMethod method) const; + String toString(CompressionMethod method) const; - std::string toString(FilterMethod method) const; + String toString(FilterMethod method) const; - std::string toString(InterlaceMethod method) const; + String toString(InterlaceMethod method) const; - bool bitDepthIsValid(ColorType colorType, unsigned char bitDepth) const; + bool bitDepthIsValid(ColorType colorType, Byte bitDepth) const; - bool compressionMethodIsValid(unsigned char method); + bool compressionMethodIsValid(Byte method); - bool filterMethodIsValid(unsigned char method); + bool filterMethodIsValid(Byte method); - std::string toString() const; + String toString() const; ColorType mColorType{ColorType::RGB}; CompressionMethod mCompressionMethod{CompressionMethod::DEFLATE}; diff --git a/src/media/image/png/PngReader.cpp b/src/media/image/png/PngReader.cpp index b0753dc..4928b6c 100644 --- a/src/media/image/png/PngReader.cpp +++ b/src/media/image/png/PngReader.cpp @@ -32,14 +32,14 @@ bool PngReader::checkSignature() return false; } - std::string fileType; + String fileType; BinaryStream::getNextString(mFile->getInHandle(), fileType, 3); if (fileType != "PNG") { return false; } - std::vector sequence{13, 10, 26, 10}; + Vector sequence{13, 10, 26, 10}; for (auto c : sequence) { if (mFile->getInHandle()->get() != c) @@ -54,7 +54,7 @@ bool PngReader::readChunk() { unsigned length = *BinaryStream::getNextDWord(mFile->getInHandle()); - std::string chunkType; + String chunkType; BinaryStream::getNextString(mFile->getInHandle(), chunkType, 4); //std::cout << "Got chunk with type: " << chunkType << " and length: " << length << std::endl; @@ -137,7 +137,7 @@ bool PngReader::readIDATChunk(unsigned length) { auto crc_check = std::make_unique(); - std::vector char_data = StringUtils::toBytes("IDAT"); + Vector char_data = StringUtils::toBytes("IDAT"); for (auto c : char_data) { crc_check->addValue(c); @@ -164,7 +164,7 @@ bool PngReader::readIDATChunk(unsigned length) } } -std::unique_ptr PngReader::read() +Ptr PngReader::read() { auto image = std::make_unique(5, 5); diff --git a/src/media/image/png/PngReader.h b/src/media/image/png/PngReader.h index 32b5e78..3a70017 100644 --- a/src/media/image/png/PngReader.h +++ b/src/media/image/png/PngReader.h @@ -5,8 +5,8 @@ #include "PngHeader.h" #include "ZlibEncoder.h" -#include -#include +#include "String.h" +#include "Pointer.h" #include class BitStream; @@ -20,7 +20,7 @@ public: ~PngReader(); void setPath(const Path& path); - std::unique_ptr read(); + Ptr read(); private: bool readChunk(); @@ -34,12 +34,12 @@ private: PngHeader mHeader; - std::unique_ptr mWorkingImage; - std::unique_ptr mFile; + Ptr mWorkingImage; + Ptr mFile; Path mPath; - std::unique_ptr mEncoder; - std::unique_ptr mInputStream; - std::unique_ptr mOutputStream; + Ptr mEncoder; + Ptr mInputStream; + Ptr mOutputStream; bool mProcessingDatablocks{false}; }; diff --git a/src/media/image/png/PngWriter.cpp b/src/media/image/png/PngWriter.cpp index e8744de..ee5caaf 100644 --- a/src/media/image/png/PngWriter.cpp +++ b/src/media/image/png/PngWriter.cpp @@ -21,11 +21,20 @@ PngWriter::~PngWriter() } -std::unique_ptr PngWriter::Create() +Ptr PngWriter::Create() { return std::make_unique(); } +void PngWriter::setCompressionMethod(Deflate::CompressionMethod method) +{ +#ifdef _WIN32 + (void)method; +#else + dynamic_cast(mWriterImpl.get())->setCompressionMethod(method); +#endif +} + void PngWriter::write(const Path& path, Image* image) { mWriterImpl->write(path, image); diff --git a/src/media/image/png/PngWriter.h b/src/media/image/png/PngWriter.h index 6cb994d..2c7ad81 100644 --- a/src/media/image/png/PngWriter.h +++ b/src/media/image/png/PngWriter.h @@ -2,9 +2,10 @@ #include "Image.h" #include "IImageWriter.h" +#include "DeflateElements.h" -#include -#include +#include "Pointer.h" +#include "String.h" class PngWriter : public IImageWriter { @@ -12,12 +13,14 @@ public: PngWriter(); ~PngWriter(); - static std::unique_ptr Create(); + static Ptr Create(); + + void setCompressionMethod(Deflate::CompressionMethod method); void write(const Path& path, Image* image) override; private: - std::unique_ptr mWriterImpl; + Ptr mWriterImpl; }; -using PngWriterPtr = std::unique_ptr; +using PngWriterPtr = Ptr; diff --git a/src/media/image/win32/Win32WicImage.h b/src/media/image/win32/Win32WicImage.h index 7f4e5fc..639d539 100644 --- a/src/media/image/win32/Win32WicImage.h +++ b/src/media/image/win32/Win32WicImage.h @@ -4,7 +4,7 @@ #include -#include +#include "Pointer.h" class Win32WicInterface; @@ -21,5 +21,5 @@ public: private: Microsoft::WRL::ComPtr mWicImage; - std::unique_ptr mWicInterface; + Ptr mWicInterface; }; \ No newline at end of file diff --git a/src/media/video/FfmegInterface.cpp b/src/media/video/FfmegInterface.cpp index 3356300..29bda66 100644 --- a/src/media/video/FfmegInterface.cpp +++ b/src/media/video/FfmegInterface.cpp @@ -12,9 +12,9 @@ extern "C" { #include } -std::vector > FfmpegInterface::decodeToImages(const std::unique_ptr