From 6c618749f10ac035fbaf8517236762fcedbe51b9 Mon Sep 17 00:00:00 2001 From: jmsgrogan Date: Mon, 2 Oct 2023 16:34:33 +0100 Subject: [PATCH 01/10] Switch to GPL V3. --- LICENSE | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) 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 . From 4b308f6c32a72bd7d5161ef428f0603c74cd3eca Mon Sep 17 00:00:00 2001 From: jmsgrogan Date: Mon, 18 Dec 2023 10:16:31 +0000 Subject: [PATCH 02/10] Initial test bootstrap. --- apps/notes_tk/main.cpp | 2 +- bootstrap.sh | 20 ++ src/base/compiler/KScope.cpp | 78 +++++ src/base/compiler/KScope.h | 86 +++++ src/base/compression/Lz77Encoder.h | 2 +- src/base/core/CMakeLists.txt | 4 + src/base/core/Color.cpp | 71 ++++ src/base/core/Color.h | 26 +- src/base/core/CommandLineArgs.cpp | 18 +- src/base/core/CommandLineArgs.h | 26 +- src/base/core/Serializeable.h | 11 + src/base/core/base_types/ByteTypes.h | 12 + src/base/core/base_types/Error.cpp | 11 + src/base/core/base_types/Error.h | 15 + src/base/core/base_types/Index.cpp | 17 + src/base/core/base_types/Index.h | 19 ++ src/base/core/base_types/Result.h | 41 +++ src/base/core/build.toml | 0 src/base/core/data_structures/CircleBuffer.h | 6 +- src/base/core/data_structures/List.h | 13 +- src/base/core/data_structures/Map.h | 6 + src/base/core/data_structures/Optional.h | 29 ++ src/base/core/data_structures/Pair.h | 27 ++ src/base/core/data_structures/RawTree.h | 2 - src/base/core/data_structures/String.cpp | 232 ++++++++++++++ src/base/core/data_structures/String.h | 59 ++++ src/base/core/data_structures/Tree.h | 10 +- src/base/core/data_structures/Vector.cpp | 0 src/base/core/data_structures/Vector.h | 233 ++++++++++++++ src/base/core/encoding/ByteUtils.h | 44 ++- src/base/core/encoding/CharUtils.cpp | 35 ++ src/base/core/encoding/CharUtils.h | 17 + src/base/core/encoding/StringUtils.h | 2 + src/base/core/file_utilities/Directory.cpp | 82 ++++- src/base/core/file_utilities/Directory.h | 14 +- src/base/core/file_utilities/File.cpp | 302 ++++++++++++------ src/base/core/file_utilities/File.h | 46 ++- src/base/core/file_utilities/FileFormats.h | 12 +- .../core/file_utilities/FileSystemPath.cpp | 114 +++++++ src/base/core/file_utilities/FileSystemPath.h | 38 +++ src/base/core/loggers/ConsoleLogger.cpp | 17 + src/base/core/loggers/ConsoleLogger.h | 11 + src/base/core/loggers/FileLogger.cpp | 17 +- src/base/core/loggers/FileLogger.h | 39 +-- src/base/core/memory/Allocator.cpp | 0 src/base/core/memory/Allocator.h | 29 ++ src/base/core/memory/Pointer.h | 61 ++++ src/base/core/streams/BitStream.cpp | 100 ++++-- src/base/core/streams/BitStream.h | 81 ++--- src/base/core/streams/BufferBitStream.cpp | 21 +- src/base/core/streams/BufferBitStream.h | 17 +- src/base/core/streams/InputBitStream.cpp | 9 +- src/base/core/streams/InputBitStream.h | 8 +- src/base/core/streams/OutputBitStream.cpp | 10 +- src/base/core/streams/OutputBitStream.h | 8 +- src/base/geometry/grid/Grid.h | 39 ++- src/console/CMakeLists.txt | 5 +- src/console/TermInfo.cpp | 111 +++++++ src/console/TermInfo.h | 17 + src/main.cpp | 43 +++ src/media/image/CMakeLists.txt | 3 + src/media/image/Image.cpp | 64 ++-- src/media/image/Image.h | 30 +- src/media/image/ImageBitStream.cpp | 14 +- src/media/image/ImageBitStream.h | 10 +- src/media/image/Pixel.cpp | 0 src/media/image/Pixel.h | 26 ++ src/media/image/png/BasicPngWriter.cpp | 12 +- src/media/image/png/BasicPngWriter.h | 6 +- src/media/image/png/PngFilter.cpp | 77 +++++ src/media/image/png/PngFilter.h | 76 +---- src/media/image/png/PngHeader.cpp | 46 ++- src/media/image/png/PngHeader.h | 42 +-- src/media/image/png/PngInfo.cpp | 24 +- src/media/image/png/PngInfo.h | 18 +- src/media/image/png/PngWriter.cpp | 9 + src/media/image/png/PngWriter.h | 3 + .../wayland/WaylandInterface.cpp | 4 +- .../ui_interfaces/wayland/WaylandSurface.cpp | 15 +- .../ui_interfaces/wayland/WaylandSurface.h | 2 +- test/CMakeLists.txt | 2 + test/bootstrap_tests.sh | 23 ++ test/console/CMakeLists.txt | 9 + test/console/TestConsoleApp.cpp | 93 ++++++ .../{TestStringUtils.cpp => TestString.cpp} | 41 ++- test/core/TestVector.cpp | 18 ++ test/image/TestPngWriter.cpp | 24 +- test/test_runner.cpp | 9 +- test/test_utils/TestCase.h | 16 +- test/test_utils/TestCaseRunner.cpp | 51 +-- test/test_utils/TestCaseRunner.h | 22 +- test/test_utils/TestFramework.h | 6 +- test/test_utils/TestUtils.h | 2 +- test/windows/TestWaylandWindow.cpp | 2 +- 94 files changed, 2543 insertions(+), 681 deletions(-) create mode 100755 bootstrap.sh create mode 100644 src/base/compiler/KScope.cpp create mode 100644 src/base/compiler/KScope.h create mode 100644 src/base/core/Serializeable.h create mode 100644 src/base/core/base_types/ByteTypes.h create mode 100644 src/base/core/base_types/Error.cpp create mode 100644 src/base/core/base_types/Error.h create mode 100644 src/base/core/base_types/Index.cpp create mode 100644 src/base/core/base_types/Index.h create mode 100644 src/base/core/base_types/Result.h create mode 100644 src/base/core/build.toml create mode 100644 src/base/core/data_structures/Map.h create mode 100644 src/base/core/data_structures/Optional.h create mode 100644 src/base/core/data_structures/Pair.h create mode 100644 src/base/core/data_structures/String.cpp create mode 100644 src/base/core/data_structures/String.h create mode 100644 src/base/core/data_structures/Vector.cpp create mode 100644 src/base/core/data_structures/Vector.h create mode 100644 src/base/core/encoding/CharUtils.cpp create mode 100644 src/base/core/encoding/CharUtils.h create mode 100644 src/base/core/file_utilities/FileSystemPath.cpp create mode 100644 src/base/core/file_utilities/FileSystemPath.h create mode 100644 src/base/core/loggers/ConsoleLogger.cpp create mode 100644 src/base/core/loggers/ConsoleLogger.h create mode 100644 src/base/core/memory/Allocator.cpp create mode 100644 src/base/core/memory/Allocator.h create mode 100644 src/base/core/memory/Pointer.h create mode 100644 src/console/TermInfo.cpp create mode 100644 src/console/TermInfo.h create mode 100644 src/main.cpp create mode 100644 src/media/image/Pixel.cpp create mode 100644 src/media/image/Pixel.h create mode 100644 src/media/image/png/PngFilter.cpp create mode 100755 test/bootstrap_tests.sh create mode 100644 test/console/CMakeLists.txt create mode 100644 test/console/TestConsoleApp.cpp rename test/core/{TestStringUtils.cpp => TestString.cpp} (57%) create mode 100644 test/core/TestVector.cpp diff --git a/apps/notes_tk/main.cpp b/apps/notes_tk/main.cpp index f864fb8..997d80f 100644 --- a/apps/notes_tk/main.cpp +++ b/apps/notes_tk/main.cpp @@ -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/bootstrap.sh b/bootstrap.sh new file mode 100755 index 0000000..addd2f6 --- /dev/null +++ b/bootstrap.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +SOURCE_DIR=$SCRIPT_DIR/src + +g++ $SOURCE_DIR/main.cpp \ + $SOURCE_DIR/base/core/base_types/Error.cpp \ + $SOURCE_DIR/base/core/base_types/Index.cpp \ + $SOURCE_DIR/base/core/data_structures/String.cpp \ + $SOURCE_DIR/base/core/file_utilities/FileSystemPath.cpp \ + $SOURCE_DIR/base/core/file_utilities/File.cpp \ + $SOURCE_DIR/base/core/file_utilities/Directory.cpp \ + $SOURCE_DIR/base/core/encoding/CharUtils.cpp \ + -o builder -g -fno-exceptions -fno-rtti \ + -I$SOURCE_DIR/base/core/data_structures \ + -I$SOURCE_DIR/base/core/base_types \ + -I$SOURCE_DIR/base/core/memory \ + -I$SOURCE_DIR/base/core/loggers \ + -I$SOURCE_DIR/base/core/encoding \ + -I$SOURCE_DIR/base/core/file_utilities 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/compression/Lz77Encoder.h b/src/base/compression/Lz77Encoder.h index 0d3ec85..64ecb79 100644 --- a/src/base/compression/Lz77Encoder.h +++ b/src/base/compression/Lz77Encoder.h @@ -33,8 +33,8 @@ public: bool hitBufferFull() const; private: - bool lookAheadSourceEmpty() const; + unsigned char getSearchBufferItem(unsigned index) const; unsigned lookAheadForMatchingChars(unsigned searchIndex); diff --git a/src/base/core/CMakeLists.txt b/src/base/core/CMakeLists.txt index d3c607d..2832eb9 100644 --- a/src/base/core/CMakeLists.txt +++ b/src/base/core/CMakeLists.txt @@ -40,8 +40,11 @@ list(APPEND SOURCES Dictionary.cpp Color.cpp CommandLineArgs.cpp + memory/Allocator.cpp data_structures/RawTree.cpp data_structures/Tree.cpp + data_structures/Vector.cpp + data_structures/String.cpp loggers/FileLogger.cpp file_utilities/Directory.cpp file_utilities/File.cpp @@ -81,6 +84,7 @@ target_include_directories(${MODULE_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/memory ${CMAKE_CURRENT_SOURCE_DIR}/streams ${CMAKE_CURRENT_SOURCE_DIR}/http + ${CMAKE_CURRENT_SOURCE_DIR}/base_types ${CMAKE_CURRENT_SOURCE_DIR}/data_structures ${CMAKE_CURRENT_SOURCE_DIR}/serializers ${CMAKE_CURRENT_SOURCE_DIR}/xml diff --git a/src/base/core/Color.cpp b/src/base/core/Color.cpp index 2fd35da..779fcde 100644 --- a/src/base/core/Color.cpp +++ b/src/base/core/Color.cpp @@ -34,6 +34,77 @@ std::unique_ptr Color::Create(unsigned char r, unsigned char g, unsigned return std::make_unique(r, g, b, a); } +std::size_t Color::getSize() const +{ + return getSize(mFormat, mBitDepth); +} + +std::size_t Color::getSize(Format format, unsigned bitDepth) +{ + return getNumChannels(format) * bitDepth / 8; +} + +std::size_t Color::getNumChannels(Format format) +{ + if (format == Format::GRAYSCALE || format == Format::LUT) + { + return 1; + } + else + { + return 4; + } +} + +uint8_t Color::getByte(std::size_t index) const +{ + if (mFormat == Format::GRAYSCALE || mFormat == Format::LUT) + { + if (index > 0) + { + throw std::range_error("Color index out of range in getByte()"); + } + 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: + throw std::range_error("Color index out of range in getByte()"); + } + } + else + { + switch(index) + { + case 0: + return mR; + case 1: + return mG; + case 2: + return mB; + case 3: + return mAlpha * 255; + default: + throw std::range_error("Color index out of range in getByte()"); + } + } +} + +void Color::setAlpha(float alpha) +{ + mAlpha = static_cast(alpha); +} + std::unique_ptr Color::Create(const Color& color) { return std::make_unique(color); diff --git a/src/base/core/Color.h b/src/base/core/Color.h index ea70540..5246fd6 100644 --- a/src/base/core/Color.h +++ b/src/base/core/Color.h @@ -3,10 +3,20 @@ #include #include #include +#include class Color { public: + enum class Format + { + GRAYSCALE, + GRAYSCALE_ALPHA, + LUT, + RGB, + ARGB, + RGBA + }; Color(const std::string& hexString); Color(unsigned char r = 0, unsigned char g = 0, unsigned char b = 0, double a = 1.0); @@ -25,10 +35,15 @@ public: std::string toString() const; - void setAlpha(float alpha) - { - mAlpha = static_cast(alpha); - } + std::size_t getSize() const; + + static std::size_t getNumChannels(Format format); + + static std::size_t getSize(Format format, unsigned bitDepth); + + uint8_t getByte(std::size_t index) const; + + void setAlpha(float alpha); bool operator==(const Color& rhs) const { @@ -49,7 +64,10 @@ private: 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}; }; using ColorPtr = std::shared_ptr; diff --git a/src/base/core/CommandLineArgs.cpp b/src/base/core/CommandLineArgs.cpp index 26ef06c..1ae103a 100644 --- a/src/base/core/CommandLineArgs.cpp +++ b/src/base/core/CommandLineArgs.cpp @@ -34,37 +34,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(); } 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/CommandLineArgs.h b/src/base/core/CommandLineArgs.h index 9a39346..b3d9614 100644 --- a/src/base/core/CommandLineArgs.h +++ b/src/base/core/CommandLineArgs.h @@ -1,33 +1,31 @@ #pragma once -#include -#include -#include -#include +#include "Pointer.h" +#include "Vector.h" +#include "String.h" +#include "FileSystemPath.h" class CommandLineArgs { public: CommandLineArgs(); - static std::unique_ptr Create(); + static Ptr Create(); - std::filesystem::path getLaunchPath(); + FileSystemPath getLaunchPath(); - const std::vector getArgs() const; + const Vector getArgs() const; - std::vector getUserArgs() const; + Vector getUserArgs() const; static void initialize(CommandLineArgs* args); void process(int argc, char *argv[]); - void process(const std::vector& args); + void process(const Vector& args); void recordLaunchPath(); private: - std::vector mArugments; - std::filesystem::path mLaunchPath; -}; - -using CommandLineArgsUPtr = std::unique_ptr; + Vector mArugments; + FileSystemPath mLaunchPath; +}; \ No newline at end of file diff --git a/src/base/core/Serializeable.h b/src/base/core/Serializeable.h new file mode 100644 index 0000000..5c7c29a --- /dev/null +++ b/src/base/core/Serializeable.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +class Serializeable +{ +public: + virtual std::size_t getSize() const = 0; + + virtual uint8_t getByte(std::size_t index) const = 0; +}; \ No newline at end of file diff --git a/src/base/core/base_types/ByteTypes.h b/src/base/core/base_types/ByteTypes.h new file mode 100644 index 0000000..b739fbd --- /dev/null +++ b/src/base/core/base_types/ByteTypes.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/Error.cpp b/src/base/core/base_types/Error.cpp new file mode 100644 index 0000000..919b9d5 --- /dev/null +++ b/src/base/core/base_types/Error.cpp @@ -0,0 +1,11 @@ +#include "Error.h" + +Error::Error(const String& msg) + : m_message(msg) +{ +} + +const String& Error::msg() const +{ + return m_message; +} \ 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..9339664 --- /dev/null +++ b/src/base/core/base_types/Error.h @@ -0,0 +1,15 @@ +#pragma once + +#include "String.h" + +class Error +{ +public: + Error(const String& msg); + + Error() = default; + + const String& msg() const; +private: + String m_message; +}; \ 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..0a62876 --- /dev/null +++ b/src/base/core/base_types/Index.cpp @@ -0,0 +1,17 @@ +#include "Index.h" + +Index::Index(std::size_t value) + : m_value(value), + m_valid(true) +{ +} + +bool Index::valid() const +{ + return m_valid; +} + +std::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..2e46485 --- /dev/null +++ b/src/base/core/base_types/Index.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +class Index +{ +public: + Index() = default; + + Index(std::size_t value); + + bool valid() const; + + std::size_t value() const; + +private: + std::size_t m_value{0}; + bool m_valid{false}; +}; \ 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..1ae75cc --- /dev/null +++ b/src/base/core/base_types/Result.h @@ -0,0 +1,41 @@ +#pragma once + +#include "Error.h" + +template +class Result +{ +public: + Result(const T& val) + : m_value(val) + { + + } + + Result(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; + } + +private: + T m_value; + Error m_error; + bool m_ok{true}; +}; \ No newline at end of file diff --git a/src/base/core/build.toml b/src/base/core/build.toml new file mode 100644 index 0000000..e69de29 diff --git a/src/base/core/data_structures/CircleBuffer.h b/src/base/core/data_structures/CircleBuffer.h index 8b83f8b..30612da 100644 --- a/src/base/core/data_structures/CircleBuffer.h +++ b/src/base/core/data_structures/CircleBuffer.h @@ -1,8 +1,6 @@ #pragma once -#include - -#include +#include "Vector.h" template class CircleBuffer @@ -60,5 +58,5 @@ public: private: std::size_t mStartPointer{0}; std::size_t mEndPointer{0}; - std::vector mData; + Vector mData; }; diff --git a/src/base/core/data_structures/List.h b/src/base/core/data_structures/List.h index 86354f5..d75f846 100644 --- a/src/base/core/data_structures/List.h +++ b/src/base/core/data_structures/List.h @@ -1,8 +1,7 @@ #pragma once -#include -#include -#include +#include "Error.h" +#include "Vector.h" class AbstractList { @@ -20,7 +19,7 @@ public: void initializeTo(std::size_t size, T value) { - mData = std::vector(size, value); + mData = Vector(size, value); } const T* getDataPtr() const @@ -28,7 +27,7 @@ public: return mData.data(); } - const std::vector& getData() const + const Vector& getData() const { return mData; } @@ -46,7 +45,7 @@ public: } } - void setData(const std::vector& data) + void setData(const Vector& data) { mData = data; } @@ -65,5 +64,5 @@ public: } private: - std::vector mData; + Vector mData; }; diff --git a/src/base/core/data_structures/Map.h b/src/base/core/data_structures/Map.h new file mode 100644 index 0000000..68e9a86 --- /dev/null +++ b/src/base/core/data_structures/Map.h @@ -0,0 +1,6 @@ +#pragma once + +template +class Map{ + +}; \ 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..aacbcca --- /dev/null +++ b/src/base/core/data_structures/Optional.h @@ -0,0 +1,29 @@ +#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; + } + +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..6d8e95a --- /dev/null +++ b/src/base/core/data_structures/Pair.h @@ -0,0 +1,27 @@ +#pragma once + +template +class Pair +{ +public: + 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/String.cpp b/src/base/core/data_structures/String.cpp new file mode 100644 index 0000000..6d509c5 --- /dev/null +++ b/src/base/core/data_structures/String.cpp @@ -0,0 +1,232 @@ +#include "String.h" + +#include + +String::String() +{ + m_data.push_back('\0'); +} + +String::String(const Vector& data) +{ + append(data); +} + +String::String(const char* data) +{ + append(data); +} + +void String::append(const char* data) +{ + if (data == nullptr) + { + m_data.push_back('\0'); + return; + } + + auto loc = data; + while(*loc != '\0') + { + m_data.push_back(*loc); + loc++; + } + m_data.push_back('\0'); +} + +const Vector& String::data() const +{ + return m_data; +} + +bool String::empty() const +{ + return m_data.empty() || m_data[0] == '\0'; +} + +void String::append(const Vector& data) +{ + if (data.capacity() == 0) + { + 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(), size(), right); + return {left, right}; + } + return {*this, {}}; +} + +bool String::slice(std::size_t idx, String& out) const +{ + if (idx >= m_data.size() - 1) + { + 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(std::size_t start, std::size_t end, String& out) const +{ + if (end >= m_data.size() - 1) + { + 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(std::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(); +} + +std::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; + } +} + +String String::to_string(size_t input) +{ + String conv; + auto input_cpy = input; + while(input_cpy > 0) + { + const auto rem = input_cpy % 10; + conv += static_cast(48 + rem); + input_cpy /= 10; + } + conv.reverse(); + return conv; +} + +char String::operator[](std::size_t idx) const +{ + return m_data[idx]; +} + +String& String::operator<<(const char* body) +{ + append(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) +{ + /* + const auto num_digits = static_cast(log10(double(idx))) + 1; + char body[num_digits+1]; + snprintf(body, num_digits+1, "%d", static_cast(idx)); + append(body); + */ + return *this; +} + +String& String::operator+=(const String& str) +{ + if (m_data.empty()) + { + m_data = str.m_data; + } + else + { + m_data.pop_back(); + m_data.extend(str.m_data); + } + return *this; +} + +String String::operator+(const String& str) const +{ + auto ret = *this; + ret += str; + return ret; +} + +String& String::operator+=(char c) +{ + m_data.push_back('\0'); + m_data[m_data.size()-2] = c; + return *this; +} + diff --git a/src/base/core/data_structures/String.h b/src/base/core/data_structures/String.h new file mode 100644 index 0000000..7b4db08 --- /dev/null +++ b/src/base/core/data_structures/String.h @@ -0,0 +1,59 @@ +#pragma once + +#include "Vector.h" +#include "Pair.h" +#include "Index.h" +#include "ByteTypes.h" + +class String +{ +public: + String(); + + String(const Vector& data); + + String(const char* data); + + const Vector& data() const; + + bool empty() const; + + const char* raw() const; + + Pair rsplit(char c) const; + + Index rindex(char c) const; + + void reverse(); + + std::size_t size() const; + + bool slice(std::size_t idx, String& out) const; + + bool slice(std::size_t start, std::size_t end, String& out) const; + + static String to_string(size_t input); + + char operator[](std::size_t idx) const; + + String& operator<<(const char* body); + + String& operator<<(size_t idx); + + 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; + +private: + void append(const Vector& data); + + void append(const char* data); + + Vector m_data; +}; \ 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.cpp b/src/base/core/data_structures/Vector.cpp new file mode 100644 index 0000000..e69de29 diff --git a/src/base/core/data_structures/Vector.h b/src/base/core/data_structures/Vector.h new file mode 100644 index 0000000..04fa077 --- /dev/null +++ b/src/base/core/data_structures/Vector.h @@ -0,0 +1,233 @@ +#pragma once + +#include "Allocator.h" +#include + +template +class Vector +{ +public: + Vector() = default; + + Vector(std::size_t size) + { + resize(size); + m_size = 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(std::size_t slice_idx, Vector& v) const + { + if (slice_idx >= m_size) + { + return false; + } + v.resize(slice_idx); + for(std::size_t idx=0; idx= m_size) + { + return false; + } + v.resize(slice_end - slice_start); + for(std::size_t idx=slice_start; idx= m_capacity) + { + const std::size_t new_size = 1.5*m_size; + resize_capacity(new_size); + } + m_data[m_size] = item; + m_size++; + } + + const T& operator[] (const std::size_t idx) const + { + return m_data[idx]; + } + + T& operator[] (const std::size_t idx) + { + return m_data[idx]; + } + + Vector& operator=(const Vector& v) + { + resize(v.size()); + for(std::size_t idx=0; idx& other) const + { + if (m_size != other.m_size) + { + return false; + } + for(std::size_t idx=0; idx 0; + } + + void resize_capacity(std::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); + for(std::size_t idx=0; idx m_capacity) + { + m_size = m_capacity; + } + } + else if(m_size != m_capacity) + { + m_size = m_capacity; + } + } + + T* m_data{nullptr}; + Allocator m_allocator; + std::size_t m_size{0}; + std::size_t m_capacity{0}; +}; \ No newline at end of file diff --git a/src/base/core/encoding/ByteUtils.h b/src/base/core/encoding/ByteUtils.h index cb15b22..80ae138 100644 --- a/src/base/core/encoding/ByteUtils.h +++ b/src/base/core/encoding/ByteUtils.h @@ -1,44 +1,40 @@ #pragma once +#include "ByteTypes.h" +#include "String.h" #include -#include -#include class ByteUtils { public: - using Word = int16_t; - using DWord = int32_t; - using QWord = int64_t; - - static bool MostSignificantBitIsOne(char c); + static bool MostSignificantBitIsOne(Byte c); static Word GetWordFirstBit(const Word word); static Word GetWordLastByte(const Word word); - static unsigned char getByteN(uint32_t input, unsigned n); + static Byte getByteN(DWord input, std::size_t n); - static unsigned char getHigherNBits(unsigned char input, unsigned num); + static Byte getHigherNBits(Byte input, std::size_t num); - static unsigned char getLowerNBits(uint32_t input, unsigned num); + static Byte getLowerNBits(DWord input, std::size_t num); - static unsigned char getTwoBitsAtN(unsigned char input, unsigned n); + static Byte getTwoBitsAtN(Byte input, std::size_t n); - static unsigned char getMBitsAtN(unsigned char input, unsigned m, unsigned n); + static Byte getMBitsAtN(Byte input, std::size_t m, std::size_t n); - static bool getBitN(uint32_t input, unsigned n); + static bool getBitN(DWord input, std::size_t n); - static unsigned char getFromString(const std::string& string); + static Byte getFromString(const String& string); - static std::string toString(uint32_t input, unsigned length = 8); + static String toString(DWord input, std::size_t length = 8); - static uint32_t mirror(uint32_t input, unsigned length=0); + static DWord mirror(DWord input, std::size_t length=0); - static void ReverseBuffer(char* buffer, char* reverse, unsigned size, unsigned targetSize); + static void ReverseBuffer(Byte* buffer, Byte* reverse, std::size_t size, std::size_t targetSize); template - static T ToType(char* buffer, bool reverse = true) + static T ToType(Byte* buffer, bool reverse = true) { T result {0}; if(reverse) @@ -54,17 +50,17 @@ public: return result; } - static Word ToWord(char* buffer, bool reverse = true); + static Word ToWord(Byte* buffer, bool reverse = true); - static DWord ToDWord(char* buffer, bool reverse = true); + static DWord ToDWord(Byte* buffer, bool reverse = true); - static QWord ToQWord(char* buffer, bool reverse = true); + static QWord ToQWord(Byte* buffer, bool reverse = true); - static bool Compare(char* buffer, const char* tag, unsigned size); + static bool Compare(Byte* buffer, const char* tag, std::size_t size); - static bool CompareDWords(char* buffer, const char* tag); + static bool CompareDWords(Byte* buffer, const char* tag); - static bool CompareWords(char* buffer, const char* tag); + static bool CompareWords(Byte* 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 diff --git a/src/base/core/encoding/CharUtils.cpp b/src/base/core/encoding/CharUtils.cpp new file mode 100644 index 0000000..b35ba7a --- /dev/null +++ b/src/base/core/encoding/CharUtils.cpp @@ -0,0 +1,35 @@ +#include "CharUtils.h" + +bool CharUtils::is_alpha_upper(char c) +{ + const auto unsigned_c = static_cast(c); + return unsigned_c >= 65 && unsigned_c <= 90; +} + +bool CharUtils::is_alpha_lower(char c) +{ + const auto unsigned_c = static_cast(c); + return unsigned_c >= 97 && unsigned_c <= 122; +} + +bool CharUtils::is_alpha(char c) +{ + return is_alpha_upper(c) || is_alpha_lower(c); +} + +bool CharUtils::is_alnum(char c) +{ + return is_alpha(c) || is_digit(c); +} + +bool CharUtils::is_digit(char c) +{ + const auto unsigned_c = static_cast(c); + return unsigned_c >= 48 && unsigned_c <= 57; +} + +bool CharUtils::is_space(char c) +{ + return c == ' ' || c == '\f' || c == '\n' + || c == '\r' || c == '\t' || c == '\v'; +} \ No newline at end of file diff --git a/src/base/core/encoding/CharUtils.h b/src/base/core/encoding/CharUtils.h new file mode 100644 index 0000000..6e76866 --- /dev/null +++ b/src/base/core/encoding/CharUtils.h @@ -0,0 +1,17 @@ +#pragma once + +class CharUtils +{ +public: + 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); +}; \ No newline at end of file diff --git a/src/base/core/encoding/StringUtils.h b/src/base/core/encoding/StringUtils.h index e91010b..b46aab0 100644 --- a/src/base/core/encoding/StringUtils.h +++ b/src/base/core/encoding/StringUtils.h @@ -1,5 +1,7 @@ #pragma once +#include "ByteTypes.h" + #include #include diff --git a/src/base/core/file_utilities/Directory.cpp b/src/base/core/file_utilities/Directory.cpp index 49aac5a..5b1f21e 100644 --- a/src/base/core/file_utilities/Directory.cpp +++ b/src/base/core/file_utilities/Directory.cpp @@ -1,30 +1,84 @@ #include "Directory.h" +#include +#include +#include -std::vector Directory::getFilesWithExtension(const Path& path, const std::string& extension, bool recursive) +Vector Directory::getSubdirectories(const FileSystemPath& path) { - std::vector paths; - if (std::filesystem::is_directory(path)) + Vector ret; + auto dirp = ::opendir(path.as_string().raw()); + while(auto ep = ::readdir(dirp)) { - for (const auto& entry : std::filesystem::directory_iterator(path)) + auto rel_path = String(ep->d_name); + if (rel_path == "." || rel_path == "..") { - if (std::filesystem::is_regular_file(entry) && entry.path().extension() == extension) + continue; + } + + auto full_path = path.join(rel_path); + struct stat sb; + auto rc = lstat(full_path.as_string().raw(), &sb); + if (rc == -1) + { + printf("Got error"); + } + if (S_ISDIR(sb.st_mode)) + { + printf("Adding full path: %s\n", full_path.as_string().raw()); + ret.push_back(full_path); + } + } + ::closedir(dirp); + return ret; +} + +Vector Directory::getFiles(const FileSystemPath& path, bool recursive) +{ + Vector paths; + if (path.is_directory()) + { + for (const auto& entry : getSubdirectories(path)) + { + if (entry.is_regular_file()) { - paths.push_back(entry.path()); + paths.push_back(entry); } - else if(recursive && std::filesystem::is_directory(entry)) + else if(recursive && entry.is_directory()) { - const auto child_paths = getFilesWithExtension(entry, extension, recursive); - paths.insert(paths.end(), child_paths.begin(), child_paths.end()); + const auto child_paths = getFiles(entry, recursive); + paths.extend(child_paths); } } } return paths; } -void Directory::createIfNotExisting(const Path& path) +Vector Directory::getFilesWithExtension(const FileSystemPath& path, const String& extension, bool recursive) { - Path working_path; - if (std::filesystem::is_directory(path)) + Vector paths; + if (path.is_directory()) + { + for (const auto& entry : getSubdirectories(path)) + { + if (entry.is_regular_file() && entry.extension() == extension) + { + paths.push_back(entry); + } + else if(recursive && entry.is_directory()) + { + const auto child_paths = getFilesWithExtension(entry, extension, recursive); + paths.extend(child_paths); + } + } + } + return paths; +} + +void Directory::create(const FileSystemPath& path, bool existsOk) +{ + (void)existsOk; + FileSystemPath working_path; + if (path.is_directory()) { working_path = path; } @@ -33,8 +87,8 @@ void Directory::createIfNotExisting(const Path& path) working_path = path.parent_path(); } - if (!std::filesystem::exists(working_path)) + if (!working_path.exists()) { - std::filesystem::create_directories(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 index a225f32..7c27b66 100644 --- a/src/base/core/file_utilities/Directory.h +++ b/src/base/core/file_utilities/Directory.h @@ -1,14 +1,16 @@ #pragma once -#include -#include - -using Path = std::filesystem::path; +#include "Vector.h" +#include "FileSystemPath.h" class Directory { public: - static void createIfNotExisting(const Path& path); + static Vector getSubdirectories(const FileSystemPath& path); - static std::vector getFilesWithExtension(const Path& path, const std::string& extension, bool recursive=false); + static void create(const FileSystemPath& path, bool existsOK = false); + + static Vector getFiles(const FileSystemPath& path, bool recursive=false); + + static Vector getFilesWithExtension(const FileSystemPath& path, const String& extension, bool recursive=false); }; diff --git a/src/base/core/file_utilities/File.cpp b/src/base/core/file_utilities/File.cpp index e09fc47..c23e8be 100644 --- a/src/base/core/file_utilities/File.cpp +++ b/src/base/core/file_utilities/File.cpp @@ -1,17 +1,116 @@ #include "File.h" -#include "FileLogger.h" +//#include "FileLogger.h" #include "ByteUtils.h" +#include "Directory.h" +#include "Result.h" -#include -#include +#include +#include +#include +#include +#include +#include +#include -File::File(std::filesystem::path path) - : mFullPath(path), - mInHandle(), - mOutHandle() +class FileImpl { +public: + void 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; + } + m_fd = ::open(path.as_string().raw(), flags); + if (accessMode == File::AccessMode::Read) + { + m_open_for_read = true; + } + else + { + m_open_for_write = true; + } + } + + void do_close() + { + ::close(m_fd); + m_open_for_read = false; + m_open_for_write = false; + } + + bool is_ok() const + { + return m_valid; + } + + bool is_open_for_read() const + { + return m_open_for_read; + } + + bool is_open_for_write() const + { + return m_open_for_write; + } + + Result do_read(VecBytes& bytes) + { + errno = 0; + const auto rc = ::read(m_fd, bytes.data(), bytes.capacity()); + if (rc < 0) + { + const auto last_err = errno; + String msg(::strerror(last_err)); + return Result(Error(msg)); + } + return Result(rc); + } + + std::size_t do_write(const VecBytes& bytes) + { + return ::write(m_fd, bytes.data(), bytes.size()); + } + + std::size_t do_write(const Vector& bytes, int size = -1) + { + if (size > -1) + { + return ::write(m_fd, bytes.data(), size); + } + else + { + return ::write(m_fd, bytes.data(), bytes.size()); + } + } + + void update_size() + { + struct stat buf; + ::fstat(m_fd, &buf); + m_size = buf.st_size; + } + + bool m_open_for_write{false}; + bool m_open_for_read{false}; + bool m_valid{false}; + std::size_t m_size{0}; + bool m_is_open{false}; + int m_fd{-1}; +}; + +File::File(const FileSystemPath& path) + : m_impl(Ptr::create()), + m_path(path) +{ } File::~File() @@ -19,145 +118,149 @@ File::~File() close(); } -std::string File::getExtension() const +String File::getExtension() const { - return mFullPath.extension().string(); + return m_path.extension(); } -std::string File::dumpBinary() +bool File::readBinary(VecBytes& buffer) +{ + auto ok = open(AccessMode::Read, true); + if (!ok) + { + return false; + } + + m_impl->update_size(); + buffer.resize(m_impl->m_size); + const auto result = m_impl->do_read(buffer); + buffer.resize(result.value()); + return true; +} + +String File::readText() +{ + VecBytes buffer; + auto ok = open(AccessMode::Read, true); + if (!ok) + { + return {}; + } + + m_impl->update_size(); + buffer.resize(m_impl->m_size); + const auto result = m_impl->do_read(buffer); + if (!result.ok()) + { + printf("Got error: %s\n", result.error().msg()); + return {}; + } + + buffer.resize(result.value()); + return String(buffer); +} + +String File::dumpBinary() { open(AccessMode::Read); - std::stringstream sstr; - sstr << "Count | Binary | Decimal | ASCII \n"; + String sstr; + sstr << "Count | Binary | Decimal | Hex | ASCII \n"; + + VecBytes buffer; + readBinary(buffer); + unsigned count = 0; - while(mInHandle->peek() != EOF) + /* + for(const auto byte : buffer) { - 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'; + 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 << " | " << ByteUtils::toString(byte) << " | " << static_cast(byte) << " | " << hex_sstr.str() << " | " << ascii_val << '\n'; if (count % 10 == 0) { sstr << "\n"; } count++; } - const auto out = sstr.str(); + */ close(); - return out; + return sstr; } -std::ifstream* File::getInHandle() const +Optional File::readNextByte() { - return mInHandle.get(); -} - -std::ofstream* File::getOutHandle() const -{ - return mOutHandle.get(); -} - -std::optional File::readNextByte() -{ - if (!mInHandle) + if (!open(AccessMode::Read)) { - if (!open(AccessMode::Read)) - { - return std::nullopt; - } + return {}; } - if (mInHandle->good()) + if (m_impl->is_ok()) { - if (auto val = mInHandle->get(); val == EOF) + VecBytes buffer(1); + m_impl->do_read(buffer); + if (buffer[0] == EOF) { - return std::nullopt; + return {}; } else { - return val; + return buffer[0]; } } else { - return std::nullopt; + return {}; } } -bool File::open(AccessMode accessMode) +bool File::open(AccessMode accessMode, bool binary) { - if (mFullPath.is_absolute() && !std::filesystem::exists(mFullPath.parent_path())) + if (m_path.is_absolute() && !m_path.parent_path().exists()) { - std::filesystem::create_directories(mFullPath.parent_path()); + Directory::create(m_path.parent_path(), true); } - 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; - } - } + m_impl->do_open(m_path, accessMode); return true; } void File::close() { - if(mOutHandle) - { - mOutHandle->close(); - } - if(mInHandle) - { - mInHandle->close(); - } + m_impl->do_close(); } FileFormat::Format File::inferFormat() const { - const auto extension = getExtension(); - return FileFormat::inferFormat(extension); + //const auto extension = getExtension(); + //return FileFormat::inferFormat(extension); + return {}; } -void File::writeText(const std::string& text) +void File::writeText(const String& text) { bool had_to_open{false}; - if (!mOutHandle) + if (!m_impl->is_open_for_write()) { had_to_open = true; - if (!open(File::AccessMode::Write)) - { - return; - } + m_impl->do_open(m_path, File::AccessMode::Write); } - (*mOutHandle) << text; + m_impl->do_write(text.data(), text.data().size() - 1); if (had_to_open) { - close(); + m_impl->do_close(); } } -std::vector File::readLines() +Vector File::readLines() { - std::vector content; + Vector content; + /* if (!pathExists()) { return {}; @@ -168,18 +271,20 @@ std::vector File::readLines() return {}; } - std::string str; + String str; while(std::getline(*mInHandle, str)) { content.push_back(str); } close(); + */ return content; } -std::string File::read() +String File::read() { + /* if (!pathExists()) { return {}; @@ -190,31 +295,16 @@ std::string File::read() return {}; } - std::stringstream buffer; + String 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; + */ + String buffer; + return buffer; } bool File::pathExists() const { - return std::filesystem::exists(mFullPath); + return m_path.exists(); } diff --git a/src/base/core/file_utilities/File.h b/src/base/core/file_utilities/File.h index b2cb3f0..09dbcfc 100644 --- a/src/base/core/file_utilities/File.h +++ b/src/base/core/file_utilities/File.h @@ -1,57 +1,53 @@ #pragma once #include "FileFormats.h" +#include "FileSystemPath.h" +#include "Optional.h" +#include "String.h" +#include "ByteTypes.h" +#include "Pointer.h" -#include -#include -#include -#include -#include -#include - -using Path = std::filesystem::path; +class FileImpl; class File { public: enum class AccessMode{ Read, - Write + Write, + ReadWrite }; public: - File(std::filesystem::path fullPath); + File(const FileSystemPath& path); ~File(); void close(); - std::string dumpBinary(); + String dumpBinary(); - std::string getExtension() const; - - std::ifstream* getInHandle() const; - - std::ofstream* getOutHandle() const; + String getExtension() const; FileFormat::Format inferFormat() const; - std::string readText(); + String readText(); - std::vector readLines(); + Vector readLines(); - std::string read(); + String read(); bool pathExists() const; - bool open(AccessMode mode); + bool open(AccessMode mode, bool binary = false); - std::optional readNextByte(); + bool readBinary(VecBytes& bytes); - void writeText(const std::string& text); + Optional readNextByte(); + + void writeText(const String& text); private: - std::filesystem::path mFullPath; - std::unique_ptr mInHandle; - std::unique_ptr mOutHandle; + Ptr m_impl; + FileSystemPath m_path; }; diff --git a/src/base/core/file_utilities/FileFormats.h b/src/base/core/file_utilities/FileFormats.h index 0dccf8f..1aeb124 100644 --- a/src/base/core/file_utilities/FileFormats.h +++ b/src/base/core/file_utilities/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/file_utilities/FileSystemPath.cpp b/src/base/core/file_utilities/FileSystemPath.cpp new file mode 100644 index 0000000..7290531 --- /dev/null +++ b/src/base/core/file_utilities/FileSystemPath.cpp @@ -0,0 +1,114 @@ +#include "FileSystemPath.h" + +#include +#include +#include +#include +#include + +FileSystemPath::FileSystemPath(const String& path) + : m_path(path) +{ + +} + +const String& FileSystemPath::as_string() const +{ + return m_path; +} + +Result FileSystemPath::is_empty() const +{ + if (!is_regular_file()) + { + return {Error("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 +{ + if (!is_regular_file()) + { + return {Error("Requested size but target is not regular file.")}; + } + + struct stat buf; + ::stat(m_path.raw(), &buf); + return buf.st_size; +} + +FileSystemPath FileSystemPath::current_dir() +{ + errno = 0; + const auto path_max = ::pathconf(".", _PC_PATH_MAX); + std::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); + const auto ret = ::getcwd(buffer.data(), path_max); + return FileSystemPath(String(buffer.data())); +} + +bool FileSystemPath::is_regular_file() const +{ + struct stat path_stat; + ::stat(m_path.raw(), &path_stat); + return S_ISREG(path_stat.st_mode); +} + +bool FileSystemPath::is_directory() const +{ + struct stat path_stat; + ::stat(m_path.raw(), &path_stat); + return 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; +} + +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/file_utilities/FileSystemPath.h b/src/base/core/file_utilities/FileSystemPath.h new file mode 100644 index 0000000..1aca9cb --- /dev/null +++ b/src/base/core/file_utilities/FileSystemPath.h @@ -0,0 +1,38 @@ +#pragma once + +#include "String.h" +#include "Result.h" + +class FileSystemPath +{ +public: + FileSystemPath() = default; + + FileSystemPath(const String& path); + + const String& as_string() const; + + static FileSystemPath current_dir(); + + String extension() const; + + bool exists() const; + + Result is_empty() const; + + Result get_size() const; + + FileSystemPath join(const String& entry) const; + + bool is_regular_file() const; + + bool is_directory() const; + + bool is_absolute() const; + + FileSystemPath parent_path() const; + +private: + String m_delimiter{"/"}; + String m_path; +}; \ No newline at end of file diff --git a/src/base/core/loggers/ConsoleLogger.cpp b/src/base/core/loggers/ConsoleLogger.cpp new file mode 100644 index 0000000..234027d --- /dev/null +++ b/src/base/core/loggers/ConsoleLogger.cpp @@ -0,0 +1,17 @@ +#include "ConsoleLogger.h" + +#include +#include + +void ConsoleLogger::logLine(const String& msg) +{ + printf("%s\n", msg.raw()); +} + +void ConsoleLogger::logLine(const char* fmt, ...) +{ + va_list(args); + va_start(args, fmt); + vprintf((String(fmt) + "\n").raw(), args); + va_end(args); +} \ No newline at end of file diff --git a/src/base/core/loggers/ConsoleLogger.h b/src/base/core/loggers/ConsoleLogger.h new file mode 100644 index 0000000..fc7e3c4 --- /dev/null +++ b/src/base/core/loggers/ConsoleLogger.h @@ -0,0 +1,11 @@ +#pragma once + +#include "String.h" + +class ConsoleLogger +{ +public: + static void logLine(const String& msg); + + static void logLine(const char* fmt, ...); +}; \ No newline at end of file diff --git a/src/base/core/loggers/FileLogger.cpp b/src/base/core/loggers/FileLogger.cpp index d9330b9..e6aa155 100644 --- a/src/base/core/loggers/FileLogger.cpp +++ b/src/base/core/loggers/FileLogger.cpp @@ -1,9 +1,20 @@ #include "FileLogger.h" #include -#include -#include -#include + +FileLogger::FileLogger() + :mWorkDirectory(), + mFileName("MT_Log.txt") +{ + +} + + +FileLogger& FileLogger::GetInstance() +{ + static FileLogger instance; + return instance; +} FileLogger::~FileLogger() { diff --git a/src/base/core/loggers/FileLogger.h b/src/base/core/loggers/FileLogger.h index 1d73311..59831ec 100644 --- a/src/base/core/loggers/FileLogger.h +++ b/src/base/core/loggers/FileLogger.h @@ -1,33 +1,21 @@ #pragma once -#define MLOG_ALL(msg, level) {std::ostringstream mt_logstream;\ +#define MLOG_ALL(msg, level) {String 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 +#include "Pointer.h" +#include "String.h" class FileLogger { - FileLogger() - :mWorkDirectory(), - mFileName("MT_Log.txt"), - mFileStream() - { - - } + FileLogger(); public: - static FileLogger& GetInstance() - { - static FileLogger instance; - return instance; - } + static FileLogger& GetInstance(); FileLogger(FileLogger const&) = delete; void operator=(FileLogger const&) = delete; @@ -36,22 +24,19 @@ public: void disable(); - void SetWorkDirectory(const std::string& workDir); + void SetWorkDirectory(const String& workDir); - void SetFileName(const std::string& fileName); + void SetFileName(const String& fileName); void Open(); void Close(); - void LogLine(const std::ostringstream& line); + void LogLine(const String& line); - void LogLine(const std::string& logType, const std::ostringstream& line, const std::string& fileName = "", const std::string& functionName = "", int lineNumber=-1); + void LogLine(const String& logType, const String& line, const String& fileName = "", const String& functionName = "", int lineNumber=-1); private: bool mDisabled{false}; - std::string mWorkDirectory; - std::string mFileName; - std::ofstream mFileStream; -}; - -using FileLoggerPtr = std::shared_ptr; + String mWorkDirectory; + String mFileName; +}; \ No newline at end of file diff --git a/src/base/core/memory/Allocator.cpp b/src/base/core/memory/Allocator.cpp new file mode 100644 index 0000000..e69de29 diff --git a/src/base/core/memory/Allocator.h b/src/base/core/memory/Allocator.h new file mode 100644 index 0000000..110ee8a --- /dev/null +++ b/src/base/core/memory/Allocator.h @@ -0,0 +1,29 @@ +#pragma once + +//#include +#include + +template +class Allocator +{ +public: + T* allocate() + { + return new T; + } + + void do_delete(T** p) + { + delete p; + } + + T* alloc_array(std::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..ad3aa85 --- /dev/null +++ b/src/base/core/memory/Pointer.h @@ -0,0 +1,61 @@ +#pragma once + +#include "Allocator.h" +#include + +template +class Ptr +{ +public: + Ptr() + { + } + + static Ptr create() + { + Ptr p; + p.allocate(); + return std::move(p); + } + + void allocate() + { + m_raw = m_allocator.allocate(); + } + + ~Ptr() + { + if (m_raw != nullptr) + { + m_allocator.do_delete(&m_raw); + } + } + + Ptr(const Ptr& other) = delete; + + Ptr(Ptr&& other) + : m_allocator(std::move(other.m_allocator)), + m_raw(other.m_raw) + { + other.m_raw = nullptr; + } + + T* get() + { + return m_raw; + } + + const T* get() const + { + return m_raw; + } + + T* operator->() + { + return m_raw; + } + +private: + Allocator m_allocator; + T* m_raw{nullptr}; +}; \ No newline at end of file diff --git a/src/base/core/streams/BitStream.cpp b/src/base/core/streams/BitStream.cpp index 28afdb6..2d43c1d 100644 --- a/src/base/core/streams/BitStream.cpp +++ b/src/base/core/streams/BitStream.cpp @@ -2,15 +2,12 @@ #include "ByteUtils.h" -#include -#include - BitStream::~BitStream() { } -unsigned char BitStream::getCurrentByte() +Byte BitStream::getCurrentByte() { if (mByteOffset < 0) { @@ -19,19 +16,18 @@ unsigned char BitStream::getCurrentByte() 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,24 +37,26 @@ int BitStream::getCurrentByteOffset() const return mByteOffset; } -unsigned BitStream::getCurrentBitOffset() const +std::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 << "Byte offset " << mByteOffset<< " | Bit offset " << mBitOffset; + ret << " | Working byte " << ByteUtils::toString(getCurrentByte()) << '\n'; + return ret; } -std::string BitStream::logNextNBytes(unsigned n) const +String BitStream::logNextNBytes(std::size_t n) const { std::stringstream sstr; - unsigned count{0}; - for(auto byte : peekNextNBytes(n)) + std::size_t count{0}; + VecBytes bytes; + peekNextNBytes(n, bytes); + for(auto byte : bytes) { sstr << mByteOffset + count << " | " << ByteUtils::toString(byte) + '\n'; count++; @@ -66,28 +64,28 @@ std::string BitStream::logNextNBytes(unsigned n) const return sstr.str(); } -void BitStream::writeNBits(uint32_t data, unsigned length) +void BitStream::writeNBits(DWord data, std::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 = ByteUtils::getLowerNBits(data, num_left); mCurrentByte |= lower_bits << mBitOffset; writeByte(mCurrentByte, false); - unsigned num_bytes = overshoot / 8; - for (unsigned idx=0; idx< num_bytes; idx++) + std::size_t num_bytes = overshoot / 8; + for (std::size_t idx=0; idx< num_bytes; idx++) { - mCurrentByte = ByteUtils::getMBitsAtN(static_cast(data), overshoot, idx*8 + num_left); + mCurrentByte = ByteUtils::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 = ByteUtils::getMBitsAtN(static_cast(data), remainder, num_bytes*8 + num_left); mBitOffset = remainder; } else @@ -98,7 +96,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,10 +105,9 @@ void BitStream::writeNBits(uint32_t data, unsigned length) mBitOffset = 0; } } - } -bool BitStream::readNextNBits(unsigned n, unsigned char& buffer) +bool BitStream::readNextNBits(std::size_t n, Byte& buffer) { if (mByteOffset < 0) { @@ -123,15 +120,15 @@ bool BitStream::readNextNBits(unsigned n, unsigned char& buffer) int overshoot = n + mBitOffset - 8; if (overshoot > 0) { - unsigned char last_byte = mCurrentByte; + const auto last_byte = mCurrentByte; if (!readNextByte()) { 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 = ByteUtils::getHigherNBits(last_byte, num_lower); + const auto higher_bits = ByteUtils::getLowerNBits(mCurrentByte, overshoot); buffer = (higher_bits << num_lower) | lower_bits; @@ -145,3 +142,44 @@ bool BitStream::readNextNBits(unsigned n, unsigned char& buffer) 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; + } +} + +std::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..e316a7d 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 "ByteTypes.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; + std::size_t getCurrentBitOffset() const; virtual bool isFinished() const = 0; - std::string logNextNBytes(unsigned n) const; + String logNextNBytes(std::size_t n) const; - std::string logLocation(); + String logLocation(); - virtual std::vector peekNextNBytes(unsigned n) const = 0; + virtual void peekNextNBytes(std::size_t n, VecBytes& bytes) const = 0; - virtual bool readNextNBits(unsigned n, unsigned char& buffer); + virtual bool readNextNBits(std::size_t n, Byte& buffer); - virtual std::optional readNextByte() = 0; + virtual Optional readNextByte() = 0; - virtual void writeNBits(uint32_t data, unsigned length); + virtual void writeNBits(DWord data, std::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}; + std::size_t mBitOffset{0}; + Byte mCurrentByte{0}; int mEndByteOffset{-1}; - unsigned mEndBitOffset{0}; - unsigned char mEndByte{0}; + std::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..12381ae 100644 --- a/src/base/core/streams/BufferBitStream.cpp +++ b/src/base/core/streams/BufferBitStream.cpp @@ -9,10 +9,10 @@ bool BufferBitStream::isFinished() const return mByteOffset == static_cast(mBuffer.size()) - 1; } -std::vector BufferBitStream::peekNextNBytes(unsigned n) const +void BufferBitStream::peekNextNBytes(std::size_t n, VecBytes& ret) const { - std::vector ret (n, 0); - unsigned count = 0; + ret.resize(n, 0); + std::size_t count = 0; int start = mByteOffset; if (start<0) @@ -28,12 +28,11 @@ std::vector BufferBitStream::peekNextNBytes(unsigned n) const } ret[count] = mBuffer[idx]; - count ++; + count++; } - return ret; } -std::optional BufferBitStream::readNextByte() +std::optional BufferBitStream::readNextByte() { if (mByteOffset + 1 == static_cast(mBuffer.size())) { @@ -47,14 +46,14 @@ std::optional BufferBitStream::readNextByte() } } -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(uint8_t data, bool checkOverflow) { - unsigned char out_byte{0}; + uint8_t out_byte{0}; if (checkOverflow && mBitOffset > 0) { out_byte = ByteUtils::getLowerNBits(mCurrentByte, mBitOffset); @@ -76,12 +75,12 @@ void BufferBitStream::writeByte(unsigned char data, bool checkOverflow) } -void BufferBitStream::writeBytes(const std::vector data) +void BufferBitStream::writeBytes(const VecBytes& data) { std::copy(data.begin(), data.end(), std::back_inserter(mBuffer)); } -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..04794fb 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(std::size_t n, VecBytes& bytes) const override; - std::optional readNextByte() override; + std::optional readNextByte() 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(uint8_t 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/InputBitStream.cpp b/src/base/core/streams/InputBitStream.cpp index 8568853..c6b19b5 100644 --- a/src/base/core/streams/InputBitStream.cpp +++ b/src/base/core/streams/InputBitStream.cpp @@ -12,16 +12,15 @@ bool InputBitStream::isFinished() const return mStream->good(); } -std::vector InputBitStream::peekNextNBytes(unsigned) const +void InputBitStream::peekNextNBytes(std::size_t, VecBytes&) const { - return {}; } -std::optional InputBitStream::readNextByte() +std::optional InputBitStream::readNextByte() { if (mStream->good()) { - return static_cast(mStream->get()); + return static_cast(mStream->get()); } else { @@ -29,7 +28,7 @@ std::optional InputBitStream::readNextByte() } } -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..c6ff565 100644 --- a/src/base/core/streams/InputBitStream.h +++ b/src/base/core/streams/InputBitStream.h @@ -10,13 +10,13 @@ class InputBitStream : public BitStream bool isFinished() const override; - std::vector peekNextNBytes(unsigned n) const override; + void peekNextNBytes(std::size_t n, VecBytes& bytes) const override; - std::optional readNextByte() override; + std::optional readNextByte() 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 { } diff --git a/src/base/core/streams/OutputBitStream.cpp b/src/base/core/streams/OutputBitStream.cpp index 2579e24..37fa6db 100644 --- a/src/base/core/streams/OutputBitStream.cpp +++ b/src/base/core/streams/OutputBitStream.cpp @@ -12,22 +12,22 @@ bool OutputBitStream::isFinished() const return true; } -std::vector OutputBitStream::peekNextNBytes(unsigned) const +void OutputBitStream::peekNextNBytes(std::size_t, VecBytes&) const { - return {}; + } -std::optional OutputBitStream::readNextByte() +std::optional OutputBitStream::readNextByte() { return std::nullopt; } -void OutputBitStream::writeByte(unsigned char data, bool) +void OutputBitStream::writeByte(uint8_t data, bool) { (*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..bd22014 100644 --- a/src/base/core/streams/OutputBitStream.h +++ b/src/base/core/streams/OutputBitStream.h @@ -11,13 +11,13 @@ public: bool isFinished() const override; - std::vector peekNextNBytes(unsigned n) const override; + void peekNextNBytes(std::size_t n, VecBytes& bytes) const override; - std::optional readNextByte() override; + std::optional readNextByte() 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}; diff --git a/src/base/geometry/grid/Grid.h b/src/base/geometry/grid/Grid.h index 424fa8a..7159f4f 100644 --- a/src/base/geometry/grid/Grid.h +++ b/src/base/geometry/grid/Grid.h @@ -12,7 +12,7 @@ public: 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(std::size_t idx, std::size_t jdx, std::size_t kdx = 1) const override { return this->mData->getItem(getOffset(idx, jdx, kdx)); } @@ -37,3 +37,40 @@ public: return this->mData->getLength(); } }; + +template +class SerializeableGrid : public Grid +{ +public: + SerializeableGrid(std::size_t itemSize, const Bounds& bounds, std::size_t numPointsX, std::size_t numPointsY, std::size_t numPointsZ = 1) + : Grid(bounds, numPointsX, numPointsY, numPointsZ), + mItemSize(itemSize) + { + } + + uint8_t getByte(std::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, std::size_t bufferMaxSize) + { + std::size_t count{0}; + std::size_t item_count{0}; + while(count < bufferMaxSize && item_count < this->mData->getLength()) + { + const auto& item = this->mData->getItem(item_count); + for(std::size_t idx = 0; idx< item.getSize(); idx++) + { + buffer[count] = item.getByte(idx); + count++; + } + item_count++; + } + } + +private: + std::size_t mItemSize{1}; +}; 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/TermInfo.cpp b/src/console/TermInfo.cpp new file mode 100644 index 0000000..ae0ab7b --- /dev/null +++ b/src/console/TermInfo.cpp @@ -0,0 +1,111 @@ +#include "TermInfo.h" + +#include +#include "File.h" +#include +#include + +bool TermInfo::load_terminfo(const std::string& terminfo_dir, + const std::string& term) +{ + const auto path = std::filesystem::path(terminfo_dir); + if (!std::filesystem::is_directory(path)) + { + return false; + } + + std::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; + } + + std::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; + } + std::vector names; + std::string working_name; + for(std::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..74e7fcf --- /dev/null +++ b/src/console/TermInfo.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +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 std::string& terminfo_dir, + const std::string& term); + + void load(); +}; + + diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..74c9d89 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,43 @@ +#include "Vector.h" +#include "String.h" +#include "FileSystemPath.h" +#include "Directory.h" +#include "File.h" + +#include + +int main() +{ + /* + FileSystemPath main_path(__FILE__); + printf("Starting build.\n"); + + auto main_directory = main_path.parent_path(); + for(const auto& subdir : Directory::getSubdirectories(main_directory)) + { + for(const auto& subsubdir : Directory::getSubdirectories(subdir)) + { + const auto build_file = subsubdir.join("build.toml"); + if (build_file.exists()) + { + printf("Found dir file: %s\n", build_file.as_string().raw()); + // Gather all files + //const auto header_files = Directory::getFilesWithExtension(subsubdir, ".h", true); + //for(const auto& header : header_files) + //{ + // printf("Found header file: %s\n", header.as_string().raw()); + // } + + // Gather all directories + + // Build library + + } + } + } + */ + + printf("Finished build.\n"); + + return 0; +} 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..be331b2 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) +std::unique_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) { - if (!mData) + if (!mGrid) { initialize(); } - if (mDataType == DataType::UCHAR) + assert(indices.size() == colors.size()); + + for (std::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(std::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, std::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..4050000 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 class Color; -class AbstractGrid; template -class Grid; +class SerializeableGrid; class Image { public: - enum class DataType - { - UCHAR - }; - 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 std::unique_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(std::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 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, std::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 > mGrid; std::unique_ptr mPlatformImage; }; diff --git a/src/media/image/ImageBitStream.cpp b/src/media/image/ImageBitStream.cpp index a53df70..75ac0fd 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 +std::vector ImageBitStream::peekNextNBytes(std::size_t) const { return {}; } -std::optional ImageBitStream::readNextByte() +std::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..a759a87 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; + std::vector peekNextNBytes(std::size_t n) const override; - std::optional readNextByte() override; + std::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 std::vector&) override { } diff --git a/src/media/image/Pixel.cpp b/src/media/image/Pixel.cpp new file mode 100644 index 0000000..e69de29 diff --git a/src/media/image/Pixel.h b/src/media/image/Pixel.h new file mode 100644 index 0000000..c5bb43f --- /dev/null +++ b/src/media/image/Pixel.h @@ -0,0 +1,26 @@ +#pragma once + +#include "Color.h" +#include "Serializeable.h" + +class Pixel : public Serializeable +{ +public: + void setColor(const Color& color) + { + mColor = color; + } + + std::size_t getSize() const override + { + return mColor.getSize(); + } + + uint8_t getByte(std::size_t index) const override + { + return mColor.getByte(index); + } + +private: + Color mColor; +}; \ No newline at end of file diff --git a/src/media/image/png/BasicPngWriter.cpp b/src/media/image/png/BasicPngWriter.cpp index c98d300..4ba964e 100644 --- a/src/media/image/png/BasicPngWriter.cpp +++ b/src/media/image/png/BasicPngWriter.cpp @@ -88,13 +88,13 @@ 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); @@ -109,7 +109,7 @@ 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) @@ -128,7 +128,7 @@ 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"); @@ -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; } @@ -158,7 +158,7 @@ void BasicPngWriter::write(const Path& path, Image* image) { std::unique_ptr out_file; - if (path.empty()) + if (!path.empty()) { out_file = std::make_unique(path); out_file->open(File::AccessMode::Write); diff --git a/src/media/image/png/BasicPngWriter.h b/src/media/image/png/BasicPngWriter.h index ee2e051..fd60e91 100644 --- a/src/media/image/png/BasicPngWriter.h +++ b/src/media/image/png/BasicPngWriter.h @@ -22,7 +22,9 @@ public: virtual ~BasicPngWriter(); - static std::unique_ptr Create(); + using Ptr = std::unique_ptr; + + static BasicPngWriter::Ptr Create(); void setCompressionMethod(Deflate::CompressionMethod method); @@ -44,7 +46,7 @@ private: std::unique_ptr mInStream; std::unique_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..1cfadfa 100644 --- a/src/media/image/png/PngHeader.cpp +++ b/src/media/image/png/PngHeader.cpp @@ -10,26 +10,46 @@ std::string PngHeader::toString() const 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 @@ -42,7 +62,7 @@ const std::string& PngHeader::getChunkName() const return mName; } -const std::vector& PngHeader::getData() const +const VecBytes& PngHeader::getData() const { return mData; } @@ -50,9 +70,9 @@ 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); diff --git a/src/media/image/png/PngHeader.h b/src/media/image/png/PngHeader.h index ba96b6b..0f4ff96 100644 --- a/src/media/image/png/PngHeader.h +++ b/src/media/image/png/PngHeader.h @@ -8,35 +8,23 @@ 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; @@ -44,20 +32,20 @@ public: 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; 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"}; - 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..6bc3f53 100644 --- a/src/media/image/png/PngInfo.cpp +++ b/src/media/image/png/PngInfo.cpp @@ -19,23 +19,9 @@ 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 @@ -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,12 +78,12 @@ 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; } diff --git a/src/media/image/png/PngInfo.h b/src/media/image/png/PngInfo.h index d6e1e08..1319ff4 100644 --- a/src/media/image/png/PngInfo.h +++ b/src/media/image/png/PngInfo.h @@ -1,12 +1,14 @@ #pragma once +#include "ByteTypes.h" + #include #include class PngInfo { public: - enum class ColorType : unsigned char + enum class ColorType : Byte { GREYSCALE = 0, RGB = 2, @@ -15,23 +17,23 @@ 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; @@ -41,11 +43,11 @@ public: std::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; diff --git a/src/media/image/png/PngWriter.cpp b/src/media/image/png/PngWriter.cpp index e8744de..c08dbfa 100644 --- a/src/media/image/png/PngWriter.cpp +++ b/src/media/image/png/PngWriter.cpp @@ -26,6 +26,15 @@ std::unique_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..03091c3 100644 --- a/src/media/image/png/PngWriter.h +++ b/src/media/image/png/PngWriter.h @@ -2,6 +2,7 @@ #include "Image.h" #include "IImageWriter.h" +#include "DeflateElements.h" #include #include @@ -14,6 +15,8 @@ public: static std::unique_ptr Create(); + void setCompressionMethod(Deflate::CompressionMethod method); + void write(const Path& path, Image* image) override; private: diff --git a/src/ui/windows/ui_interfaces/wayland/WaylandInterface.cpp b/src/ui/windows/ui_interfaces/wayland/WaylandInterface.cpp index e5f02b9..1cdf19d 100644 --- a/src/ui/windows/ui_interfaces/wayland/WaylandInterface.cpp +++ b/src/ui/windows/ui_interfaces/wayland/WaylandInterface.cpp @@ -12,6 +12,7 @@ #include #include +#include void WaylandInterface::registryHandleGlobalEvent(void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version) @@ -41,6 +42,7 @@ void WaylandInterface::registryHandleGlobalEvent(void *data, struct wl_registry void WaylandInterface::registryHandleGlobalRemoveEvent(void *data, struct wl_registry *registry, uint32_t name) { + std::cout << "remove handler called " << std::endl; (void)data; (void)registry; (void)name; @@ -90,7 +92,7 @@ void WaylandInterface::initialize() addWindow(mDesktopManager->getWindowManager()->getWindow(idx)); } - mDesktopManager->getWindowManager()->getMainWindow()->show(); + mDesktopManager->getWindowManager()->getMainWindow()->show(); } void WaylandInterface::initializeHardwareRendering() diff --git a/src/ui/windows/ui_interfaces/wayland/WaylandSurface.cpp b/src/ui/windows/ui_interfaces/wayland/WaylandSurface.cpp index f3fe6a0..c26e6c9 100644 --- a/src/ui/windows/ui_interfaces/wayland/WaylandSurface.cpp +++ b/src/ui/windows/ui_interfaces/wayland/WaylandSurface.cpp @@ -6,6 +6,8 @@ #include "DrawingContext.h" #include "FontsManager.h" +#include + void WaylandSurface::add(mt::Window* window, wl_compositor* compositor, xdg_wm_base* xdg_wm_base, std::shared_ptr buffer, FontsManager* fontsManager, WaylandEglInterface* eglInterface) { auto wayland_window = std::make_unique(window, compositor, xdg_wm_base, buffer, eglInterface); @@ -78,7 +80,7 @@ void WaylandSurface::initialize() void WaylandSurface::onConfigure(xdg_surface *xdg_surface, uint32_t serial) { xdg_surface_ack_configure(xdg_surface, serial); - beforePaint(nullptr); + mWindow->doPaint(nullptr); } void WaylandSurface::beforePaint(mt::Screen* screen) @@ -124,21 +126,30 @@ void WaylandSurface::beforePaintSoftware() const auto height = mWindow->getHeight(); const int stride = width * mWorkingBitDepth; + std::cout << "before paint" << std::endl; + const int shm_pool_size = getImageBufferSize(); mBuffer->initializeSharedBuffer(shm_pool_size); mBuffer->setUpPool(shm_pool_size, width, height, stride); + //int offset{0}; + + mWindow->getImage()->toBuffer(mBuffer->getPoolData(), width*height*stride, Image::Format::ARGB); + //ImagePrimitives::drawCheckerboard(mBuffer->getPoolData(), width, height, offset); + std::cout << "checkerboard drawn" << std::endl; } void WaylandSurface::afterPaintSoftware() { + std::cout << "after paint" << std::endl; + const int shm_pool_size = getImageBufferSize(); mBuffer->tearDownPool(shm_pool_size); wl_surface_attach(mSurface, mBuffer->getWorkingBuffer(), 0, 0); - //wl_surface_damage(mSurface, 0, 0, UINT32_MAX, UINT32_MAX); + wl_surface_damage(mSurface, 0, 0, UINT32_MAX, UINT32_MAX); wl_surface_commit(mSurface); } diff --git a/src/ui/windows/ui_interfaces/wayland/WaylandSurface.h b/src/ui/windows/ui_interfaces/wayland/WaylandSurface.h index 275e548..ec91148 100644 --- a/src/ui/windows/ui_interfaces/wayland/WaylandSurface.h +++ b/src/ui/windows/ui_interfaces/wayland/WaylandSurface.h @@ -53,7 +53,7 @@ private: unsigned getImageBufferSize() const; - mt::Window* mWindow{nullptr}; + //mt::Window* mWindow{nullptr}; wl_compositor* mCompositor{nullptr}; xdg_wm_base* mXdgWmBase{nullptr}; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3f41db8..d94c95e 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -4,6 +4,7 @@ set(UNIT_TEST_TARGETS) set(INTEGRATION_TEST_TARGETS) add_subdirectory(core) +#add_subdirectory(console) add_subdirectory(database) add_subdirectory(fonts) add_subdirectory(geometry) @@ -18,6 +19,7 @@ set(TEST_MODULES audio compiler compression + console image ipc mesh diff --git a/test/bootstrap_tests.sh b/test/bootstrap_tests.sh new file mode 100755 index 0000000..327deb7 --- /dev/null +++ b/test/bootstrap_tests.sh @@ -0,0 +1,23 @@ +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +CORE_SRC_DIR=$SCRIPT_DIR/../src/base/core + +g++ $SCRIPT_DIR/test_runner.cpp \ + $SCRIPT_DIR/../src/base/core/CommandLineArgs.cpp \ + $CORE_SRC_DIR/base_types/Error.cpp \ + $CORE_SRC_DIR/base_types/Index.cpp \ + $CORE_SRC_DIR/data_structures/String.cpp \ + $CORE_SRC_DIR/file_utilities/FileSystemPath.cpp \ + $CORE_SRC_DIR/loggers/ConsoleLogger.cpp \ + $SCRIPT_DIR/test_utils/TestCaseRunner.cpp \ + $SCRIPT_DIR/core/TestString.cpp \ + $SCRIPT_DIR/core/TestVector.cpp \ + -o bootstrap_tests -g \ + -I$SCRIPT_DIR/test_utils \ + -I$CORE_SRC_DIR \ + -I$CORE_SRC_DIR/encoding \ + -I$CORE_SRC_DIR/loggers \ + -I$CORE_SRC_DIR/data_structures \ + -I$CORE_SRC_DIR/base_types \ + -I$CORE_SRC_DIR/memory \ + -I$CORE_SRC_DIR/file_utilities \ No newline at end of file diff --git a/test/console/CMakeLists.txt b/test/console/CMakeLists.txt new file mode 100644 index 0000000..bae7845 --- /dev/null +++ b/test/console/CMakeLists.txt @@ -0,0 +1,9 @@ +include(TestTargets) + +unit_tests( + MODULE_NAME console + FILES + TestConsoleApp.cpp + DEPENDENCIES + console +) diff --git a/test/console/TestConsoleApp.cpp b/test/console/TestConsoleApp.cpp new file mode 100644 index 0000000..bb15f0b --- /dev/null +++ b/test/console/TestConsoleApp.cpp @@ -0,0 +1,93 @@ +#include "TestFramework.h" +#include "TestUtils.h" + +#include "TermInfo.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +TEST_CASE(TestConsoleApp, "console") +{ + //std::cout << "Hi from test console\n"; + + int ttyfd = open("/dev/tty", O_RDWR); + if (ttyfd > 0) + { + std::cout << "opened tty ok\n" << std::endl; + } + + if (isatty(ttyfd)) + { + auto tty_name = ttyname(ttyfd); + std::string tty_name_str; + if (tty_name != nullptr) + { + tty_name_str = std::string(tty_name); + } + + std::string fd_msg = "Hello tty: '" + tty_name_str + "'\n"; + //write(ttyfd, fd_msg.data(), fd_msg.size()); + + TermInfo term_info; + term_info.load(); + /* + + termios orig_tios; + tcgetattr(ttyfd, &orig_tios); + + termios tios; + memcpy(&tios, &orig_tios, sizeof(tios)); + + cfmakeraw(&tios); + tios.c_cc[VMIN] = 1; + tios.c_cc[VTIME] = 0; + + tcsetattr(ttyfd, TCSAFLUSH, &tios); + + //int cap_enter_ca = 23; + //int cap_exit_ca = 24; + //int cap_hide_cursor = 26; + //int cap_clear_screen = 27; + + + fd_set fds; + FD_ZERO(&fds); + + int timeout = 2000; + timeval tv; + tv.tv_sec = timeout/1000; + tv.tv_usec = (timeout - (tv.tv_sec*1000))*1000; + + while(true) + { + + int select_rv = select(1, &fds, nullptr, nullptr, &tv); + + if (select_rv == 0) + { + std::cout << "timeout" << std::endl; + break; + } + std::vector buffer(100); + auto read_size = read(ttyfd, buffer.data(), buffer.size()); + std::string out(buffer.begin(), buffer.begin()+read_size); + std::cout << "buf: " << out << std::endl; + } + std::cout << "loop break" << std::endl; + tcsetattr(ttyfd, TCSAFLUSH, &orig_tios); + */ + + } + + close(ttyfd); +} diff --git a/test/core/TestStringUtils.cpp b/test/core/TestString.cpp similarity index 57% rename from test/core/TestStringUtils.cpp rename to test/core/TestString.cpp index 7c7e005..5441d79 100644 --- a/test/core/TestStringUtils.cpp +++ b/test/core/TestString.cpp @@ -1,8 +1,43 @@ -#include "StringUtils.h" +#include "String.h" #include "TestFramework.h" -#include "TestUtils.h" +//#include "TestUtils.h" +#include +TEST_CASE(TestBasicStringOps, "core") +{ + String str; + str += 'a'; + str += 'b'; + str += 'c'; + str += 'd'; + REQUIRE(str == "abcd"); +} + +TEST_CASE(TestStringReverse, "core") +{ + String str0; + str0.reverse(); + REQUIRE(str0.empty()); + + String str1("a"); + str1.reverse(); + REQUIRE(str1 == "a"); + + String str2("ab"); + str2.reverse(); + REQUIRE(str2 == "ba"); + + String str3("abc"); + str3.reverse(); + REQUIRE(str3 == "cba"); + + String str4("abcd"); + str4.reverse(); + REQUIRE(str4 == "dcba"); +} + +/* TEST_CASE(TestStringUtils_StripSurroundingWhitepsace, "core") { std::string input = " super() "; @@ -28,3 +63,5 @@ TEST_CASE(TestStringUtils_startsWith, "core") starts_with = StringUtils::startsWith(input, "```", ignore_whitespace); REQUIRE(starts_with); } + +*/ diff --git a/test/core/TestVector.cpp b/test/core/TestVector.cpp new file mode 100644 index 0000000..938676a --- /dev/null +++ b/test/core/TestVector.cpp @@ -0,0 +1,18 @@ +#include "Vector.h" + +#include "TestFramework.h" + +#include + +TEST_CASE(TestVectorOps, "core") +{ + Vector vec; + for(size_t idx=0;idx<100;idx++) + { + vec.push_back(idx); + } + for(size_t idx=0; idx<100; idx++) + { + REQUIRE(vec[idx] == idx); + } +} diff --git a/test/image/TestPngWriter.cpp b/test/image/TestPngWriter.cpp index 3db10b3..a340064 100644 --- a/test/image/TestPngWriter.cpp +++ b/test/image/TestPngWriter.cpp @@ -11,7 +11,7 @@ #include "TestUtils.h" #include -TEST_CASE(TestCompressedPng, "image") +TEST_CASE(TestUncompressedPng, "image") { unsigned width = 20; unsigned height = 20; @@ -30,13 +30,14 @@ TEST_CASE(TestCompressedPng, "image") image->getGridT()->setData(data); PngWriter writer; - //writer.setCompressionMethod(Deflate::CompressionMethod::NONE); - writer.write(TestUtils::getTestOutputDir() / "test_compressed.png", image.get()); + writer.setCompressionMethod(Deflate::CompressionMethod::NONE); + writer.write(TestUtils::getTestOutputDir(__FILE__) / "test_uncompressed.png", image.get()); - return; - File test_file(TestUtils::getTestOutputDir() / "test_compressed.png"); + File test_file(TestUtils::getTestOutputDir(__FILE__) / "test_uncompressed.png"); test_file.open(File::AccessMode::Read); + std::cout << test_file.dumpBinary(); + return; while(auto byte = test_file.readNextByte()) { //std::cout << static_cast(*byte) << std::endl; @@ -63,13 +64,8 @@ TEST_CASE(TestFixedPng, "image") image->getGridT()->setData(data); PngWriter writer; - //writer.setCompressionMethod(Deflate::CompressionMethod::FIXED_HUFFMAN); - writer.write(TestUtils::getTestOutputDir() / "test_fixed.png", image.get()); - - //return; - File test_file(TestUtils::getTestOutputDir() / "test_fixed.png"); - //std::cout << test_file.dumpBinary(); - + writer.setCompressionMethod(Deflate::CompressionMethod::FIXED_HUFFMAN); + writer.write(TestUtils::getTestOutputDir(__FILE__) / "test_fixed.png", image.get()); } TEST_CASE(TestDynamicCompressedPng, "image") @@ -93,9 +89,9 @@ TEST_CASE(TestDynamicCompressedPng, "image") PngWriter writer; //writer.setPath(TestUtils::getTestOutputDir() / "test_dynamic.png"); - writer.write(TestUtils::getTestOutputDir() / "test_dynamic.png", image.get()); + writer.write(TestUtils::getTestOutputDir(__FILE__) / "test_dynamic.png", image.get()); //return; - File test_file(TestUtils::getTestOutputDir() / "test_dynamic.png"); + File test_file(TestUtils::getTestOutputDir(__FILE__) / "test_dynamic.png"); //std::cout << test_file.dumpBinary(); } diff --git a/test/test_runner.cpp b/test/test_runner.cpp index b2cb3f7..30ab10f 100644 --- a/test/test_runner.cpp +++ b/test/test_runner.cpp @@ -1,6 +1,7 @@ #include "TestFramework.h" #include "CommandLineArgs.h" +#include "ConsoleLogger.h" #ifdef _WIN32 #include @@ -13,10 +14,12 @@ int main(int argc, char *argv[]) CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); #endif - auto args = CommandLineArgs::Create(); - args->process(argc, argv); + CommandLineArgs args; + args.process(argc, argv); - TestCaseRunner::getInstance().run(args->getUserArgs()); + ConsoleLogger::logLine("Starting test run."); + TestCaseRunner::getInstance().run(args.getUserArgs()); + ConsoleLogger::logLine("Finished test run."); #ifdef _WIN32 CoUninitialize(); diff --git a/test/test_utils/TestCase.h b/test/test_utils/TestCase.h index 1a01a45..21df33c 100644 --- a/test/test_utils/TestCase.h +++ b/test/test_utils/TestCase.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "String.h" +#include "Pointer.h" #include class TestCase @@ -9,7 +9,7 @@ class TestCase public: using TestCaseFunction = std::function; - TestCase(const std::string& name, const std::string& tags, TestCaseFunction func) + TestCase(const String& name, const String& tags, TestCaseFunction func) : mTestFunction(func), mName(name), mTags(tags) @@ -19,12 +19,12 @@ public: virtual ~TestCase() = default; - const std::string& getName() const + const String& getName() const { return mName; } - const std::string& getTags() const + const String& getTags() const { return mTags; } @@ -38,8 +38,8 @@ public: TestCaseFunction mTestFunction{nullptr}; private: - std::string mName; - std::string mTags; + String mName; + String mTags; }; -using TestCasePtr = std::unique_ptr; +using TestCasePtr = Ptr; diff --git a/test/test_utils/TestCaseRunner.cpp b/test/test_utils/TestCaseRunner.cpp index 8d5ffc2..0979866 100644 --- a/test/test_utils/TestCaseRunner.cpp +++ b/test/test_utils/TestCaseRunner.cpp @@ -1,13 +1,11 @@ #include "TestCaseRunner.h" #include "FileLogger.h" -#include "TestUiApplication.h" - -#include -#include +#include "ConsoleLogger.h" +//#include "TestUiApplication.h" bool TestCaseRunner::sLastTestFailed = false; -std::string TestCaseRunner::sFailureLine = {}; +String TestCaseRunner::sFailureLine = {}; TestCaseRunner::TestCaseRunner() { @@ -19,6 +17,7 @@ TestCaseRunner::~TestCaseRunner() } +/* TestUiApplication* TestCaseRunner::getTestApplication() { return mTestApplication; @@ -28,6 +27,7 @@ void TestCaseRunner::setTestApplication(TestUiApplication* app) { mTestApplication = app; } +*/ TestCaseRunner& TestCaseRunner::getInstance() { @@ -35,26 +35,26 @@ TestCaseRunner& TestCaseRunner::getInstance() return instance; } -void TestCaseRunner::addTestCase(const std::string& label, const std::string& tag, TestCase::TestCaseFunction func) +void TestCaseRunner::addTestCase(const String& label, const String& tag, TestCase::TestCaseFunction func) { auto test_case = new TestCase(label, tag, func); mCases.push_back(test_case); } -void TestCaseRunner::markTestFailure(const std::string& line) +void TestCaseRunner::markTestFailure(const String& line) { sLastTestFailed = true; sFailureLine = line; } -bool TestCaseRunner::run(const std::vector& args) +bool TestCaseRunner::run(const Vector& args) { - std::string test_to_run; + String test_to_run; if (args.size() > 0 ) { test_to_run = args[0]; } - FileLogger::GetInstance().disable(); + //FileLogger::GetInstance().disable(); for (auto test_case : mCases) { if (!test_to_run.empty()) @@ -66,41 +66,22 @@ bool TestCaseRunner::run(const std::vector& args) } sLastTestFailed = false; - std::cout << "TestFramework: Running Test - " << test_case->getName() << std::endl; - - try - { - test_case->run(); - } - catch (const std::runtime_error& re) - { - std::cout << "Failed with runtime error: " << re.what() << std::endl; - mFailingTests.push_back(test_case->getName()); - } - catch (const std::exception& e) - { - std::cout << "Failed with exception: " << e.what() << std::endl; - mFailingTests.push_back(test_case->getName()); - } - catch(...) - { - std::cout << "Failed with unknown exception" << std::endl; - mFailingTests.push_back(test_case->getName()); - }; - + ConsoleLogger::logLine("TestFramework: Running Test - %s", test_case->getName().raw()); + test_case->run(); + if (sLastTestFailed) { - std::cout << "Failed at line: " << sFailureLine << std::endl; + ConsoleLogger::logLine("Failed at line %s", sFailureLine.raw()); mFailingTests.push_back(test_case->getName()); } } if (mFailingTests.size() > 0) { - std::cout << mFailingTests.size() << " failing tests: " << std::endl; + ConsoleLogger::logLine("%d failing tests", mFailingTests.size()); for(const auto& name : mFailingTests) { - std::cout << name << std::endl; + ConsoleLogger::logLine(name); } } diff --git a/test/test_utils/TestCaseRunner.h b/test/test_utils/TestCaseRunner.h index e44b20e..9b7135b 100644 --- a/test/test_utils/TestCaseRunner.h +++ b/test/test_utils/TestCaseRunner.h @@ -2,8 +2,8 @@ #include "TestCase.h" -#include -#include +#include "Vector.h" +#include "String.h" class TestUiApplication; @@ -16,20 +16,20 @@ public: ~TestCaseRunner(); - TestUiApplication* getTestApplication(); + //TestUiApplication* getTestApplication(); - void addTestCase(const std::string& label, const std::string& tag, TestCase::TestCaseFunction func); + void addTestCase(const String& label, const String& tag, TestCase::TestCaseFunction func); - void markTestFailure(const std::string& line); + void markTestFailure(const String& line); - bool run(const std::vector& args); + bool run(const Vector& args); - void setTestApplication(TestUiApplication* app); + //void setTestApplication(TestUiApplication* app); private: - TestUiApplication* mTestApplication{ nullptr }; - std::vector mFailingTests; + //TestUiApplication* mTestApplication{ nullptr }; + Vector mFailingTests; static bool sLastTestFailed; - static std::string sFailureLine; - std::vector mCases; + static String sFailureLine; + Vector mCases; }; diff --git a/test/test_utils/TestFramework.h b/test/test_utils/TestFramework.h index 7e86d06..68755ad 100644 --- a/test/test_utils/TestFramework.h +++ b/test/test_utils/TestFramework.h @@ -4,7 +4,7 @@ struct Holder { - Holder(const std::string& name, const std::string& tags, std::function func) + Holder(const String& name, const String& tags, std::function func) { TestCaseRunner::getInstance().addTestCase(name, tags, func); } @@ -19,8 +19,8 @@ struct Holder #define REQUIRE(predicate) \ if(!bool(predicate)) \ { \ - TestCaseRunner::getInstance().markTestFailure(std::to_string(__LINE__) + " with check: '" + std::string(#predicate) + "'"); \ - return; \ + const auto msg = String::to_string(__LINE__) + String(" with check: '") + String(#predicate) + String("'"); \ + TestCaseRunner::getInstance().markTestFailure(msg); \ } \ diff --git a/test/test_utils/TestUtils.h b/test/test_utils/TestUtils.h index 43e0ab8..d1d892d 100644 --- a/test/test_utils/TestUtils.h +++ b/test/test_utils/TestUtils.h @@ -1,6 +1,6 @@ #pragma once -#include "TestDataLocations.h" +//#include "TestDataLocations.h" #include diff --git a/test/windows/TestWaylandWindow.cpp b/test/windows/TestWaylandWindow.cpp index 861b1de..ac71c0a 100644 --- a/test/windows/TestWaylandWindow.cpp +++ b/test/windows/TestWaylandWindow.cpp @@ -16,5 +16,5 @@ TEST_CASE(TestWaylandWindow, "web") //app->setUiInterfaceBackend(UiInterfaceFactory::Backend::WAYLAND); app->setUiInterfaceBackend(UiInterfaceFactory::Backend::WAYLAND_RASTER); - app->run(); + //app->run(); } From 521486be62b2160dd70998c0028e0966ff45ff69 Mon Sep 17 00:00:00 2001 From: jmsgrogan Date: Wed, 20 Dec 2023 16:58:22 +0000 Subject: [PATCH 03/10] Start working on build system. --- bootstrap.sh | 36 ++-- src/base/compiler/BuildLibrary.cpp | 25 +++ src/base/compiler/BuildLibrary.h | 22 +++ src/base/compiler/BuildSession.cpp | 73 +++++++ src/base/compiler/BuildSession.h | 24 +++ src/base/core/{ => base_types}/Color.cpp | 0 src/base/core/{ => base_types}/Color.h | 0 src/base/core/base_types/Error.cpp | 32 +++ src/base/core/base_types/Error.h | 45 +++++ src/base/core/base_types/Result.h | 13 +- .../core/{ => data_structures}/Dictionary.cpp | 0 .../core/{ => data_structures}/Dictionary.h | 0 src/base/core/data_structures/RawTree.cpp | 0 src/base/core/data_structures/String.cpp | 80 ++++++-- src/base/core/data_structures/String.h | 19 +- src/base/core/data_structures/Tree.cpp | 0 src/base/core/data_structures/Vector.cpp | 0 src/base/core/data_structures/Vector.h | 56 +++--- src/base/core/{ => events}/Event.cpp | 0 src/base/core/{ => events}/Event.h | 0 src/base/core/file_utilities/Directory.cpp | 94 --------- src/base/core/file_utilities/Directory.h | 16 -- src/base/core/filesystem/Directory.cpp | 128 ++++++++++++ src/base/core/filesystem/Directory.h | 24 +++ .../{file_utilities => filesystem}/File.cpp | 186 +++++++++++++----- .../{file_utilities => filesystem}/File.h | 16 +- .../FileFormats.cpp | 0 .../FileFormats.h | 0 .../FileSystemPath.cpp | 83 ++++++-- .../FileSystemPath.h | 14 +- .../PathUtils.cpp | 0 .../PathUtils.h | 0 src/base/core/loggers/ConsoleLogger.cpp | 17 -- src/base/core/loggers/ConsoleLogger.h | 11 -- src/base/core/logging/ConsoleLogger.cpp | 24 +++ src/base/core/logging/ConsoleLogger.h | 13 ++ .../core/{loggers => logging}/FileLogger.cpp | 0 .../core/{loggers => logging}/FileLogger.h | 7 - src/base/core/logging/Logger.cpp | 48 +++++ src/base/core/logging/Logger.h | 36 ++++ src/base/core/memory/Allocator.cpp | 0 src/base/core/memory/Allocator.h | 2 +- src/base/core/memory/Pointer.h | 24 ++- .../core/{http => protocol}/HttpHeader.cpp | 0 src/base/core/{http => protocol}/HttpHeader.h | 0 .../core/{http => protocol}/HttpParser.cpp | 0 src/base/core/{http => protocol}/HttpParser.h | 0 .../core/{http => protocol}/HttpPreamble.h | 0 .../core/{http => protocol}/HttpRequest.cpp | 0 .../core/{http => protocol}/HttpRequest.h | 0 .../core/{http => protocol}/HttpResponse.cpp | 0 .../core/{http => protocol}/HttpResponse.h | 0 src/base/core/{ => random}/RandomUtils.cpp | 0 src/base/core/{ => random}/RandomUtils.h | 0 .../{ => serialization}/AbstractNamedItem.h | 0 .../core/{ => serialization}/Serializeable.h | 0 .../TomlReader.cpp | 0 .../TomlReader.h | 0 .../{ => serialization}/xml/XmlDocument.cpp | 0 .../{ => serialization}/xml/XmlDocument.h | 0 .../{ => serialization}/xml/XmlParser.cpp | 0 .../core/{ => serialization}/xml/XmlParser.h | 0 .../{ => serialization}/xml/XmlWriter.cpp | 0 .../core/{ => serialization}/xml/XmlWriter.h | 0 .../xml/xml-elements/XmlAttribute.cpp | 0 .../xml/xml-elements/XmlAttribute.h | 0 .../xml/xml-elements/XmlElement.cpp | 0 .../xml/xml-elements/XmlElement.h | 0 .../xml/xml-elements/XmlProlog.cpp | 0 .../xml/xml-elements/XmlProlog.h | 0 .../core/{ => system}/Win32BaseIncludes.h | 0 .../core/{ => system/process}/AbstractApp.h | 0 .../{ => system/process}/AbstractWebApp.h | 0 .../{ => system/process}/CommandLineArgs.cpp | 4 +- .../{ => system/process}/CommandLineArgs.h | 0 src/base/core/system/process/Process.h | 40 ++++ .../core/{ => thread}/ThreadCollection.cpp | 0 src/base/core/{ => thread}/ThreadCollection.h | 0 src/base/core/time/Time.cpp | 29 +++ src/base/core/time/Time.h | 9 + src/main.cpp | 45 +---- test/bootstrap_tests.sh | 17 +- test/core/TestFileSystemPath.cpp | 18 ++ test/core/TestString.cpp | 34 +++- test/core/TestVector.cpp | 31 ++- test/test_runner.cpp | 6 +- test/test_utils/TestCaseRunner.cpp | 10 +- test/test_utils/TestFramework.h | 3 +- 88 files changed, 1065 insertions(+), 349 deletions(-) create mode 100644 src/base/compiler/BuildLibrary.cpp create mode 100644 src/base/compiler/BuildLibrary.h create mode 100644 src/base/compiler/BuildSession.cpp create mode 100644 src/base/compiler/BuildSession.h rename src/base/core/{ => base_types}/Color.cpp (100%) rename src/base/core/{ => base_types}/Color.h (100%) rename src/base/core/{ => data_structures}/Dictionary.cpp (100%) rename src/base/core/{ => data_structures}/Dictionary.h (100%) delete mode 100644 src/base/core/data_structures/RawTree.cpp delete mode 100644 src/base/core/data_structures/Tree.cpp delete mode 100644 src/base/core/data_structures/Vector.cpp rename src/base/core/{ => events}/Event.cpp (100%) rename src/base/core/{ => events}/Event.h (100%) delete mode 100644 src/base/core/file_utilities/Directory.cpp delete mode 100644 src/base/core/file_utilities/Directory.h create mode 100644 src/base/core/filesystem/Directory.cpp create mode 100644 src/base/core/filesystem/Directory.h rename src/base/core/{file_utilities => filesystem}/File.cpp (52%) rename src/base/core/{file_utilities => filesystem}/File.h (64%) rename src/base/core/{file_utilities => filesystem}/FileFormats.cpp (100%) rename src/base/core/{file_utilities => filesystem}/FileFormats.h (100%) rename src/base/core/{file_utilities => filesystem}/FileSystemPath.cpp (50%) rename src/base/core/{file_utilities => filesystem}/FileSystemPath.h (62%) rename src/base/core/{file_utilities => filesystem}/PathUtils.cpp (100%) rename src/base/core/{file_utilities => filesystem}/PathUtils.h (100%) delete mode 100644 src/base/core/loggers/ConsoleLogger.cpp delete mode 100644 src/base/core/loggers/ConsoleLogger.h create mode 100644 src/base/core/logging/ConsoleLogger.cpp create mode 100644 src/base/core/logging/ConsoleLogger.h rename src/base/core/{loggers => logging}/FileLogger.cpp (100%) rename src/base/core/{loggers => logging}/FileLogger.h (71%) create mode 100644 src/base/core/logging/Logger.cpp create mode 100644 src/base/core/logging/Logger.h delete mode 100644 src/base/core/memory/Allocator.cpp rename src/base/core/{http => protocol}/HttpHeader.cpp (100%) rename src/base/core/{http => protocol}/HttpHeader.h (100%) rename src/base/core/{http => protocol}/HttpParser.cpp (100%) rename src/base/core/{http => protocol}/HttpParser.h (100%) rename src/base/core/{http => protocol}/HttpPreamble.h (100%) rename src/base/core/{http => protocol}/HttpRequest.cpp (100%) rename src/base/core/{http => protocol}/HttpRequest.h (100%) rename src/base/core/{http => protocol}/HttpResponse.cpp (100%) rename src/base/core/{http => protocol}/HttpResponse.h (100%) rename src/base/core/{ => random}/RandomUtils.cpp (100%) rename src/base/core/{ => random}/RandomUtils.h (100%) rename src/base/core/{ => serialization}/AbstractNamedItem.h (100%) rename src/base/core/{ => serialization}/Serializeable.h (100%) rename src/base/core/{serializers => serialization}/TomlReader.cpp (100%) rename src/base/core/{serializers => serialization}/TomlReader.h (100%) rename src/base/core/{ => serialization}/xml/XmlDocument.cpp (100%) rename src/base/core/{ => serialization}/xml/XmlDocument.h (100%) rename src/base/core/{ => serialization}/xml/XmlParser.cpp (100%) rename src/base/core/{ => serialization}/xml/XmlParser.h (100%) rename src/base/core/{ => serialization}/xml/XmlWriter.cpp (100%) rename src/base/core/{ => serialization}/xml/XmlWriter.h (100%) rename src/base/core/{ => serialization}/xml/xml-elements/XmlAttribute.cpp (100%) rename src/base/core/{ => serialization}/xml/xml-elements/XmlAttribute.h (100%) rename src/base/core/{ => serialization}/xml/xml-elements/XmlElement.cpp (100%) rename src/base/core/{ => serialization}/xml/xml-elements/XmlElement.h (100%) rename src/base/core/{ => serialization}/xml/xml-elements/XmlProlog.cpp (100%) rename src/base/core/{ => serialization}/xml/xml-elements/XmlProlog.h (100%) rename src/base/core/{ => system}/Win32BaseIncludes.h (100%) rename src/base/core/{ => system/process}/AbstractApp.h (100%) rename src/base/core/{ => system/process}/AbstractWebApp.h (100%) rename src/base/core/{ => system/process}/CommandLineArgs.cpp (94%) rename src/base/core/{ => system/process}/CommandLineArgs.h (100%) create mode 100644 src/base/core/system/process/Process.h rename src/base/core/{ => thread}/ThreadCollection.cpp (100%) rename src/base/core/{ => thread}/ThreadCollection.h (100%) create mode 100644 src/base/core/time/Time.cpp create mode 100644 src/base/core/time/Time.h create mode 100644 test/core/TestFileSystemPath.cpp diff --git a/bootstrap.sh b/bootstrap.sh index addd2f6..09e9459 100755 --- a/bootstrap.sh +++ b/bootstrap.sh @@ -2,19 +2,29 @@ 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 \ - $SOURCE_DIR/base/core/base_types/Error.cpp \ - $SOURCE_DIR/base/core/base_types/Index.cpp \ - $SOURCE_DIR/base/core/data_structures/String.cpp \ - $SOURCE_DIR/base/core/file_utilities/FileSystemPath.cpp \ - $SOURCE_DIR/base/core/file_utilities/File.cpp \ - $SOURCE_DIR/base/core/file_utilities/Directory.cpp \ - $SOURCE_DIR/base/core/encoding/CharUtils.cpp \ + $CORE_SRC_DIR/base_types/Error.cpp \ + $CORE_SRC_DIR/base_types/Index.cpp \ + $SOURCE_DIR/base/compiler/BuildLibrary.cpp \ + $SOURCE_DIR/base/compiler/BuildSession.cpp \ + $CORE_SRC_DIR/data_structures/String.cpp \ + $CORE_SRC_DIR/encoding/CharUtils.cpp \ + $CORE_SRC_DIR/filesystem/FileSystemPath.cpp \ + $CORE_SRC_DIR/filesystem/File.cpp \ + $CORE_SRC_DIR/filesystem/Directory.cpp \ + $CORE_SRC_DIR/logging/ConsoleLogger.cpp \ + $CORE_SRC_DIR/logging/Logger.cpp \ + $CORE_SRC_DIR/time/Time.cpp \ -o builder -g -fno-exceptions -fno-rtti \ - -I$SOURCE_DIR/base/core/data_structures \ - -I$SOURCE_DIR/base/core/base_types \ - -I$SOURCE_DIR/base/core/memory \ - -I$SOURCE_DIR/base/core/loggers \ - -I$SOURCE_DIR/base/core/encoding \ - -I$SOURCE_DIR/base/core/file_utilities + -I$CORE_SRC_DIR/base_types \ + -I$SOURCE_DIR/base/compiler \ + -I$CORE_SRC_DIR/data_structures \ + -I$CORE_SRC_DIR/encoding \ + -I$CORE_SRC_DIR/filesystem \ + -I$CORE_SRC_DIR/logging \ + -I$CORE_SRC_DIR/memory \ + -I$CORE_SRC_DIR/system/process \ + -I$CORE_SRC_DIR/time + diff --git a/src/base/compiler/BuildLibrary.cpp b/src/base/compiler/BuildLibrary.cpp new file mode 100644 index 0000000..ffd7cc9 --- /dev/null +++ b/src/base/compiler/BuildLibrary.cpp @@ -0,0 +1,25 @@ +#include "BuildLibrary.h" + +#include "Logger.h" +#include "Directory.h" + +BuildLibrary::BuildLibrary(const FileSystemPath& build_config) + : m_build_config(build_config) +{ +} + +Status BuildLibrary::scan() +{ + LOG_INFO("Scanning build file at: " << m_build_config); + const auto search_dir = m_build_config.parent_path(); + const auto status = Directory::getFilesWithExtension(search_dir, + ".cpp", + m_sources, + true); + return status; +} + +const Vector& BuildLibrary::get_sources() const +{ + return m_sources; +} \ No newline at end of file diff --git a/src/base/compiler/BuildLibrary.h b/src/base/compiler/BuildLibrary.h new file mode 100644 index 0000000..f1777b1 --- /dev/null +++ b/src/base/compiler/BuildLibrary.h @@ -0,0 +1,22 @@ +#pragma once + +#include "FileSystemPath.h" +#include "String.h" + +class BuildLibrary +{ +public: + BuildLibrary() = default; + + BuildLibrary(const FileSystemPath& build_config); + + Status scan(); + + const Vector& get_sources() const; + +private: + FileSystemPath m_build_config; + Vector m_sources; + Vector m_includes; + String m_name; +}; \ No newline at end of file diff --git a/src/base/compiler/BuildSession.cpp b/src/base/compiler/BuildSession.cpp new file mode 100644 index 0000000..257bde8 --- /dev/null +++ b/src/base/compiler/BuildSession.cpp @@ -0,0 +1,73 @@ +#include "BuildSession.h" + +#include "Logger.h" +#include "Process.h" +#include "Directory.h" + +BuildSession::BuildSession(const String& source_dir, + const String& build_dir) + : m_source_dir(source_dir) +{ + if (build_dir.empty()) + { + m_build_dir = FileSystemPath::current_dir().value(); + } + else + { + m_build_dir = build_dir; + } +} + +Status BuildSession::scan() +{ + LOG_INFO("Scanning sources at:" << m_source_dir); + Vector toml_files; + STATUS_CHECK(Directory::getFilesWithExtension( + m_source_dir, + ".toml", + toml_files, + true), "Error looking for build files"); + + for(const auto& toml_file : toml_files) + { + if (toml_file.file_name() == "build") + { + STATUS_CHECK(add_library(toml_file), + "Error adding library"); + } + } + return {}; + +} + +Status BuildSession::add_library(const FileSystemPath& config_path) +{ + LOG_INFO("Adding library at: " << config_path); + BuildLibrary lib(config_path); + STATUS_CHECK(lib.scan(), "Error scanning library"); + m_libraries.push_back(lib); + return {}; +} + +Status BuildSession::build() +{ + for(const auto& library : m_libraries) + { + for(const auto& source : library.get_sources()) + { + String compiler_command = m_compiler_command + " -c "; + compiler_command += source.str() + " "; + LOG_INFO("Running command: " << compiler_command); + + const auto self_name = Process::get_self_name(); + if (!self_name.ok()) + { + return Status(self_name.error()); + } + LOG_INFO("Self name is: " << self_name.value()); + break; + } + break; + } + return {}; +} \ No newline at end of file diff --git a/src/base/compiler/BuildSession.h b/src/base/compiler/BuildSession.h new file mode 100644 index 0000000..c5bdf89 --- /dev/null +++ b/src/base/compiler/BuildSession.h @@ -0,0 +1,24 @@ +#pragma once + +#include "BuildLibrary.h" +#include "Error.h" + +class BuildSession +{ +public: + BuildSession(const String& source_dir, + const String& build_dir = {}); + + Status scan(); + + Status build(); + + Status add_library(const FileSystemPath& config_path); + +private: + String m_compiler_command{"g++"}; + String m_compiler_flags{"-g -fno-exceptions -fno-rtti"}; + FileSystemPath m_source_dir; + FileSystemPath m_build_dir; + Vector m_libraries; +}; \ No newline at end of file diff --git a/src/base/core/Color.cpp b/src/base/core/base_types/Color.cpp similarity index 100% rename from src/base/core/Color.cpp rename to src/base/core/base_types/Color.cpp diff --git a/src/base/core/Color.h b/src/base/core/base_types/Color.h similarity index 100% rename from src/base/core/Color.h rename to src/base/core/base_types/Color.h diff --git a/src/base/core/base_types/Error.cpp b/src/base/core/base_types/Error.cpp index 919b9d5..2ecbb09 100644 --- a/src/base/core/base_types/Error.cpp +++ b/src/base/core/base_types/Error.cpp @@ -1,5 +1,8 @@ #include "Error.h" +#include +#include + Error::Error(const String& msg) : m_message(msg) { @@ -8,4 +11,33 @@ Error::Error(const String& 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) +{ + +} + +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; } \ No newline at end of file diff --git a/src/base/core/base_types/Error.h b/src/base/core/base_types/Error.h index 9339664..8944ed8 100644 --- a/src/base/core/base_types/Error.h +++ b/src/base/core/base_types/Error.h @@ -2,6 +2,31 @@ #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: @@ -10,6 +35,26 @@ public: Error() = default; const String& msg() const; + + static String from_errno(); private: String m_message; +}; + +class Status +{ +public: + Status() = default; + + Status(const Error& err); + + void on_errno(const String& prefix_msg); + + const Error& error() const; + + bool ok() const; + +private: + Error m_error; + bool m_ok{true}; }; \ No newline at end of file diff --git a/src/base/core/base_types/Result.h b/src/base/core/base_types/Result.h index 1ae75cc..bac9d7b 100644 --- a/src/base/core/base_types/Result.h +++ b/src/base/core/base_types/Result.h @@ -6,7 +6,7 @@ template class Result { public: - Result(const T& val) + Result(const T& val = T()) : m_value(val) { @@ -19,6 +19,12 @@ public: } + void on_error(const Error& error) + { + m_error = error; + m_ok = false; + } + const Error& error() const { return m_error; @@ -34,6 +40,11 @@ public: return m_value; } + T& value() + { + return m_value; + } + private: T m_value; Error m_error; diff --git a/src/base/core/Dictionary.cpp b/src/base/core/data_structures/Dictionary.cpp similarity index 100% rename from src/base/core/Dictionary.cpp rename to src/base/core/data_structures/Dictionary.cpp diff --git a/src/base/core/Dictionary.h b/src/base/core/data_structures/Dictionary.h similarity index 100% rename from src/base/core/Dictionary.h rename to src/base/core/data_structures/Dictionary.h diff --git a/src/base/core/data_structures/RawTree.cpp b/src/base/core/data_structures/RawTree.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/base/core/data_structures/String.cpp b/src/base/core/data_structures/String.cpp index 6d509c5..bb020dc 100644 --- a/src/base/core/data_structures/String.cpp +++ b/src/base/core/data_structures/String.cpp @@ -1,6 +1,7 @@ #include "String.h" #include +#include String::String() { @@ -17,6 +18,49 @@ String::String(const char* data) append(data); } +String String::fmt(const char* fmt, ...) +{ + String ret; + + va_list args; + va_start(args, fmt); + + char format_delim = '%'; + bool in_format = false; + while(*fmt != '\0') + { + if (*fmt == format_delim) + { + in_format = true; + } + else if(in_format && *fmt == 's') + { + in_format = false; + const auto s = va_arg(args, char*); + ret.append(s); + } + else if(in_format && *fmt == 'd') + { + in_format = false; + const auto i = va_arg(args, int); + ret += to_string(i); + } + else if(in_format && *fmt == 'c') + { + in_format = false; + const auto c = va_arg(args, int); + ret +=c; + } + else + { + ret += *fmt; + } + ++fmt; + } + va_end(args); + return ret; +} + void String::append(const char* data) { if (data == nullptr) @@ -26,9 +70,18 @@ void String::append(const char* data) } auto loc = data; + bool first=true; while(*loc != '\0') { - m_data.push_back(*loc); + if (!m_data.empty() && first) + { + m_data[m_data.size() - 1] = *loc; + } + else + { + m_data.push_back(*loc); + } + first = false; loc++; } m_data.push_back('\0'); @@ -46,7 +99,7 @@ bool String::empty() const void String::append(const Vector& data) { - if (data.capacity() == 0) + if (data.empty()) { m_data.push_back('\0'); return; @@ -79,7 +132,7 @@ Pair String::rsplit(char c) const slice(0, index.value(), left); String right; - slice(index.value(), size(), right); + slice(index.value() + 1, size(), right); return {left, right}; } return {*this, {}}; @@ -87,7 +140,7 @@ Pair String::rsplit(char c) const bool String::slice(std::size_t idx, String& out) const { - if (idx >= m_data.size() - 1) + if (idx >= m_data.size()) { return false; } @@ -102,7 +155,7 @@ bool String::slice(std::size_t idx, String& out) const bool String::slice(std::size_t start, std::size_t end, String& out) const { - if (end >= m_data.size() - 1) + if (end >= m_data.size()) { return false; } @@ -181,6 +234,12 @@ String& String::operator<<(const char* 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; @@ -193,12 +252,7 @@ bool String::operator!=(const String& other) const String& String::operator<<(size_t idx) { - /* - const auto num_digits = static_cast(log10(double(idx))) + 1; - char body[num_digits+1]; - snprintf(body, num_digits+1, "%d", static_cast(idx)); - append(body); - */ + *this += to_string(idx); return *this; } @@ -225,6 +279,10 @@ String String::operator+(const String& str) const String& String::operator+=(char c) { + if (m_data.empty()) + { + m_data.push_back('\0'); + } m_data.push_back('\0'); m_data[m_data.size()-2] = c; return *this; diff --git a/src/base/core/data_structures/String.h b/src/base/core/data_structures/String.h index 7b4db08..28e039c 100644 --- a/src/base/core/data_structures/String.h +++ b/src/base/core/data_structures/String.h @@ -14,6 +14,10 @@ public: String(const char* data); + static String fmt(const char* fmt, ...); + + void append(const Vector& data); + const Vector& data() const; bool empty() const; @@ -36,10 +40,19 @@ public: char operator[](std::size_t idx) const; + String& operator<<(const String& body); + String& operator<<(const char* body); String& operator<<(size_t idx); + template + String& operator<<(const T& stringable) + { + *this += stringable.str(); + return *this; + } + String& operator+=(const String& str); String& operator+=(char c); @@ -51,9 +64,9 @@ public: bool operator!=(const String& other) const; private: - void append(const Vector& data); - void append(const char* data); Vector m_data; -}; \ No newline at end of file +}; + +using _s = String; \ No newline at end of file diff --git a/src/base/core/data_structures/Tree.cpp b/src/base/core/data_structures/Tree.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/base/core/data_structures/Vector.cpp b/src/base/core/data_structures/Vector.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/base/core/data_structures/Vector.h b/src/base/core/data_structures/Vector.h index 04fa077..8cb9199 100644 --- a/src/base/core/data_structures/Vector.h +++ b/src/base/core/data_structures/Vector.h @@ -12,7 +12,6 @@ public: Vector(std::size_t size) { resize(size); - m_size = size; } Vector(const Vector& v) @@ -56,22 +55,20 @@ public: { v.m_data[idx] = m_data[idx]; } - v.m_size = slice_idx; return true; } bool slice(std::size_t slice_start, std::size_t slice_end, Vector& v) const { - if (slice_end >= m_size) + if (slice_end > m_size) { return false; } v.resize(slice_end - slice_start); for(std::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 0; } + size_t remaining_capacity() const + { + return m_capacity - m_size; + } + void resize_capacity(std::size_t new_capacity) { if (!has_allocated()) @@ -206,23 +217,18 @@ private: else if (new_capacity != m_capacity) { auto temp = m_allocator.alloc_array(new_capacity); - for(std::size_t idx=0; idx m_capacity) - { - m_size = m_capacity; - } - } - else if(m_size != m_capacity) - { - m_size = m_capacity; } } 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 5b1f21e..0000000 --- a/src/base/core/file_utilities/Directory.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "Directory.h" -#include -#include -#include - -Vector Directory::getSubdirectories(const FileSystemPath& path) -{ - Vector ret; - auto dirp = ::opendir(path.as_string().raw()); - while(auto ep = ::readdir(dirp)) - { - auto rel_path = String(ep->d_name); - if (rel_path == "." || rel_path == "..") - { - continue; - } - - auto full_path = path.join(rel_path); - struct stat sb; - auto rc = lstat(full_path.as_string().raw(), &sb); - if (rc == -1) - { - printf("Got error"); - } - if (S_ISDIR(sb.st_mode)) - { - printf("Adding full path: %s\n", full_path.as_string().raw()); - ret.push_back(full_path); - } - } - ::closedir(dirp); - return ret; -} - -Vector Directory::getFiles(const FileSystemPath& path, bool recursive) -{ - Vector paths; - if (path.is_directory()) - { - for (const auto& entry : getSubdirectories(path)) - { - if (entry.is_regular_file()) - { - paths.push_back(entry); - } - else if(recursive && entry.is_directory()) - { - const auto child_paths = getFiles(entry, recursive); - paths.extend(child_paths); - } - } - } - return paths; -} - -Vector Directory::getFilesWithExtension(const FileSystemPath& path, const String& extension, bool recursive) -{ - Vector paths; - if (path.is_directory()) - { - for (const auto& entry : getSubdirectories(path)) - { - if (entry.is_regular_file() && entry.extension() == extension) - { - paths.push_back(entry); - } - else if(recursive && entry.is_directory()) - { - const auto child_paths = getFilesWithExtension(entry, extension, recursive); - paths.extend(child_paths); - } - } - } - return paths; -} - -void Directory::create(const FileSystemPath& path, bool existsOk) -{ - (void)existsOk; - FileSystemPath working_path; - if (path.is_directory()) - { - working_path = path; - } - else - { - working_path = path.parent_path(); - } - - if (!working_path.exists()) - { - //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 7c27b66..0000000 --- a/src/base/core/file_utilities/Directory.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "Vector.h" -#include "FileSystemPath.h" - -class Directory -{ -public: - static Vector getSubdirectories(const FileSystemPath& path); - - static void create(const FileSystemPath& path, bool existsOK = false); - - static Vector getFiles(const FileSystemPath& path, bool recursive=false); - - static Vector getFilesWithExtension(const FileSystemPath& path, const String& extension, bool recursive=false); -}; diff --git a/src/base/core/filesystem/Directory.cpp b/src/base/core/filesystem/Directory.cpp new file mode 100644 index 0000000..879ede0 --- /dev/null +++ b/src/base/core/filesystem/Directory.cpp @@ -0,0 +1,128 @@ +#include "Directory.h" +#include "ConsoleLogger.h" + +#include +#include +#include + +Status Directory::getDirectoryContents(const FileSystemPath& path, Vector& ret) +{ + 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_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::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 + { + LOG_INFO("Adding entry " << entry); + ret.push_back(entry); + } + } + else if(recursive) + { + IF_OK_AND_TRUE(entry.is_directory()) + { + Vector child_paths; + STATUS_CHECK(getFiles(entry, child_paths, recursive), "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) +{ + (void)existsOk; + FileSystemPath working_path; + if (path.is_directory().value()) + { + working_path = path; + } + else + { + working_path = path.parent_path(); + } + + if (!working_path.exists()) + { + //std::filesystem::create_directories(working_path); + } + return {}; +} diff --git a/src/base/core/filesystem/Directory.h b/src/base/core/filesystem/Directory.h new file mode 100644 index 0000000..f2c2dc9 --- /dev/null +++ b/src/base/core/filesystem/Directory.h @@ -0,0 +1,24 @@ +#pragma once + +#include "Vector.h" +#include "FileSystemPath.h" +#include "Result.h" + +class Directory +{ +public: + static Status getDirectoryContents(const FileSystemPath& path, + Vector& content); + + static Status create(const FileSystemPath& path, bool existsOK = false); + + 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/file_utilities/File.cpp b/src/base/core/filesystem/File.cpp similarity index 52% rename from src/base/core/file_utilities/File.cpp rename to src/base/core/filesystem/File.cpp index c23e8be..317b8c0 100644 --- a/src/base/core/file_utilities/File.cpp +++ b/src/base/core/filesystem/File.cpp @@ -16,7 +16,7 @@ class FileImpl { public: - void do_open(const FileSystemPath& path, File::AccessMode accessMode) + Status do_open(const FileSystemPath& path, File::AccessMode accessMode) { int flags{0}; if (accessMode == File::AccessMode::Read) @@ -28,8 +28,15 @@ public: flags |= O_WRONLY; flags |= O_CREAT; } + errno = 0; + m_fd = ::open(path.str().raw(), flags); + if (m_fd < 0) + { + Status ret; + ret.on_errno("Failed to open file with"); + return ret; + } - m_fd = ::open(path.as_string().raw(), flags); if (accessMode == File::AccessMode::Read) { m_open_for_read = true; @@ -38,13 +45,22 @@ public: { m_open_for_write = true; } + return {}; } - void do_close() + Status do_close() { - ::close(m_fd); + errno = 0; + const auto rc = ::close(m_fd); + if (rc < 0) + { + Status ret; + ret.on_errno("Failed to close file with"); + return ret; + } m_open_for_read = false; m_open_for_write = false; + return {}; } bool is_ok() const @@ -68,35 +84,56 @@ public: const auto rc = ::read(m_fd, bytes.data(), bytes.capacity()); if (rc < 0) { - const auto last_err = errno; - String msg(::strerror(last_err)); + const auto msg = _s("Error in read impl | ") + Error::from_errno(); return Result(Error(msg)); } return Result(rc); } - std::size_t do_write(const VecBytes& bytes) + Result do_write(const VecBytes& bytes) { - return ::write(m_fd, bytes.data(), bytes.size()); + 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); } - std::size_t do_write(const Vector& bytes, int size = -1) + Result do_write(const Vector& bytes, int size = -1) { + errno = 0; + int rc = 0; if (size > -1) { - return ::write(m_fd, bytes.data(), size); + rc = ::write(m_fd, bytes.data(), size); } else { - return ::write(m_fd, bytes.data(), bytes.size()); + 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); } - void update_size() + Status update_size() { struct stat buf; - ::fstat(m_fd, &buf); + const auto rc = ::fstat(m_fd, &buf); + if (rc != 0) + { + Status ret; + ret.on_errno("Failed to get size with fstat"); + return ret; + } m_size = buf.st_size; + return {}; } bool m_open_for_write{false}; @@ -123,41 +160,77 @@ String File::getExtension() const return m_path.extension(); } -bool File::readBinary(VecBytes& buffer) +Status File::readBinary(VecBytes& buffer) { - auto ok = open(AccessMode::Read, true); - if (!ok) + auto status = open(AccessMode::Read, true); + if (!status.ok()) { - return false; + return status; } - m_impl->update_size(); - buffer.resize(m_impl->m_size); - const auto result = m_impl->do_read(buffer); - buffer.resize(result.value()); - return true; -} - -String File::readText() -{ - VecBytes buffer; - auto ok = open(AccessMode::Read, true); - if (!ok) + status = m_impl->update_size(); + if (!status.ok()) { - return {}; + return status; } - m_impl->update_size(); buffer.resize(m_impl->m_size); const auto result = m_impl->do_read(buffer); if (!result.ok()) { - printf("Got error: %s\n", result.error().msg()); - return {}; + return Status(result.error()); + } + buffer.resize(result.value()); + return {}; +} + +Status File::readText(String& ret) +{ + auto status = open(AccessMode::Read, true); + if (!status.ok()) + { + return status; } - buffer.resize(result.value()); - return String(buffer); + VecBytes buffer; + status = m_impl->update_size(); + if (status.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 {}; } String File::dumpBinary() @@ -192,7 +265,7 @@ String File::dumpBinary() Optional File::readNextByte() { - if (!open(AccessMode::Read)) + if (!open(AccessMode::Read).ok()) { return {}; } @@ -216,20 +289,19 @@ Optional File::readNextByte() } } -bool File::open(AccessMode accessMode, bool binary) +Status File::open(AccessMode accessMode, bool binary) { if (m_path.is_absolute() && !m_path.parent_path().exists()) { Directory::create(m_path.parent_path(), true); } - m_impl->do_open(m_path, accessMode); - return true; + return m_impl->do_open(m_path, accessMode); } -void File::close() +Status File::close() { - m_impl->do_close(); + return m_impl->do_close(); } FileFormat::Format File::inferFormat() const @@ -239,27 +311,34 @@ FileFormat::Format File::inferFormat() const return {}; } -void File::writeText(const String& text) +Status File::writeText(const String& text) { bool had_to_open{false}; + Status status; if (!m_impl->is_open_for_write()) { had_to_open = true; - m_impl->do_open(m_path, File::AccessMode::Write); + 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()); } - - m_impl->do_write(text.data(), text.data().size() - 1); if (had_to_open) { - m_impl->do_close(); + status = m_impl->do_close(); } + return status; } -Vector File::readLines() +Status File::readLines(Vector& lines) { - Vector content; - /* if (!pathExists()) { @@ -279,10 +358,10 @@ Vector File::readLines() close(); */ - return content; + return {}; } -String File::read() +Status File::read(String& ret) { /* if (!pathExists()) @@ -300,11 +379,10 @@ String File::read() close(); */ - String buffer; - return buffer; + return {}; } -bool File::pathExists() const +bool File::exists() const { return m_path.exists(); } diff --git a/src/base/core/file_utilities/File.h b/src/base/core/filesystem/File.h similarity index 64% rename from src/base/core/file_utilities/File.h rename to src/base/core/filesystem/File.h index 09dbcfc..28fbcb5 100644 --- a/src/base/core/file_utilities/File.h +++ b/src/base/core/filesystem/File.h @@ -23,7 +23,7 @@ public: ~File(); - void close(); + Status close(); String dumpBinary(); @@ -31,21 +31,21 @@ public: FileFormat::Format inferFormat() const; - String readText(); + Status readText(String& buffer); - Vector readLines(); + Status readLines(Vector& lines); - String read(); + Status read(String& buffer); - bool pathExists() const; + bool exists() const; - bool open(AccessMode mode, bool binary = false); + Status open(AccessMode mode, bool binary = false); - bool readBinary(VecBytes& bytes); + Status readBinary(VecBytes& bytes); Optional readNextByte(); - void writeText(const String& text); + Status writeText(const String& text); private: Ptr m_impl; diff --git a/src/base/core/file_utilities/FileFormats.cpp b/src/base/core/filesystem/FileFormats.cpp similarity index 100% rename from src/base/core/file_utilities/FileFormats.cpp rename to src/base/core/filesystem/FileFormats.cpp diff --git a/src/base/core/file_utilities/FileFormats.h b/src/base/core/filesystem/FileFormats.h similarity index 100% rename from src/base/core/file_utilities/FileFormats.h rename to src/base/core/filesystem/FileFormats.h diff --git a/src/base/core/file_utilities/FileSystemPath.cpp b/src/base/core/filesystem/FileSystemPath.cpp similarity index 50% rename from src/base/core/file_utilities/FileSystemPath.cpp rename to src/base/core/filesystem/FileSystemPath.cpp index 7290531..79bfa4a 100644 --- a/src/base/core/file_utilities/FileSystemPath.cpp +++ b/src/base/core/filesystem/FileSystemPath.cpp @@ -4,26 +4,25 @@ #include #include #include -#include + +FileSystemPath::FileSystemPath() +{ +} FileSystemPath::FileSystemPath(const String& path) : m_path(path) { - } -const String& FileSystemPath::as_string() const +const String& FileSystemPath::str() const { return m_path; } Result FileSystemPath::is_empty() const { - if (!is_regular_file()) - { - return {Error("Requested empty check but target is not regular file.")}; - } - + 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()) { @@ -34,21 +33,24 @@ Result FileSystemPath::is_empty() const Result FileSystemPath::get_size() const { - if (!is_regular_file()) - { - return {Error("Requested size but target is not regular file.")}; - } + ERROR_IF_NOT_OK_OR_TRUE(is_regular_file(), + "Requested size check but target is not regular file."); struct stat buf; - ::stat(m_path.raw(), &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; } -FileSystemPath FileSystemPath::current_dir() +Result FileSystemPath::current_dir() { errno = 0; const auto path_max = ::pathconf(".", _PC_PATH_MAX); - std::size_t size{0}; + size_t size{0}; if (path_max == -1) { size = 1024; @@ -63,24 +65,48 @@ FileSystemPath FileSystemPath::current_dir() } 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())); } -bool FileSystemPath::is_regular_file() const +Result FileSystemPath::is_regular_file() const { struct stat path_stat; - ::stat(m_path.raw(), &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); } -bool FileSystemPath::is_directory() const +Result FileSystemPath::is_directory() const { struct stat path_stat; - ::stat(m_path.raw(), &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; @@ -100,6 +126,21 @@ String FileSystemPath::extension() const return result; } +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; @@ -108,7 +149,7 @@ bool FileSystemPath::exists() const FileSystemPath FileSystemPath::join(const String& entry) const { auto new_path = *this; - new_path.m_path+=m_delimiter; - new_path.m_path+=entry; + 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/file_utilities/FileSystemPath.h b/src/base/core/filesystem/FileSystemPath.h similarity index 62% rename from src/base/core/file_utilities/FileSystemPath.h rename to src/base/core/filesystem/FileSystemPath.h index 1aca9cb..363086f 100644 --- a/src/base/core/file_utilities/FileSystemPath.h +++ b/src/base/core/filesystem/FileSystemPath.h @@ -6,16 +6,18 @@ class FileSystemPath { public: - FileSystemPath() = default; + FileSystemPath(); FileSystemPath(const String& path); - const String& as_string() const; + const String& str() const; - static FileSystemPath current_dir(); + static Result current_dir(); String extension() const; + String file_name() const; + bool exists() const; Result is_empty() const; @@ -24,9 +26,11 @@ public: FileSystemPath join(const String& entry) const; - bool is_regular_file() const; + Result is_regular_file() const; - bool is_directory() const; + Result is_directory() const; + + Result is_regular_file_or_directory() const; bool is_absolute() const; diff --git a/src/base/core/file_utilities/PathUtils.cpp b/src/base/core/filesystem/PathUtils.cpp similarity index 100% rename from src/base/core/file_utilities/PathUtils.cpp rename to src/base/core/filesystem/PathUtils.cpp diff --git a/src/base/core/file_utilities/PathUtils.h b/src/base/core/filesystem/PathUtils.h similarity index 100% rename from src/base/core/file_utilities/PathUtils.h rename to src/base/core/filesystem/PathUtils.h diff --git a/src/base/core/loggers/ConsoleLogger.cpp b/src/base/core/loggers/ConsoleLogger.cpp deleted file mode 100644 index 234027d..0000000 --- a/src/base/core/loggers/ConsoleLogger.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include "ConsoleLogger.h" - -#include -#include - -void ConsoleLogger::logLine(const String& msg) -{ - printf("%s\n", msg.raw()); -} - -void ConsoleLogger::logLine(const char* fmt, ...) -{ - va_list(args); - va_start(args, fmt); - vprintf((String(fmt) + "\n").raw(), args); - va_end(args); -} \ No newline at end of file diff --git a/src/base/core/loggers/ConsoleLogger.h b/src/base/core/loggers/ConsoleLogger.h deleted file mode 100644 index fc7e3c4..0000000 --- a/src/base/core/loggers/ConsoleLogger.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "String.h" - -class ConsoleLogger -{ -public: - static void logLine(const String& msg); - - static void logLine(const char* fmt, ...); -}; \ No newline at end of file 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/loggers/FileLogger.cpp b/src/base/core/logging/FileLogger.cpp similarity index 100% rename from src/base/core/loggers/FileLogger.cpp rename to src/base/core/logging/FileLogger.cpp diff --git a/src/base/core/loggers/FileLogger.h b/src/base/core/logging/FileLogger.h similarity index 71% rename from src/base/core/loggers/FileLogger.h rename to src/base/core/logging/FileLogger.h index 59831ec..8b867ed 100644 --- a/src/base/core/loggers/FileLogger.h +++ b/src/base/core/logging/FileLogger.h @@ -1,12 +1,5 @@ #pragma once -#define MLOG_ALL(msg, level) {String 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 "Pointer.h" #include "String.h" 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.cpp b/src/base/core/memory/Allocator.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/src/base/core/memory/Allocator.h b/src/base/core/memory/Allocator.h index 110ee8a..54e57c2 100644 --- a/src/base/core/memory/Allocator.h +++ b/src/base/core/memory/Allocator.h @@ -12,7 +12,7 @@ public: return new T; } - void do_delete(T** p) + void do_delete(T* p) { delete p; } diff --git a/src/base/core/memory/Pointer.h b/src/base/core/memory/Pointer.h index ad3aa85..b74fcfe 100644 --- a/src/base/core/memory/Pointer.h +++ b/src/base/core/memory/Pointer.h @@ -27,17 +27,28 @@ public: { if (m_raw != nullptr) { - m_allocator.do_delete(&m_raw); + m_allocator.do_delete(m_raw); } } Ptr(const Ptr& other) = delete; Ptr(Ptr&& other) - : m_allocator(std::move(other.m_allocator)), - m_raw(other.m_raw) { - other.m_raw = nullptr; + *this = std::move(other); + } + + 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; } T* get() @@ -55,6 +66,11 @@ public: return m_raw; } + void clear_raw() + { + m_raw = nullptr; + } + private: Allocator m_allocator; T* m_raw{nullptr}; diff --git a/src/base/core/http/HttpHeader.cpp b/src/base/core/protocol/HttpHeader.cpp similarity index 100% rename from src/base/core/http/HttpHeader.cpp rename to src/base/core/protocol/HttpHeader.cpp diff --git a/src/base/core/http/HttpHeader.h b/src/base/core/protocol/HttpHeader.h similarity index 100% rename from src/base/core/http/HttpHeader.h rename to src/base/core/protocol/HttpHeader.h diff --git a/src/base/core/http/HttpParser.cpp b/src/base/core/protocol/HttpParser.cpp similarity index 100% rename from src/base/core/http/HttpParser.cpp rename to src/base/core/protocol/HttpParser.cpp diff --git a/src/base/core/http/HttpParser.h b/src/base/core/protocol/HttpParser.h similarity index 100% rename from src/base/core/http/HttpParser.h rename to src/base/core/protocol/HttpParser.h diff --git a/src/base/core/http/HttpPreamble.h b/src/base/core/protocol/HttpPreamble.h similarity index 100% rename from src/base/core/http/HttpPreamble.h rename to src/base/core/protocol/HttpPreamble.h diff --git a/src/base/core/http/HttpRequest.cpp b/src/base/core/protocol/HttpRequest.cpp similarity index 100% rename from src/base/core/http/HttpRequest.cpp rename to src/base/core/protocol/HttpRequest.cpp diff --git a/src/base/core/http/HttpRequest.h b/src/base/core/protocol/HttpRequest.h similarity index 100% rename from src/base/core/http/HttpRequest.h rename to src/base/core/protocol/HttpRequest.h diff --git a/src/base/core/http/HttpResponse.cpp b/src/base/core/protocol/HttpResponse.cpp similarity index 100% rename from src/base/core/http/HttpResponse.cpp rename to src/base/core/protocol/HttpResponse.cpp diff --git a/src/base/core/http/HttpResponse.h b/src/base/core/protocol/HttpResponse.h similarity index 100% rename from src/base/core/http/HttpResponse.h rename to src/base/core/protocol/HttpResponse.h diff --git a/src/base/core/RandomUtils.cpp b/src/base/core/random/RandomUtils.cpp similarity index 100% rename from src/base/core/RandomUtils.cpp rename to src/base/core/random/RandomUtils.cpp diff --git a/src/base/core/RandomUtils.h b/src/base/core/random/RandomUtils.h similarity index 100% rename from src/base/core/RandomUtils.h rename to src/base/core/random/RandomUtils.h diff --git a/src/base/core/AbstractNamedItem.h b/src/base/core/serialization/AbstractNamedItem.h similarity index 100% rename from src/base/core/AbstractNamedItem.h rename to src/base/core/serialization/AbstractNamedItem.h diff --git a/src/base/core/Serializeable.h b/src/base/core/serialization/Serializeable.h similarity index 100% rename from src/base/core/Serializeable.h rename to src/base/core/serialization/Serializeable.h diff --git a/src/base/core/serializers/TomlReader.cpp b/src/base/core/serialization/TomlReader.cpp similarity index 100% rename from src/base/core/serializers/TomlReader.cpp rename to src/base/core/serialization/TomlReader.cpp diff --git a/src/base/core/serializers/TomlReader.h b/src/base/core/serialization/TomlReader.h similarity index 100% rename from src/base/core/serializers/TomlReader.h rename to src/base/core/serialization/TomlReader.h diff --git a/src/base/core/xml/XmlDocument.cpp b/src/base/core/serialization/xml/XmlDocument.cpp similarity index 100% rename from src/base/core/xml/XmlDocument.cpp rename to src/base/core/serialization/xml/XmlDocument.cpp diff --git a/src/base/core/xml/XmlDocument.h b/src/base/core/serialization/xml/XmlDocument.h similarity index 100% rename from src/base/core/xml/XmlDocument.h rename to src/base/core/serialization/xml/XmlDocument.h diff --git a/src/base/core/xml/XmlParser.cpp b/src/base/core/serialization/xml/XmlParser.cpp similarity index 100% rename from src/base/core/xml/XmlParser.cpp rename to src/base/core/serialization/xml/XmlParser.cpp diff --git a/src/base/core/xml/XmlParser.h b/src/base/core/serialization/xml/XmlParser.h similarity index 100% rename from src/base/core/xml/XmlParser.h rename to src/base/core/serialization/xml/XmlParser.h diff --git a/src/base/core/xml/XmlWriter.cpp b/src/base/core/serialization/xml/XmlWriter.cpp similarity index 100% rename from src/base/core/xml/XmlWriter.cpp rename to src/base/core/serialization/xml/XmlWriter.cpp diff --git a/src/base/core/xml/XmlWriter.h b/src/base/core/serialization/xml/XmlWriter.h similarity index 100% rename from src/base/core/xml/XmlWriter.h rename to src/base/core/serialization/xml/XmlWriter.h diff --git a/src/base/core/xml/xml-elements/XmlAttribute.cpp b/src/base/core/serialization/xml/xml-elements/XmlAttribute.cpp similarity index 100% rename from src/base/core/xml/xml-elements/XmlAttribute.cpp rename to src/base/core/serialization/xml/xml-elements/XmlAttribute.cpp diff --git a/src/base/core/xml/xml-elements/XmlAttribute.h b/src/base/core/serialization/xml/xml-elements/XmlAttribute.h similarity index 100% rename from src/base/core/xml/xml-elements/XmlAttribute.h rename to src/base/core/serialization/xml/xml-elements/XmlAttribute.h diff --git a/src/base/core/xml/xml-elements/XmlElement.cpp b/src/base/core/serialization/xml/xml-elements/XmlElement.cpp similarity index 100% rename from src/base/core/xml/xml-elements/XmlElement.cpp rename to src/base/core/serialization/xml/xml-elements/XmlElement.cpp diff --git a/src/base/core/xml/xml-elements/XmlElement.h b/src/base/core/serialization/xml/xml-elements/XmlElement.h similarity index 100% rename from src/base/core/xml/xml-elements/XmlElement.h rename to src/base/core/serialization/xml/xml-elements/XmlElement.h diff --git a/src/base/core/xml/xml-elements/XmlProlog.cpp b/src/base/core/serialization/xml/xml-elements/XmlProlog.cpp similarity index 100% rename from src/base/core/xml/xml-elements/XmlProlog.cpp rename to src/base/core/serialization/xml/xml-elements/XmlProlog.cpp diff --git a/src/base/core/xml/xml-elements/XmlProlog.h b/src/base/core/serialization/xml/xml-elements/XmlProlog.h similarity index 100% rename from src/base/core/xml/xml-elements/XmlProlog.h rename to src/base/core/serialization/xml/xml-elements/XmlProlog.h 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 100% rename from src/base/core/AbstractApp.h rename to src/base/core/system/process/AbstractApp.h 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 94% rename from src/base/core/CommandLineArgs.cpp rename to src/base/core/system/process/CommandLineArgs.cpp index 1ae103a..47a5b48 100644 --- a/src/base/core/CommandLineArgs.cpp +++ b/src/base/core/system/process/CommandLineArgs.cpp @@ -2,7 +2,9 @@ #include "UnicodeUtils.h" +#ifdef _WIN32 #include "Win32BaseIncludes.h" +#endif CommandLineArgs::CommandLineArgs() : mArugments(), @@ -46,7 +48,7 @@ FileSystemPath CommandLineArgs::getLaunchPath() void CommandLineArgs::recordLaunchPath() { - mLaunchPath = FileSystemPath::current_dir(); + mLaunchPath = FileSystemPath::current_dir().value(); } void CommandLineArgs::process(int argc, char *argv[]) diff --git a/src/base/core/CommandLineArgs.h b/src/base/core/system/process/CommandLineArgs.h similarity index 100% rename from src/base/core/CommandLineArgs.h rename to src/base/core/system/process/CommandLineArgs.h diff --git a/src/base/core/system/process/Process.h b/src/base/core/system/process/Process.h new file mode 100644 index 0000000..9c100f2 --- /dev/null +++ b/src/base/core/system/process/Process.h @@ -0,0 +1,40 @@ +#pragma once + +#include "String.h" + +#include "File.h" +#include "Result.h" +#include + +class Process +{ +public: + Status launch(const String& command) + { + const auto pid = fork(); + if (pid < 0) + { + ON_ERRNO("Failed to fork"); + } + + if (pid == 0) + { + //pass + } + return {}; + } + + static Result get_self_name() + { + FileSystemPath path(String("/proc/self/cmdline")); + File sys_file(path); + + Result ret; + const auto rc = sys_file.readText(ret.value()); + if (!rc.ok()) + { + ret.on_error(rc.error()); + } + return ret; + } +}; \ No newline at end of file diff --git a/src/base/core/ThreadCollection.cpp b/src/base/core/thread/ThreadCollection.cpp similarity index 100% rename from src/base/core/ThreadCollection.cpp rename to src/base/core/thread/ThreadCollection.cpp diff --git a/src/base/core/ThreadCollection.h b/src/base/core/thread/ThreadCollection.h similarity index 100% rename from src/base/core/ThreadCollection.h rename to src/base/core/thread/ThreadCollection.h 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/main.cpp b/src/main.cpp index 74c9d89..adecad8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,43 +1,16 @@ -#include "Vector.h" -#include "String.h" -#include "FileSystemPath.h" -#include "Directory.h" -#include "File.h" +#include "BuildSession.h" +#include "ConsoleLogger.h" -#include - -int main() +int main(int argc, char** argv) { - /* - FileSystemPath main_path(__FILE__); - printf("Starting build.\n"); - - auto main_directory = main_path.parent_path(); - for(const auto& subdir : Directory::getSubdirectories(main_directory)) + if (argc == 1) { - for(const auto& subsubdir : Directory::getSubdirectories(subdir)) - { - const auto build_file = subsubdir.join("build.toml"); - if (build_file.exists()) - { - printf("Found dir file: %s\n", build_file.as_string().raw()); - // Gather all files - //const auto header_files = Directory::getFilesWithExtension(subsubdir, ".h", true); - //for(const auto& header : header_files) - //{ - // printf("Found header file: %s\n", header.as_string().raw()); - // } - - // Gather all directories - - // Build library - - } - } + LOG_ERROR("Missing arg with path to source dir"); + return -1; } - */ - printf("Finished build.\n"); - + BuildSession build(argv[1]); + build.scan(); + build.build(); return 0; } diff --git a/test/bootstrap_tests.sh b/test/bootstrap_tests.sh index 327deb7..3225e3b 100755 --- a/test/bootstrap_tests.sh +++ b/test/bootstrap_tests.sh @@ -3,21 +3,26 @@ SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) CORE_SRC_DIR=$SCRIPT_DIR/../src/base/core g++ $SCRIPT_DIR/test_runner.cpp \ - $SCRIPT_DIR/../src/base/core/CommandLineArgs.cpp \ + $CORE_SRC_DIR/system/process/CommandLineArgs.cpp \ $CORE_SRC_DIR/base_types/Error.cpp \ $CORE_SRC_DIR/base_types/Index.cpp \ $CORE_SRC_DIR/data_structures/String.cpp \ - $CORE_SRC_DIR/file_utilities/FileSystemPath.cpp \ - $CORE_SRC_DIR/loggers/ConsoleLogger.cpp \ + $CORE_SRC_DIR/filesystem/FileSystemPath.cpp \ + $CORE_SRC_DIR/logging/Logger.cpp \ + $CORE_SRC_DIR/logging/ConsoleLogger.cpp \ + $CORE_SRC_DIR/time/Time.cpp \ $SCRIPT_DIR/test_utils/TestCaseRunner.cpp \ + $SCRIPT_DIR/core/TestFileSystemPath.cpp \ $SCRIPT_DIR/core/TestString.cpp \ $SCRIPT_DIR/core/TestVector.cpp \ - -o bootstrap_tests -g \ + -o test_runner -g \ -I$SCRIPT_DIR/test_utils \ -I$CORE_SRC_DIR \ -I$CORE_SRC_DIR/encoding \ - -I$CORE_SRC_DIR/loggers \ + -I$CORE_SRC_DIR/logging \ -I$CORE_SRC_DIR/data_structures \ -I$CORE_SRC_DIR/base_types \ -I$CORE_SRC_DIR/memory \ - -I$CORE_SRC_DIR/file_utilities \ No newline at end of file + -I$CORE_SRC_DIR/time \ + -I$CORE_SRC_DIR/system/process \ + -I$CORE_SRC_DIR/filesystem \ No newline at end of file diff --git a/test/core/TestFileSystemPath.cpp b/test/core/TestFileSystemPath.cpp new file mode 100644 index 0000000..cf4d87b --- /dev/null +++ b/test/core/TestFileSystemPath.cpp @@ -0,0 +1,18 @@ +#include "FileSystemPath.h" + +#include "TestFramework.h" +//#include "TestUtils.h" +#include + +TEST_CASE(FileSystemPath_Join, "core") +{ + FileSystemPath path("/home/jgrogan/code/compilz/src/src"); + auto new_path = path.join("test"); + REQUIRE(new_path.str() == "/home/jgrogan/code/compilz/src/src/test"); +} + +TEST_CASE(FileSystemPath_Extension, "core") +{ + FileSystemPath path("test.dat"); + REQUIRE(path.extension() == ".dat"); +} \ No newline at end of file diff --git a/test/core/TestString.cpp b/test/core/TestString.cpp index 5441d79..a72b7de 100644 --- a/test/core/TestString.cpp +++ b/test/core/TestString.cpp @@ -4,7 +4,7 @@ //#include "TestUtils.h" #include -TEST_CASE(TestBasicStringOps, "core") +TEST_CASE(String_Append, "core") { String str; str += 'a'; @@ -12,9 +12,10 @@ TEST_CASE(TestBasicStringOps, "core") str += 'c'; str += 'd'; REQUIRE(str == "abcd"); + String long_string("abc/def/ghi/jkl"); } -TEST_CASE(TestStringReverse, "core") +TEST_CASE(String_Reverse, "core") { String str0; str0.reverse(); @@ -37,6 +38,35 @@ TEST_CASE(TestStringReverse, "core") REQUIRE(str4 == "dcba"); } +TEST_CASE(String_Extend, "core") +{ + String str("/home/jgrogan/code/compilz/src/src"); + auto str_cpy = str; + str += "/"; + str += "test"; + REQUIRE(str == String("/home/jgrogan/code/compilz/src/src/test")); + + str_cpy += "/"; + str_cpy += "test"; + REQUIRE(str == str_cpy); +} + +TEST_CASE(String_Slice, "core") +{ + String str("test.dat"); + const auto rindex = str.rindex('.'); + REQUIRE(rindex.valid()); + REQUIRE(rindex.value() == 4); + + String right; + str.slice(rindex.value(), str.size(), right); + REQUIRE(right == ".dat"); + + const auto split = str.rsplit('.'); + REQUIRE(split.first() == "test"); + REQUIRE(split.second() == "dat"); +} + /* TEST_CASE(TestStringUtils_StripSurroundingWhitepsace, "core") { diff --git a/test/core/TestVector.cpp b/test/core/TestVector.cpp index 938676a..df208f0 100644 --- a/test/core/TestVector.cpp +++ b/test/core/TestVector.cpp @@ -4,15 +4,38 @@ #include -TEST_CASE(TestVectorOps, "core") +TEST_CASE(TestVectorExtend, "core") { Vector vec; - for(size_t idx=0;idx<100;idx++) + for(size_t idx=0; idx<16; idx++) { vec.push_back(idx); } - for(size_t idx=0; idx<100; idx++) + REQUIRE(vec.size() == 16); + + Vector vec0; + for(size_t idx=16; idx<19; idx++) { - REQUIRE(vec[idx] == idx); + vec0.push_back(idx); } + vec.extend(vec0); + REQUIRE(vec.size() == 19); +} + +TEST_CASE(TestVectorSlize, "core") +{ + Vector vec; + for(size_t idx=0; idx<8; idx++) + { + vec.push_back(idx); + } + + Vector bottom_half; + vec.slice(4, bottom_half); + REQUIRE(bottom_half.size() == 4); + + Vector top_half; + vec.slice(4, 8, top_half); + REQUIRE(top_half.size() == 4); + } diff --git a/test/test_runner.cpp b/test/test_runner.cpp index 30ab10f..c7a3859 100644 --- a/test/test_runner.cpp +++ b/test/test_runner.cpp @@ -1,7 +1,7 @@ #include "TestFramework.h" #include "CommandLineArgs.h" -#include "ConsoleLogger.h" +#include "Logger.h" #ifdef _WIN32 #include @@ -17,9 +17,9 @@ int main(int argc, char *argv[]) CommandLineArgs args; args.process(argc, argv); - ConsoleLogger::logLine("Starting test run."); + LOG_INFO("Starting test run."); TestCaseRunner::getInstance().run(args.getUserArgs()); - ConsoleLogger::logLine("Finished test run."); + LOG_INFO("Finished test run."); #ifdef _WIN32 CoUninitialize(); diff --git a/test/test_utils/TestCaseRunner.cpp b/test/test_utils/TestCaseRunner.cpp index 0979866..44f80fd 100644 --- a/test/test_utils/TestCaseRunner.cpp +++ b/test/test_utils/TestCaseRunner.cpp @@ -1,7 +1,7 @@ #include "TestCaseRunner.h" #include "FileLogger.h" -#include "ConsoleLogger.h" +#include "Logger.h" //#include "TestUiApplication.h" bool TestCaseRunner::sLastTestFailed = false; @@ -66,22 +66,22 @@ bool TestCaseRunner::run(const Vector& args) } sLastTestFailed = false; - ConsoleLogger::logLine("TestFramework: Running Test - %s", test_case->getName().raw()); + LOG_INFO("TestFramework: Running Test - " << test_case->getName()); test_case->run(); if (sLastTestFailed) { - ConsoleLogger::logLine("Failed at line %s", sFailureLine.raw()); + LOG_INFO("Failed at line: " << sFailureLine); mFailingTests.push_back(test_case->getName()); } } if (mFailingTests.size() > 0) { - ConsoleLogger::logLine("%d failing tests", mFailingTests.size()); + LOG_INFO(String::fmt("%d failing tests", mFailingTests.size())); for(const auto& name : mFailingTests) { - ConsoleLogger::logLine(name); + LOG_INFO(name); } } diff --git a/test/test_utils/TestFramework.h b/test/test_utils/TestFramework.h index 68755ad..d7051d0 100644 --- a/test/test_utils/TestFramework.h +++ b/test/test_utils/TestFramework.h @@ -20,7 +20,8 @@ struct Holder if(!bool(predicate)) \ { \ const auto msg = String::to_string(__LINE__) + String(" with check: '") + String(#predicate) + String("'"); \ - TestCaseRunner::getInstance().markTestFailure(msg); \ + TestCaseRunner::getInstance().markTestFailure(msg); \ + return; \ } \ From c25a56ee197459566b92acc0e3c7b61441b271ef Mon Sep 17 00:00:00 2001 From: jmsgrogan Date: Thu, 21 Dec 2023 09:18:44 +0000 Subject: [PATCH 04/10] Do bulk replace of stl types. --- apps/notes_tk/NotesTk.cpp | 2 +- apps/notes_tk/NotesTk.h | 2 +- .../notes_tk/audio_editor/AudioEditorView.cpp | 2 +- apps/notes_tk/audio_editor/AudioEditorView.h | 4 +- apps/notes_tk/canvas/CanvasController.cpp | 2 +- apps/notes_tk/canvas/CanvasController.h | 4 +- apps/notes_tk/canvas/CanvasDrawingArea.h | 2 +- apps/notes_tk/canvas/CanvasView.cpp | 4 +- apps/notes_tk/canvas/CanvasView.h | 8 +-- .../notes_tk/image_editor/ImageEditorView.cpp | 2 +- apps/notes_tk/image_editor/ImageEditorView.h | 4 +- apps/notes_tk/image_editor/ImageViewWidget.h | 2 +- apps/notes_tk/main-win.cpp | 4 +- apps/notes_tk/main.cpp | 2 +- apps/notes_tk/mesh_viewer/MeshViewerView.cpp | 2 +- apps/notes_tk/mesh_viewer/MeshViewerView.h | 6 +-- .../text_editor/PlainTextDocument.cpp | 6 +-- apps/notes_tk/text_editor/PlainTextDocument.h | 14 +++--- .../text_editor/TextEditorController.cpp | 6 +-- .../text_editor/TextEditorController.h | 10 ++-- apps/notes_tk/text_editor/TextEditorModel.cpp | 2 +- apps/notes_tk/text_editor/TextEditorModel.h | 6 +-- apps/notes_tk/text_editor/TextEditorView.cpp | 2 +- apps/notes_tk/text_editor/TextEditorView.h | 4 +- apps/notes_tk/web_client/WebClientView.cpp | 2 +- apps/notes_tk/web_client/WebClientView.h | 4 +- apps/website-generator/ContentFile.cpp | 4 +- apps/website-generator/ContentFile.h | 16 +++--- .../MarkdownContentParser.cpp | 10 ++-- .../website-generator/MarkdownContentParser.h | 12 ++--- .../website-generator/SiteGeneratorConfig.cpp | 4 +- apps/website-generator/SiteGeneratorConfig.h | 8 +-- apps/website-generator/WebsiteGenerator.cpp | 2 +- apps/website-generator/WebsiteGenerator.h | 14 +++--- plugins/circuits/src/CircuitElement.h | 4 +- plugins/circuits/src/ElectronicCircuit.h | 24 ++++----- plugins/circuits/src/Terminal.cpp | 2 +- plugins/circuits/src/Terminal.h | 8 +-- plugins/circuits/src/TruthTable.h | 4 +- plugins/circuits/src/Wire.h | 2 +- plugins/circuits/src/gates/LogicGate.cpp | 6 +-- plugins/circuits/src/gates/LogicGate.h | 10 ++-- .../src/visuals/ElectronicCircuitNode.h | 8 +-- plugins/circuits/src/visuals/LogicGateNode.h | 4 +- .../src/visuals/LogicGatePrimitiveShapes.cpp | 4 +- .../src/visuals/LogicGatePrimitiveShapes.h | 6 +-- plugins/circuits/src/visuals/TerminalNode.h | 2 +- plugins/circuits/src/visuals/WireNode.cpp | 2 +- plugins/circuits/src/visuals/WireNode.h | 2 +- plugins/music/src/midi/MetaMidiEvent.cpp | 4 +- plugins/music/src/midi/MetaMidiEvent.h | 12 ++--- plugins/music/src/midi/MidiChannelEvent.cpp | 2 +- plugins/music/src/midi/MidiChannelEvent.h | 6 +-- plugins/music/src/midi/MidiDocument.cpp | 6 +-- plugins/music/src/midi/MidiDocument.h | 16 +++--- plugins/music/src/midi/MidiEvent.cpp | 2 +- plugins/music/src/midi/MidiEvent.h | 6 +-- plugins/music/src/midi/MidiTrack.cpp | 4 +- plugins/music/src/midi/MidiTrack.h | 12 ++--- .../src/midi/reader/MidiMetaEventAdapter.cpp | 6 +-- plugins/music/src/midi/reader/MidiReader.h | 4 +- .../quantum_computing/src/QuantumCircuit.cpp | 8 +-- .../quantum_computing/src/QuantumCircuit.h | 20 ++++---- .../src/QuantumCircuitReader.cpp | 22 ++++---- .../src/QuantumCircuitReader.h | 20 ++++---- .../quantum_computing/src/QuantumState.cpp | 6 +-- plugins/quantum_computing/src/QuantumState.h | 10 ++-- plugins/quantum_computing/src/Qubit.cpp | 4 +- plugins/quantum_computing/src/Qubit.h | 4 +- .../circuit_elements/QuantumCircuitElement.h | 2 +- .../src/circuit_elements/QuantumGate.cpp | 6 +-- .../src/circuit_elements/QuantumGate.h | 10 ++-- .../src/circuit_elements/QuantumTerminal.cpp | 2 +- .../src/circuit_elements/QuantumTerminal.h | 10 ++-- .../src/circuit_elements/QuantumWire.h | 2 +- .../src/visuals/BlochSphereNode.cpp | 2 +- .../src/visuals/BlochSphereNode.h | 18 +++---- .../src/visuals/QuantumCircuitNode.h | 8 +-- .../src/visuals/QuantumGateNode.cpp | 2 +- .../src/visuals/QuantumGateNode.h | 6 +-- .../src/visuals/QuantumTerminalNode.cpp | 2 +- .../src/visuals/QuantumTerminalNode.h | 4 +- .../src/visuals/QuantumWireNode.cpp | 2 +- .../src/visuals/QuantumWireNode.h | 2 +- src/base/compiler/BuildLibrary.cpp | 17 +++++-- src/base/compiler/BuildLibrary.h | 4 +- src/base/compiler/BuildSession.cpp | 26 ++++++---- src/base/compiler/BuildSession.h | 4 +- src/base/compiler/Lexer.cpp | 6 +-- src/base/compiler/Lexer.h | 6 +-- .../template_engine/TemplateElements.cpp | 46 ++++++++--------- .../template_engine/TemplateElements.h | 44 ++++++++-------- .../compiler/template_engine/TemplateFile.cpp | 24 ++++----- .../compiler/template_engine/TemplateFile.h | 34 ++++++------- .../compiler/template_engine/TemplateNode.cpp | 14 +++--- .../compiler/template_engine/TemplateNode.h | 20 ++++---- .../TemplateSubstitutionContext.h | 10 ++-- .../template_engine/TemplatingEngine.cpp | 4 +- .../template_engine/TemplatingEngine.h | 14 +++--- src/base/compression/AbstractEncoder.h | 4 +- .../compression/CyclicRedundancyChecker.cpp | 2 +- .../compression/CyclicRedundancyChecker.h | 4 +- src/base/compression/Lz77Encoder.cpp | 12 ++--- src/base/compression/Lz77Encoder.h | 14 +++--- src/base/compression/RunLengthEncoder.cpp | 8 +-- src/base/compression/RunLengthEncoder.h | 6 +-- src/base/compression/ZlibEncoder.cpp | 8 +-- src/base/compression/ZlibEncoder.h | 14 +++--- src/base/compression/deflate/DeflateBlock.cpp | 4 +- src/base/compression/deflate/DeflateBlock.h | 6 +-- .../compression/deflate/DeflateElements.h | 4 +- .../compression/deflate/DeflateEncoder.cpp | 2 +- src/base/compression/deflate/DeflateEncoder.h | 6 +-- .../huffman/HuffmanCodeLengthTable.cpp | 16 +++--- .../huffman/HuffmanCodeLengthTable.h | 20 ++++---- .../compression/huffman/HuffmanEncoder.cpp | 14 +++--- src/base/compression/huffman/HuffmanEncoder.h | 10 ++-- .../compression/huffman/HuffmanFixedCodes.h | 8 +-- .../compression/huffman/HuffmanStream.cpp | 10 ++-- src/base/compression/huffman/HuffmanStream.h | 10 ++-- src/base/compression/huffman/HuffmanTree.cpp | 6 +-- src/base/compression/huffman/HuffmanTree.h | 12 ++--- src/base/core/base_types/Color.cpp | 12 ++--- src/base/core/base_types/Color.h | 20 ++++---- src/base/core/data_structures/Dictionary.cpp | 22 ++++---- src/base/core/data_structures/Dictionary.h | 28 +++++------ src/base/core/encoding/ByteUtils.cpp | 6 +-- src/base/core/encoding/StringUtils.cpp | 44 ++++++++-------- src/base/core/encoding/StringUtils.h | 28 +++++------ src/base/core/encoding/UnicodeUtils.cpp | 16 +++--- src/base/core/encoding/UnicodeUtils.h | 10 ++-- src/base/core/filesystem/Directory.cpp | 50 ++++++++++++++++--- src/base/core/filesystem/Directory.h | 5 +- src/base/core/filesystem/FileFormats.cpp | 6 +-- src/base/core/filesystem/PathUtils.cpp | 6 +-- src/base/core/filesystem/PathUtils.h | 8 +-- src/base/core/logging/FileLogger.cpp | 8 +-- src/base/core/memory/SharedMemory.cpp | 8 +-- src/base/core/memory/SharedMemory.h | 8 +-- src/base/core/protocol/HttpHeader.cpp | 10 ++-- src/base/core/protocol/HttpHeader.h | 36 ++++++------- src/base/core/protocol/HttpParser.cpp | 2 +- src/base/core/protocol/HttpParser.h | 2 +- src/base/core/protocol/HttpPreamble.h | 8 +-- src/base/core/protocol/HttpRequest.cpp | 16 +++--- src/base/core/protocol/HttpRequest.h | 10 ++-- src/base/core/protocol/HttpResponse.cpp | 22 ++++---- src/base/core/protocol/HttpResponse.h | 22 ++++---- src/base/core/random/RandomUtils.cpp | 4 +- src/base/core/random/RandomUtils.h | 4 +- .../core/serialization/AbstractNamedItem.h | 6 +-- src/base/core/serialization/TomlReader.cpp | 22 ++++---- src/base/core/serialization/TomlReader.h | 36 ++++++------- .../core/serialization/xml/XmlDocument.cpp | 13 ++--- src/base/core/serialization/xml/XmlDocument.h | 15 ++---- src/base/core/serialization/xml/XmlParser.cpp | 2 +- src/base/core/serialization/xml/XmlParser.h | 16 +++--- src/base/core/serialization/xml/XmlWriter.cpp | 13 +++-- src/base/core/serialization/xml/XmlWriter.h | 5 +- .../xml/xml-elements/XmlAttribute.cpp | 10 ++-- .../xml/xml-elements/XmlAttribute.h | 20 ++++---- .../xml/xml-elements/XmlElement.cpp | 30 +++++------ .../xml/xml-elements/XmlElement.h | 47 ++++++++--------- .../xml/xml-elements/XmlProlog.cpp | 8 +-- .../xml/xml-elements/XmlProlog.h | 14 +++--- src/base/core/streams/BinaryStream.cpp | 2 +- src/base/core/streams/BinaryStream.h | 4 +- src/base/core/streams/BitStream.cpp | 2 +- src/base/core/system/process/AbstractApp.h | 6 +-- .../core/system/process/CommandLineArgs.cpp | 2 +- src/base/core/system/process/Process.h | 41 ++++++++++++++- src/base/core/thread/ThreadCollection.cpp | 6 +-- src/base/core/thread/ThreadCollection.h | 10 ++-- src/base/database/Database.cpp | 2 +- src/base/database/Database.h | 8 +-- src/base/database/DatabaseManager.cpp | 4 +- src/base/database/DatabaseManager.h | 8 +-- .../database_interfaces/SqliteInterface.cpp | 4 +- .../database_interfaces/SqliteInterface.h | 8 +-- src/base/geometry/grid/AbstractGrid.h | 4 +- src/base/geometry/grid/Grid.h | 2 +- src/base/geometry/grid/TypedGrid.h | 4 +- src/base/geometry/math/Matrix.cpp | 10 ++-- src/base/geometry/math/Matrix.h | 6 +-- src/base/geometry/math/Vector.cpp | 8 +-- src/base/geometry/math/Vector.h | 8 +-- src/base/geometry/path/Line.cpp | 2 +- src/base/geometry/path/Line.h | 6 +-- src/base/geometry/path/LineSegment.cpp | 2 +- src/base/geometry/path/LineSegment.h | 2 +- src/base/geometry/path/Path.cpp | 2 +- src/base/geometry/path/Path.h | 18 +++---- src/base/geometry/points/DiscretePoint.h | 2 +- src/base/geometry/points/Point.cpp | 6 +-- src/base/geometry/points/Point.h | 8 +-- src/base/geometry/points/PointCollection.cpp | 4 +- src/base/geometry/points/PointCollection.h | 8 +-- src/base/geometry/points/PointParser.cpp | 12 ++--- src/base/geometry/points/PointParser.h | 10 ++-- src/base/geometry/primitives/Polygon.cpp | 2 +- src/base/geometry/primitives/Polygon.h | 2 +- src/base/network/NetworkManager.cpp | 2 +- src/base/network/NetworkManager.h | 12 ++--- src/base/network/client/HttpClient.h | 8 +-- .../network/client/PlatformSocketClient.h | 12 ++--- .../network/client/unix/UnixSocketClient.cpp | 2 +- .../network/client/unix/UnixSocketClient.h | 4 +- .../network/client/win32/WinsockClient.cpp | 2 +- src/base/network/client/win32/WinsockClient.h | 6 +-- src/base/network/server/HttpServer.cpp | 4 +- src/base/network/server/HttpServer.h | 10 ++-- .../network/server/PlatformSocketServer.h | 10 ++-- src/base/network/server/UnixSocketServer.cpp | 4 +- src/base/network/server/UnixSocketServer.h | 4 +- src/base/network/server/WinsockServer.cpp | 4 +- src/base/network/server/WinsockServer.h | 6 +-- src/base/network/server/win32/Win32TempFile.h | 2 +- .../network/server/win32/Win32WebRequest.cpp | 2 +- .../network/server/win32/Win32WebRequest.h | 10 ++-- .../network/server/win32/Win32WebResponse.h | 10 ++-- .../network/server/win32/Win32WebServer.h | 4 +- src/base/network/sockets/BerkeleySocket.cpp | 14 +++--- src/base/network/sockets/BerkeleySocket.h | 12 ++--- .../network/sockets/ISocketMessageHandler.h | 4 +- src/base/network/sockets/Socket.cpp | 4 +- src/base/network/sockets/Socket.h | 22 ++++---- src/base/network/sockets/WinsockSocket.cpp | 14 +++--- src/base/network/sockets/WinsockSocket.h | 10 ++-- src/console/MainApplication.cpp | 12 ++--- src/console/MainApplication.h | 8 +-- src/console/TermInfo.cpp | 18 +++---- src/console/TermInfo.h | 6 +-- src/main.cpp | 15 +++++- src/media/audio/AudioDevice.cpp | 6 +-- src/media/audio/AudioDevice.h | 14 +++--- src/media/audio/AudioManager.cpp | 2 +- src/media/audio/AudioManager.h | 10 ++-- src/media/audio/AudioSample.cpp | 4 +- src/media/audio/AudioSample.h | 12 ++--- src/media/audio/AudioSynth.cpp | 4 +- src/media/audio/AudioSynth.h | 2 +- src/media/audio/AudioWriter.h | 6 +-- .../audio/audio_interfaces/AlsaInterface.cpp | 4 +- .../audio/audio_interfaces/AlsaInterface.h | 6 +-- .../audio/audio_interfaces/IAudioInterface.h | 4 +- .../audio_interfaces/NullAudioInterface.cpp | 4 +- .../audio_interfaces/NullAudioInterface.h | 4 +- .../audio_interfaces/WasapiInterface.cpp | 4 +- .../audio/audio_interfaces/WasapiInterface.h | 6 +-- src/media/image/Image.cpp | 4 +- src/media/image/Image.h | 14 +++--- src/media/image/ImageBitStream.cpp | 2 +- src/media/image/ImageBitStream.h | 4 +- src/media/image/ImagePrimitives.h | 2 +- src/media/image/png/BasicPngWriter.cpp | 10 ++-- src/media/image/png/BasicPngWriter.h | 10 ++-- src/media/image/png/PngHeader.cpp | 10 ++-- src/media/image/png/PngHeader.h | 10 ++-- src/media/image/png/PngInfo.cpp | 12 ++--- src/media/image/png/PngInfo.h | 12 ++--- src/media/image/png/PngReader.cpp | 10 ++-- src/media/image/png/PngReader.h | 16 +++--- src/media/image/png/PngWriter.cpp | 2 +- src/media/image/png/PngWriter.h | 10 ++-- src/media/image/win32/Win32WicImage.h | 4 +- src/media/video/FfmegInterface.cpp | 6 +-- src/media/video/FfmpegInterface.h | 6 +-- src/media/video/Video.cpp | 6 +-- src/media/video/Video.h | 14 +++--- src/publishing/DocumentConverter.cpp | 2 +- src/publishing/DocumentConverter.h | 2 +- src/publishing/latex/LatexMathExpression.cpp | 10 ++-- src/publishing/latex/LatexMathExpression.h | 28 +++++------ src/publishing/latex/LatexSymbols.cpp | 14 +++--- src/publishing/latex/LatexSymbols.h | 22 ++++---- src/publishing/pdf/PdfDictionary.cpp | 4 +- src/publishing/pdf/PdfDictionary.h | 2 +- src/publishing/pdf/PdfDocument.cpp | 12 ++--- src/publishing/pdf/PdfDocument.h | 24 ++++----- src/publishing/pdf/PdfDocumentCatalog.cpp | 2 +- src/publishing/pdf/PdfDocumentCatalog.h | 6 +-- src/publishing/pdf/PdfObject.cpp | 8 +-- src/publishing/pdf/PdfObject.h | 14 +++--- src/publishing/pdf/PdfOutline.cpp | 6 +-- src/publishing/pdf/PdfOutline.h | 10 ++-- src/publishing/pdf/PdfPage.cpp | 10 ++-- src/publishing/pdf/PdfPage.h | 10 ++-- src/publishing/pdf/PdfPageTree.cpp | 6 +-- src/publishing/pdf/PdfPageTree.h | 4 +- src/publishing/pdf/PdfStream.cpp | 6 +-- src/publishing/pdf/PdfStream.h | 6 +-- src/publishing/pdf/PdfWriter.cpp | 4 +- src/publishing/pdf/PdfWriter.h | 6 +-- src/publishing/pdf/PdfXRefTable.cpp | 4 +- src/publishing/pdf/PdfXRefTable.h | 12 ++--- src/publishing/plotting/EquationNode.cpp | 4 +- src/publishing/plotting/EquationNode.h | 4 +- src/publishing/plotting/Plot.h | 28 +++++------ src/publishing/plotting/PlotCaptionNode.h | 4 +- src/publishing/plotting/PlotNode.cpp | 4 +- src/publishing/plotting/PlotNode.h | 12 ++--- src/rendering/fonts/BasicFontEngine.h | 4 +- src/rendering/fonts/FontGlyph.cpp | 6 +-- src/rendering/fonts/FontGlyph.h | 18 +++---- src/rendering/fonts/FontItem.cpp | 4 +- src/rendering/fonts/FontItem.h | 8 +-- src/rendering/fonts/FontReader.cpp | 10 ++-- src/rendering/fonts/FontReader.h | 20 ++++---- src/rendering/fonts/FontsManager.cpp | 4 +- src/rendering/fonts/FontsManager.h | 14 +++--- src/rendering/fonts/FreeTypeFontEngine.cpp | 4 +- src/rendering/fonts/FreeTypeFontEngine.h | 4 +- src/rendering/fonts/IFontEngine.h | 6 +-- src/rendering/fonts/TrueTypeFont.cpp | 4 +- src/rendering/fonts/TrueTypeFont.h | 2 +- .../fonts/directx/DirectWriteFontEngine.cpp | 20 ++++---- .../fonts/directx/DirectWriteFontEngine.h | 22 ++++---- .../fonts/directx/DirectWriteHelpers.cpp | 4 +- .../fonts/directx/DirectWriteHelpers.h | 14 +++--- src/rendering/graphics/DrawingContext.cpp | 2 +- src/rendering/graphics/DrawingContext.h | 10 ++-- src/rendering/graphics/DrawingSurface.cpp | 2 +- src/rendering/graphics/DrawingSurface.h | 8 +-- src/rendering/graphics/PainterFactory.cpp | 2 +- src/rendering/graphics/PainterFactory.h | 4 +- src/rendering/graphics/RasterPainter.h | 4 +- .../graphics/directx/DirectXInterface.h | 4 +- .../graphics/directx/DirectXMesh.cpp | 2 +- src/rendering/graphics/directx/DirectXMesh.h | 8 +-- .../graphics/directx/DirectXMeshPainter.h | 8 +-- .../graphics/directx/DirectXPainter.h | 10 ++-- .../graphics/directx/DirectXTextPainter.h | 2 +- .../graphics/opengl/OpenGlMeshPainter.cpp | 6 +-- .../graphics/opengl/OpenGlMeshPainter.h | 8 +-- src/rendering/graphics/opengl/OpenGlPainter.h | 6 +-- .../graphics/opengl/OpenGlTextPainter.h | 6 +-- src/rendering/mesh/AbstractFace.cpp | 4 +- src/rendering/mesh/AbstractFace.h | 18 +++---- src/rendering/mesh/AbstractMesh.cpp | 12 ++--- src/rendering/mesh/AbstractMesh.h | 26 +++++----- src/rendering/mesh/Edge.cpp | 2 +- src/rendering/mesh/Edge.h | 8 +-- src/rendering/mesh/FaceMesh.cpp | 16 +++--- src/rendering/mesh/FaceMesh.h | 22 ++++---- src/rendering/mesh/LineMesh.cpp | 6 +-- src/rendering/mesh/LineMesh.h | 10 ++-- src/rendering/mesh/MeshBuilder.cpp | 4 +- src/rendering/mesh/MeshBuilder.h | 12 ++--- src/rendering/mesh/MeshObjWriter.cpp | 4 +- src/rendering/mesh/MeshObjWriter.h | 4 +- src/rendering/mesh/MeshPrimitives.cpp | 14 +++--- src/rendering/mesh/MeshPrimitives.h | 14 +++--- src/rendering/mesh/Node.cpp | 6 +-- src/rendering/mesh/Node.h | 16 +++--- src/rendering/mesh/TriFace.cpp | 8 +-- src/rendering/mesh/TriFace.h | 8 +-- src/rendering/mesh/TriMesh.cpp | 2 +- src/rendering/mesh/TriMesh.h | 2 +- src/rendering/visual_elements/TextData.h | 6 +-- .../visual_elements/basic_shapes/LineNode.cpp | 2 +- .../visual_elements/basic_shapes/LineNode.h | 10 ++-- .../basic_shapes/PolygonNode.cpp | 2 +- .../basic_shapes/PolygonNode.h | 4 +- .../basic_shapes/RectangleNode.cpp | 2 +- .../basic_shapes/RectangleNode.h | 6 +-- .../nodes/AbstractVisualNode.cpp | 10 ++-- .../nodes/AbstractVisualNode.h | 22 ++++---- .../visual_elements/nodes/GeometryNode.h | 4 +- .../visual_elements/nodes/GridNode.cpp | 4 +- .../visual_elements/nodes/GridNode.h | 8 +-- .../visual_elements/nodes/LineEndNode.h | 2 +- .../visual_elements/nodes/MaterialNode.h | 2 +- .../visual_elements/nodes/MeshNode.h | 2 +- .../visual_elements/nodes/PathNode.cpp | 8 +-- .../visual_elements/nodes/PathNode.h | 12 ++--- .../visual_elements/nodes/TextNode.cpp | 16 +++--- .../visual_elements/nodes/TextNode.h | 22 ++++---- .../postscript/PostscriptReader.cpp | 2 +- .../postscript/PostscriptReader.h | 16 +++--- .../postscript/PostscriptWriter.cpp | 28 +++++------ .../postscript/PostscriptWriter.h | 16 +++--- src/rendering/visual_elements/scene/Scene.cpp | 2 +- src/rendering/visual_elements/scene/Scene.h | 12 ++--- .../visual_elements/scene/SceneItem.cpp | 4 +- .../visual_elements/scene/SceneItem.h | 10 ++-- .../visual_elements/scene/SceneModel.cpp | 8 +-- .../visual_elements/scene/SceneModel.h | 20 ++++---- .../visual_elements/svg/SvgDocument.cpp | 4 +- .../visual_elements/svg/SvgDocument.h | 2 +- .../visual_elements/svg/SvgElement.cpp | 2 +- .../visual_elements/svg/SvgElement.h | 2 +- src/rendering/visual_elements/svg/SvgNode.cpp | 8 +-- src/rendering/visual_elements/svg/SvgNode.h | 14 +++--- .../visual_elements/svg/SvgPainter.cpp | 8 +-- .../visual_elements/svg/SvgPainter.h | 6 +-- .../visual_elements/svg/SvgReader.cpp | 4 +- src/rendering/visual_elements/svg/SvgReader.h | 2 +- .../visual_elements/svg/SvgShapeElement.cpp | 16 +++--- .../visual_elements/svg/SvgShapeElement.h | 6 +-- .../visual_elements/svg/SvgTextElement.cpp | 6 +-- .../visual_elements/svg/SvgTextElement.h | 4 +- .../visual_elements/svg/SvgWriter.cpp | 4 +- src/rendering/visual_elements/svg/SvgWriter.h | 4 +- .../svg/elements/SvgShapeElements.cpp | 20 ++++---- .../svg/elements/SvgShapeElements.h | 12 ++--- src/ui/client/GuiApplication.cpp | 2 +- src/ui/client/GuiApplication.h | 10 ++-- src/ui/client/StatusBar.cpp | 2 +- src/ui/client/StatusBar.h | 4 +- src/ui/client/TabbedPanelWidget.cpp | 4 +- src/ui/client/TabbedPanelWidget.h | 8 +-- src/ui/client/TopBar.cpp | 2 +- src/ui/client/TopBar.h | 4 +- src/ui/ui_controls/Button.cpp | 4 +- src/ui/ui_controls/Button.h | 14 +++--- src/ui/ui_controls/ButtonGroup.h | 2 +- src/ui/ui_controls/HorizontalSpacer.cpp | 2 +- src/ui/ui_controls/HorizontalSpacer.h | 8 +-- src/ui/ui_controls/Label.cpp | 4 +- src/ui/ui_controls/Label.h | 12 ++--- src/ui/ui_controls/StackWidget.cpp | 2 +- src/ui/ui_controls/StackWidget.h | 4 +- src/ui/ui_controls/TextBox.cpp | 8 +-- src/ui/ui_controls/TextBox.h | 16 +++--- src/ui/ui_controls/VerticalSpacer.cpp | 2 +- src/ui/ui_controls/VerticalSpacer.h | 6 +-- src/ui/ui_elements/IconNode.cpp | 2 +- src/ui/ui_elements/IconNode.h | 4 +- .../desktop_elements/IPlatformScreen.h | 4 +- .../desktop_elements/IPlatformWindow.h | 4 +- .../ui_elements/desktop_elements/Keyboard.cpp | 4 +- .../ui_elements/desktop_elements/Keyboard.h | 10 ++-- .../ui_elements/desktop_elements/Screen.cpp | 2 +- src/ui/ui_elements/desktop_elements/Screen.h | 8 +-- .../ui_elements/desktop_elements/Window.cpp | 8 +-- src/ui/ui_elements/desktop_elements/Window.h | 26 +++++----- src/ui/ui_elements/style/ColorPalette.cpp | 2 +- src/ui/ui_elements/style/ColorPalette.h | 4 +- src/ui/ui_elements/style/FontTokens.cpp | 2 +- src/ui/ui_elements/style/FontTokens.h | 4 +- .../style/MediaResourceManager.cpp | 2 +- .../ui_elements/style/MediaResourceManager.h | 2 +- src/ui/ui_elements/style/Theme.h | 2 +- src/ui/ui_elements/style/ThemeManager.h | 2 +- .../ui_elements/ui_events/KeyboardEvent.cpp | 6 +-- src/ui/ui_elements/ui_events/KeyboardEvent.h | 14 +++--- src/ui/ui_elements/ui_events/MouseEvent.cpp | 2 +- src/ui/ui_elements/ui_events/MouseEvent.h | 6 +-- src/ui/ui_elements/ui_events/PaintEvent.cpp | 2 +- src/ui/ui_elements/ui_events/PaintEvent.h | 6 +-- src/ui/ui_elements/ui_events/ResizeEvent.cpp | 2 +- src/ui/ui_elements/ui_events/ResizeEvent.h | 6 +-- src/ui/ui_elements/ui_events/UiEvent.cpp | 2 +- src/ui/ui_elements/ui_events/UiEvent.h | 6 +-- src/ui/ui_elements/widgets/Widget.cpp | 6 +-- src/ui/ui_elements/widgets/Widget.h | 26 +++++----- src/ui/windows/AbstractDesktopApp.h | 2 +- src/ui/windows/managers/DesktopManager.cpp | 2 +- src/ui/windows/managers/DesktopManager.h | 12 ++--- src/ui/windows/managers/EventManager.cpp | 2 +- src/ui/windows/managers/EventManager.h | 8 +-- src/ui/windows/managers/WindowManager.cpp | 6 +-- src/ui/windows/managers/WindowManager.h | 12 ++--- .../ui_interfaces/AbstractUiInterface.h | 2 +- .../ui_interfaces/UiInterfaceFactory.cpp | 2 +- .../ui_interfaces/UiInterfaceFactory.h | 4 +- .../ui_interfaces/wayland/WaylandBuffer.h | 4 +- .../wayland/WaylandInterface.cpp | 2 +- .../ui_interfaces/wayland/WaylandInterface.h | 8 +-- .../ui_interfaces/wayland/WaylandKeyboard.h | 2 +- .../wayland/WaylandSeatInterface.h | 6 +-- .../ui_interfaces/wayland/WaylandSurface.h | 4 +- .../ui_interfaces/win32/Win32UIInterface.h | 2 +- .../ui_interfaces/win32/Win32Window.cpp | 2 +- .../windows/ui_interfaces/win32/Win32Window.h | 4 +- .../win32/Win32WindowInterface.h | 4 +- .../win32/directx/DirectX2dIntegration.h | 6 +-- .../win32/directx/DirectXBuffers.h | 4 +- .../win32/directx/Win32DxWindowInterface.h | 12 ++--- .../ui_interfaces/x11/XcbEventInterface.cpp | 10 ++-- .../ui_interfaces/x11/XcbEventInterface.h | 14 +++--- .../ui_interfaces/x11/XcbExtensionInterface.h | 4 +- .../ui_interfaces/x11/XcbGlInterface.cpp | 2 +- .../ui_interfaces/x11/XcbGlInterface.h | 6 +-- .../ui_interfaces/x11/XcbGlWindowInterface.h | 4 +- .../windows/ui_interfaces/x11/XcbInterface.h | 10 ++-- .../windows/ui_interfaces/x11/XcbKeyboard.cpp | 6 +-- .../windows/ui_interfaces/x11/XcbKeyboard.h | 6 +-- .../windows/ui_interfaces/x11/XcbScreen.cpp | 2 +- src/ui/windows/ui_interfaces/x11/XcbScreen.h | 4 +- src/ui/windows/ui_interfaces/x11/XcbWindow.h | 6 +-- src/web/html/HtmlDocument.cpp | 4 +- src/web/html/HtmlDocument.h | 8 +-- src/web/html/HtmlElement.cpp | 2 +- src/web/html/HtmlElement.h | 10 ++-- src/web/html/HtmlTextRun.h | 2 +- src/web/html/HtmlWriter.cpp | 6 +-- src/web/html/HtmlWriter.h | 6 +-- .../html/elements/HtmlParagraphElement.cpp | 4 +- src/web/html/elements/HtmlParagraphElement.h | 2 +- src/web/markdown/MarkdownComponents.cpp | 26 +++++----- src/web/markdown/MarkdownComponents.h | 48 +++++++++--------- src/web/markdown/MarkdownConverter.cpp | 2 +- src/web/markdown/MarkdownConverter.h | 4 +- src/web/markdown/MarkdownCustomElement.h | 22 ++++---- src/web/markdown/MarkdownDocument.cpp | 10 ++-- src/web/markdown/MarkdownDocument.h | 18 +++---- src/web/markdown/MarkdownElement.cpp | 6 +-- src/web/markdown/MarkdownElement.h | 12 ++--- src/web/markdown/MarkdownParser.cpp | 46 ++++++++--------- src/web/markdown/MarkdownParser.h | 40 +++++++-------- test/compiler/TestLexer.cpp | 6 +-- test/compression/TestHuffmanStream.cpp | 10 ++-- test/compression/TestLz77Encoder.cpp | 4 +- test/compression/TestStreamCompressor.cpp | 10 ++-- test/console/TestConsoleApp.cpp | 10 ++-- test/core/TestBitStream.cpp | 2 +- test/core/TestString.cpp | 10 ++-- test/database/TestDatabase.cpp | 14 +++--- test/graphics/TestD2dOffScreenRendering.cpp | 18 +++---- test/graphics/TestD2dRendering.cpp | 4 +- test/graphics/TestDirectXRendering.cpp | 4 +- test/graphics/TestOpenGlRendering.cpp | 4 +- test/image/TestPngWriter.cpp | 6 +-- test/publishing/TestPlotting.cpp | 2 +- test/test_utils/TestRenderUtils.h | 6 +-- test/test_utils/TestUiApplication.cpp | 2 +- test/test_utils/TestUiApplication.h | 4 +- test/test_utils/TestUtils.h | 2 +- test/web/TestMarkdownParser.cpp | 4 +- test/web/TestXmlParser.cpp | 2 +- 531 files changed, 2274 insertions(+), 2181 deletions(-) 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..8722a00 100644 --- a/apps/notes_tk/canvas/CanvasController.h +++ b/apps/notes_tk/canvas/CanvasController.h @@ -1,9 +1,9 @@ #pragma once -#include +#include "Memory.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 997d80f..7b2f7cb 100644 --- a/apps/notes_tk/main.cpp +++ b/apps/notes_tk/main.cpp @@ -1,4 +1,4 @@ -#include +#include "Memory.h" #include "NotesTk.h" #include "MainApplication.h" 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..4c255fc 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 "Memory.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..fe3fe44 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 "Memory.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..7353c9c 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 "Memory.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..572d835 100644 --- a/apps/website-generator/ContentFile.h +++ b/apps/website-generator/ContentFile.h @@ -3,7 +3,7 @@ #include "MarkdownContentParser.h" #include "File.h" -#include +#include "String.h" #include #include @@ -12,8 +12,8 @@ class MarkdownDocument; class ContentFile { public: - using FileMetadata = std::unordered_map; - using FileContentBody = std::vector; + using FileMetadata = std::unordered_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..98d3964 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 +std::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..a9a3224 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 -#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 = std::unordered_map; - std::pair> run(const Path& path); + std::pair> run(const Path& path); private: - std::optional checkForMetadataItem(const std::string& line) const; + std::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..2ada094 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 "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/plugins/circuits/src/CircuitElement.h b/plugins/circuits/src/CircuitElement.h index 03fe480..0b4ced4 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 "Memory.h" class CircuitElement diff --git a/plugins/circuits/src/ElectronicCircuit.h b/plugins/circuits/src/ElectronicCircuit.h index b24fe34..449a27c 100644 --- a/plugins/circuits/src/ElectronicCircuit.h +++ b/plugins/circuits/src/ElectronicCircuit.h @@ -1,13 +1,13 @@ #pragma once -#include -#include +#include "Memory.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..2564f8f 100644 --- a/plugins/circuits/src/TruthTable.h +++ b/plugins/circuits/src/TruthTable.h @@ -1,12 +1,12 @@ #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) //: mNumInputColumns(numInputColumns), 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..b8a7512 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(std::size_t numIn, std::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,7 +20,7 @@ NInMOutLogicGate::NInMOutLogicGate(std::size_t numIn, std::size_t numOut, std::v } else { - mOutputs = std::vector(numOut, nullptr); + mOutputs = Vector(numOut, nullptr); } } diff --git a/plugins/circuits/src/gates/LogicGate.h b/plugins/circuits/src/gates/LogicGate.h index 6a6ef9a..4a588c4 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 "Memory.h" +#include "Vector.h" class LogicGate : public CircuitElement { @@ -41,7 +41,7 @@ public: class NInMOutLogicGate : public LogicGate { public: - NInMOutLogicGate(std::size_t numIn, std::size_t numOut, std::vector inputs = {}, std::vector outputs = {}); + NInMOutLogicGate(std::size_t numIn, std::size_t numOut, Vector inputs = {}, Vector outputs = {}); virtual ~NInMOutLogicGate() = default; @@ -61,8 +61,8 @@ private: std::size_t mNumIn{ 1 }; std::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.h b/plugins/circuits/src/visuals/ElectronicCircuitNode.h index e38a4ee..5d41d42 100644 --- a/plugins/circuits/src/visuals/ElectronicCircuitNode.h +++ b/plugins/circuits/src/visuals/ElectronicCircuitNode.h @@ -31,10 +31,10 @@ 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; 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..fff269f 100644 --- a/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.cpp +++ b/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.cpp @@ -1,6 +1,6 @@ #include "LogicGatePrimitiveShapes.h" -std::string LogicGatePrimitiveShapes::getAndGateShape() +String LogicGatePrimitiveShapes::getAndGateShape() { return "M4 8 h24 a16 16 0 0 1 0 32 h-24Z"; } @@ -24,7 +24,7 @@ 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"; } diff --git a/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.h b/plugins/circuits/src/visuals/LogicGatePrimitiveShapes.h index 2350087..4323086 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 std::string getAndGateShape(); + static String getAndGateShape(); static Point2 getOrGateConnectionLocation(bool isInput, std::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..0eed5a6 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 "Memory.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..e9835e6 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 "Memory.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..d36e460 100644 --- a/plugins/music/src/midi/MidiEvent.h +++ b/plugins/music/src/midi/MidiEvent.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Memory.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..fc3e3ab 100644 --- a/plugins/music/src/midi/MidiTrack.cpp +++ b/plugins/music/src/midi/MidiTrack.cpp @@ -27,9 +27,9 @@ std::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..f9f5963 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 "Memory.h" +#include "String.h" #include "MidiEvent.h" class MidiEvent; -using MidiEventPtr = std::unique_ptr; +using MidiEventPtr = Ptr; class MidiTrack { @@ -22,9 +22,9 @@ public: std::size_t GetNumEvents(); - std::string Serialize() const; + String Serialize() const; private: - std::vector mEvents; + Vector mEvents; }; diff --git a/plugins/music/src/midi/reader/MidiMetaEventAdapter.cpp b/plugins/music/src/midi/reader/MidiMetaEventAdapter.cpp index 5e475a6..d272a7c 100644 --- a/plugins/music/src/midi/reader/MidiMetaEventAdapter.cpp +++ b/plugins/music/src/midi/reader/MidiMetaEventAdapter.cpp @@ -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,7 +104,7 @@ int MidiMetaEventAdapter::ReadIntEvent(std::ifstream* file, MetaMidiEvent* event byteCount ++; } - std::string buffer; + String buffer; BinaryStream::getNextNBytes(file, buffer.data(), length); byteCount += length; @@ -119,7 +119,7 @@ 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; 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/quantum_computing/src/QuantumCircuit.cpp b/plugins/quantum_computing/src/QuantumCircuit.cpp index 2ee58f1..b025f37 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; } 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..cef516a 100644 --- a/plugins/quantum_computing/src/QuantumCircuitReader.cpp +++ b/plugins/quantum_computing/src/QuantumCircuitReader.cpp @@ -10,13 +10,13 @@ #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(); @@ -31,7 +31,7 @@ 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, std::size_t jdx) { mWorkingString.clear(); std::size_t cursor = 0; @@ -39,7 +39,7 @@ void QuantumCircuitReader::onLine(const std::string& line, std::size_t jdx) 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,7 +157,7 @@ void QuantumCircuitReader::onKet(Location, const std::string value) mWorkingCircuit->addInputTerminal(std::move(input_terminal)); } -std::size_t QuantumCircuitReader::getWireEnd(const std::string& segment) +std::size_t QuantumCircuitReader::getWireEnd(const String& segment) { std::size_t idx = 0; for (const auto c : segment) @@ -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..3e1c786 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; - void onLine(const std::string& line, std::size_t jdx); + void onLine(const String& line, std::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); + std::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..49603d8 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(std::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..4223214 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(std::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..bd8bc13 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 "Memory.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..47a2fcb 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(std::size_t numIn, std::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,7 +20,7 @@ NInMOutQuantumGate::NInMOutQuantumGate(std::size_t numIn, std::size_t numOut, st } else { - mOutputs = std::vector(numOut, nullptr); + mOutputs = Vector(numOut, nullptr); } } diff --git a/plugins/quantum_computing/src/circuit_elements/QuantumGate.h b/plugins/quantum_computing/src/circuit_elements/QuantumGate.h index 704db82..36570f5 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 { @@ -39,13 +39,13 @@ 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(std::size_t numIn, std::size_t numOut, Vector inputs = {}, Vector outputs = {}); virtual ~NInMOutQuantumGate() = default; @@ -85,8 +85,8 @@ private: std::size_t mNumIn{ 1 }; std::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..a8e6707 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 "Memory.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..140aae4 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 "Memory.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.h b/plugins/quantum_computing/src/visuals/QuantumCircuitNode.h index 2aad470..be9baef 100644 --- a/plugins/quantum_computing/src/visuals/QuantumCircuitNode.h +++ b/plugins/quantum_computing/src/visuals/QuantumCircuitNode.h @@ -29,10 +29,10 @@ 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; diff --git a/plugins/quantum_computing/src/visuals/QuantumGateNode.cpp b/plugins/quantum_computing/src/visuals/QuantumGateNode.cpp index eb9716a..c47dcba 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"; 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/base/compiler/BuildLibrary.cpp b/src/base/compiler/BuildLibrary.cpp index ffd7cc9..1c4486b 100644 --- a/src/base/compiler/BuildLibrary.cpp +++ b/src/base/compiler/BuildLibrary.cpp @@ -12,14 +12,25 @@ Status BuildLibrary::scan() { LOG_INFO("Scanning build file at: " << m_build_config); const auto search_dir = m_build_config.parent_path(); - const auto status = Directory::getFilesWithExtension(search_dir, + + STATUS_CHECK(Directory::getFilesWithExtension(search_dir, ".cpp", m_sources, - true); - return status; + true), "Error collecting source files") + + m_include_dirs.push_back(search_dir); + + STATUS_CHECK(Directory::getAllSubDirectories(search_dir, + m_include_dirs), "Error collecting include dirs") + return {}; } const Vector& BuildLibrary::get_sources() const { return m_sources; +} + +const Vector& BuildLibrary::get_include_dirs() const +{ + return m_include_dirs; } \ No newline at end of file diff --git a/src/base/compiler/BuildLibrary.h b/src/base/compiler/BuildLibrary.h index f1777b1..7bc9243 100644 --- a/src/base/compiler/BuildLibrary.h +++ b/src/base/compiler/BuildLibrary.h @@ -14,9 +14,11 @@ public: const Vector& get_sources() const; + const Vector& get_include_dirs() const; + private: FileSystemPath m_build_config; Vector m_sources; - Vector m_includes; + Vector m_include_dirs; String m_name; }; \ No newline at end of file diff --git a/src/base/compiler/BuildSession.cpp b/src/base/compiler/BuildSession.cpp index 257bde8..c4f2180 100644 --- a/src/base/compiler/BuildSession.cpp +++ b/src/base/compiler/BuildSession.cpp @@ -16,6 +16,9 @@ BuildSession::BuildSession(const String& source_dir, { m_build_dir = build_dir; } + m_compiler_flags.push_back("-g"); + m_compiler_flags.push_back("-fno-exceptions"); + m_compiler_flags.push_back("-fno-rtti"); } Status BuildSession::scan() @@ -55,19 +58,22 @@ Status BuildSession::build() { for(const auto& source : library.get_sources()) { - String compiler_command = m_compiler_command + " -c "; - compiler_command += source.str() + " "; - LOG_INFO("Running command: " << compiler_command); - - const auto self_name = Process::get_self_name(); - if (!self_name.ok()) + Vector args = m_compiler_flags; + args.push_back("-c"); + for(const auto& include_dir : library.get_include_dirs()) { - return Status(self_name.error()); + args.push_back(_s("-I") + include_dir.str()); } - LOG_INFO("Self name is: " << self_name.value()); - break; + args.push_back(source.str()); + LOG_INFO("Compiling " << source.file_name()); + const auto run_status = Process::launch(m_compiler_command, args); + if (!run_status.ok()) + { + return run_status; + } + //break; } - break; + //break; } return {}; } \ No newline at end of file diff --git a/src/base/compiler/BuildSession.h b/src/base/compiler/BuildSession.h index c5bdf89..9c5a689 100644 --- a/src/base/compiler/BuildSession.h +++ b/src/base/compiler/BuildSession.h @@ -16,8 +16,8 @@ public: Status add_library(const FileSystemPath& config_path); private: - String m_compiler_command{"g++"}; - String m_compiler_flags{"-g -fno-exceptions -fno-rtti"}; + String m_compiler_command{"/usr/bin/g++"}; + Vector m_compiler_flags; FileSystemPath m_source_dir; FileSystemPath m_build_dir; Vector m_libraries; 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/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..0a6073a 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,14 +73,14 @@ void TemplateFile::onTextSpanFinished() mWorkingLineContent.clear(); } -std::size_t TemplateFile::checkForStatement(const std::string& lineSection) +std::size_t TemplateFile::checkForStatement(const String& lineSection) { if (lineSection.empty()) { return 0; } - std::vector hits; + Vector hits; std::size_t hit_size{0}; if (Lexer::matchPattern("{%@%}", lineSection, '@', hits)) { @@ -97,14 +97,14 @@ std::size_t TemplateFile::checkForStatement(const std::string& lineSection) return hit_size; } -std::size_t TemplateFile::checkForExpression(const std::string& lineSection) +std::size_t TemplateFile::checkForExpression(const String& lineSection) { if (lineSection.empty()) { return 0; } - std::vector hits; + Vector hits; std::size_t hit_size{0}; if (Lexer::matchPattern("{{@}}", lineSection, '@', hits)) { @@ -121,7 +121,7 @@ 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; mWorkingLineContent.clear(); @@ -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..15a009c 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); + std::size_t checkForStatement(const String& lineSection); - std::size_t checkForExpression(const std::string& lineSection); + std::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..20f8c82 100644 --- a/src/base/compiler/template_engine/TemplateNode.cpp +++ b/src/base/compiler/template_engine/TemplateNode.cpp @@ -13,7 +13,7 @@ TemplateNode* TemplateNode::getParent() const return mParent; } -void TemplateNode::addChild(std::unique_ptr child) +void TemplateNode::addChild(Ptr child) { mChildren.push_back(std::move(child)); } @@ -23,7 +23,7 @@ std::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,7 +50,7 @@ TemplateNode::Type TemplateNode::getType() const return Type::NONE; } -std::string TemplateNode::getIdentifier() const +String TemplateNode::getIdentifier() const { return {}; } @@ -60,9 +60,9 @@ TemplateNode* TemplateNode::getChild(std::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..0693ad4 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 "Memory.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* 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; 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..ef137fe 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 "String.h" #include 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; + std::unordered_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..0398414 100644 --- a/src/base/compiler/template_engine/TemplatingEngine.h +++ b/src/base/compiler/template_engine/TemplatingEngine.h @@ -3,9 +3,9 @@ #include "File.h" #include "TemplateFile.h" -#include -#include -#include +#include "Vector.h" +#include "String.h" +#include "Memory.h" #include 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; + std::unordered_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/CyclicRedundancyChecker.cpp b/src/base/compression/CyclicRedundancyChecker.cpp index 97f518b..f73abfc 100644 --- a/src/base/compression/CyclicRedundancyChecker.cpp +++ b/src/base/compression/CyclicRedundancyChecker.cpp @@ -2,7 +2,7 @@ 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++) { diff --git a/src/base/compression/CyclicRedundancyChecker.h b/src/base/compression/CyclicRedundancyChecker.h index a20a1cf..9f0ec5a 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 { @@ -20,5 +20,5 @@ private: uint32_t mLastValue{0xffffffffL}; static const std::size_t TABLE_SIZE{ 256 }; - std::vector mTable; + Vector mTable; }; diff --git a/src/base/compression/Lz77Encoder.cpp b/src/base/compression/Lz77Encoder.cpp index e5f649b..94810cc 100644 --- a/src/base/compression/Lz77Encoder.cpp +++ b/src/base/compression/Lz77Encoder.cpp @@ -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; } @@ -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 64ecb79..fb5c6b4 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 "Memory.h" #include class PrefixCodeGenerator; @@ -22,13 +22,13 @@ 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; @@ -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..f766016 100644 --- a/src/base/compression/ZlibEncoder.cpp +++ b/src/base/compression/ZlibEncoder.cpp @@ -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"; } @@ -76,9 +76,9 @@ void ZlibEncoder::parseExtraFlags(unsigned char extraFlags, unsigned char compre mFlagLevel = static_cast(ByteUtils::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..f8a8642 100644 --- a/src/base/compression/ZlibEncoder.h +++ b/src/base/compression/ZlibEncoder.h @@ -4,8 +4,8 @@ #include "DeflateElements.h" -#include -#include +#include "Memory.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..6a977d2 100644 --- a/src/base/compression/deflate/DeflateBlock.cpp +++ b/src/base/compression/deflate/DeflateBlock.cpp @@ -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'; diff --git a/src/base/compression/deflate/DeflateBlock.h b/src/base/compression/deflate/DeflateBlock.h index 5658464..4872f22 100644 --- a/src/base/compression/deflate/DeflateBlock.h +++ b/src/base/compression/deflate/DeflateBlock.h @@ -5,7 +5,7 @@ #include "BitStream.h" -#include +#include "Memory.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..9536c2e 100644 --- a/src/base/compression/deflate/DeflateEncoder.cpp +++ b/src/base/compression/deflate/DeflateEncoder.cpp @@ -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) diff --git a/src/base/compression/deflate/DeflateEncoder.h b/src/base/compression/deflate/DeflateEncoder.h index 9d74cc0..4e750e4 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 "Memory.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..35d0c03 100644 --- a/src/base/compression/huffman/HuffmanCodeLengthTable.cpp +++ b/src/base/compression/huffman/HuffmanCodeLengthTable.cpp @@ -77,19 +77,19 @@ void HuffmanCodeLengthTable::buildCompressedLengthSequence() } } - mCompressedLengthCounts = std::vector(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; } @@ -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,7 +173,7 @@ 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; @@ -201,7 +201,7 @@ const PrefixCode& HuffmanCodeLengthTable::getCode(std::size_t index) const return mCodes[index]; } -std::string HuffmanCodeLengthTable::dumpPrefixCodes() const +String HuffmanCodeLengthTable::dumpPrefixCodes() const { return mTree.dump(); } @@ -233,13 +233,13 @@ unsigned HuffmanCodeLengthTable::getCodeLength(std::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); + mInputLengthSequence = Vector(DEFLATE_PERMUTATION_SIZE, 0); for(std::size_t idx=0; idx -#include +#include "Vector.h" +#include "String.h" #include class BitStream; @@ -15,7 +15,7 @@ public: void buildCompressedLengthSequence(); - std::string dumpPrefixCodes() const; + String dumpPrefixCodes() const; std::optional findMatch(std::size_t treeIndex, uint32_t code) const; @@ -26,9 +26,9 @@ public: std::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; @@ -36,7 +36,7 @@ public: std::size_t mapToDeflateIndex(std::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..a0906b3 100644 --- a/src/base/compression/huffman/HuffmanEncoder.cpp +++ b/src/base/compression/huffman/HuffmanEncoder.cpp @@ -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) { @@ -92,7 +92,7 @@ void HuffmanEncoder::encode(const std::vector& counts) void HuffmanEncoder::encode(const std::unordered_map& counts) { - std::vector just_counts; + Vector just_counts; for (const auto& data: counts) { mSymbolMapping.push_back(data.first); @@ -132,12 +132,12 @@ std::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..e4e4e6c 100644 --- a/src/base/compression/huffman/HuffmanEncoder.h +++ b/src/base/compression/huffman/HuffmanEncoder.h @@ -5,7 +5,7 @@ #include "HuffmanCodeLengthTable.h" #include "HuffmanFixedCodes.h" -#include +#include "Vector.h" #include #include @@ -26,7 +26,7 @@ class HuffmanEncoder : public PrefixCodeGenerator using Hit = std::tuple; public: - void encode(const std::vector& counts); + void encode(const Vector& counts); void encode(const std::unordered_map& counts); uint32_t getLengthValue(unsigned length); @@ -39,18 +39,18 @@ public: std::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 -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}; @@ -330,7 +330,7 @@ void HuffmanStream::readCodingsTable() unsigned num_code_lengths = h_clen + 4; //std::cout << "Got HCLEN " << num_code_lengths << std::endl; - auto sequence = std::vector(num_code_lengths, 0); + auto sequence = Vector(num_code_lengths, 0); unsigned char buffer{0}; for(unsigned idx = 0; idx< num_code_lengths; idx++) { 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..792c053 100644 --- a/src/base/compression/huffman/HuffmanTree.cpp +++ b/src/base/compression/huffman/HuffmanTree.cpp @@ -17,7 +17,7 @@ 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) { @@ -106,9 +106,9 @@ unsigned HuffmanTree::getCodeLength(std::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..acd2682 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,11 +35,11 @@ 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; @@ -51,5 +51,5 @@ public: void sortTable(); private: - std::vector mTable; + Vector mTable; }; diff --git a/src/base/core/base_types/Color.cpp b/src/base/core/base_types/Color.cpp index 779fcde..29b3cd7 100644 --- a/src/base/core/base_types/Color.cpp +++ b/src/base/core/base_types/Color.cpp @@ -9,7 +9,7 @@ Color::Color(unsigned char r, unsigned char g, unsigned char b, double a) } -Color::Color(const std::string& hexString) +Color::Color(const String& hexString) { if (hexString.size() < 7) { @@ -24,12 +24,12 @@ Color::Color(const std::string& hexString) mB = toDecimal(hexString.substr(5, 2)); } -unsigned char Color::toDecimal(const std::string& hex) const +unsigned char Color::toDecimal(const 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 ) +Ptr Color::Create(unsigned char r, unsigned char g, unsigned char b, double a ) { return std::make_unique(r, g, b, a); } @@ -105,7 +105,7 @@ void Color::setAlpha(float alpha) mAlpha = static_cast(alpha); } -std::unique_ptr Color::Create(const Color& color) +Ptr Color::Create(const Color& color) { return std::make_unique(color); } @@ -130,7 +130,7 @@ double Color::getAlpha() const return mAlpha; } -std::vector Color::getAsVectorDouble() const +Vector Color::getAsVectorDouble() const { return { mR / 255.0, mG / 255.0, mB / 255.0, mAlpha }; } @@ -140,7 +140,7 @@ uint32_t Color::getAsUInt32() const return static_cast(mB + (mG << 8) + (mR << 16)); } -std::string Color::toString() const +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/base_types/Color.h b/src/base/core/base_types/Color.h index 5246fd6..fd116d3 100644 --- a/src/base/core/base_types/Color.h +++ b/src/base/core/base_types/Color.h @@ -1,8 +1,8 @@ #pragma once -#include -#include -#include +#include "Memory.h" +#include "Vector.h" +#include "String.h" #include class Color @@ -18,22 +18,22 @@ public: RGBA }; - Color(const std::string& hexString); + Color(const 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); + 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; - std::vector getAsVectorDouble() const; + Vector getAsVectorDouble() const; uint32_t getAsUInt32() const; - std::string toString() const; + String toString() const; std::size_t getSize() const; @@ -59,7 +59,7 @@ public: } private: - unsigned char toDecimal(const std::string& hex) const; + unsigned char toDecimal(const String& hex) const; unsigned char mR{0}; unsigned char mG{0}; @@ -71,4 +71,4 @@ private: }; using ColorPtr = std::shared_ptr; -using ColorUPtr = std::unique_ptr; +using ColorUPtr = Ptr; diff --git a/src/base/core/data_structures/Dictionary.cpp b/src/base/core/data_structures/Dictionary.cpp index 4268458..916f640 100644 --- a/src/base/core/data_structures/Dictionary.cpp +++ b/src/base/core/data_structures/Dictionary.cpp @@ -1,23 +1,23 @@ #include "Dictionary.h" -bool Dictionary::hasKey(const std::string& key) const +bool Dictionary::hasKey(const String& key) const { return hasStringKey(key) || hasDictKey(key); } -bool Dictionary::hasStringKey(const std::string& key) const +bool Dictionary::hasStringKey(const String& key) const { return mStringData.count(key) > 0; } -bool Dictionary::hasDictKey(const std::string& key) const +bool Dictionary::hasDictKey(const String& key) const { return mDictData.count(key) > 0; } -std::vector Dictionary::getStringKeys() const +Vector Dictionary::getStringKeys() const { - std::vector keys; + Vector keys; for (const auto& item : mStringData) { keys.push_back(item.first); @@ -25,9 +25,9 @@ std::vector Dictionary::getStringKeys() const return keys; } -std::vector Dictionary::getDictKeys() const +Vector Dictionary::getDictKeys() const { - std::vector keys; + Vector keys; for (const auto& item : mDictData) { keys.push_back(item.first); @@ -35,22 +35,22 @@ std::vector Dictionary::getDictKeys() const return keys; } -Dictionary* Dictionary::getDict(const std::string& key) const +Dictionary* Dictionary::getDict(const String& key) const { return mDictData.at(key).get(); } -std::string Dictionary::getItem(const std::string& key) const +String Dictionary::getItem(const String& key) const { return mStringData.at(key); } -void Dictionary::addStringItem(const std::string& key, const std::string& item) +void Dictionary::addStringItem(const String& key, const String& item) { mStringData[key] = item; } -void Dictionary::addDictItem(const std::string& key, std::unique_ptr dict) +void Dictionary::addDictItem(const String& key, Ptr dict) { mDictData[key] = std::move(dict); } diff --git a/src/base/core/data_structures/Dictionary.h b/src/base/core/data_structures/Dictionary.h index c26468e..e8439d4 100644 --- a/src/base/core/data_structures/Dictionary.h +++ b/src/base/core/data_structures/Dictionary.h @@ -1,8 +1,8 @@ #pragma once -#include -#include +#include "String.h" +#include "Vector.h" #include -#include +#include "Memory.h" class Dictionary { @@ -10,25 +10,25 @@ public: Dictionary() = default; virtual ~Dictionary() = default; - void addStringItem(const std::string& key, const std::string& item); + void addStringItem(const String& key, const String& item); - void addDictItem(const std::string& key, std::unique_ptr dict); + void addDictItem(const String& key, Ptr dict); - Dictionary* getDict(const std::string& key) const; + Dictionary* getDict(const String& key) const; - std::vector getDictKeys() const; + Vector getDictKeys() const; - std::vector getStringKeys() const; + Vector getStringKeys() const; - std::string getItem(const std::string& key) const; + String getItem(const String& key) const; - bool hasKey(const std::string& key) const; + bool hasKey(const String& key) const; - bool hasStringKey(const std::string& key) const; + bool hasStringKey(const String& key) const; - bool hasDictKey(const std::string& key) const; + bool hasDictKey(const String& key) const; protected: - std::map mStringData; - std::map > mDictData; + std::map mStringData; + std::map > mDictData; }; diff --git a/src/base/core/encoding/ByteUtils.cpp b/src/base/core/encoding/ByteUtils.cpp index 61f943f..8710031 100644 --- a/src/base/core/encoding/ByteUtils.cpp +++ b/src/base/core/encoding/ByteUtils.cpp @@ -99,7 +99,7 @@ bool ByteUtils::getBitN(uint32_t input, unsigned n) return input & (1 << n); } -unsigned char ByteUtils::getFromString(const std::string& string) +unsigned char ByteUtils::getFromString(const String& string) { unsigned char ret{0}; @@ -118,9 +118,9 @@ unsigned char ByteUtils::getFromString(const std::string& string) return ret; } -std::string ByteUtils::toString(uint32_t input, unsigned length) +String ByteUtils::toString(uint32_t input, unsigned length) { - std::string ret; + String ret; if (length > 8) { unsigned overshoot = length - 8; diff --git a/src/base/core/encoding/StringUtils.cpp b/src/base/core/encoding/StringUtils.cpp index e1e56e3..c6bf8e0 100644 --- a/src/base/core/encoding/StringUtils.cpp +++ b/src/base/core/encoding/StringUtils.cpp @@ -20,28 +20,28 @@ bool StringUtils::isAlphabetical(char c) return std::isalpha(c); } -std::vector StringUtils::toBytes(const std::string& input) +Vector StringUtils::toBytes(const String& input) { return {input.begin(), input.end()}; } -std::string StringUtils::toString(const std::vector& bytes) +String StringUtils::toString(const Vector& bytes) { return {bytes.begin(), bytes.end()}; } -std::vector StringUtils::toLines(const std::string& input) +Vector StringUtils::toLines(const String& input) { - auto result = std::vector{}; - auto ss = std::stringstream{input}; - for (std::string line; std::getline(ss, line, '\n');) + auto result = Vector{}; + auto ss = Stringstream{input}; + for (String line; std::getline(ss, line, '\n');) { result.push_back(line); } return result; } -bool StringUtils::isWhitespaceOnly(const std::string& input) +bool StringUtils::isWhitespaceOnly(const String& input) { if (input.empty()) { @@ -53,10 +53,10 @@ bool StringUtils::isWhitespaceOnly(const std::string& input) } } -std::size_t StringUtils::countFirstConsecutiveHits(const std::string& input, char c) +std::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; } @@ -78,7 +78,7 @@ std::size_t StringUtils::countFirstConsecutiveHits(const std::string& input, cha } } -std::string StringUtils::stripSurroundingWhitepsace(const std::string& input) +String StringUtils::stripSurroundingWhitepsace(const String& input) { if (input.empty()) { @@ -112,10 +112,10 @@ std::string StringUtils::stripSurroundingWhitepsace(const std::string& input) return input.substr(first_nonspace, last_nonspace-first_nonspace + 1); } -std::vector StringUtils::split(const std::string& input) +Vector StringUtils::split(const String& input) { - std::vector substrings; - std::string working_string; + Vector substrings; + String working_string; std::locale loc; bool last_was_nonspace{ false }; for (auto c : input) @@ -142,21 +142,21 @@ std::vector StringUtils::split(const std::string& input) return substrings; } -std::string StringUtils::toLower(const std::string& s) +String StringUtils::toLower(const String& s) { - std::string ret; + 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) +String StringUtils::toPaddedString(unsigned numBytes, unsigned entry) { - std::stringstream sstr; + Stringstream sstr; sstr << std::setfill('0') << std::setw(numBytes) << entry; return sstr.str(); } -std::string StringUtils::stripQuotes(const std::string& input) +String StringUtils::stripQuotes(const String& input) { if (input.size() < 3) { @@ -175,10 +175,10 @@ std::string StringUtils::stripQuotes(const std::string& input) return input.substr(start_index, end_index - start_index + 1); } -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) + if (found != String::npos) { return input.substr(found + prefix.size(), input.size()-found); } @@ -188,12 +188,12 @@ std::string StringUtils::removeUpTo(const std::string& input, const std::string& } } -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; } diff --git a/src/base/core/encoding/StringUtils.h b/src/base/core/encoding/StringUtils.h index b46aab0..a3e98ba 100644 --- a/src/base/core/encoding/StringUtils.h +++ b/src/base/core/encoding/StringUtils.h @@ -2,8 +2,8 @@ #include "ByteTypes.h" -#include -#include +#include "String.h" +#include "Vector.h" class StringUtils { @@ -18,7 +18,7 @@ public: static constexpr char SINGLE_QUOTE = '\''; static constexpr char COLON = ':'; - static std::size_t countFirstConsecutiveHits(const std::string& input, char c); + static std::size_t countFirstConsecutiveHits(const String& input, char c); static bool isAlphaNumeric(char c); @@ -26,25 +26,25 @@ public: static bool isSpace(char c); - static bool isWhitespaceOnly(const std::string& input); + static bool isWhitespaceOnly(const String& input); - static std::string removeUpTo(const std::string& input, const std::string& prefix); + static String removeUpTo(const String& input, const String& prefix); - static std::vector split(const std::string& input); + static Vector split(const String& input); - static bool startsWith(const std::string& input, const std::string& prefix, bool ignoreWhitespace = false); + static bool startsWith(const String& input, const String& prefix, bool ignoreWhitespace = false); - static std::string stripSurroundingWhitepsace(const std::string& input); + static String stripSurroundingWhitepsace(const String& input); - static std::string stripQuotes(const std::string& input); + static String stripQuotes(const String& input); - static std::vector toBytes(const std::string& input); + static Vector toBytes(const String& input); - static std::string toLower(const std::string& s); + static String toLower(const String& s); - static std::vector toLines(const std::string& input); + static Vector toLines(const String& input); - static std::string toPaddedString(unsigned numBytes, unsigned entry); + static String toPaddedString(unsigned numBytes, unsigned entry); - static std::string toString(const std::vector& bytes); + static String toString(const Vector& bytes); }; diff --git a/src/base/core/encoding/UnicodeUtils.cpp b/src/base/core/encoding/UnicodeUtils.cpp index fe02353..db6fbee 100644 --- a/src/base/core/encoding/UnicodeUtils.cpp +++ b/src/base/core/encoding/UnicodeUtils.cpp @@ -2,21 +2,21 @@ #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 @@ -24,7 +24,7 @@ std::string UnicodeUtils::utf16ToUtf8String(const std::wstring& input) #endif } -std::wstring UnicodeUtils::utf8ToUtf16WString(const std::string& input) +std::wstring UnicodeUtils::utf8ToUtf16WString(const String& input) { if (input.empty()) { @@ -33,7 +33,7 @@ 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 @@ -41,11 +41,11 @@ std::wstring UnicodeUtils::utf8ToUtf16WString(const std::string& input) #endif } -std::vector UnicodeUtils::utf8ToUtf32(const std::string& input) +Vector UnicodeUtils::utf8ToUtf32(const String& input) { const auto utf_16 = utf8ToUtf16WString(input); - std::vector output; + Vector output; std::size_t pos = 0; while (pos < utf_16.size()) { diff --git a/src/base/core/encoding/UnicodeUtils.h b/src/base/core/encoding/UnicodeUtils.h index 4c3d2d4..d8bebae 100644 --- a/src/base/core/encoding/UnicodeUtils.h +++ b/src/base/core/encoding/UnicodeUtils.h @@ -1,17 +1,17 @@ #pragma once -#include -#include +#include "String.h" +#include "Vector.h" #include class UnicodeUtils { public: - static std::string utf16ToUtf8String(const std::wstring& input); + static String utf16ToUtf8String(const std::wstring& input); - static std::wstring utf8ToUtf16WString(const std::string& input); + static std::wstring utf8ToUtf16WString(const String& input); - static std::vector utf8ToUtf32(const std::string& input); + static Vector utf8ToUtf32(const String& input); private: static bool isSurrogate(wchar_t c); diff --git a/src/base/core/filesystem/Directory.cpp b/src/base/core/filesystem/Directory.cpp index 879ede0..03a69ab 100644 --- a/src/base/core/filesystem/Directory.cpp +++ b/src/base/core/filesystem/Directory.cpp @@ -5,7 +5,8 @@ #include #include -Status Directory::getDirectoryContents(const FileSystemPath& path, Vector& ret) +Status Directory::getDirectoryContents(const FileSystemPath& path, + Vector& ret, bool directoryOnly) { Status status; errno = 0; @@ -24,9 +25,19 @@ Status Directory::getDirectoryContents(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, @@ -59,7 +99,6 @@ Status Directory::getFiles(const FileSystemPath& path, { return Status(is_dir.error()); } - if (!is_dir.value()) { return {}; @@ -82,7 +121,6 @@ Status Directory::getFiles(const FileSystemPath& path, } else { - LOG_INFO("Adding entry " << entry); ret.push_back(entry); } } @@ -91,7 +129,7 @@ Status Directory::getFiles(const FileSystemPath& path, IF_OK_AND_TRUE(entry.is_directory()) { Vector child_paths; - STATUS_CHECK(getFiles(entry, child_paths, recursive), "Failed to get files"); + STATUS_CHECK(getFiles(entry, child_paths, recursive, extension), "Failed to get files"); ret.extend(child_paths); } } diff --git a/src/base/core/filesystem/Directory.h b/src/base/core/filesystem/Directory.h index f2c2dc9..ec9d283 100644 --- a/src/base/core/filesystem/Directory.h +++ b/src/base/core/filesystem/Directory.h @@ -8,10 +8,13 @@ class Directory { public: static Status getDirectoryContents(const FileSystemPath& path, - Vector& content); + 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, diff --git a/src/base/core/filesystem/FileFormats.cpp b/src/base/core/filesystem/FileFormats.cpp index 925b28d..201199f 100644 --- a/src/base/core/filesystem/FileFormats.cpp +++ b/src/base/core/filesystem/FileFormats.cpp @@ -11,12 +11,12 @@ FileFormat::ExtensionMap FileFormat::mExtensions = [] return ret; }(); -bool FileFormat::isFormat(const std::string& extension, Format format) +bool FileFormat::isFormat(const String& extension, Format format) { return StringUtils::toLower(extension) == mExtensions[format]; } -FileFormat::Format FileFormat::inferFormat(const std::string& query) +FileFormat::Format FileFormat::inferFormat(const String& query) { for(const auto& extension : mExtensions) { @@ -28,7 +28,7 @@ FileFormat::Format FileFormat::inferFormat(const std::string& query) return Format::Unknown; } -std::string FileFormat::getExtension(Format format) +String FileFormat::getExtension(Format format) { return mExtensions[format]; } diff --git a/src/base/core/filesystem/PathUtils.cpp b/src/base/core/filesystem/PathUtils.cpp index a56c0bb..1b18251 100644 --- a/src/base/core/filesystem/PathUtils.cpp +++ b/src/base/core/filesystem/PathUtils.cpp @@ -1,7 +1,7 @@ #include "PathUtils.h" -std::string PathUtils::getBaseFilename(const Path& path) +String PathUtils::getBaseFilename(const Path& path) { return path.stem().string(); } @@ -11,9 +11,9 @@ Path PathUtils::getRelativePath(const Path& input, const Path& relativeTo) return std::filesystem::relative(input, relativeTo); } -std::string PathUtils::getPathDelimited(const Path& path, char delimiter) +String PathUtils::getPathDelimited(const Path& path, char delimiter) { - std::string name; + String name; unsigned count = 0; for(const auto& element : path) diff --git a/src/base/core/filesystem/PathUtils.h b/src/base/core/filesystem/PathUtils.h index 5c59dea..eaa308f 100644 --- a/src/base/core/filesystem/PathUtils.h +++ b/src/base/core/filesystem/PathUtils.h @@ -1,17 +1,17 @@ #pragma once #include -#include -#include +#include "String.h" +#include "Vector.h" using Path = std::filesystem::path; class PathUtils { public: - static std::string getBaseFilename(const Path& path); + static String getBaseFilename(const Path& path); static Path getRelativePath(const Path& path, const Path& relativeTo); - static std::string getPathDelimited(const Path& path, char delimiter='-'); + static String getPathDelimited(const Path& path, char delimiter='-'); }; diff --git a/src/base/core/logging/FileLogger.cpp b/src/base/core/logging/FileLogger.cpp index e6aa155..2849ca8 100644 --- a/src/base/core/logging/FileLogger.cpp +++ b/src/base/core/logging/FileLogger.cpp @@ -21,12 +21,12 @@ FileLogger::~FileLogger() } -void FileLogger::SetWorkDirectory(const std::string& workDir) +void FileLogger::SetWorkDirectory(const String& workDir) { mWorkDirectory = workDir; } -void FileLogger::SetFileName(const std::string& fileName) +void FileLogger::SetFileName(const String& fileName) { mFileName = fileName; } @@ -64,7 +64,7 @@ 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) +void FileLogger::LogLine(const String& logType, const std::ostringstream& line, const String& fileName, const String& functionName, int lineNumber) { if (mDisabled) { @@ -72,7 +72,7 @@ void FileLogger::LogLine(const std::string& logType, const std::ostringstream& l } std::time_t t = std::time(nullptr); - const std::string cleanedFileName = fileName.substr(fileName.find_last_of("/\\") + 1); + const String cleanedFileName = fileName.substr(fileName.find_last_of("/\\") + 1); std::tm time_buf{ }; #ifdef WIN32 gmtime_s(&time_buf, &t); diff --git a/src/base/core/memory/SharedMemory.cpp b/src/base/core/memory/SharedMemory.cpp index 5cb9901..481e701 100644 --- a/src/base/core/memory/SharedMemory.cpp +++ b/src/base/core/memory/SharedMemory.cpp @@ -10,7 +10,7 @@ #include #endif -void SharedMemory::allocate(const std::string& namePrefix, std::size_t size) +void SharedMemory::allocate(const String& namePrefix, std::size_t size) { createFile(namePrefix); @@ -45,7 +45,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; @@ -67,9 +67,9 @@ 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); diff --git a/src/base/core/memory/SharedMemory.h b/src/base/core/memory/SharedMemory.h index d483438..0aa1699 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, std::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/protocol/HttpHeader.cpp b/src/base/core/protocol/HttpHeader.cpp index f4c84bc..993fb4d 100644 --- a/src/base/core/protocol/HttpHeader.cpp +++ b/src/base/core/protocol/HttpHeader.cpp @@ -9,20 +9,20 @@ 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) { diff --git a/src/base/core/protocol/HttpHeader.h b/src/base/core/protocol/HttpHeader.h index d9b231d..8515115 100644 --- a/src/base/core/protocol/HttpHeader.h +++ b/src/base/core/protocol/HttpHeader.h @@ -1,32 +1,32 @@ #pragma once -#include -#include +#include "String.h" +#include "Vector.h" #include class HttpHeader { public: HttpHeader(); - void parse(const std::vector& message); + void parse(const Vector& message); - std::string getContentType() const; + String getContentType() const; - std::string getHttpVersion() const; + 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; + String mHttpVersion; + String mContentType; + String mHost; + String mUserAgent; + String mAccept; + String mAcceptLanguage; + String mAcceptEncoding; + String mConnection; + String mReferer; + String mSecFetchDest; + String mSecFetchMode; + String mSecFetchSite; - std::map mOtherFields; + std::map mOtherFields; }; diff --git a/src/base/core/protocol/HttpParser.cpp b/src/base/core/protocol/HttpParser.cpp index 6b66639..64d209b 100644 --- a/src/base/core/protocol/HttpParser.cpp +++ b/src/base/core/protocol/HttpParser.cpp @@ -2,7 +2,7 @@ #include "StringUtils.h" -bool HttpParser::parsePreamble(const std::string& line, HttpPreamble& preamble) +bool HttpParser::parsePreamble(const String& line, HttpPreamble& preamble) { bool inPath{ false }; bool inMethod{ true }; diff --git a/src/base/core/protocol/HttpParser.h b/src/base/core/protocol/HttpParser.h index 78ec0d1..2283d13 100644 --- a/src/base/core/protocol/HttpParser.h +++ b/src/base/core/protocol/HttpParser.h @@ -5,5 +5,5 @@ class HttpParser { public: - static bool parsePreamble(const std::string& line, HttpPreamble& preamble); + 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 index c92d9c7..8cf321b 100644 --- a/src/base/core/protocol/HttpPreamble.h +++ b/src/base/core/protocol/HttpPreamble.h @@ -1,10 +1,10 @@ #pragma once -#include +#include "String.h" struct HttpPreamble { - std::string mMethod; - std::string mPath; - std::string mVersion; + String mMethod; + String mPath; + String mVersion; }; \ No newline at end of file diff --git a/src/base/core/protocol/HttpRequest.cpp b/src/base/core/protocol/HttpRequest.cpp index ce813a1..14b5005 100644 --- a/src/base/core/protocol/HttpRequest.cpp +++ b/src/base/core/protocol/HttpRequest.cpp @@ -5,7 +5,7 @@ #include -HttpRequest::HttpRequest(Verb verb, const std::string& path) +HttpRequest::HttpRequest(Verb verb, const String& path) : mVerb(verb) { mPreamble.mPath = path; @@ -16,14 +16,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) { @@ -37,14 +37,14 @@ std::string HttpRequest::toString(const std::string& host) const return out; } -void HttpRequest::fromString(const std::string& message) +void HttpRequest::fromString(const String& message) { - std::stringstream ss(message); + Stringstream ss(message); - std::string buffer; + String buffer; bool firstLine{ true }; - std::vector headers; + Vector headers; while (std::getline(ss, buffer, '\n')) { if (firstLine) diff --git a/src/base/core/protocol/HttpRequest.h b/src/base/core/protocol/HttpRequest.h index f54371d..b5a728c 100644 --- a/src/base/core/protocol/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,15 +21,15 @@ 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; diff --git a/src/base/core/protocol/HttpResponse.cpp b/src/base/core/protocol/HttpResponse.cpp index 6f3a0d5..8d2ae1a 100644 --- a/src/base/core/protocol/HttpResponse.cpp +++ b/src/base/core/protocol/HttpResponse.cpp @@ -28,24 +28,24 @@ unsigned short HttpResponse::getStatusCode() const return mStatusCode; } -const std::string& HttpResponse::getBody() const +const String& HttpResponse::getBody() const { return mBody; } -void HttpResponse::setBody(const std::string& body) +void HttpResponse::setBody(const String& body) { mBody = body; } -void HttpResponse::fromMessage(const std::string& message) +void HttpResponse::fromMessage(const String& message) { - std::stringstream ss(message); + Stringstream ss(message); - std::string buffer; + String buffer; bool firstLine{ true }; - std::vector headers; + Vector headers; while (std::getline(ss, buffer, '\n')) { if (firstLine) @@ -71,20 +71,20 @@ void HttpResponse::setClientError(const ClientError& error) mClientError = error; } -std::string HttpResponse::getHeaderString() const +String HttpResponse::getHeaderString() const { - std::string header = "HTTP/" + mHeader.getHttpVersion() + " " + std::to_string(mStatusCode) + " " + mResponseReason + "\n"; + 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 +const String& HttpResponse::getResponseReason() const { return mResponseReason; } -std::string HttpResponse::toString() const +String HttpResponse::toString() const { return getHeaderString() + "\n\n" + mBody; } @@ -94,7 +94,7 @@ void HttpResponse::setStatusCode(unsigned short code) mStatusCode = code; } -void HttpResponse::setResponseReason(const std::string& reason) +void HttpResponse::setResponseReason(const String& reason) { mResponseReason = reason; } diff --git a/src/base/core/protocol/HttpResponse.h b/src/base/core/protocol/HttpResponse.h index 80dd903..4a06746 100644 --- a/src/base/core/protocol/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/random/RandomUtils.cpp b/src/base/core/random/RandomUtils.cpp index fa31fab..8564ca4 100644 --- a/src/base/core/random/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(std::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 index 062bd34..f07ea37 100644 --- a/src/base/core/random/RandomUtils.h +++ b/src/base/core/random/RandomUtils.h @@ -1,10 +1,10 @@ #pragma once -#include +#include "Vector.h" class RandomUtils { public: - static std::vector getRandomVecUnsigned(std::size_t size); + static Vector getRandomVecUnsigned(std::size_t size); }; diff --git a/src/base/core/serialization/AbstractNamedItem.h b/src/base/core/serialization/AbstractNamedItem.h index e68dca8..7f07073 100644 --- a/src/base/core/serialization/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/TomlReader.cpp b/src/base/core/serialization/TomlReader.cpp index 3693a4f..38f8213 100644 --- a/src/base/core/serialization/TomlReader.cpp +++ b/src/base/core/serialization/TomlReader.cpp @@ -4,7 +4,7 @@ #include #include -TomlTable::TomlTable(const std::string& header) +TomlTable::TomlTable(const String& header) : mHeader(header) { @@ -15,22 +15,22 @@ 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); } -void TomlTable::addKeyValuePair(const std::string& key, const std::string& value) +void TomlTable::addKeyValuePair(const String& key, const String& value) { mMap[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) { return mTables[path].get(); } @@ -52,7 +52,7 @@ 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); } @@ -83,13 +83,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) @@ -137,7 +137,7 @@ void TomlReader::processLine(const std::string& line) } } -void TomlReader::onHeader(const std::string& header) +void TomlReader::onHeader(const String& header) { auto new_table = std::make_unique(header); auto table_temp = new_table.get(); @@ -145,7 +145,7 @@ void TomlReader::onHeader(const std::string& header) 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/TomlReader.h b/src/base/core/serialization/TomlReader.h index 7e4dfa5..7fc9b08 100644 --- a/src/base/core/serialization/TomlReader.h +++ b/src/base/core/serialization/TomlReader.h @@ -3,37 +3,37 @@ #include "File.h" #include -#include +#include "Memory.h" #include -#include +#include "String.h" using Path = std::filesystem::path; class TomlTable { public: - using Comment = std::pair; - using KeyValuePairs = std::unordered_map; + using Comment = std::pair; + using KeyValuePairs = std::unordered_map; - TomlTable(const std::string& header); + TomlTable(const String& header); void addComment(const Comment& comment); - void addTable(std::unique_ptr table); + void addTable(Ptr table); - void addKeyValuePair(const std::string& key, const std::string& value); + void addKeyValuePair(const String& key, const String& value); - std::string getHeader() const; + String getHeader() const; - TomlTable* getTable(const std::string& path); + TomlTable* getTable(const String& path); KeyValuePairs getKeyValuePairs() const; private: - std::string mHeader; - std::unordered_map > mTables; + String mHeader; + std::unordered_map > mTables; KeyValuePairs mMap; - std::vector mComments; + Vector mComments; }; class TomlContent @@ -43,10 +43,10 @@ public: TomlTable* getRootTable() const; - TomlTable* getTable(const std::string& path) const; + TomlTable* getTable(const String& path) const; private: - std::unique_ptr mRootTable; + Ptr mRootTable; }; class TomlReader @@ -58,14 +58,14 @@ public: void read(const Path& input_path); - void processLine(const std::string& line); + void processLine(const String& line); - void onHeader(const std::string& header); + void onHeader(const String& header); - void onKeyValuePair(const std::string key, const std::string value); + void onKeyValuePair(const String key, const String value); private: unsigned mLastSectionOffset{ 0 }; - std::unique_ptr mContent; + Ptr mContent; TomlTable* mWorkingTable{nullptr}; }; diff --git a/src/base/core/serialization/xml/XmlDocument.cpp b/src/base/core/serialization/xml/XmlDocument.cpp index f2bf626..7bd3c29 100644 --- a/src/base/core/serialization/xml/XmlDocument.cpp +++ b/src/base/core/serialization/xml/XmlDocument.cpp @@ -3,10 +3,8 @@ #include "XmlProlog.h" #include "XmlElement.h" -#include - XmlDocument::XmlDocument() - :mProlog(XmlProlog::Create("xml")) + : mProlog(XmlProlog::Create("xml")) { } @@ -16,12 +14,7 @@ XmlDocument::~XmlDocument() } -XmlDocumentPtr XmlDocument::Create() -{ - return std::make_unique(); -} - -void XmlDocument::setProlog(XmlPrologPtr prolog) +void XmlDocument::setProlog(Ptr prolog) { mProlog = std::move(prolog); } @@ -31,7 +24,7 @@ XmlProlog* XmlDocument::getProlog() const return mProlog.get(); } -void XmlDocument::setRoot(XmlElementPtr root) +void XmlDocument::setRoot(Ptr root) { mRoot = std::move(root); } diff --git a/src/base/core/serialization/xml/XmlDocument.h b/src/base/core/serialization/xml/XmlDocument.h index 049b0ef..7995916 100644 --- a/src/base/core/serialization/xml/XmlDocument.h +++ b/src/base/core/serialization/xml/XmlDocument.h @@ -1,14 +1,13 @@ #pragma once -#include -#include + +#include "Pointer.h" +#include "String.h" #include "XmlElement.h" #include "XmlProlog.h" class XmlElement; class XmlProlog; -using XmlPrologPtr = std::unique_ptr; -using XmlElementPtr = std::unique_ptr; class XmlDocument { @@ -16,16 +15,12 @@ public: XmlDocument(); virtual ~XmlDocument(); - static std::unique_ptr Create(); - XmlProlog* getProlog() const; XmlElement* getRoot() const; - void setProlog(XmlPrologPtr prolog); - void setRoot(XmlElementPtr root); + void setProlog(Ptr prolog); + void setRoot(Ptr root); private: XmlPrologPtr mProlog; XmlElementPtr mRoot; }; - -using XmlDocumentPtr = std::unique_ptr; diff --git a/src/base/core/serialization/xml/XmlParser.cpp b/src/base/core/serialization/xml/XmlParser.cpp index 9760e86..6973426 100644 --- a/src/base/core/serialization/xml/XmlParser.cpp +++ b/src/base/core/serialization/xml/XmlParser.cpp @@ -20,7 +20,7 @@ XmlParser::XmlParser() } -void XmlParser::processLine(const std::string& input) +void XmlParser::processLine(const String& input) { for (std::size_t idx=0; idx +#include "String.h" #include -#include +#include "Memory.h" class XmlDocument; -using XmlDocumentPtr = std::unique_ptr; +using XmlDocumentPtr = Ptr; class XmlElement; @@ -38,7 +38,7 @@ public: public: XmlParser(); - void processLine(const std::string& input); + void processLine(const String& input); XmlDocumentPtr getDocument(); @@ -95,8 +95,8 @@ private: XmlDocumentPtr mDocument; std::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 index a9e741f..8d94f63 100644 --- a/src/base/core/serialization/xml/XmlWriter.cpp +++ b/src/base/core/serialization/xml/XmlWriter.cpp @@ -3,22 +3,21 @@ #include "XmlDocument.h" #include "XmlAttribute.h" -std::string XmlWriter::toString(XmlDocument* document) +Status XmlWriter::toString(XmlDocument* document, String& output) { - std::string content; if (auto prolog = document->getProlog()) { - content += "getAttributes()) { - content += " " + attribute->getName() + "=\"" + attribute->getValue() + "\""; + output += " " + attribute->getName() + "=\"" + attribute->getValue() + "\""; } - content += "?>\n"; + output += "?>\n"; } if (auto root = document->getRoot()) { - content += root->toString(); + output += root->toString(); } - return content; + return {}; } diff --git a/src/base/core/serialization/xml/XmlWriter.h b/src/base/core/serialization/xml/XmlWriter.h index 0b9869d..d02afcc 100644 --- a/src/base/core/serialization/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 index 7c4142e..b89c784 100644 --- a/src/base/core/serialization/xml/xml-elements/XmlAttribute.cpp +++ b/src/base/core/serialization/xml/xml-elements/XmlAttribute.cpp @@ -1,28 +1,28 @@ #include "XmlAttribute.h" -XmlAttribute::XmlAttribute(const std::string& name) +XmlAttribute::XmlAttribute(const String& name) : mName(name), mValue() { } -XmlAttributePtr XmlAttribute::Create(const std::string& name) +XmlAttributePtr XmlAttribute::Create(const String& name) { return std::make_unique(name); } -const std::string& XmlAttribute::getName() const +const String& XmlAttribute::getName() const { return mName; } -const std::string& XmlAttribute::getValue() const +const String& XmlAttribute::getValue() const { return mValue; } -void XmlAttribute::setValue(const std::string& value) +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 index 302c5bf..8cdb730 100644 --- a/src/base/core/serialization/xml/xml-elements/XmlAttribute.h +++ b/src/base/core/serialization/xml/xml-elements/XmlAttribute.h @@ -1,23 +1,23 @@ #pragma once -#include -#include +#include "Memory.h" +#include "String.h" class XmlAttribute { public: - XmlAttribute(const std::string& name); + XmlAttribute(const String& name); - static std::unique_ptr Create(const std::string& name); + static Ptr Create(const String& name); - const std::string& getName() const; + const String& getName() const; - const std::string& getValue() const; + const String& getValue() const; - void setValue(const std::string& value); + void setValue(const String& value); private: - std::string mName; - std::string mValue; + String mName; + String mValue; }; -using XmlAttributePtr = std::unique_ptr; +using XmlAttributePtr = Ptr; diff --git a/src/base/core/serialization/xml/xml-elements/XmlElement.cpp b/src/base/core/serialization/xml/xml-elements/XmlElement.cpp index 7cdd4cd..ba0e819 100644 --- a/src/base/core/serialization/xml/xml-elements/XmlElement.cpp +++ b/src/base/core/serialization/xml/xml-elements/XmlElement.cpp @@ -2,7 +2,7 @@ #include "XmlAttribute.h" -XmlElement::XmlElement(const std::string& tagName) +XmlElement::XmlElement(const String& tagName) : mTagName(tagName), mChildren() { @@ -14,12 +14,12 @@ XmlElement::~XmlElement() } -XmlElementPtr XmlElement::Create(const std::string& tagName) +XmlElementPtr XmlElement::Create(const String& tagName) { return std::make_unique(tagName); } -void XmlElement::setTagName(const std::string& tagName) +void XmlElement::setTagName(const String& tagName) { mTagName = tagName; } @@ -34,29 +34,29 @@ void XmlElement::addAttribute(XmlAttributePtr attribute) mAttributes[attribute->getName()] = std::move(attribute); } -void XmlElement::addAttribute(const std::string& name, const std::string& value) +void XmlElement::addAttribute(const String& name, const String& value) { auto attr = std::make_unique(name); attr->setValue(value); addAttribute(std::move(attr)); } -const std::string& XmlElement::getTagName() const +const String& XmlElement::getTagName() const { return mTagName; } -const std::string& XmlElement::getText() const +const String& XmlElement::getText() const { return mText; } -void XmlElement::setText(const std::string& text) +void XmlElement::setText(const String& text) { mText = text; } -XmlElement* XmlElement::getFirstChildWithTagName(const std::string& tag) +XmlElement* XmlElement::getFirstChildWithTagName(const String& tag) { for(auto& child : mChildren) { @@ -69,12 +69,12 @@ XmlElement* XmlElement::getFirstChildWithTagName(const std::string& tag) return nullptr; } -bool XmlElement::hasAttribute(const std::string& attribute) const +bool XmlElement::hasAttribute(const String& attribute) const { return (bool)(getAttribute(attribute)); } -XmlAttribute* XmlElement::getAttribute(const std::string& attributeName) const +XmlAttribute* XmlElement::getAttribute(const String& attributeName) const { if (auto iter = mAttributes.find(attributeName); iter != mAttributes.end()) { @@ -83,21 +83,21 @@ XmlAttribute* XmlElement::getAttribute(const std::string& attributeName) const return nullptr; } -const std::unordered_map& XmlElement::getAttributes() const +const std::unordered_map& XmlElement::getAttributes() const { return mAttributes; } -const std::vector >& XmlElement::getChildren() const +const Vector >& XmlElement::getChildren() const { return mChildren; } -std::string XmlElement::toString(unsigned depth, bool keepInline) const +String XmlElement::toString(unsigned depth, bool keepInline) const { - const auto prefix = std::string(2*depth, ' '); + const auto prefix = String(2*depth, ' '); - std::string line_ending = keepInline ? "" : "\n"; + String line_ending = keepInline ? "" : "\n"; auto content = prefix + "<" + getTagName(); for (const auto& [key, attribute] : getAttributes()) diff --git a/src/base/core/serialization/xml/xml-elements/XmlElement.h b/src/base/core/serialization/xml/xml-elements/XmlElement.h index 1b3139f..e176b4b 100644 --- a/src/base/core/serialization/xml/xml-elements/XmlElement.h +++ b/src/base/core/serialization/xml/xml-elements/XmlElement.h @@ -1,47 +1,44 @@ #pragma once -#include -#include -#include -#include +#include "Pointer.h" +#include "String.h" +#include "Map.h" class XmlAttribute; -using XmlAttributePtr = std::unique_ptr; class XmlElement { public: - XmlElement(const std::string& tagName); + XmlElement(const String& tagName); virtual ~XmlElement(); - static std::unique_ptr Create(const std::string& tagName); + static Ptr Create(const String& tagName); void addAttribute(XmlAttributePtr attribute); - void addAttribute(const std::string& name, const std::string& value); - void addChild(std::unique_ptr child); + void addAttribute(const String& name, const String& value); + void addChild(Ptr child); - const std::string& getTagName() const; - const std::string& getText() const; + const String& getTagName() const; + const String& getText() const; - bool hasAttribute(const std::string& attribute) const; - XmlAttribute* getAttribute(const std::string& attribute) const; - const std::unordered_map& getAttributes() const; + XmlAttribute* getAttribute(const String& attribute) const; + const Map >& getAttributes() const; - const std::vector >& getChildren() const; + const Vector >& getChildren() const; - XmlElement* getFirstChildWithTagName(const std::string& tag); + XmlElement* getFirstChildWithTagName(const String& tag); - void setText(const std::string& text); - void setTagName(const std::string& tagName); + bool hasAttribute(const String& attribute) const; - virtual std::string toString(unsigned depth = 0, bool keepInline = false) const; + void setText(const String& text); + void setTagName(const String& tagName); + + virtual String toString(unsigned depth = 0, bool keepInline = false) const; protected: - std::string mTagName; - std::string mText; + String mTagName; + String mText; - std::unordered_map mAttributes; - std::vector > mChildren; + Map > mAttributes; + Vector > mChildren; }; - -using XmlElementPtr = std::unique_ptr; diff --git a/src/base/core/serialization/xml/xml-elements/XmlProlog.cpp b/src/base/core/serialization/xml/xml-elements/XmlProlog.cpp index eb9f622..a88712b 100644 --- a/src/base/core/serialization/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,7 +10,7 @@ XmlProlog::XmlProlog(const std::string& tagName) } -XmlPrologPtr XmlProlog::Create(const std::string& tagName) +XmlPrologPtr XmlProlog::Create(const String& tagName) { return std::make_unique(tagName); } @@ -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/serialization/xml/xml-elements/XmlProlog.h b/src/base/core/serialization/xml/xml-elements/XmlProlog.h index 8a30288..7458e04 100644 --- a/src/base/core/serialization/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 "Memory.h" +#include "Vector.h" class XmlProlog : public XmlElement { @@ -17,15 +17,15 @@ 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: @@ -33,4 +33,4 @@ private: Encoding mEncoding; }; -using XmlPrologPtr = std::unique_ptr; +using XmlPrologPtr = Ptr; diff --git a/src/base/core/streams/BinaryStream.cpp b/src/base/core/streams/BinaryStream.cpp index aee7ac2..68f9798 100644 --- a/src/base/core/streams/BinaryStream.cpp +++ b/src/base/core/streams/BinaryStream.cpp @@ -82,7 +82,7 @@ bool BinaryStream::checkNextDWord(std::basic_istream* stream, const char* return true; } -bool BinaryStream::getNextString(std::basic_istream* stream, std::string& target, unsigned numBytes) +bool BinaryStream::getNextString(std::basic_istream* stream, String& target, unsigned numBytes) { char c; for(unsigned idx=0; idx #include -#include +#include "String.h" #include #include "ByteUtils.h" @@ -36,5 +36,5 @@ public: static bool checkNextDWord(std::basic_istream* stream, const char* target); - static bool getNextString(std::basic_istream* stream, std::string& target, unsigned numBytes); + static bool getNextString(std::basic_istream* stream, String& target, unsigned numBytes); }; diff --git a/src/base/core/streams/BitStream.cpp b/src/base/core/streams/BitStream.cpp index 2d43c1d..38c58be 100644 --- a/src/base/core/streams/BitStream.cpp +++ b/src/base/core/streams/BitStream.cpp @@ -52,7 +52,7 @@ String BitStream::logLocation() String BitStream::logNextNBytes(std::size_t n) const { - std::stringstream sstr; + Stringstream sstr; std::size_t count{0}; VecBytes bytes; peekNextNBytes(n, bytes); diff --git a/src/base/core/system/process/AbstractApp.h b/src/base/core/system/process/AbstractApp.h index ab34aa4..2434bf9 100644 --- a/src/base/core/system/process/AbstractApp.h +++ b/src/base/core/system/process/AbstractApp.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Memory.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/system/process/CommandLineArgs.cpp b/src/base/core/system/process/CommandLineArgs.cpp index 47a5b48..309d199 100644 --- a/src/base/core/system/process/CommandLineArgs.cpp +++ b/src/base/core/system/process/CommandLineArgs.cpp @@ -23,7 +23,7 @@ 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]); diff --git a/src/base/core/system/process/Process.h b/src/base/core/system/process/Process.h index 9c100f2..524d0d4 100644 --- a/src/base/core/system/process/Process.h +++ b/src/base/core/system/process/Process.h @@ -4,12 +4,17 @@ #include "File.h" #include "Result.h" +#include "Logger.h" + #include +#include +#include class Process { public: - Status launch(const String& command) + static Status launch(const String& command, + const Vector& args) { const auto pid = fork(); if (pid < 0) @@ -19,7 +24,39 @@ public: if (pid == 0) { - //pass + 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 {}; } diff --git a/src/base/core/thread/ThreadCollection.cpp b/src/base/core/thread/ThreadCollection.cpp index 6394204..b3d32e5 100644 --- a/src/base/core/thread/ThreadCollection.cpp +++ b/src/base/core/thread/ThreadCollection.cpp @@ -1,8 +1,8 @@ #include "ThreadCollection.h" -#include +#include "Vector.h" -bool ThreadCollection::add(std::unique_ptr thread) +bool ThreadCollection::add(Ptr thread) { if (!mAccepting) { @@ -18,7 +18,7 @@ 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) diff --git a/src/base/core/thread/ThreadCollection.h b/src/base/core/thread/ThreadCollection.h index d8412d9..762330e 100644 --- a/src/base/core/thread/ThreadCollection.h +++ b/src/base/core/thread/ThreadCollection.h @@ -1,16 +1,16 @@ #pragma once #include -#include +#include "Memory.h" #include #include #include -#include +#include "Vector.h" class ThreadCollection { public: - bool add(std::unique_ptr thread); + bool add(Ptr thread); void joinAndClearAll(); @@ -26,6 +26,6 @@ private: mutable std::mutex mMutex; std::atomic mAccepting{ true }; - std::vector mMarkedForRemoval; - std::unordered_map > mThreads; + Vector mMarkedForRemoval; + std::unordered_map > mThreads; }; \ No newline at end of file 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..f3cb25d 100644 --- a/src/base/database/Database.h +++ b/src/base/database/Database.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Memory.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..8cc62d6 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 "Memory.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..9b04946 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 "Memory.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/geometry/grid/AbstractGrid.h b/src/base/geometry/grid/AbstractGrid.h index c2ef52e..4c36aca 100644 --- a/src/base/geometry/grid/AbstractGrid.h +++ b/src/base/geometry/grid/AbstractGrid.h @@ -2,8 +2,8 @@ #include "Bounds.h" -#include -#include +#include "Vector.h" +#include "Memory.h" class AbstractGrid { diff --git a/src/base/geometry/grid/Grid.h b/src/base/geometry/grid/Grid.h index 7159f4f..75d77ff 100644 --- a/src/base/geometry/grid/Grid.h +++ b/src/base/geometry/grid/Grid.h @@ -22,7 +22,7 @@ public: 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); } diff --git a/src/base/geometry/grid/TypedGrid.h b/src/base/geometry/grid/TypedGrid.h index 6e0df7a..d5973a8 100644 --- a/src/base/geometry/grid/TypedGrid.h +++ b/src/base/geometry/grid/TypedGrid.h @@ -3,7 +3,7 @@ #include "List.h" #include "AbstractGrid.h" -#include +#include "Memory.h" template class TypedGrid : public AbstractGrid @@ -26,5 +26,5 @@ public: return mData.get(); } protected: - std::unique_ptr > mData; + Ptr > mData; }; diff --git a/src/base/geometry/math/Matrix.cpp b/src/base/geometry/math/Matrix.cpp index 6e3ff48..9feaaa2 100644 --- a/src/base/geometry/math/Matrix.cpp +++ b/src/base/geometry/math/Matrix.cpp @@ -1,12 +1,12 @@ #include "Matrix.h" -#include +#include "String.h" #include template Matrix::Matrix(T value) { - mData = std::vector(M * N, value); + mData = Vector(M * N, value); } template @@ -14,12 +14,12 @@ 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); } } @@ -44,7 +44,7 @@ void Matrix::setDiagonals(T value) } template -void Matrix::setDiagonals(const std::vector& values) +void Matrix::setDiagonals(const Vector& values) { if (!isSquare()) { diff --git a/src/base/geometry/math/Matrix.h b/src/base/geometry/math/Matrix.h index c04980d..6999238 100644 --- a/src/base/geometry/math/Matrix.h +++ b/src/base/geometry/math/Matrix.h @@ -2,7 +2,7 @@ #include "Vector.h" -#include +#include "Vector.h" #include template @@ -33,7 +33,7 @@ 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); @@ -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..b8c73f8 100644 --- a/src/base/geometry/math/Vector.cpp +++ b/src/base/geometry/math/Vector.cpp @@ -9,7 +9,7 @@ template Vector::Vector(Primitive p) { - mData = std::vector(DIM, 0.0); + mData = Vector(DIM, 0.0); switch(p) { case Primitive::UNIT_X: @@ -34,9 +34,9 @@ Vector::Vector(Primitive p) } template -Vector::Vector(const std::vector& values) +Vector::Vector(const Vector& values) { - mData = std::vector(DIM, 0.0); + mData = Vector(DIM, 0.0); if (values.empty()) { @@ -143,7 +143,7 @@ Vector Vector::getNormalized() const } template -void Vector::scale(const std::vector&) +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..77df354 100644 --- a/src/base/geometry/math/Vector.h +++ b/src/base/geometry/math/Vector.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Vector.h" #include template @@ -19,7 +19,7 @@ public: Vector(Primitive p); - Vector(const std::vector& values = {}); + Vector(const Vector& values = {}); ~Vector(); @@ -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 { @@ -85,7 +85,7 @@ public: } private: - std::vector mData; + Vector mData; }; using Vector4 = Vector; diff --git a/src/base/geometry/path/Line.cpp b/src/base/geometry/path/Line.cpp index e8ec117..d0b5d70 100644 --- a/src/base/geometry/path/Line.cpp +++ b/src/base/geometry/path/Line.cpp @@ -8,7 +8,7 @@ Line::Line(const PointCollection& points) } template -Line::Line(InputBufferType bufferType, const std::vector& buffer) +Line::Line(InputBufferType bufferType, const Vector& buffer) { if (bufferType == InputBufferType::XY) { diff --git a/src/base/geometry/path/Line.h b/src/base/geometry/path/Line.h index 85a0466..25a6f6c 100644 --- a/src/base/geometry/path/Line.h +++ b/src/base/geometry/path/Line.h @@ -3,8 +3,8 @@ #include "PathElement.h" #include "PointCollection.h" -#include -#include +#include "Vector.h" +#include "String.h" template class Line : public PathElement @@ -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..20c8112 100644 --- a/src/base/geometry/path/LineSegment.cpp +++ b/src/base/geometry/path/LineSegment.cpp @@ -9,7 +9,7 @@ LineSegment::LineSegment(const Point& p0, const Point& p1) } template -std::unique_ptr > LineSegment ::Create(const Point& p0, const Point& p1) +Ptr > LineSegment ::Create(const Point& p0, const Point& p1) { return std::make_unique >(p0, p1); } diff --git a/src/base/geometry/path/LineSegment.h b/src/base/geometry/path/LineSegment.h index 5ad7e72..9d83eba 100644 --- a/src/base/geometry/path/LineSegment.h +++ b/src/base/geometry/path/LineSegment.h @@ -9,7 +9,7 @@ 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..1634cb8 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 "Memory.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/points/DiscretePoint.h b/src/base/geometry/points/DiscretePoint.h index f87185c..6dfbc9a 100644 --- a/src/base/geometry/points/DiscretePoint.h +++ b/src/base/geometry/points/DiscretePoint.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Memory.h" class DiscretePoint { diff --git a/src/base/geometry/points/Point.cpp b/src/base/geometry/points/Point.cpp index d436168..9f61198 100644 --- a/src/base/geometry/points/Point.cpp +++ b/src/base/geometry/points/Point.cpp @@ -15,7 +15,7 @@ Point Point::from(const Point<2>& p) template Point::Point(double x, double y, double z) { - mCoords = std::vector(DIM); + mCoords = Vector(DIM); if (DIM > 0) { mCoords[0] = x; @@ -33,7 +33,7 @@ Point::Point(double x, double y, double z) template Point::Point(const Vector& v) { - mCoords = std::vector(DIM); + mCoords = Vector(DIM); for (std::size_t idx = 0; idx < DIM; idx++) { mCoords[idx] = v.getEntry(idx); @@ -50,7 +50,7 @@ Point::Point(const DiscretePoint& point) 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; diff --git a/src/base/geometry/points/Point.h b/src/base/geometry/points/Point.h index d2e2451..e95e594 100644 --- a/src/base/geometry/points/Point.h +++ b/src/base/geometry/points/Point.h @@ -3,7 +3,7 @@ #include "DiscretePoint.h" #include "Vector.h" -#include +#include "Memory.h" class Transform; @@ -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..d8a4e74 100644 --- a/src/base/geometry/points/PointCollection.cpp +++ b/src/base/geometry/points/PointCollection.cpp @@ -1,7 +1,7 @@ #include "PointCollection.h" template -PointCollection::PointCollection(const std::vector > points) +PointCollection::PointCollection(const Vector > points) : mPoints(points) { @@ -54,7 +54,7 @@ Point PointCollection::getEndPoint() const } template -const std::vector >& PointCollection::getPoints() const +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..62ef6c9 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 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..1f2bf12 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, std::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, std::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, std::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, std::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..3f7b646 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 = " ", std::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 = " ", std::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 = " ", std::size_t precision = 0); - static std::string toString(double x, std::size_t precision = 0); + static String toString(double x, std::size_t precision = 0); }; diff --git a/src/base/geometry/primitives/Polygon.cpp b/src/base/geometry/primitives/Polygon.cpp index abdbdf1..543a605 100644 --- a/src/base/geometry/primitives/Polygon.cpp +++ b/src/base/geometry/primitives/Polygon.cpp @@ -2,7 +2,7 @@ namespace ntk { template - Polygon::Polygon(const std::vector >& points) + Polygon::Polygon(const Vector >& points) : AbstractGeometricItem() { mPoints = PointCollection(points); diff --git a/src/base/geometry/primitives/Polygon.h b/src/base/geometry/primitives/Polygon.h index 07a005d..49c2586 100644 --- a/src/base/geometry/primitives/Polygon.h +++ b/src/base/geometry/primitives/Polygon.h @@ -9,7 +9,7 @@ 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/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..49f05ae 100644 --- a/src/base/network/NetworkManager.h +++ b/src/base/network/NetworkManager.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Memory.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..e838799 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 "Memory.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..310ed40 100644 --- a/src/base/network/server/HttpServer.h +++ b/src/base/network/server/HttpServer.h @@ -2,7 +2,7 @@ #include "PlatformSocketServer.h" -#include +#include "Memory.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..0a51a6c 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 "Memory.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..007213e 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 "Memory.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..6052c29 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 "Memory.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..6c51706 100644 --- a/src/base/network/sockets/Socket.h +++ b/src/base/network/sockets/Socket.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Memory.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/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..ab8f96a 100644 --- a/src/console/MainApplication.h +++ b/src/console/MainApplication.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "Memory.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 index ae0ab7b..499aa77 100644 --- a/src/console/TermInfo.cpp +++ b/src/console/TermInfo.cpp @@ -1,12 +1,12 @@ #include "TermInfo.h" -#include +#include "Vector.h" #include "File.h" #include #include -bool TermInfo::load_terminfo(const std::string& terminfo_dir, - const std::string& term) +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)) @@ -14,7 +14,7 @@ bool TermInfo::load_terminfo(const std::string& terminfo_dir, return false; } - std::string suffix = "/" + term; + String suffix = "/" + term; suffix = term[0] + suffix; const auto file_path = path / std::filesystem::path(suffix); @@ -32,7 +32,7 @@ bool TermInfo::load_terminfo(const std::string& terminfo_dir, return false; } - std::vector content; + Vector content; file.readBinary(content); short header_size = 12; if (content.size() < static_cast(header_size)) @@ -58,8 +58,8 @@ bool TermInfo::load_terminfo(const std::string& terminfo_dir, { std::cerr << "unexpected terminfo size" << std::endl; } - std::vector names; - std::string working_name; + Vector names; + String working_name; for(std::size_t idx=header_size; idx common_paths = {"/usr/share/terminfo"}; + Vector common_paths = {"/usr/share/terminfo"}; for (const auto& path : common_paths) { if (load_terminfo(path, term)) diff --git a/src/console/TermInfo.h b/src/console/TermInfo.h index 74e7fcf..e2e7bda 100644 --- a/src/console/TermInfo.h +++ b/src/console/TermInfo.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "String.h" class TermInfo { @@ -8,8 +8,8 @@ class TermInfo // https://man7.org/linux/man-pages/man5/terminfo.5.html // Best grab a coffee public: - bool load_terminfo(const std::string& terminfo_dir, - const std::string& term); + bool load_terminfo(const String& terminfo_dir, + const String& term); void load(); }; diff --git a/src/main.cpp b/src/main.cpp index adecad8..455159c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -10,7 +10,18 @@ int main(int argc, char** argv) } BuildSession build(argv[1]); - build.scan(); - build.build(); + const auto scan_status = build.scan(); + if (!scan_status.ok()) + { + LOG_ERROR("Scan failed with " << scan_status.error().msg()); + return -1; + } + + const auto build_status = build.build(); + if (!build_status.ok()) + { + LOG_ERROR("Build failed with " << build_status.error().msg()); + return -1; + } return 0; } diff --git a/src/media/audio/AudioDevice.cpp b/src/media/audio/AudioDevice.cpp index 3670110..fa339c8 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(); } @@ -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; } diff --git a/src/media/audio/AudioDevice.h b/src/media/audio/AudioDevice.h index 57e19d8..dfecc4b 100644 --- a/src/media/audio/AudioDevice.h +++ b/src/media/audio/AudioDevice.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include "Memory.h" +#include "String.h" class AudioDevice { @@ -11,7 +11,7 @@ public: ~AudioDevice(); - static std::unique_ptr Create(); + static Ptr Create(); unsigned getSampleRate() const; @@ -23,9 +23,9 @@ public: 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); @@ -37,7 +37,7 @@ public: void setIsOpen(bool isOpen); private: - std::string mName {"unset"}; + String mName {"unset"}; unsigned mSampleRate {44100}; unsigned mNumChannels {1}; unsigned mPeriod {2}; @@ -45,4 +45,4 @@ private: 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..dada9d1 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(); } diff --git a/src/media/audio/AudioManager.h b/src/media/audio/AudioManager.h index dacef02..f1679b0 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 "Memory.h" +#include "Vector.h" class AudioSample; @@ -16,7 +16,7 @@ public: ~AudioManager(); - static std::unique_ptr Create(); + static Ptr Create(); void addAudioDevice(AudioDevicePtr device); @@ -27,8 +27,8 @@ public: 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..b1c6727 100644 --- a/src/media/audio/AudioSample.cpp +++ b/src/media/audio/AudioSample.cpp @@ -5,7 +5,7 @@ AudioSample::AudioSample() } -std::unique_ptr AudioSample::Create() +Ptr AudioSample::Create() { return std::make_unique(); } @@ -43,5 +43,5 @@ AudioSample::ChannelData AudioSample::getChannelData(std::size_t channel) const { return mData[channel]; } - return std::vector(); + return Vector(); } diff --git a/src/media/audio/AudioSample.h b/src/media/audio/AudioSample.h index 08cfc8c..d367e4a 100644 --- a/src/media/audio/AudioSample.h +++ b/src/media/audio/AudioSample.h @@ -1,16 +1,16 @@ #pragma once -#include -#include +#include "Vector.h" +#include "Memory.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; @@ -22,7 +22,7 @@ public: 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..6dd2c23 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 "Memory.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..1f71969 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 "Memory.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..5851e97 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 "Memory.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..c10cc0d 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 "Memory.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..a153c08 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 "Memory.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/Image.cpp b/src/media/image/Image.cpp index be331b2..4598c28 100644 --- a/src/media/image/Image.cpp +++ b/src/media/image/Image.cpp @@ -22,7 +22,7 @@ Image::~Image() } -std::unique_ptr Image::Create(unsigned width, unsigned height, Color::Format format) +Ptr Image::Create(unsigned width, unsigned height, Color::Format format) { return std::make_unique(width, height, format); } @@ -34,7 +34,7 @@ void Image::initialize() 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 (!mGrid) { diff --git a/src/media/image/Image.h b/src/media/image/Image.h index 4050000..128472f 100644 --- a/src/media/image/Image.h +++ b/src/media/image/Image.h @@ -3,8 +3,8 @@ #include "PlatformImage.h" #include "Pixel.h" -#include -#include +#include "Memory.h" +#include "Vector.h" class Color; @@ -15,11 +15,11 @@ class Image { public: using Index = std::pair; - using Indices = std::vector; + using Indices = Vector; Image(unsigned width, unsigned height, Color::Format format = Color::Format::RGBA); ~Image(); - static std::unique_ptr Create(unsigned width, unsigned height, Color::Format format = Color::Format::RGBA); + static Ptr Create(unsigned width, unsigned height, Color::Format format = Color::Format::RGBA); unsigned getBytesPerRow() const; unsigned getWidth() const; @@ -33,7 +33,7 @@ public: 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); @@ -48,6 +48,6 @@ private: unsigned mBitDepth{8}; Color::Format mFormat{Color::Format::RGBA}; - std::unique_ptr > mGrid; - std::unique_ptr mPlatformImage; + Ptr > mGrid; + Ptr mPlatformImage; }; diff --git a/src/media/image/ImageBitStream.cpp b/src/media/image/ImageBitStream.cpp index 75ac0fd..3f997f1 100644 --- a/src/media/image/ImageBitStream.cpp +++ b/src/media/image/ImageBitStream.cpp @@ -15,7 +15,7 @@ bool ImageBitStream::isFinished() const return mByteOffset == static_cast(mImage->getGrid()->getDataSize()); } -std::vector ImageBitStream::peekNextNBytes(std::size_t) const +Vector ImageBitStream::peekNextNBytes(std::size_t) const { return {}; } diff --git a/src/media/image/ImageBitStream.h b/src/media/image/ImageBitStream.h index a759a87..2a011f1 100644 --- a/src/media/image/ImageBitStream.h +++ b/src/media/image/ImageBitStream.h @@ -13,13 +13,13 @@ public: bool isFinished() const override; - std::vector peekNextNBytes(std::size_t n) const override; + Vector peekNextNBytes(std::size_t n) const override; std::optional readNextByte() 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 BasicPngWriter::Create() +Ptr BasicPngWriter::Create() { return std::make_unique(); } @@ -99,7 +99,7 @@ void BasicPngWriter::writeEndChunk() 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) @@ -131,7 +131,7 @@ void BasicPngWriter::writeDataChunks(const BufferBitStream& buffer) 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; @@ -156,7 +156,7 @@ 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()) { @@ -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 fd60e91..78f4e8d 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 "Memory.h" +#include "String.h" #include using Path = std::filesystem::path; @@ -22,7 +22,7 @@ public: virtual ~BasicPngWriter(); - using Ptr = std::unique_ptr; + using Ptr = Ptr; static BasicPngWriter::Ptr Create(); @@ -43,8 +43,8 @@ private: //void writeIDatChunk(); Image* mWorkingImage{ nullptr }; - std::unique_ptr mInStream; - std::unique_ptr mOutStream; + Ptr mInStream; + Ptr mOutStream; bool mPngInfoUserSet{ false }; PngInfo mPngInfo; diff --git a/src/media/image/png/PngHeader.cpp b/src/media/image/png/PngHeader.cpp index 1cfadfa..d984027 100644 --- a/src/media/image/png/PngHeader.cpp +++ b/src/media/image/png/PngHeader.cpp @@ -4,9 +4,9 @@ #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"; @@ -52,12 +52,12 @@ void PngHeader::getSignature(VecBytes& sig) const 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; } @@ -91,7 +91,7 @@ void PngHeader::updateData() 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 0f4ff96..2f9969f 100644 --- a/src/media/image/png/PngHeader.h +++ b/src/media/image/png/PngHeader.h @@ -2,7 +2,7 @@ #include "PngInfo.h" -#include +#include "Vector.h" #include class PngHeader @@ -26,15 +26,15 @@ public: 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(DWord width, DWord height, Byte bitDepth); - std::string toString() const; + String toString() const; void updateData(); @@ -43,7 +43,7 @@ private: DWord mHeight{0}; Byte mBitDepth{0}; PngInfo mPngInfo; - std::string mName{"IHDR"}; + String mName{"IHDR"}; DWord mCachedCrc{0}; diff --git a/src/media/image/png/PngInfo.cpp b/src/media/image/png/PngInfo.cpp index 6bc3f53..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) { @@ -24,7 +24,7 @@ ColorType PngInfo::ColorType() const return mColorType; } -std::string PngInfo::toString(CompressionMethod method) const +String PngInfo::toString(CompressionMethod method) const { switch(method) { @@ -35,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) { @@ -46,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) { @@ -88,9 +88,9 @@ 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 1319ff4..8f0966e 100644 --- a/src/media/image/png/PngInfo.h +++ b/src/media/image/png/PngInfo.h @@ -2,7 +2,7 @@ #include "ByteTypes.h" -#include +#include "String.h" #include class PngInfo @@ -35,13 +35,13 @@ public: 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, Byte bitDepth) const; @@ -49,7 +49,7 @@ public: 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..ea06f8b 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 "Memory.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 c08dbfa..ee5caaf 100644 --- a/src/media/image/png/PngWriter.cpp +++ b/src/media/image/png/PngWriter.cpp @@ -21,7 +21,7 @@ PngWriter::~PngWriter() } -std::unique_ptr PngWriter::Create() +Ptr PngWriter::Create() { return std::make_unique(); } diff --git a/src/media/image/png/PngWriter.h b/src/media/image/png/PngWriter.h index 03091c3..c71dd1a 100644 --- a/src/media/image/png/PngWriter.h +++ b/src/media/image/png/PngWriter.h @@ -4,8 +4,8 @@ #include "IImageWriter.h" #include "DeflateElements.h" -#include -#include +#include "Memory.h" +#include "String.h" class PngWriter : public IImageWriter { @@ -13,14 +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..2603ce0 100644 --- a/src/media/image/win32/Win32WicImage.h +++ b/src/media/image/win32/Win32WicImage.h @@ -4,7 +4,7 @@ #include -#include +#include "Memory.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